55 lines
2.2 KiB
Python
55 lines
2.2 KiB
Python
|
|
import importlib.util
|
||
|
|
import json
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
import pytest
|
||
|
|
|
||
|
|
SPEC = importlib.util.spec_from_file_location("openrouter_key_check", Path(__file__).resolve().parents[1] / "tools/openrouter_key_check.py")
|
||
|
|
probe = importlib.util.module_from_spec(SPEC)
|
||
|
|
SPEC.loader.exec_module(probe)
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize("status,body,result", [
|
||
|
|
(200, b'{"data":{"label":"SYNTHETIC-KEY","usage":999}}', "authenticated"),
|
||
|
|
(401, b'SYNTHETIC-KEY', "refused"),
|
||
|
|
(302, b'SYNTHETIC-KEY', "refused"),
|
||
|
|
(500, b'SYNTHETIC-KEY', "refused"),
|
||
|
|
(200, b'bad SYNTHETIC-KEY', "check_failed"),
|
||
|
|
(200, b'{"data":null}', "invalid_response"),
|
||
|
|
(200, b'x' * (probe.MAX_BODY + 1), "invalid_response"),
|
||
|
|
])
|
||
|
|
def test_probe_is_one_fixed_read_and_never_returns_provider_content(status, body, result):
|
||
|
|
calls = []
|
||
|
|
class Connection:
|
||
|
|
def __init__(self, host, timeout):
|
||
|
|
assert (host, timeout) == ("openrouter.ai", 10)
|
||
|
|
def request(self, method, path, headers):
|
||
|
|
calls.append((method, path))
|
||
|
|
assert headers["Authorization"] == "Bearer SYNTHETIC-KEY"
|
||
|
|
def getresponse(self): return self
|
||
|
|
def read(self, size):
|
||
|
|
assert size == probe.MAX_BODY + 1
|
||
|
|
return body[:size]
|
||
|
|
def close(self): calls.append("closed")
|
||
|
|
Connection.status = status
|
||
|
|
output = probe.check("SYNTHETIC-KEY", connection_factory=Connection)
|
||
|
|
assert output["result"] == result
|
||
|
|
assert "SYNTHETIC-KEY" not in json.dumps(output)
|
||
|
|
assert calls == [("GET", "/api/v1/key"), "closed"]
|
||
|
|
|
||
|
|
|
||
|
|
def test_transport_error_is_sanitized_and_connection_closed():
|
||
|
|
closed = []
|
||
|
|
class Broken:
|
||
|
|
def __init__(self, *a, **kw): pass
|
||
|
|
def request(self, *a, **kw): raise OSError("SYNTHETIC-KEY")
|
||
|
|
def close(self): closed.append(True)
|
||
|
|
assert probe.check("SYNTHETIC-KEY", connection_factory=Broken) == {"result": "check_failed"}
|
||
|
|
assert closed == [True]
|
||
|
|
|
||
|
|
|
||
|
|
@pytest.mark.parametrize("key", ["", "key\r\nInjected: value", "key with spaces", "non-ascii-ä"])
|
||
|
|
def test_bad_input_never_opens_connection(key):
|
||
|
|
def forbidden(*a, **kw): pytest.fail("must not connect")
|
||
|
|
assert probe.check(key, connection_factory=forbidden) == {"result": "invalid_input"}
|