Отзыв устройства отвечает ok:false, если отзывать нечего; fail не переписывает уже закрытую проверку; событие потока для abandoned не выдаётся за done. Проверки mock: 19, отпечаток набора и перечень обновлены. Co-Authored-By: Claude Code <noreply@anthropic.com>
373 lines
20 KiB
Python
373 lines
20 KiB
Python
"""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"
|
||
|
||
|
||
def test_tool_choice_for_absent_function_makes_no_call(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": "function", "function": {
|
||
"name": "other_fn", "parameters": {"type": "object"}}}],
|
||
"tool_choice": {"type": "function",
|
||
"function": {"name": "find_base_price"}}},
|
||
headers=dict(h, **{"X-Tab-Id": "mock-tab-1"}))
|
||
assert "tool_calls" not in r.text and "Заглушка mock" in r.text
|
||
|
||
|
||
def test_revoke_reports_whether_device_found(device):
|
||
c = device["client"]
|
||
missing = c.post("/api/device/revoke", json={"id": 999}, headers=device["site"])
|
||
assert missing.status_code == 200 and missing.json() == {"ok": False}
|
||
real = c.post("/api/device/revoke", json={"id": device["token"]["device_id"]},
|
||
headers=device["site"])
|
||
assert real.json() == {"ok": True}
|
||
|
||
|
||
def test_fail_does_not_rewrite_closed_review(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"]
|
||
c.post(f"/api/reviews/{rid}/cancel", headers=device["site"])
|
||
r = c.post(f"/api/reviews/{rid}/fail", json={"reason": "поздно"}, headers=h)
|
||
assert r.status_code == 200 and r.json() == {"ok": True}
|
||
detail = c.get(f"/api/reviews/{rid}", headers=device["site"]).json()["review"]
|
||
assert detail["status"] == "stopped" and detail["error"] is None
|