File size: 2,799 Bytes
111ee96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""El subproceso `claude -p` nunca debe ver ANTHROPIC_API_KEY, y los errores de acceso no se reintentan.
No se llama a la CLI real: subprocess.run se sustituye por una función falsa."""
import json
import subprocess

import pytest

from licitabench.corredores import claude_cli


class _Proc:
    def __init__(self, stdout):
        self.stdout, self.stderr, self.returncode = stdout, "", 0


def _falso_run(capturas, payload):
    def run(cmd, **kw):
        capturas.append({"cmd": cmd, "env": kw.get("env"), "cwd": kw.get("cwd")})
        return _Proc(json.dumps(payload))
    return run


def test_entorno_sin_clave(monkeypatch):
    monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-prueba")
    monkeypatch.delenv("CLAUDE_CODE_OAUTH_TOKEN", raising=False)
    capturas = []
    monkeypatch.setattr(subprocess, "run", _falso_run(capturas, {"is_error": False, "result": '{"a": 1}', "structured_output": {"a": 1}, "total_cost_usd": 0.0}))
    c = claude_cli.CorredorClaude(modelo="claude-haiku-5-5")
    r, uso = c.generar_con_uso("hola", {"type": "object"})
    assert r == {"a": 1}
    assert capturas and "ANTHROPIC_API_KEY" not in capturas[0]["env"]
    assert "--json-schema" in capturas[0]["cmd"] and "--tools" in capturas[0]["cmd"]


def test_entorno_sin_clave_aunque_no_haya_token_oauth():
    import os
    os.environ["ANTHROPIC_API_KEY"] = "sk-ant-prueba"
    try:
        assert "ANTHROPIC_API_KEY" not in claude_cli.entorno_sin_clave()
    finally:
        del os.environ["ANTHROPIC_API_KEY"]


@pytest.mark.parametrize("mensaje,tipo", [
    ("API Error: 400 You have reached your specified API usage limits. You will regain access on 2026-12-01 at 00:00 UTC.", claude_cli.LimiteUso),
    ("Failed to authenticate: OAuth session expired and could not be refreshed", claude_cli.SinAcceso),
    ("API Error: 429 rate limit", claude_cli.LimiteUso),
])
def test_errores_de_acceso_no_se_reintentan(monkeypatch, mensaje, tipo):
    capturas = []
    monkeypatch.setattr(subprocess, "run", _falso_run(capturas, {"is_error": True, "result": mensaje}))
    monkeypatch.setattr(claude_cli.time, "sleep", lambda s: None)
    c = claude_cli.CorredorClaude(reintentos=2)
    with pytest.raises(tipo):
        c.generar("hola")
    assert len(capturas) == 1          # una sola llamada: nada de reintentos


def test_limite_uso_extrae_reinicio():
    e = claude_cli.LimiteUso("You have reached your specified API usage limits. You will regain access on 2026-12-01 at 00:00 UTC.")
    assert e.reinicio and e.reinicio.startswith("2026-12-01")


def test_comprobar_aborta(monkeypatch):
    monkeypatch.setattr(subprocess, "run", _falso_run([], {"is_error": True, "result": "Failed to authenticate: OAuth session expired"}))
    with pytest.raises(claude_cli.SinAcceso):
        claude_cli.comprobar()