#!/usr/bin/env python3 """R-04: контрактный прогон договора arm-v1 на живой среде (или mock). Проходит сценарий программы целиком: вход сайта → код устройства → пропуск → обе двери → оценка → создание проверки → аренда → продление → закрытие строки → завершение → список, карточка и поток на сайте → шлюз (текст и вызов инструмента) → пара «вопрос — ответ» → сбой программы → инструменты нормативов по HTTP → продление пропуска → отказы (401/426). С `--expect-sha` сверяет отпечаток набора артефактов. Пишет отчёт строками и возвращает 0 только если ВСЁ сошлось. Запуск: python3 scripts/arm_contract_run.py --base https://infosmeta.ru:8443 \\ --user arm-test@infosmeta.ru --password ... --app-version 0.2.2-rc.3 """ from __future__ import annotations import argparse import json import sys import urllib.error import urllib.request from pathlib import Path ROOT = Path(__file__).resolve().parent.parent CONTRACT_DIR = ROOT / "docs" / "contracts" / "arm-v1" sys.path.insert(0, str(ROOT / "scripts")) import arm_contract_digest # noqa: E402 — одно правило отпечатка на обе стороны def call(base: str, method: str, path: str, body: dict | None = None, headers: dict | None = None, timeout: float = 60.0): data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(base + path, data=data, method=method, headers={"Content-Type": "application/json", **(headers or {})}) try: with urllib.request.urlopen(req, timeout=timeout) as resp: return resp.status, resp.read().decode("utf-8", "replace"), dict(resp.headers) except urllib.error.HTTPError as err: return err.code, err.read().decode("utf-8", "replace"), dict(err.headers) except (urllib.error.URLError, TimeoutError, OSError) as err: # Среда недоступна — это шаг прогона, а не падение скрипта с трейсбеком. return 0, f"нет связи: {err}", {} def as_json(text: str) -> dict: """Тело ответа как словарь: не-JSON (страница ошибки прокси) не должен ронять прогон.""" try: value = json.loads(text) except ValueError: return {} return value if isinstance(value, dict) else {} def contract_sha() -> str: """Полный отпечаток набора; правило — scripts/arm_contract_digest.py.""" return arm_contract_digest.digest(CONTRACT_DIR) def parse_sse(text: str) -> tuple[list[dict], bool, bool]: """Разбор потока: события, признак [DONE] и признак ошибки провайдера.""" events: list[dict] = [] done = error = False for line in text.splitlines(): if not line.startswith("data:"): continue payload = line[5:].strip() if payload == "[DONE]": done = True continue try: event = json.loads(payload) except ValueError: continue if not isinstance(event, dict): continue if "error" in event: error = True events.append(event) return events, done, error def has_keys(payload: dict, keys: set[str]) -> bool: return isinstance(payload, dict) and keys <= set(payload) TOKEN_KEYS = {"access", "refresh", "expires_in", "tab_id", "min_version", "device_id"} REFRESH_KEYS = {"access", "refresh", "expires_in", "tab_id", "min_version"} ESTIMATE_KEYS = {"est_rub", "provisional", "suggested_budget_rub", "rub_left"} ITEM_KEYS = {"ord", "text", "target_path", "target_sheet", "target_row", "lease"} LIST_KEYS = {"id", "title", "status", "stop_reason", "created_at", "finished_at", "total", "n_fixed", "n_partial", "n_not_fixed", "n_unknown", "est_rub", "budget_rub", "price_rub", "notify_state"} def scenario(base: str, user: str, password: str, app_version: str, tab_id: str = "", tool_choice: str = "required") -> list[tuple[str, bool, str]]: checks: list[tuple[str, bool, str]] = [] def step(name: str, ok: bool, note: str = "") -> None: checks.append((name, ok, note)) status, body, _ = call(base, "GET", "/health") step("среда отвечает", status == 200, f"код {status}") step("версия среды получена", bool(as_json(body).get("version")), as_json(body).get("version", "")) status, body, _ = call(base, "POST", "/api/login", {"username": user, "password": password}) site_token = as_json(body).get("token", "") if status == 200 else "" step("вход сайта", status == 200 and bool(site_token), f"код {status}") site = {"Authorization": "Bearer " + site_token} status, body, _ = call(base, "POST", "/api/reviews/estimate", {"items": []}, site) step("не та дверь: сайт в программной ручке", status == 403 and as_json(body).get("code") == "wrong_door", f"код {status}") status, body, _ = call(base, "POST", "/api/device/codes", {"tab_id": tab_id}, site) code = as_json(body).get("code", "") if status == 200 else "" step("код устройства", status == 200 and bool(code), f"код {status}") status, body, _ = call(base, "POST", "/api/device/token", {"code": code, "device_name": "arm-contract", "app_version": app_version}) token = as_json(body) if status == 200 else {} access = token.get("access", "") tab_id = token.get("tab_id") or tab_id step("обмен кода на пропуск", status == 200 and has_keys(token, TOKEN_KEYS), f"код {status}, tab_id={tab_id or '—'}") device = {"Authorization": "Bearer " + access, "X-App-Version": app_version} status, body, _ = call(base, "GET", "/api/reviews/quota", None, device) step("не та дверь: программа на сайтовой ручке", status == 403 and as_json(body).get("code") == "wrong_door", f"код {status}") status, body, _ = call(base, "POST", "/api/reviews/estimate", {"items": [{"ord": 1, "text": "проверка контракта"}]}, device) estimate = as_json(body) if status == 200 else {} step("оценка расхода", status == 200 and has_keys(estimate, ESTIMATE_KEYS), f"код {status}") status, body, _ = call(base, "POST", "/api/reviews", {"confirmed": True, "items": [{"ord": 1, "text": "проверка контракта"}], "budget_rub": 100}, device) created = as_json(body) if status == 200 else {} review_id = created.get("id") step("создание проверки", status == 200 and bool(review_id) and created.get("created") is True and "tab_id" in created, f"код {status}, id={review_id}") if not review_id: return checks # без проверки остальные шаги бессмысленны status, body, _ = call(base, "POST", f"/api/reviews/{review_id}/claim", None, device) claim = as_json(body) if status == 200 else {} item = claim.get("item") or {} step("выдача строки", status == 200 and has_keys(item, ITEM_KEYS), f"код {status}, ord={item.get('ord')}") status, body, _ = call(base, "POST", f"/api/reviews/{review_id}/renew", {"ord": item.get("ord"), "lease": item.get("lease")}, device) renew = as_json(body) if status == 200 else {} step("продление аренды", status == 200 and renew.get("ok") is True and "status" in renew, f"код {status}") status, body, _ = call(base, "POST", f"/api/reviews/{review_id}/item", {"ord": item.get("ord"), "lease": item.get("lease"), "state": "fixed", "verdict": "контрактный прогон", "evidence": {"file": "после/КА.xlsx", "sheet": "Лист1", "row": 44, "before": "a", "after": "b", "rule": "п. 8"}}, device) step("закрытие строки", status == 200 and as_json(body).get("ok") is True, f"код {status}") status, body, _ = call(base, "POST", f"/api/reviews/{review_id}/claim", None, device) step("очередь кончилась", status == 200 and as_json(body) == {"done": True}, f"код {status}") status, body, _ = call(base, "POST", f"/api/reviews/{review_id}/finish", None, device) step("завершение проверки", status == 200 and as_json(body).get("ok") is True, f"код {status}") status, body, _ = call(base, "GET", "/api/reviews", None, site) listing = as_json(body) if status == 200 else {} items = listing.get("items") or [] step("список проверок на сайте", status == 200 and bool(items) and has_keys(items[0], LIST_KEYS), f"код {status}") status, body, _ = call(base, "GET", f"/api/reviews/{review_id}", None, site) detail = as_json(body) if status == 200 else {} step("карточка проверки на сайте", status == 200 and set(detail) == {"review", "items"} and detail["review"].get("status") == "done", f"код {status}") status, body, _ = call(base, "POST", f"/api/reviews/{review_id}/resume", {"budget_rub": 100}, site) step("продолжение — только после остановки по потолку", status == 409, f"код {status}") # Завершённая проверка закрывает поток сразу; срок нужен, чтобы несделанная проверка # не подвесила прогон на полминуты молчания. status, body, _ = call(base, "GET", f"/api/reviews/{review_id}/stream", None, site, timeout=10.0) step("поток проверки начинается снимком", status == 200 and "event: snapshot" in body, f"код {status}") status, body, _ = call(base, "POST", "/api/gateway/v1/chat/completions", {"model": "smeta", "messages": [{"role": "user", "content": "прогон контракта"}]}, dict(device, **{"X-Tab-Id": tab_id})) events, done, error = parse_sse(body) content = "".join( (chunk.get("delta") or {}).get("content") or "" for event in events for chunk in (event.get("choices") or [])) step("шлюз: текст", status == 200 and done and not error and bool(content), f"код {status}, событий {len(events)}") status, body, _ = call(base, "POST", "/api/reviews", {"confirmed": True, "items": [{"ord": 1, "text": "шлюз с инструментами"}], "budget_rub": 100}, device) tool_review = as_json(body).get("id") if status == 200 else None if tool_review: status, body, _ = call(base, "POST", "/api/gateway/v1/chat/completions", {"model": "smeta", # пометка [tool] — для заглушки провайдера; живой модели прямо # говорим, каким инструментом пользоваться "messages": [{"role": "user", "content": "Найди цену по коду 1-14-1 и вызови для этого " "подходящий инструмент [tool]"}], "tool_choice": tool_choice, "tools": [{"type": "function", "function": { "name": "find_base_price", "description": "Найти цену ресурса по коду расценки", "parameters": {"type": "object", "properties": {"query": { "type": "string", "description": "код, например 1-14-1"}}, "required": ["query"]}}}]}, dict(device, **{"X-Review-Id": str(tool_review)})) events, done, error = parse_sse(body) fragments = [frag for event in events for chunk in (event.get("choices") or []) for frag in ((chunk.get("delta") or {}).get("tool_calls") or [])] finish = [chunk.get("finish_reason") for event in events for chunk in (event.get("choices") or [])] name = ((fragments[0].get("function") or {}).get("name") if fragments else "") args_text = "".join((frag.get("function") or {}).get("arguments", "") for frag in fragments) try: args = json.loads(args_text) if args_text else {} except ValueError: args = {} step("шлюз: вызов инструмента", status == 200 and not error and done and name == "find_base_price" and isinstance(args, dict) and bool(args) and "tool_calls" in finish, f"код {status}, аргументов {len(args)}" + (", ошибка провайдера в потоке" if error else "")) status, body, _ = call(base, "POST", f"/api/reviews/{tool_review}/cancel", None, site) step("уборка проверки с инструментами", status == 200 and as_json(body) == {"status": "ok"}, f"код {status}") else: step("создание проверки для инструментов", False, "нет id") status, body, _ = call(base, "POST", "/api/chat/turn", {"tab_id": tab_id, "question": "вопрос", "answer": "ответ"}, device) step("пара «вопрос — ответ» из программы", status == 200 and as_json(body).get("ok") is True, f"код {status}") status, body, _ = call(base, "POST", "/api/reviews", {"confirmed": True, "items": [{"ord": 1, "text": "сбой программы"}], "budget_rub": 100}, device) fail_review = as_json(body).get("id") if status == 200 else None if fail_review: status, body, _ = call(base, "POST", f"/api/reviews/{fail_review}/fail", {"reason": "контрактный прогон"}, device) step("сбой программы фиксируется", status == 200 and as_json(body).get("ok") is True, f"код {status}") else: step("создание проверки для сбоя", False, "нет id") status, body, _ = call(base, "POST", "/api/mcp", {"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, device) tools = ((as_json(body).get("result") or {}).get("tools") or []) if status == 200 else [] step("инструменты нормативов по HTTP", status == 200 and len(tools) == 15, f"код {status}, инструментов {len(tools)}") status, body, _ = call(base, "POST", "/api/device/refresh", {"refresh": token.get("refresh"), "app_version": app_version}) refreshed = as_json(body) if status == 200 else {} step("продление пропуска", status == 200 and has_keys(refreshed, REFRESH_KEYS), f"код {status}") status, body, _ = call(base, "POST", "/api/reviews/estimate", {"items": []}, {"Authorization": "Bearer " + access, "X-App-Version": app_version}) step("старый пропуск после продления не действует", status == 401, f"код {status}") status, body, _ = call(base, "POST", "/api/reviews/estimate", {"items": []}) step("отказ без пропуска", status == 401 and as_json(body).get("code") == "token_invalid", f"код {status}") status, body, _ = call(base, "POST", "/api/reviews/estimate", {"items": []}, {"Authorization": "Bearer " + refreshed.get("access", ""), "X-App-Version": "0.0.1"}) step("отказ старой версии", status == 426 and as_json(body).get("code") == "app_too_old", f"код {status}") return checks def main(argv: list[str] | None = None) -> int: ap = argparse.ArgumentParser(description="контрактный прогон arm-v1") ap.add_argument("--base", default="https://infosmeta.ru:8443") ap.add_argument("--user", required=True) ap.add_argument("--password", default="", help="пароль; лучше передавать через --password-env, чтобы его не было в ps") ap.add_argument("--password-env", default="ARM_TEST_PASSWORD", help="имя переменной окружения с паролем") ap.add_argument("--app-version", default="0.2.2-rc.3") ap.add_argument("--tab-id", default="", help="диалог сайта, из которого выдан код") ap.add_argument("--tool-choice", default="required", choices=("auto", "required", "none"), help="обязательность вызова инструмента: живые провайдеры с размышлением " "отвергают required — там нужен auto") ap.add_argument("--expect-sha", default="", help="ожидаемый отпечаток набора (пусто — только показать)") args = ap.parse_args(argv) if not args.password: import os args.password = os.environ.get(args.password_env, "") if not args.password: print(f"нет пароля: задайте --password или переменную {args.password_env}") return 2 print(f"среда: {args.base}") print(f"договор: {CONTRACT_DIR}") try: print(f"отпечаток набора: {contract_sha()}") except RuntimeError as err: print(f"набор не прочитан: {err}") return 2 checks = scenario(args.base, args.user, args.password, args.app_version, args.tab_id, args.tool_choice) if args.expect_sha: actual = contract_sha() checks.append(("отпечаток набора совпал", actual == args.expect_sha or actual.startswith(args.expect_sha), f"{actual} против {args.expect_sha}")) failed = 0 for name, ok, note in checks: print(f" {'✓' if ok else '✗'} {name}" + (f" — {note}" if note else "")) failed += 0 if ok else 1 print(f"итог: {len(checks) - failed} из {len(checks)} сошлось") return 0 if failed == 0 else 1 if __name__ == "__main__": sys.exit(main())