astrbot_plugin_private_comp.../tests/test_ops_status_projection.py

183 行
8.9 KiB
Python

from __future__ import annotations
import importlib.util
import json
from pathlib import Path
import unittest
ROOT = Path(__file__).resolve().parents[1]
MODULE_PATH = ROOT / "ops_status_projection.py"
SPEC = importlib.util.spec_from_file_location("ops_status_projection_under_test", MODULE_PATH)
assert SPEC and SPEC.loader
projection = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(projection)
AFFINITY_SPEC = importlib.util.spec_from_file_location(
"p4_affinity_confinement_for_ops_status_test", ROOT / "p4_affinity_confinement.py"
)
assert AFFINITY_SPEC and AFFINITY_SPEC.loader
affinity = importlib.util.module_from_spec(AFFINITY_SPEC)
AFFINITY_SPEC.loader.exec_module(affinity)
def _effect_state(*, warmth_score: int = 1, confined: bool = False) -> dict:
state = affinity.new_shadow_state()
state["mode"] = "effect_preparation"
state["score"] = -1200 if confined else warmth_score
state["warning_stage"] = "confinement" if confined else "none"
state["confinement_state"] = "active" if confined else "none"
state["confinement_round"] = 3 if confined else 0
state["confinement_until"] = "2099-01-01T00:00:00Z" if confined else ""
state["confinement_duration_days"] = 9 if confined else 0
return state
class OpsStatusProjectionTests(unittest.TestCase):
def test_p3_to_p6_projection_contains_only_allowlisted_summary_fields(self) -> None:
result = projection.build_ops_status_projection(
p4_runtime_enabled=True,
p4_manual_review_enabled=True,
p4_review_container={
"version": 1,
"candidates": {
"candidate-secret": {"person_id": "person-secret", "raw": "must-not-leak"},
},
"event_index": {"event-secret": {"candidate_id": "candidate-secret"}},
"decisions": {},
},
p4_effect_container={
"people": {
"person-secret": {"state": _effect_state(warmth_score=1)},
"person-confined": {"state": _effect_state(confined=True)},
},
},
p5_source_observer_enabled=True,
p5_protection_flags={
"enable_p5_b1_recall_gate": True,
"enable_p5_b1_bridge_gate": True,
"enable_p5c_tool_parameter_gate": True,
"enable_p5d_manual_recovery": True,
"unused": True,
},
p6_registry_status={
"profiles": 2,
"identity_links": 3,
"audit_events": 4,
"operations": 5,
"person_id": "person-secret",
"ledger": {"raw": "must-not-leak"},
},
)
self.assertEqual(
{"schema_version", "p3", "p4", "p5", "p6"},
set(result),
)
self.assertEqual({"contract_version", "status"}, set(result["p3"]))
self.assertEqual(
{
"runtime_enabled", "protection_status", "review_enabled", "review_candidate_count",
"review_status", "runtime_status", "warmth_band_counts", "active_confinement_count",
},
set(result["p4"]),
)
self.assertEqual(1, result["p4"]["review_candidate_count"])
self.assertEqual(1, result["p4"]["warmth_band_counts"]["warm"])
self.assertEqual(1, result["p4"]["warmth_band_counts"]["confinement"])
self.assertEqual(1, result["p4"]["active_confinement_count"])
self.assertEqual({"source_observer_enabled", "b_gate_count", "c_gate_count", "d_gate_count", "protected_sink_count", "protection_status"}, set(result["p5"]))
self.assertEqual((2, 1, 1, 4), (result["p5"]["b_gate_count"], result["p5"]["c_gate_count"], result["p5"]["d_gate_count"], result["p5"]["protected_sink_count"]))
self.assertEqual({"health", "reason_code", "counts"}, set(result["p6"]))
serialized = json.dumps(result, ensure_ascii=True, sort_keys=True)
for forbidden in ("person-secret", "person-confined", "candidate-secret", "event-secret", "must-not-leak", '"score"', '"ledger"', '"attestation"', '"credential"'):
self.assertNotIn(forbidden, serialized)
def test_user_projection_does_not_guess_a_p4_principal_or_offer_actions(self) -> None:
result = projection.build_user_p4_status_projection(runtime_enabled=True)
self.assertEqual(
{
"schema_version", "runtime_enabled", "warmth_band", "confinement_state",
"confinement_until", "review_candidate_count", "review_status",
"action_available", "action_unavailable_reason",
},
set(result),
)
self.assertTrue(result["runtime_enabled"])
self.assertEqual("identity_not_verifiably_linked", result["review_status"])
self.assertFalse(result["action_available"])
self.assertEqual("host_principal_unavailable", result["action_unavailable_reason"])
serialized = json.dumps(result, ensure_ascii=True, sort_keys=True)
for forbidden in ("person_id", "event_id", "score", "ledger", "attestation", "credential"):
self.assertNotIn(forbidden, serialized)
def test_missing_p6_registry_is_unverifiable_not_a_healthy_zero(self) -> None:
result = projection.build_ops_status_projection(
p4_runtime_enabled=True,
p4_manual_review_enabled=False,
p4_review_container=None,
p4_effect_container=None,
p5_source_observer_enabled=False,
p5_protection_flags=None,
p6_registry_status=None,
)
self.assertEqual("unverifiable", result["p6"]["health"])
self.assertEqual("registry_status_unavailable", result["p6"]["reason_code"])
def test_status_api_failure_message_is_not_derived_from_exception_detail(self) -> None:
page_api = (ROOT / "page_api.py").read_text(encoding="utf-8")
start = page_api.index("async def get_ops_status")
end = page_api.index("def _ops_status_projection_locked", start)
status_api = page_api[start:end]
self.assertIn('return self._error("安全状态暂不可用")', status_api)
self.assertNotIn("return self._error(str(exc))", status_api)
class OpsStatusPageWiringTests(unittest.TestCase):
def test_relationship_panel_and_final_temperature_wiring_are_present(self) -> None:
page_api = (ROOT / "page_api.py").read_text(encoding="utf-8")
users_api = (ROOT / "page_api_users_groups.py").read_text(encoding="utf-8")
app_js = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8")
main_py = (ROOT / "main.py").read_text(encoding="utf-8")
self.assertIn('"relationship_panel"', users_api)
self.assertIn("def _relationship_panel", page_api)
self.assertIn("function renderRelationshipPanel", app_js)
self.assertIn("最终回复温度", app_js)
self.assertIn("关系网节点", app_js)
self.assertIn("compose_reply_temperature(", main_py)
self.assertIn("p4_cap", main_py)
self.assertNotIn("relationship_score", app_js[app_js.index("function renderUserDetail"):app_js.index("function renderPrivateDeliveryRoute")])
def test_page_route_and_safe_ui_bindings_are_present(self) -> None:
page_api = (ROOT / "page_api.py").read_text(encoding="utf-8")
app_js = (ROOT / "pages" / "陪伴面板" / "app.js").read_text(encoding="utf-8")
index_html = (ROOT / "pages" / "陪伴面板" / "index.html").read_text(encoding="utf-8")
self.assertIn('(\"/ops/status\", self.get_ops_status, [\"GET\"]', page_api)
self.assertIn('"p4_runtime": self._user_p4_status_projection()', (ROOT / "page_api_users_groups.py").read_text(encoding="utf-8"))
self.assertIn('fetchJson("/ops/status")', app_js)
self.assertIn('id="opsProtectionSummary"', index_html)
self.assertIn('data-tab="private"><i>04</i><span>用户</span>', index_html)
start = app_js.index("function renderUserP4RuntimeStatus")
end = app_js.index("\nfunction renderPrivateDeliveryRoute", start)
user_p4_renderer = app_js[start:end]
self.assertIn("identity_not_verifiably_linked", user_p4_renderer)
for forbidden in ("relationship_score", "person_id", "event_id", "candidate_id", "audit", "ledger", "attestation", "credential"):
self.assertNotIn(forbidden, user_p4_renderer)
def test_primary_private_scope_is_presented_as_users(self) -> None:
page_path = next((ROOT / "pages").glob("*/index.html"))
page = page_path.read_text(encoding="utf-8")
script = (page_path.parent / "app.js").read_text(encoding="utf-8")
self.assertIn('data-tab="private"><i>04</i><span>用户</span>', page)
self.assertIn("<h2>用户关系分布</h2>", page)
self.assertIn("statCard(`用户 ${privateInfo.enabled_user_count", script)
self.assertIn('label: "用户陪伴"', script)
if __name__ == "__main__":
unittest.main()