Files
smeta-web/tests/test_claude_bridge_provider_args.py
T

220 lines
8.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Горячий путь claude_bridge: эфемерный ~/.claude по профилю + --model из профиля.
_ephemeral_claude_home(settings_path, exclude_creds): внешний провайдер (exclude_creds=True)
не тащит OAuth-креды подписки. stream_claude берёт модель из профиля провайдера юзера
(provider_chain[0].model), а НЕ из глобальной CLAUDE_MODEL.
"""
import asyncio
import importlib
import os
import shutil
import sys
import pytest
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if ROOT not in sys.path:
sys.path.insert(0, ROOT)
def _src_home(tmp_path):
src = tmp_path / "claude_src"
src.mkdir()
(src / ".credentials.json").write_text("oauth-secret")
(src / "CLAUDE.md").write_text("instructions")
return src
def test_ephemeral_excludes_creds_when_flag(monkeypatch, tmp_path):
import claude_bridge
monkeypatch.setattr(claude_bridge, "CLAUDE_CONFIG_DIR", str(_src_home(tmp_path)))
monkeypatch.setenv("HOME", str(tmp_path)) # ~/.claude.json отсутствует → "{}"
settings = tmp_path / "s.json"
settings.write_text("{}")
cdir, _cjson, tmp = claude_bridge._ephemeral_claude_home(str(settings), exclude_creds=True)
try:
# mutation: убрать `if exclude_creds` → креды скопируются и этот assert упадёт
assert not os.path.exists(os.path.join(cdir, ".credentials.json"))
assert os.path.exists(os.path.join(cdir, "CLAUDE.md"))
finally:
shutil.rmtree(tmp, ignore_errors=True)
def test_ephemeral_keeps_creds_without_flag(monkeypatch, tmp_path):
import claude_bridge
monkeypatch.setattr(claude_bridge, "CLAUDE_CONFIG_DIR", str(_src_home(tmp_path)))
monkeypatch.setenv("HOME", str(tmp_path))
settings = tmp_path / "s.json"
settings.write_text("{}")
cdir, _cjson, tmp = claude_bridge._ephemeral_claude_home(str(settings), exclude_creds=False)
try:
assert os.path.exists(os.path.join(cdir, ".credentials.json"))
finally:
shutil.rmtree(tmp, ignore_errors=True)
class _FakeStream:
async def readline(self):
return b"" # EOF сразу — стрим завершается, docker не запускается
class _FakeProc:
def __init__(self):
self.stdout = _FakeStream()
self.stderr = _FakeStream()
self.returncode = 0 # не None → finally не зовёт terminate
async def wait(self):
return 0
def terminate(self):
pass
def test_stream_claude_uses_profile_model(monkeypatch, tmp_path):
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(ROOT)
import db
importlib.reload(db)
db.init_db()
import claude_bridge
importlib.reload(claude_bridge)
import agent_provider
monkeypatch.setattr(claude_bridge, "CLAUDE_CONFIG_DIR", str(_src_home(tmp_path)))
settings = tmp_path / "s.json"
settings.write_text("{}")
fixed = agent_provider.ProviderProfile(
name="deepseek", settings_path=str(settings),
model="deepseek-v4-flash", uses_api_token=True,
)
monkeypatch.setattr(agent_provider, "provider_chain", lambda _u: [fixed])
captured = {}
async def fake_exec(*cmd, **kwargs):
captured["cmd"] = list(cmd)
return _FakeProc()
monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec)
async def run():
# message без смета+единица-триггеров → не тянем corpus-инъекцию
return [c async for c in claude_bridge.stream_claude("привет", "u@x", "tab")]
asyncio.run(run())
cmd = captured["cmd"]
i = cmd.index("--model")
# mutation: вернуть CLAUDE_MODEL вместо prof.model → тут будет "sonnet", assert упадёт
assert cmd[i + 1] == "deepseek-v4-flash"
# 30.09.2026: без кусочков ответа сторож первого ответа не отличает думающую модель от
# мёртвой и бросает зайку на большом диалоге. mutation: убрать ключ → assert упадёт.
assert "--include-partial-messages" in cmd
class _LinesStream:
def __init__(self, lines):
self._lines = list(lines)
async def readline(self):
return self._lines.pop(0) if self._lines else b""
def test_stream_event_becomes_alive_not_text(monkeypatch, tmp_path):
"""Кусочек ответа модели (stream_event) — признак жизни для сторожа, а не текст человеку:
готовый текст всё равно придёт целым сообщением assistant, и второй раз его печатать нельзя."""
import json as _json
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(ROOT)
import db
importlib.reload(db)
db.init_db()
import claude_bridge
importlib.reload(claude_bridge)
import agent_provider
monkeypatch.setattr(claude_bridge, "CLAUDE_CONFIG_DIR", str(_src_home(tmp_path)))
settings = tmp_path / "s.json"
settings.write_text("{}")
prof = agent_provider.ProviderProfile(name="glm", settings_path=str(settings),
model="glm-5.3", uses_api_token=True)
lines = [
_json.dumps({"type": "stream_event", "event": {"type": "message_start"}}).encode() + b"\n",
_json.dumps({"type": "stream_event", "event": {
"type": "content_block_delta", "delta": {"type": "text_delta", "text": "кус"}}}).encode() + b"\n",
_json.dumps({"type": "assistant", "message": {"id": "m1", "content": [
{"type": "text", "text": "кусок целиком"}]}}).encode() + b"\n",
]
class _P(_FakeProc):
def __init__(self):
super().__init__()
self.stdout = _LinesStream(lines)
async def fake_exec(*cmd, **kwargs):
return _P()
monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec)
work = tmp_path / "w"
work.mkdir()
async def run():
return [item async for item in claude_bridge._run_profile(
prof, "привет", "u@x", "tab", work, tmp_path / "none.md", tmp_path / "none.md",
False, False)]
items = asyncio.run(run())
kinds = [k for k, _ in items]
assert kinds[:2] == ["alive", "alive"]
texts = [c for k, c in items if k == "text"]
assert len(texts) == 1 and "кусок целиком" in texts[0]
def test_stream_events_still_send_heartbeat(monkeypatch, tmp_path):
"""Пока идут кусочки ответа, тишины нет, и сердцебиение по тишине не шлётся. Без него
веб-сервер рвёт соединение через 300 с без байтов — сердцебиение обязано идти и тут."""
import json as _json
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
monkeypatch.setenv("HOME", str(tmp_path))
monkeypatch.chdir(ROOT)
import db
importlib.reload(db)
db.init_db()
import claude_bridge
importlib.reload(claude_bridge)
import agent_provider
monkeypatch.setattr(claude_bridge, "CLAUDE_CONFIG_DIR", str(_src_home(tmp_path)))
monkeypatch.setattr(claude_bridge, "AGENT_HEARTBEAT", 1e-7) # 0 обрывает чтение по тишине
settings = tmp_path / "s.json"
settings.write_text("{}")
prof = agent_provider.ProviderProfile(name="glm", settings_path=str(settings),
model="glm-5.3", uses_api_token=True)
line = _json.dumps({"type": "stream_event", "event": {"type": "ping"}}).encode() + b"\n"
class _P(_FakeProc):
def __init__(self):
super().__init__()
self.stdout = _LinesStream([line, line])
async def fake_exec(*cmd, **kwargs):
return _P()
monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_exec)
work = tmp_path / "w"
work.mkdir()
async def run():
return [k async for k, _ in claude_bridge._run_profile(
prof, "привет", "u@x", "tab", work, tmp_path / "none.md", tmp_path / "none.md",
False, False)]
kinds = asyncio.run(run())
assert kinds.count("keepalive") >= 1 # mutation: убрать сердцебиение в ветке → 0