95 lines
3.0 KiB
Python
95 lines
3.0 KiB
Python
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
|
|
from backend.ai_config import DeepSeekConfig
|
|
from backend.deepseek_client import DeepSeekClient
|
|
|
|
|
|
class FakeResponse:
|
|
def __init__(self, payload):
|
|
self.payload = payload
|
|
|
|
def __enter__(self):
|
|
return self
|
|
|
|
def __exit__(self, exc_type, exc, tb):
|
|
return False
|
|
|
|
def read(self):
|
|
return json.dumps(self.payload).encode("utf-8")
|
|
|
|
|
|
def make_config() -> DeepSeekConfig:
|
|
return DeepSeekConfig(
|
|
api_key="test-key",
|
|
base_url="https://coding.simgreek.com",
|
|
model="qwen-plus",
|
|
audio_model="qwen-plus",
|
|
provider="qwen",
|
|
protocol="anthropic",
|
|
translation_batch_size=20,
|
|
timeout_seconds=180,
|
|
)
|
|
|
|
|
|
def test_anthropic_chat_json_posts_messages_request(monkeypatch):
|
|
captured = {}
|
|
|
|
def fake_urlopen(request, timeout):
|
|
captured["url"] = request.full_url
|
|
captured["headers"] = dict(request.header_items())
|
|
captured["body"] = json.loads(request.data.decode("utf-8"))
|
|
return FakeResponse({
|
|
"content": [
|
|
{"type": "text", "text": '{"translations":[{"index":1,"zh":"你好"}]}'}
|
|
]
|
|
})
|
|
|
|
monkeypatch.setattr("backend.deepseek_client.urllib.request.urlopen", fake_urlopen)
|
|
client = DeepSeekClient(make_config())
|
|
|
|
result = client.chat_json("Return JSON only.", {"cues": [{"index": 1, "text": "Hello"}]})
|
|
|
|
assert captured["url"] == "https://coding.simgreek.com/v1/messages"
|
|
assert captured["body"]["model"] == "qwen-plus"
|
|
assert captured["body"]["system"] == "Return JSON only."
|
|
assert captured["body"]["messages"][0]["role"] == "user"
|
|
assert "x-api-key" in {key.lower(): value for key, value in captured["headers"].items()}
|
|
assert result["translations"][0]["zh"] == "你好"
|
|
|
|
|
|
def test_chat_json_accepts_markdown_wrapped_json(monkeypatch):
|
|
def fake_urlopen(request, timeout):
|
|
return FakeResponse({
|
|
"content": [
|
|
{
|
|
"type": "text",
|
|
"text": 'Here is the result:\n```json\n{"translations":[{"index":1,"zh":"你好"}]}\n```',
|
|
}
|
|
]
|
|
})
|
|
|
|
monkeypatch.setattr("backend.deepseek_client.urllib.request.urlopen", fake_urlopen)
|
|
client = DeepSeekClient(make_config())
|
|
|
|
result = client.chat_json("Return JSON only.", {"cues": [{"index": 1, "text": "Hello"}]})
|
|
|
|
assert result["translations"][0]["zh"] == "你好"
|
|
|
|
|
|
if __name__ == "__main__":
|
|
class MonkeyPatch:
|
|
def setattr(self, target, value):
|
|
parts = target.split(".")
|
|
module = __import__(".".join(parts[:2]), fromlist=[parts[1]])
|
|
current = module
|
|
for part in parts[2:-1]:
|
|
current = getattr(current, part)
|
|
setattr(current, parts[-1], value)
|
|
|
|
test_anthropic_chat_json_posts_messages_request(MonkeyPatch())
|
|
test_chat_json_accepts_markdown_wrapped_json(MonkeyPatch())
|