R-01: X-Request-Id на каждом ответе (включая 500), code и request_id в теле отказа, старые поля detail/error/message сохранены; коды: wrong_door, token_invalid, app_too_old, quota_exceeded, budget_exceeded, provider_failed/timeout, internal. Ручка квоты больше не перехватывается динамической (переставлена); нечисло в пути снова даёт 422. R-06: шлюз проводит tools/tool_calls в обе стороны (OpenAI-вид у клиента, Anthropic у провайдера): перевод сообщений, tool-результатов, ролей, tool_choice; индекс вызова считается по вызовам, finish_reason max_tokens -> length; промах кэша входит во вход, попадание — в cache_tokens. Проверки: 130 зелёных в наборе проверки; мутации (заголовок, код, 422-обработчик, индекс вызова, finish_reason, tool_choice, кэш-токены, роли) краснеют. Co-Authored-By: Claude Code <noreply@anthropic.com>
190 lines
8.5 KiB
Python
190 lines
8.5 KiB
Python
"""R-01: номер запроса на каждом ответе и машинный код в теле ошибки.
|
|
|
|
Договор с программой: клиент различает отказы по полю `code`, а разбор сбоя ведёт по
|
|
одному номеру `X-Request-Id` на обеих сторонах. Старые поля (`detail`, `error`, `message`)
|
|
остаются — сайт и админка их читают.
|
|
"""
|
|
import importlib
|
|
import os
|
|
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)
|
|
|
|
|
|
@pytest.fixture()
|
|
def env(tmp_path, monkeypatch):
|
|
monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db"))
|
|
monkeypatch.setenv("SESSION_SECRET", "test-secret")
|
|
monkeypatch.setenv("AI_BACKEND", "claude")
|
|
monkeypatch.setenv("DEVICE_MIN_VERSION", "1.0.0")
|
|
monkeypatch.setenv("REVIEWS_ENABLED", "on")
|
|
monkeypatch.chdir(ROOT)
|
|
import auth, db, device_auth, gateway, main
|
|
for m in (db, auth, device_auth, gateway, main):
|
|
importlib.reload(m)
|
|
db.init_db()
|
|
db.create_user("u@x", auth.hash_password("Passw0rd!ok"))
|
|
db.admin_verify_user("u@x")
|
|
db.save_message("u@x", "tab-own", "user", "привет")
|
|
from fastapi.testclient import TestClient
|
|
client = TestClient(main.app)
|
|
site = {"Authorization": "Bearer " + auth._make_token("u@x", "user")}
|
|
code = client.post("/api/device/codes", json={"tab_id": "tab-own"}, headers=site).json()
|
|
dev = client.post("/api/device/token", json={
|
|
"code": code["code"], "device_name": "ПК", "app_version": "1.4.0"}).json()
|
|
device = {"Authorization": "Bearer " + dev["access"], "X-App-Version": "1.4.0"}
|
|
return {"client": client, "site": site, "device": device, "db": db, "gateway": gateway}
|
|
|
|
|
|
def _body(r):
|
|
try:
|
|
return r.json()
|
|
except Exception: # noqa: BLE001
|
|
return {}
|
|
|
|
|
|
def test_every_response_has_request_id(env):
|
|
ok = env["client"].get("/health")
|
|
bad = env["client"].get("/api/reviews/999999", headers=env["site"])
|
|
assert ok.headers.get("X-Request-Id")
|
|
assert bad.headers.get("X-Request-Id")
|
|
|
|
|
|
def test_client_request_id_is_echoed_when_sane(env):
|
|
r = env["client"].get("/health", headers={"X-Request-Id": "arm-2026-11-18-0001"})
|
|
assert r.headers.get("X-Request-Id") == "arm-2026-11-18-0001"
|
|
|
|
|
|
def test_broken_request_id_is_replaced(env):
|
|
r = env["client"].get("/health", headers={"X-Request-Id": "bad id with spaces"})
|
|
assert r.headers.get("X-Request-Id") not in (None, "bad id with spaces")
|
|
|
|
|
|
def test_not_found_carries_code_and_request_id(env):
|
|
r = env["client"].get("/api/reviews/999999", headers=env["site"])
|
|
assert r.status_code == 404
|
|
body = _body(r)
|
|
assert body["code"] == "not_found"
|
|
assert body["request_id"] == r.headers["X-Request-Id"]
|
|
assert body["detail"] == "Проверка не найдена" # прежний текст не подменён
|
|
|
|
|
|
def test_wrong_door_403_has_code(env):
|
|
# Ручка создания — только программе; вход сайта должен получить «не та дверь».
|
|
r = env["client"].post("/api/reviews", json={"confirmed": True, "items": [],
|
|
"budget_rub": 1}, headers=env["site"])
|
|
assert r.status_code == 403
|
|
assert _body(r)["code"] == "wrong_door"
|
|
|
|
|
|
def test_expired_pass_401_has_code(env):
|
|
r = env["client"].post("/api/reviews/estimate", json={"items": []},
|
|
headers={"Authorization": "Bearer invalid-token", "X-App-Version": "1.4.0"})
|
|
assert r.status_code == 401
|
|
assert _body(r)["code"] == "token_invalid"
|
|
|
|
|
|
def test_old_version_426_has_code(env):
|
|
r = env["client"].post("/api/reviews/estimate", json={"items": []},
|
|
headers=dict(env["device"], **{"X-App-Version": "0.1.0"}))
|
|
assert r.status_code == 426
|
|
assert _body(r)["code"] == "app_too_old"
|
|
|
|
|
|
def _create_review(env, budget=100.0):
|
|
return env["client"].post("/api/reviews", json={
|
|
"confirmed": True, "items": [{"ord": 1, "text": "x"}], "budget_rub": budget},
|
|
headers=env["device"]).json()["id"]
|
|
|
|
|
|
def test_gateway_quota_429_has_code(env, monkeypatch):
|
|
"""Суточный предел: 429 с кодом quota_exceeded, поля error/message сохранены."""
|
|
import quotas
|
|
monkeypatch.setattr(quotas, "limits_snapshot", lambda user: {
|
|
"unlimited": False, "rub": {"left": 0.0}, "requests": {"left": 10},
|
|
"tokens": {"left": 10}, "next_release": {"at": 0}})
|
|
rid = _create_review(env)
|
|
r = env["client"].post("/api/gateway/v1/chat/completions",
|
|
json={"model": "x", "messages": [{"role": "user", "content": "x"}]},
|
|
headers=dict(env["device"], **{"X-Review-Id": str(rid)}))
|
|
assert r.status_code == 429, r.text
|
|
body = _body(r)
|
|
assert body["code"] == "quota_exceeded" and body["error"] == "limit"
|
|
assert body["message"] and body["request_id"] == r.headers["X-Request-Id"]
|
|
|
|
|
|
def test_gateway_budget_402_keeps_old_fields_and_adds_code(env):
|
|
# Потолок проверки = 0.5 ₽ при брони 1 ₽ даёт отказ 402 до вызова провайдера.
|
|
rid = _create_review(env, budget=0.5)
|
|
r = env["client"].post("/api/gateway/v1/chat/completions",
|
|
json={"model": "x", "messages": [{"role": "user", "content": "x"}]},
|
|
headers=dict(env["device"], **{"X-Review-Id": str(rid)}))
|
|
assert r.status_code == 402
|
|
body = _body(r)
|
|
assert body["error"] == "budget" and body["message"]
|
|
assert body["code"] == "budget_exceeded"
|
|
assert body["request_id"] == r.headers["X-Request-Id"]
|
|
assert body["message"] == "Потолок проверки исчерпан — проверка остановлена."
|
|
|
|
|
|
def test_gateway_missing_provider_503_has_code(env, monkeypatch):
|
|
import agent_provider
|
|
monkeypatch.setattr(agent_provider, "provider_chain", lambda user: [])
|
|
rid = env["client"].post("/api/reviews", json={
|
|
"confirmed": True, "items": [{"ord": 1, "text": "x"}], "budget_rub": 100},
|
|
headers=env["device"]).json()["id"]
|
|
r = env["client"].post("/api/gateway/v1/chat/completions",
|
|
json={"model": "x", "messages": [{"role": "user", "content": "x"}]},
|
|
headers=dict(env["device"], **{"X-Review-Id": str(rid)}))
|
|
assert r.status_code == 503
|
|
body = _body(r)
|
|
assert body["code"] == "provider_failed" and body["error"] == "provider"
|
|
|
|
|
|
def test_validation_error_422_has_code(env):
|
|
# job_id объявлен целым без конвертера: нечисло даёт настоящую ошибку проверки FastAPI.
|
|
r = env["client"].get("/api/jobs/abc/stream")
|
|
assert r.status_code == 422, r.text
|
|
body = _body(r)
|
|
assert body["code"] == "validation_failed"
|
|
assert body["request_id"] == r.headers["X-Request-Id"]
|
|
assert isinstance(body["detail"], list)
|
|
|
|
|
|
def test_unhandled_exception_gets_id_and_code(env):
|
|
"""Необработанный сбой: 500 с номером и кодом, а не голая страница без заголовка."""
|
|
async def boom():
|
|
raise RuntimeError("boom")
|
|
env["client"].app.add_api_route("/__arm_boom", boom)
|
|
r = env["client"].get("/__arm_boom")
|
|
assert r.status_code == 500
|
|
body = _body(r)
|
|
assert body["code"] == "internal"
|
|
assert body["request_id"] == r.headers["X-Request-Id"]
|
|
|
|
|
|
def test_chat_conflict_has_code(env):
|
|
"""Прямой ответ ручки (409 чата) тоже обязан нести код и номер."""
|
|
env["db"].save_message("u@x", "tab-other", "user", "чужой диалог")
|
|
con = env["db"]._conn()
|
|
con.execute("UPDATE messages SET username='v@x' WHERE tab_id='tab-other'")
|
|
con.commit(); con.close()
|
|
r = env["client"].post("/api/chat", json={"message": "привет", "tab_id": "tab-other"},
|
|
headers=env["site"])
|
|
assert r.status_code == 409, r.text
|
|
body = _body(r)
|
|
assert body["code"] == "conflict"
|
|
assert body["request_id"] == r.headers["X-Request-Id"]
|
|
assert body["error"] # прежнее поле осталось
|
|
|
|
|
|
def test_invalid_review_id_is_validation_error(env):
|
|
"""Нечисло в пути остаётся ошибкой проверки 422, а не превращается в 404."""
|
|
r = env["client"].get("/api/reviews/abc", headers=env["site"])
|
|
assert r.status_code == 422, r.text
|
|
assert _body(r)["code"] == "validation_failed"
|