# 审计锚定端点 API 黄金测试(§3.6) # ============================================================ from __future__ import annotations import pytest from fastapi.testclient import TestClient class _Store: def __init__(self): self.tenant_uuid = "platform" self.world_key = "default" self.data = {"auditEvents": [ {"id": 1, "at": "2026-08-01T00:00:00+08:00", "ts": "2026-08-01T00:00:00+08:00", "actor": "tester", "category": "TEST", "action": "test.one", "target": {"type": "TEST"}, "power": "P0", "rationale": {}, "prevHash": "GENESIS", "hash": "0" * 64}, ]} def next_id(self, _kind: str) -> int: return 2 def save(self) -> None: pass @pytest.fixture def client(monkeypatch, tmp_path): import server.gateway.app as gateway_module from tests.auth_provider import install_test_auth install_test_auth(monkeypatch, "tenant-anchor-api") store = _Store() monkeypatch.setattr(gateway_module, "get_store", lambda: store) c = TestClient(gateway_module.create_app()) login = c.post("/api/auth/login", json={"username": "planner", "password": "test"}) assert login.status_code == 200, login.text return c, store def test_audit_get_reports_unanchored_then_anchor(client, tmp_path): c, store = client # 隔离账本目录:通过环境变量注入(在调用端点前设置) import os os.environ["APS_AUDIT_LEDGER_DIR"] = str(tmp_path / "ledger") try: g = c.get("/api/gov/audit") assert g.status_code == 200, g.text anchor = g.json()["anchor"] assert anchor["anchored"] is False assert anchor["reason"] == "not-anchored" a = c.post("/api/gov/audit/anchor") assert a.status_code == 200, a.text assert a.json()["anchored"] is True assert a.json()["status"]["ok"] is True g2 = c.get("/api/gov/audit") assert g2.json()["anchor"]["anchored"] is True assert g2.json()["anchor"]["ok"] is True finally: os.environ.pop("APS_AUDIT_LEDGER_DIR", None)