feat(контракт): артефакты договора arm-v1 и общий mock (R-02, R-03)
R-02: схемы ответов (17), примеры (12), описание OpenAPI (22 операции), каталог ошибок, перечень проверок и SHA256 набора; проверки держат набор полей живых ответов, типы через JSON-схемы, отсутствие дублей путей и совпадение отпечатка. Отказ 429 при создании проверки теперь несёт retry_seconds полем. R-03: общий mock повторяет правила сервера — две двери, ротация и сроки пропуска, переиспользование живой проверки, аренда строки со сроком, автоматическое завершение, владение проверкой на уровне человека, проверка владельца и состояния в шлюзе, tool_choice, /chat/turn и поток событий. Выложен на https://infosmeta.ru:8444. Проверки: 170 в наборе (173 с соседними), мутации схем, примеров, описания, отпечатка и правил mock краснеют. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,225 @@
|
||||
"""R-02: артефакты договора — схемы, примеры, описание, отпечаток набора.
|
||||
|
||||
Заморозка держится на трёх вещах: набор полей живых ответов совпадает со схемой
|
||||
(иначе поле тихо переименуют), примеры проходят по схемам, и SHA256 набора совпадает
|
||||
с содержимым каталога. Любая правка артефакта без обновления SHA — красный гейт.
|
||||
"""
|
||||
import hashlib
|
||||
import importlib
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
BASE = ROOT / "docs" / "contracts" / "arm-v1"
|
||||
|
||||
|
||||
def _schema(name: str) -> dict:
|
||||
return json.loads((BASE / "schemas" / name).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _example(name: str):
|
||||
return json.loads((BASE / "examples" / name).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
EXAMPLES = {
|
||||
"device_token.json": "device_token.json",
|
||||
"claim_item.json": "claim.json",
|
||||
"claim_wait.json": "claim.json",
|
||||
"claim_done.json": "claim.json",
|
||||
"renew.json": "renew.json",
|
||||
"renew_stopped.json": "renew.json",
|
||||
"estimate.json": "estimate.json",
|
||||
"review_created.json": "review_created.json",
|
||||
"ok.json": "ok.json",
|
||||
"error_review_404.json": "error.json",
|
||||
"error_gateway_429.json": "error.json",
|
||||
}
|
||||
|
||||
|
||||
def test_all_schemas_are_valid():
|
||||
from jsonschema import Draft202012Validator
|
||||
for path in sorted((BASE / "schemas").glob("*.json")):
|
||||
Draft202012Validator.check_schema(json.loads(path.read_text(encoding="utf-8")))
|
||||
|
||||
|
||||
def test_examples_fit_schemas():
|
||||
from jsonschema import Draft202012Validator
|
||||
for example, schema_name in EXAMPLES.items():
|
||||
Draft202012Validator(_schema(schema_name)).validate(_example(example))
|
||||
|
||||
|
||||
def test_openapi_has_no_duplicate_paths():
|
||||
"""Повтор ключа пути YAML молча съедает: остаётся последняя операция."""
|
||||
lines = (BASE / "openapi.yaml").read_text(encoding="utf-8").splitlines()
|
||||
seen, duplicates = set(), []
|
||||
for line in lines:
|
||||
if line.startswith(" /") and line.rstrip().endswith(":"):
|
||||
key = line.rstrip()[:-1]
|
||||
if key in seen:
|
||||
duplicates.append(key)
|
||||
seen.add(key)
|
||||
assert not duplicates, f"путь объявлен дважды: {duplicates}"
|
||||
|
||||
|
||||
def test_openapi_describes_real_routes():
|
||||
doc = yaml.safe_load((BASE / "openapi.yaml").read_text(encoding="utf-8"))
|
||||
import main
|
||||
real = set()
|
||||
for route in main.app.routes:
|
||||
path = getattr(route, "path", "")
|
||||
for method in (getattr(route, "methods", set()) or set()):
|
||||
if method in ("GET", "POST", "PUT", "DELETE", "PATCH"):
|
||||
real.add((path, method.lower()))
|
||||
described = {(path, method) for path, ops in doc["paths"].items() for method in ops}
|
||||
missing = sorted(pair for pair in described if pair not in real)
|
||||
assert not missing, f"описание обещает ручки, которых нет: {missing}"
|
||||
|
||||
|
||||
def test_openapi_schema_refs_exist():
|
||||
doc = yaml.safe_load((BASE / "openapi.yaml").read_text(encoding="utf-8"))
|
||||
refs = set()
|
||||
|
||||
def walk(node):
|
||||
if isinstance(node, dict):
|
||||
for key, value in node.items():
|
||||
if key == "$ref" and isinstance(value, str) and not value.startswith("#"):
|
||||
refs.add(value)
|
||||
else:
|
||||
walk(value)
|
||||
elif isinstance(node, list):
|
||||
for item in node:
|
||||
walk(item)
|
||||
|
||||
walk(doc)
|
||||
assert refs, "в описании нет ссылок на схемы"
|
||||
for ref in sorted(refs):
|
||||
assert (BASE / ref).is_file(), f"ссылка на несуществующую схему: {ref}"
|
||||
|
||||
|
||||
def test_sha256_matches_the_set():
|
||||
expected = (BASE / "SHA256").read_text(encoding="utf-8").strip().splitlines()
|
||||
actual = []
|
||||
for path in sorted(BASE.rglob("*")):
|
||||
if path.is_file() and path.name != "SHA256" and "__pycache__" not in path.parts:
|
||||
digest = hashlib.sha256(path.read_bytes()).hexdigest()
|
||||
actual.append(f"{digest} {path.relative_to(BASE)}")
|
||||
assert expected == actual
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def env(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("DB_PATH", str(tmp_path / "t_test.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, "dev": dev, "db": db}
|
||||
|
||||
|
||||
def _same_keys(payload: dict, schema_name: str, where: str):
|
||||
"""Обязательные поля на месте, лишних нет; необязательные могут отсутствовать."""
|
||||
schema = _schema(schema_name)
|
||||
required, allowed = set(schema.get("required") or []), set(schema["properties"])
|
||||
assert required <= set(payload) <= allowed, (
|
||||
f"{where}: не хватает {sorted(required - set(payload))}, "
|
||||
f"лишние {sorted(set(payload) - allowed)}")
|
||||
|
||||
|
||||
def test_live_shapes_match_schemas(env):
|
||||
c, site, device = env["client"], env["site"], env["device"]
|
||||
|
||||
_same_keys(c.post("/api/device/codes", json={"tab_id": "tab-own"},
|
||||
headers=site).json(), "device_code.json", "код устройства")
|
||||
_same_keys(env["dev"], "device_token.json", "обмен кода")
|
||||
refreshed = c.post("/api/device/refresh", json={
|
||||
"refresh": env["dev"]["refresh"], "app_version": "1.4.0"}).json()
|
||||
_same_keys(refreshed, "device_refresh.json", "продление")
|
||||
device = {"Authorization": "Bearer " + refreshed["access"], "X-App-Version": "1.4.0"}
|
||||
devices = c.get("/api/device/devices", headers=site).json()
|
||||
item_schema = _schema("device_devices.json")["properties"]["items"]["items"]
|
||||
assert set(devices["items"][0]) == set(item_schema["properties"])
|
||||
|
||||
est = c.post("/api/reviews/estimate", json={"items": [{"ord": 1, "text": "x"},
|
||||
{"ord": 2, "text": "y"}]},
|
||||
headers=device).json()
|
||||
_same_keys(est, "estimate.json", "оценка")
|
||||
|
||||
created = c.post("/api/reviews", json={
|
||||
"confirmed": True, "items": [{"ord": 1, "text": "x"}, {"ord": 2, "text": "y"}],
|
||||
"budget_rub": 100}, headers=device).json()
|
||||
_same_keys(created, "review_created.json", "создание")
|
||||
rid = created["id"]
|
||||
|
||||
claim = c.post(f"/api/reviews/{rid}/claim", headers=device).json()
|
||||
assert set(claim) == {"item"}
|
||||
assert set(claim["item"]) == {"ord", "text", "target_path", "target_sheet",
|
||||
"target_row", "lease"}
|
||||
lease = claim["item"]["lease"]
|
||||
renew = c.post(f"/api/reviews/{rid}/renew", json={"ord": 1, "lease": lease},
|
||||
headers=device).json()
|
||||
_same_keys(renew, "renew.json", "продление аренды")
|
||||
ok = c.post(f"/api/reviews/{rid}/item", json={
|
||||
"ord": 1, "lease": lease, "state": "fixed", "verdict": "исправлено",
|
||||
"evidence": {"file": "после/КА.xlsx", "sheet": "Лист1", "row": 44,
|
||||
"before": "a", "after": "b", "rule": "п. 8"}}, headers=device).json()
|
||||
_same_keys(ok, "ok.json", "закрытие строки")
|
||||
claim = c.post(f"/api/reviews/{rid}/claim", headers=device).json()
|
||||
lease = claim["item"]["lease"]
|
||||
c.post(f"/api/reviews/{rid}/item", json={
|
||||
"ord": 2, "lease": lease, "state": "partial", "verdict": "частично",
|
||||
"evidence": {"file": "после/КА.xlsx", "before": "a", "after": "b", "rule": "п. 8"}},
|
||||
headers=device)
|
||||
done = c.post(f"/api/reviews/{rid}/claim", headers=device).json()
|
||||
assert done == {"done": True}
|
||||
_same_keys(c.post(f"/api/reviews/{rid}/finish", headers=device).json(), "ok.json",
|
||||
"завершение")
|
||||
|
||||
detail = c.get(f"/api/reviews/{rid}", headers=site).json()
|
||||
assert set(detail) == {"review", "items"}
|
||||
assert set(detail["review"]) == set(_schema("review.json")["properties"])
|
||||
assert set(detail["items"][0]) == set(_schema("review_item.json")["properties"])
|
||||
|
||||
listing = c.get("/api/reviews", headers=site).json()
|
||||
assert set(listing["items"][0]) == set(_schema("review_list.json")
|
||||
["properties"]["items"]["items"]["properties"])
|
||||
|
||||
_same_keys(c.get("/api/reviews/quota", headers=site).json(), "quota.json", "квота")
|
||||
|
||||
second = c.post("/api/reviews", json={"confirmed": True,
|
||||
"items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=device).json()
|
||||
fail = c.post(f"/api/reviews/{second['id']}/fail", json={"reason": "папка исчезла"},
|
||||
headers=device).json()
|
||||
_same_keys(fail, "ok.json", "сбой программы")
|
||||
third = c.post("/api/reviews", json={"confirmed": True,
|
||||
"items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=device).json()
|
||||
cancelled = c.post(f"/api/reviews/{third['id']}/cancel", headers=site).json()
|
||||
assert cancelled == {"status": "ok"}
|
||||
|
||||
error = c.get("/api/reviews/999999", headers=site).json()
|
||||
from jsonschema import Draft202012Validator
|
||||
Draft202012Validator(_schema("error.json")).validate(error)
|
||||
@@ -0,0 +1,340 @@
|
||||
"""R-03: общий mock договора arm-v1 — формы и правила, как у настоящего сервера.
|
||||
|
||||
Mock повторяет существенное поведение: две двери, ротацию и срок пропуска, переиспользование
|
||||
живой проверки, аренду со сроком, автоматическое завершение, владельца в шлюзе, tool_choice.
|
||||
Формы ответов сверяются со схемами замороженного набора, а не только по именам полей.
|
||||
"""
|
||||
import itertools
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(ROOT))
|
||||
|
||||
BASE = ROOT / "docs" / "contracts" / "arm-v1"
|
||||
sys.path.insert(0, str(BASE / "mock"))
|
||||
|
||||
import server # noqa: E402 — модуль mock лежит в docs/contracts/arm-v1/mock
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client():
|
||||
from fastapi.testclient import TestClient
|
||||
server.STATE.update({"site_tokens": {}, "codes": {}, "devices": {}, "reviews": {},
|
||||
"items": {}, "next_review": itertools.count(1),
|
||||
"next_device": itertools.count(1)})
|
||||
return TestClient(server.APP)
|
||||
|
||||
|
||||
def _schema(name: str) -> dict:
|
||||
return json.loads((BASE / "schemas" / name).read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
def _valid(payload: dict, schema_name: str):
|
||||
from jsonschema import Draft202012Validator
|
||||
Draft202012Validator(_schema(schema_name)).validate(payload)
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def device(client):
|
||||
site = client.post("/api/login", json={"username": "mock@local",
|
||||
"password": "mock-pass"})
|
||||
assert site.status_code == 200, site.text
|
||||
site_headers = {"Authorization": "Bearer " + site.json()["token"]}
|
||||
code = client.post("/api/device/codes", json={"tab_id": "mock-tab-1"},
|
||||
headers=site_headers)
|
||||
assert code.status_code == 200, code.text
|
||||
_valid(code.json(), "device_code.json")
|
||||
token = client.post("/api/device/token", json={
|
||||
"code": code.json()["code"], "device_name": "ПК", "app_version": "0.2.2-rc.3"})
|
||||
assert token.status_code == 200, token.text
|
||||
data = token.json()
|
||||
_valid(data, "device_token.json")
|
||||
headers = {"Authorization": "Bearer " + data["access"], "X-App-Version": "0.2.2-rc.3"}
|
||||
return {"client": client, "site": site_headers, "headers": headers, "token": data}
|
||||
|
||||
|
||||
def test_doors_are_different(device):
|
||||
c = device["client"]
|
||||
# Сайтовый вход на программную ручку — 403 wrong_door, а не 401.
|
||||
r = c.post("/api/reviews/estimate", json={"items": []}, headers=device["site"])
|
||||
assert r.status_code == 403 and r.json()["code"] == "wrong_door"
|
||||
# Программный пропуск на сайтовую ручку — тоже 403.
|
||||
r = c.get("/api/reviews/quota", headers=device["headers"])
|
||||
assert r.status_code == 403 and r.json()["code"] == "wrong_door"
|
||||
# Без входа — 401.
|
||||
r = c.get("/api/reviews/quota")
|
||||
assert r.status_code == 401 and r.json()["code"] == "auth_required"
|
||||
|
||||
|
||||
def test_pass_rotates_and_expires(device):
|
||||
c = device["client"]
|
||||
old = device["headers"]
|
||||
refreshed = c.post("/api/device/refresh", json={"refresh": device["token"]["refresh"],
|
||||
"app_version": "0.2.2-rc.3"})
|
||||
assert refreshed.status_code == 200
|
||||
_valid(refreshed.json(), "device_refresh.json")
|
||||
# Старый пропуск после продления не действует.
|
||||
r = c.post("/api/reviews/estimate", json={"items": []}, headers=old)
|
||||
assert r.status_code == 401 and r.json()["code"] == "token_invalid"
|
||||
# Старая версия — 426.
|
||||
r = c.post("/api/reviews/estimate", json={"items": []},
|
||||
headers={"Authorization": "Bearer " + refreshed.json()["access"],
|
||||
"X-App-Version": "0.0.1"})
|
||||
assert r.status_code == 426 and r.json()["code"] == "app_too_old"
|
||||
|
||||
|
||||
def test_scenario_matches_contract(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
devices = c.get("/api/device/devices", headers=device["site"])
|
||||
assert devices.status_code == 200
|
||||
item_schema = _schema("device_devices.json")["properties"]["items"]["items"]
|
||||
assert set(devices.json()["items"][0]) == set(item_schema["properties"])
|
||||
|
||||
est = c.post("/api/reviews/estimate", json={"items": [{"ord": 1, "text": "x"}]},
|
||||
headers=h)
|
||||
assert est.status_code == 200
|
||||
_valid(est.json(), "estimate.json")
|
||||
created = c.post("/api/reviews", json={"confirmed": True,
|
||||
"items": [{"ord": 1, "text": "x"},
|
||||
{"ord": 2, "text": "y"}],
|
||||
"budget_rub": 10}, headers=h)
|
||||
assert created.status_code == 200
|
||||
_valid(created.json(), "review_created.json")
|
||||
rid = created.json()["id"]
|
||||
# Живая проверка переиспользуется: второй вызов даёт created=false.
|
||||
again = c.post("/api/reviews", json={"confirmed": True,
|
||||
"items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=h).json()
|
||||
assert again == {"id": rid, "created": False, "tab_id": created.json()["tab_id"]}
|
||||
|
||||
claim = c.post(f"/api/reviews/{rid}/claim", headers=h)
|
||||
assert claim.status_code == 200
|
||||
_valid(claim.json(), "claim.json")
|
||||
lease = claim.json()["item"]["lease"]
|
||||
renew = c.post(f"/api/reviews/{rid}/renew", json={"ord": 1, "lease": lease}, headers=h)
|
||||
_valid(renew.json(), "renew.json")
|
||||
assert renew.json()["ok"] is True
|
||||
# Чужой пропуск строки отвергается.
|
||||
bad = c.post(f"/api/reviews/{rid}/item", json={"ord": 1, "lease": "чужой",
|
||||
"state": "fixed", "verdict": "x",
|
||||
"evidence": {}}, headers=h)
|
||||
assert bad.status_code == 409 and bad.json()["code"] == "conflict"
|
||||
ok = c.post(f"/api/reviews/{rid}/item", json={
|
||||
"ord": 1, "lease": lease, "state": "fixed", "verdict": "ок",
|
||||
"evidence": {"file": "после/КА.xlsx", "before": "a", "after": "b", "rule": "п. 8"}},
|
||||
headers=h)
|
||||
assert ok.status_code == 200
|
||||
_valid(ok.json(), "ok.json")
|
||||
second = c.post(f"/api/reviews/{rid}/claim", headers=h).json()
|
||||
assert set(second) == {"item"}
|
||||
c.post(f"/api/reviews/{rid}/item", json={
|
||||
"ord": 2, "lease": second["item"]["lease"], "state": "partial", "verdict": "ч",
|
||||
"evidence": {"file": "после/КА.xlsx", "before": "a", "after": "b", "rule": "п. 8"}},
|
||||
headers=h)
|
||||
# Последняя строка закрывает проверку сама.
|
||||
assert c.post(f"/api/reviews/{rid}/claim", headers=h).json() == {"done": True}
|
||||
assert c.post(f"/api/reviews/{rid}/finish", headers=h).json() == {"ok": True}
|
||||
|
||||
detail = c.get(f"/api/reviews/{rid}", headers=device["site"]).json()
|
||||
assert set(detail) == {"review", "items"}
|
||||
_valid(detail["review"], "review.json") # ссылки между файлами разворачиваем тут
|
||||
for item in detail["items"]:
|
||||
_valid(item, "review_item.json")
|
||||
listing = c.get("/api/reviews", headers=device["site"]).json()
|
||||
_valid(listing, "review_list.json")
|
||||
_valid(c.get("/api/reviews/quota", headers=device["site"]).json(), "quota.json")
|
||||
|
||||
|
||||
def test_cancel_and_resume_rules(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
rid = c.post("/api/reviews", json={"confirmed": True,
|
||||
"items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=h).json()["id"]
|
||||
r = c.post(f"/api/reviews/{rid}/cancel", headers=device["site"])
|
||||
assert r.status_code == 200 and r.json() == {"status": "ok"}
|
||||
# Продолжить можно только после остановки по потолку, а не после отмены человеком.
|
||||
r = c.post(f"/api/reviews/{rid}/resume", json={"budget_rub": 20}, headers=device["site"])
|
||||
assert r.status_code == 409
|
||||
|
||||
|
||||
def test_gateway_checks_owner_and_tools(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
rid = c.post("/api/reviews", json={"confirmed": True,
|
||||
"items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=h).json()["id"]
|
||||
text = c.post("/api/gateway/v1/chat/completions",
|
||||
json={"model": "smeta", "messages": [{"role": "user", "content": "привет"}]},
|
||||
headers=dict(h, **{"X-Tab-Id": "mock-tab-1"}))
|
||||
assert text.status_code == 200 and "Заглушка mock" in text.text
|
||||
assert "[DONE]" in text.text
|
||||
|
||||
# Чужой диалог и несуществующая проверка — 404, а не «нашлось».
|
||||
foreign = c.post("/api/gateway/v1/chat/completions",
|
||||
json={"model": "smeta", "messages": [{"role": "user", "content": "x"}]},
|
||||
headers=dict(h, **{"X-Tab-Id": "foreign-tab"}))
|
||||
assert foreign.status_code == 404
|
||||
missing = c.post("/api/gateway/v1/chat/completions",
|
||||
json={"model": "smeta", "messages": [{"role": "user", "content": "x"}]},
|
||||
headers=dict(h, **{"X-Review-Id": "9999"}))
|
||||
assert missing.status_code == 404
|
||||
|
||||
tools = c.post("/api/gateway/v1/chat/completions",
|
||||
json={"model": "smeta", "messages": [{"role": "user", "content": "x"}],
|
||||
"tools": [{"type": "function", "function": {
|
||||
"name": "find_base_price", "description": "d",
|
||||
"parameters": {"type": "object"}}}]},
|
||||
headers=dict(h, **{"X-Review-Id": str(rid)}))
|
||||
chunks = [json.loads(line[5:]) for line in tools.text.splitlines()
|
||||
if line.startswith("data:") and line[5:].strip() != "[DONE]"]
|
||||
calls = [ch["choices"][0]["delta"]["tool_calls"] for ch in chunks
|
||||
if (ch["choices"][0].get("delta") or {}).get("tool_calls")]
|
||||
assert calls[0][0]["function"]["name"] == "find_base_price"
|
||||
assert any(ch["choices"][0].get("finish_reason") == "tool_calls" for ch in chunks)
|
||||
|
||||
# tool_choice=none запрещает вызов — приходит обычный текст.
|
||||
none = c.post("/api/gateway/v1/chat/completions",
|
||||
json={"model": "smeta", "messages": [{"role": "user", "content": "x"}],
|
||||
"tools": [{"type": "function", "function": {
|
||||
"name": "find_base_price", "description": "d",
|
||||
"parameters": {"type": "object"}}}],
|
||||
"tool_choice": "none"},
|
||||
headers=dict(h, **{"X-Tab-Id": "mock-tab-1"}))
|
||||
assert "tool_calls" not in none.text and "Заглушка mock" in none.text
|
||||
|
||||
|
||||
def test_fail_on_missing_review_is_404(device):
|
||||
r = device["client"].post("/api/reviews/999/fail", json={"reason": "папка исчезла"},
|
||||
headers=device["headers"])
|
||||
assert r.status_code == 404 and r.json()["code"] == "not_found"
|
||||
|
||||
|
||||
def test_version_compare_is_numeric(device):
|
||||
# 0.10.0 новее 0.2.2 — строковое сравнение ошиблось бы.
|
||||
c = device["client"]
|
||||
r = c.post("/api/device/refresh", json={"refresh": device["token"]["refresh"],
|
||||
"app_version": "0.10.0"})
|
||||
assert r.status_code == 200
|
||||
|
||||
|
||||
def test_chat_turn_and_foreign_tab(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
ok = c.post("/api/chat/turn", json={"tab_id": "mock-tab-1", "question": "в",
|
||||
"answer": "о"}, headers=h)
|
||||
assert ok.status_code == 200 and ok.json() == {"ok": True}
|
||||
foreign = c.post("/api/chat/turn", json={"tab_id": "foreign-tab", "question": "в",
|
||||
"answer": "о"}, headers=h)
|
||||
assert foreign.status_code == 404
|
||||
|
||||
|
||||
def test_stream_snapshot_and_end(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
rid = c.post("/api/reviews", json={"confirmed": True,
|
||||
"items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=h).json()["id"]
|
||||
claim = c.post(f"/api/reviews/{rid}/claim", headers=h).json()
|
||||
c.post(f"/api/reviews/{rid}/item", json={
|
||||
"ord": 1, "lease": claim["item"]["lease"], "state": "fixed", "verdict": "ок",
|
||||
"evidence": {"file": "a.xlsx", "before": "a", "after": "b", "rule": "п. 8"}},
|
||||
headers=h)
|
||||
stream = c.get(f"/api/reviews/{rid}/stream", headers=device["site"])
|
||||
assert stream.status_code == 200
|
||||
assert "event: snapshot" in stream.text
|
||||
assert "event: done" in stream.text
|
||||
|
||||
|
||||
def test_item_on_missing_objects_is_404(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
r = c.post("/api/reviews/999/item", json={"ord": 1, "lease": "x", "state": "fixed",
|
||||
"verdict": "v", "evidence": {}}, headers=h)
|
||||
assert r.status_code == 404 and r.json()["code"] == "not_found"
|
||||
rid = c.post("/api/reviews", json={"confirmed": True, "items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=h).json()["id"]
|
||||
r = c.post(f"/api/reviews/{rid}/item", json={"ord": 77, "lease": "x", "state": "fixed",
|
||||
"verdict": "v", "evidence": {}}, headers=h)
|
||||
assert r.status_code == 404
|
||||
|
||||
|
||||
def test_garbage_input_is_client_error(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
r = c.post("/api/reviews", json={"confirmed": True, "items": "строка",
|
||||
"budget_rub": 10}, headers=h)
|
||||
assert r.status_code == 400
|
||||
r = c.post("/api/reviews", json={"confirmed": True, "items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": "десять"}, headers=h)
|
||||
assert r.status_code == 400
|
||||
tools = c.post("/api/gateway/v1/chat/completions",
|
||||
json={"model": "smeta", "messages": [{"role": "user", "content": "x"}],
|
||||
"tools": [None, "строка", 1]},
|
||||
headers=dict(h, **{"X-Tab-Id": "mock-tab-1"}))
|
||||
assert tools.status_code == 200 and "Заглушка mock" in tools.text
|
||||
|
||||
|
||||
def _new_device(client, site_headers, name, tab_id="mock-tab-1"):
|
||||
code = client.post("/api/device/codes", json={"tab_id": tab_id},
|
||||
headers=site_headers).json()["code"]
|
||||
data = client.post("/api/device/token", json={
|
||||
"code": code, "device_name": name, "app_version": "0.2.2-rc.3"}).json()
|
||||
return {"Authorization": "Bearer " + data["access"], "X-App-Version": "0.2.2-rc.3"}
|
||||
|
||||
|
||||
def test_expired_lease_is_refused(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
rid = c.post("/api/reviews", json={"confirmed": True, "items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=h).json()["id"]
|
||||
claim = c.post(f"/api/reviews/{rid}/claim", headers=h).json()["item"]
|
||||
server.STATE["items"][rid][0]["lease_until"] = 0 # аренда истекла
|
||||
r = c.post(f"/api/reviews/{rid}/item", json={
|
||||
"ord": 1, "lease": claim["lease"], "state": "fixed", "verdict": "x",
|
||||
"evidence": {"file": "a.xlsx", "before": "a", "after": "b", "rule": "п. 8"}}, headers=h)
|
||||
assert r.status_code == 409
|
||||
|
||||
|
||||
def test_second_device_of_same_user_can_take_review(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
other = _new_device(c, device["site"], "Второй ПК", tab_id="mock-tab-2")
|
||||
rid = c.post("/api/reviews", json={"confirmed": True, "items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=h).json()["id"]
|
||||
# Живая проверка одна на человека: второе устройство получает ту же.
|
||||
again = c.post("/api/reviews", json={"confirmed": True, "items": [{"ord": 1, "text": "x"}],
|
||||
"budget_rub": 10}, headers=other).json()
|
||||
assert again["id"] == rid and again["created"] is False
|
||||
claim = c.post(f"/api/reviews/{rid}/claim", headers=other)
|
||||
assert claim.status_code == 200 and "item" in claim.json()
|
||||
|
||||
|
||||
def test_counters_reflect_items(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
rid = c.post("/api/reviews", json={"confirmed": True,
|
||||
"items": [{"ord": 1, "text": "a"},
|
||||
{"ord": 2, "text": "b"}],
|
||||
"budget_rub": 10}, headers=h).json()["id"]
|
||||
first = c.post(f"/api/reviews/{rid}/claim", headers=h).json()["item"]
|
||||
c.post(f"/api/reviews/{rid}/item", json={
|
||||
"ord": first["ord"], "lease": first["lease"], "state": "partial", "verdict": "ч",
|
||||
"evidence": {"file": "a.xlsx", "before": "a", "after": "b", "rule": "п. 8"}}, headers=h)
|
||||
detail = c.get(f"/api/reviews/{rid}", headers=device["site"]).json()["review"]
|
||||
assert detail["n_partial"] == 1 and detail["n_fixed"] == 0 and detail["total"] == 2
|
||||
|
||||
|
||||
def test_non_function_tools_are_ignored(device):
|
||||
c, h = device["client"], device["headers"]
|
||||
r = c.post("/api/gateway/v1/chat/completions",
|
||||
json={"model": "smeta", "messages": [{"role": "user", "content": "x"}],
|
||||
"tools": [{"type": "other", "name": "что-то"}]},
|
||||
headers=dict(h, **{"X-Tab-Id": "mock-tab-1"}))
|
||||
assert "tool_calls" not in r.text and "Заглушка mock" in r.text
|
||||
|
||||
|
||||
def test_expired_refresh_is_refused(device):
|
||||
c = device["client"]
|
||||
token = device["token"]["refresh"]
|
||||
for entry in server.STATE["devices"].values():
|
||||
if entry["refresh"] == token:
|
||||
entry["refresh_expires"] = 0
|
||||
r = c.post("/api/device/refresh", json={"refresh": token, "app_version": "0.2.2-rc.3"})
|
||||
assert r.status_code == 401 and r.json()["code"] == "token_invalid"
|
||||
Reference in New Issue
Block a user