import sys import time import json import os import tempfile import unittest from pathlib import Path from unittest.mock import patch sys.path.insert(0, str(Path(__file__).parents[1])) sys.path.insert(0, str(Path(__file__).parents[2] / "scripts")) from graph_view import GraphView, GraphViewCache class GraphViewTests(unittest.TestCase): def setUp(self): self.gk = {"id": "gk395", "kind": "article", "label": "Статья 395 ГК РФ"} self.plenum = {"id": "plenum72", "kind": "point", "label": "Пункт 72"} self.data = {"snapshot": "s1", "stale": False, "warnings": [], "nodes": [self.gk, self.plenum], "edges": [{ "source": "plenum72", "target": "gk395", "relation": "references", "evidence": {"excerpt": "пункт 6 статьи 395 ГК РФ", "source_url": "https://example.test/a", "revision": "24.06.2025"}}]} def test_ego_keeps_exact_opaque_ids_and_evidence(self): view = GraphView(self.data) result = view.ego("gk395") self.assertEqual({node["id"] for node in result["nodes"]}, {"gk395", "plenum72"}) self.assertEqual(result["edges"][0]["evidence"]["revision"], "24.06.2025") page = view.ego("gk395", limit=1, offset=1) self.assertEqual(page["offset"], 1) self.assertIn("has_more", page) def test_cluster_filter_and_edge_lookup(self): view = GraphView(self.data) self.assertEqual(view.clustered(kind="article")["nodes"], []) self.assertEqual(view.clustered(query="статья 395")["nodes"][0]["id"], "gk395") self.assertEqual(view.edge("plenum72", "gk395")["status"], "ok") def test_graph_view_keeps_metadata_without_retaining_node_body(self): data = {**self.data, "nodes": [{**self.gk, "body": "large text"}]} node = GraphView(data).nodes["gk395"] self.assertEqual(node["label"], "Статья 395 ГК РФ") self.assertNotIn("body", node) def test_network_overview_aggregates_real_edges_and_atoms_keep_references(self): data = { "snapshot": "s1", "nodes": [ {"id": "doc-gk", "kind": "document", "resource_id": "gk", "label": "Гражданский кодекс"}, {"id": "doc-gpk", "kind": "document", "resource_id": "gpk", "label": "Гражданский процессуальный кодекс"}, {"id": "gk395", "kind": "article", "resource_id": "gk", "label": "Статья 395 ГК РФ"}, {"id": "gpk131", "kind": "article", "resource_id": "gpk", "label": "Статья 131 ГПК РФ"}, ], "edges": [ {"source": "gk395", "target": "gpk131", "relation": "references", "evidence": {"excerpt": "395"}}, {"source": "gk395", "target": "gpk131", "relation": "references"}, {"source": "doc-gk", "target": "gk395", "relation": "contains"}, {"source": "doc-gpk", "target": "gpk131", "relation": "contains"}, ], } view = GraphView(data) overview = view.network() self.assertEqual({n["id"] for n in overview["nodes"]}, {"doc-gk", "doc-gpk"}) self.assertEqual(len(overview["edges"]), 1) self.assertEqual(overview["edges"][0]["count"], 2) self.assertEqual(overview["edges"][0]["evidence"]["excerpt"], "395") atoms = view.network(level="atoms", resource_id="gk") self.assertEqual({n["id"] for n in atoms["nodes"]}, {"gk395", "gpk131"}) self.assertEqual({e["relation"] for e in atoms["edges"]}, {"references"}) self.assertLessEqual(len(atoms["nodes"]), 1000) self.assertLessEqual(len(atoms["edges"]), 5000) def test_network_query_and_bounds_are_deterministic(self): view = GraphView({ "nodes": [{"id": "d", "kind": "document", "resource_id": "r", "label": "Нужный документ"}], "edges": [], }) result = view.network(query="нужный", max_nodes=0, max_edges=0) self.assertEqual(result["nodes"][0]["id"], "d") self.assertEqual(result["displayed_nodes"], 1) def test_network_kind_uses_resource_id_when_snapshot_lacks_document_kind(self): view = GraphView({ "nodes": [ {"id": "plenum-doc", "kind": "document", "resource_id": "legal-corpus:plenum:vs-1", "label": "Пленум"}, {"id": "act-doc", "kind": "document", "resource_id": "legal-corpus:act:act-1", "label": "Акт"}, ], "edges": []}) result = view.network(kind="plenum") self.assertEqual([node["id"] for node in result["nodes"]], ["plenum-doc"]) atoms = GraphView({"nodes": [ {"id": "p1", "kind": "article", "resource_id": "legal-corpus:plenum:p", "label": "Пункт 1"}, {"id": "c1", "kind": "article", "resource_id": "legal-corpus:code:c", "label": "Статья 1"}, ], "edges": []}).network(level="atoms", kind="plenum") self.assertEqual([node["id"] for node in atoms["nodes"]], ["p1"]) def test_atomic_focus_is_exact_and_keeps_inbound_outbound_and_children(self): data = {"nodes": [ {"id": "a", "kind": "article", "resource_id": "r", "label": "Статья 1"}, {"id": "child", "kind": "point", "resource_id": "r", "label": "Пункт 1"}, {"id": "incoming", "kind": "article", "resource_id": "other", "label": "Статья 2"}, {"id": "outgoing", "kind": "point", "resource_id": "other", "label": "Пункт 2"}, {"id": "unrelated", "kind": "article", "resource_id": "r", "label": "Статья 99"}, ], "edges": [ {"source": "a", "target": "child", "relation": "contains"}, {"source": "incoming", "target": "a", "relation": "references"}, {"source": "a", "target": "outgoing", "relation": "references"}, {"source": "child", "target": "incoming", "relation": "references"}, ]} result = GraphView(data).network(level="atoms", node_id="a", max_nodes=10) self.assertEqual({n["id"] for n in result["nodes"]}, {"a", "child", "incoming", "outgoing"}) self.assertEqual({e["relation"] for e in result["edges"]}, {"contains", "references"}) self.assertEqual(result["focus_id"], "a") self.assertNotIn("unrelated", {n["id"] for n in result["nodes"]}) def test_atomic_focus_unknown_is_honest_and_anchor_survives_limit(self): data = {"nodes": [{"id": "a", "kind": "article", "resource_id": "r", "label": "Статья 1"}], "edges": []} view = GraphView(data) self.assertEqual(view.network(level="atoms", node_id="missing")["status"], "focus_not_found") self.assertEqual(view.network(level="atoms", node_id="a", max_nodes=1)["nodes"][0]["id"], "a") def test_atomic_numeric_query_does_not_match_larger_article_number(self): view = GraphView({"nodes": [ {"id": "a395", "kind": "article", "resource_id": "r", "label": "Статья 395"}, {"id": "a1395", "kind": "article", "resource_id": "r", "label": "Статья 1395"}, ], "edges": []}) self.assertEqual([n["id"] for n in view.network(level="atoms", query="ст. 395")["nodes"]], ["a395"]) def test_cache_ensure_is_nonblocking_and_loads_in_background(self): with patch("scripts.legal_graph.graph_data", return_value=self.data): cache = GraphViewCache("/tmp/themiz") started = time.monotonic() state = cache.ensure() self.assertLess(time.monotonic() - started, 0.1) self.assertTrue(state["loading"]) for _ in range(50): if cache.get() is not None: break time.sleep(0.01) self.assertEqual(cache.get().snapshot, "s1") def test_repeated_ensure_does_not_reload_same_pointer(self): with patch("scripts.legal_graph.graph_data", return_value=self.data) as loader: cache = GraphViewCache("/tmp/themiz") cache.ensure() for _ in range(50): if cache.get() is not None: break time.sleep(0.01) self.assertTrue(cache.get()) state = cache.ensure() self.assertFalse(state["loading"]) self.assertEqual(loader.call_count, 1) def test_same_pointer_does_not_reload_after_refresh_interval(self): with patch("scripts.legal_graph.graph_data", return_value=self.data) as loader: cache = GraphViewCache("/tmp/themiz") cache.ensure() for _ in range(50): if cache.get() is not None: break time.sleep(0.01) cache._checked = 0.0 state = cache.ensure() self.assertFalse(state["loading"]) self.assertEqual(loader.call_count, 1) def test_source_metadata_change_marks_cached_view_stale(self): with tempfile.TemporaryDirectory() as directory: root = Path(directory) state = root / ".agent/maintenance/legal-graph" snapshot = state / "snapshots/s1" source = root / "source.md" source.write_text("original", encoding="utf-8") snapshot.mkdir(parents=True) (state / "current.json").write_text("{}", encoding="utf-8") (snapshot / "source-manifest.json").write_text( json.dumps({"documents": [{"relative_path": "source.md"}]}), encoding="utf-8", ) with patch("scripts.legal_graph.graph_data", return_value=self.data): cache = GraphViewCache(root) cache.ensure() for _ in range(50): if cache.get() is not None: break time.sleep(0.01) os.utime(source, ns=(source.stat().st_atime_ns, source.stat().st_mtime_ns + 1_000_000)) cache._checked = 0.0 state = cache.ensure() self.assertTrue(state["stale"]) if __name__ == "__main__": unittest.main()