172 lines
8.7 KiB
Python
172 lines
8.7 KiB
Python
#!/usr/bin/env python3
|
||
"""Небольшие контракты данных, от которых зависит UI библиотеки Eunomia."""
|
||
from __future__ import annotations
|
||
|
||
import sys
|
||
import tempfile
|
||
import unittest
|
||
from pathlib import Path
|
||
from unittest import mock
|
||
|
||
ROOT = Path(__file__).resolve().parents[2]
|
||
sys.path.insert(0, str(ROOT / "scripts"))
|
||
sys.path.insert(0, str(ROOT))
|
||
|
||
import legal_graph # noqa: E402
|
||
from eunomia.library import Library, fragments # noqa: E402
|
||
from eunomia.server import App # noqa: E402
|
||
from eunomia.graph_view import GraphView # noqa: E402
|
||
|
||
|
||
def act(*, kind="plenum", title="Акт", number=None, date=None):
|
||
return {
|
||
"id": "legal-corpus:%s:synthetic" % kind,
|
||
"kind": kind,
|
||
"url": "https://example.test/synthetic",
|
||
"output": "knowledge/plenumy/synthetic.md",
|
||
"title": title,
|
||
"number": number,
|
||
"date": date,
|
||
"entry": {},
|
||
}
|
||
|
||
|
||
class LibrarySummaryContractTests(unittest.TestCase):
|
||
def setUp(self):
|
||
self.tmp = tempfile.TemporaryDirectory()
|
||
self.addCleanup(self.tmp.cleanup)
|
||
self.library = Library(Path(self.tmp.name))
|
||
|
||
def summary(self, resource, body, *, meta=None):
|
||
return self.library._summary(resource, meta or {}, body, True)
|
||
|
||
def test_act_date_comes_from_identity_not_revision(self):
|
||
resource = act(
|
||
title="Федеральный закон от 12.03.2024 № 42-ФЗ О порядке обращения",
|
||
)
|
||
value = self.summary(
|
||
resource,
|
||
"# Федеральный закон от 12.03.2024 № 42-ФЗ О порядке обращения\n",
|
||
meta={"дата_редакции": "08.09.2026"},
|
||
)
|
||
self.assertEqual(value["act_date"], "12.03.2024")
|
||
self.assertEqual(value["revision"], "08.09.2026")
|
||
self.assertNotEqual(value["act_date"], value["revision"])
|
||
|
||
def test_plenum_subject_after_title_and_revision_is_extracted(self):
|
||
resource = act(
|
||
title="Постановление Пленума ВС РФ от 12.03.2024 № 42 (ред. от 01.09.2026)"
|
||
)
|
||
body = (
|
||
"# Постановление Пленума ВС РФ от 12.03.2024 № 42 (ред. от 01.09.2026)\n\n"
|
||
"О некоторых вопросах применения судами законодательства о доказательствах\n\n"
|
||
"1. Разъяснить судам порядок применения.\n"
|
||
)
|
||
value = self.summary(resource, body, meta={"дата_редакции": "01.09.2026"})
|
||
self.assertEqual(value["act_date"], "12.03.2024")
|
||
self.assertEqual(value["number"], "42")
|
||
self.assertEqual(
|
||
value["subject"],
|
||
"О некоторых вопросах применения судами законодательства о доказательствах",
|
||
)
|
||
|
||
def test_number_is_numeric_and_unknown_date_stays_null(self):
|
||
resource = act(
|
||
title="Постановление Пленума ВС РФ № 7 О практике рассмотрения дел",
|
||
)
|
||
value = self.summary(
|
||
resource,
|
||
"# Постановление Пленума ВС РФ № 7 О практике рассмотрения дел\n",
|
||
meta={"дата_редакции": "08.09.2026", "закон": "№ 7"},
|
||
)
|
||
self.assertIsNone(value["act_date"])
|
||
self.assertEqual(value["number"], "7")
|
||
self.assertIsInstance(value["number"], str)
|
||
|
||
def test_fragment_anchors_are_stable_and_unique(self):
|
||
resource = act(kind="code", title="ГПК РФ")
|
||
body = (
|
||
"# ГПК РФ\n\n"
|
||
"## Статья 131. Форма заявления\n"
|
||
"1. Первый пункт.\n2. Второй пункт.\n\n"
|
||
"## Статья 132. Приложения\n"
|
||
"1. Документы.\n"
|
||
)
|
||
items = fragments(resource["id"], body)
|
||
ids = [item["id"] for item in items]
|
||
anchors = [anchor["id"] for item in items for anchor in item.get("anchors", [])]
|
||
base = legal_graph._graph_id(resource["id"])
|
||
self.assertIn(f"{base}_article_131", ids)
|
||
self.assertIn(f"{base}_article_132", ids)
|
||
self.assertEqual(len(ids), len(set(ids)))
|
||
self.assertEqual(len(anchors), len(set(anchors)))
|
||
self.assertIn(f"{base}_article_131_point_1", anchors)
|
||
self.assertIn(f"{base}_article_131_point_2", anchors)
|
||
|
||
def test_status_keeps_readable_fallback_when_schedule_fails(self):
|
||
app = App(Path(self.tmp.name))
|
||
with mock.patch("background_corpus.status", return_value={"queue": {}, "jobs": []}), \
|
||
mock.patch("background_corpus.enabled", return_value=False), \
|
||
mock.patch("background_corpus.schedule", side_effect=RuntimeError("queue unavailable")):
|
||
status = app.status()
|
||
self.assertEqual(status["schedule"]["next_run"], None)
|
||
self.assertFalse(status["schedule"]["enabled"])
|
||
self.assertIn("ручные задания", status["schedule"]["detail"].lower())
|
||
|
||
def test_graph_reader_point_does_not_resolve_to_parent_article(self):
|
||
resource = act(kind="code", title="ГПК РФ")
|
||
body = "## Статья 131. Форма заявления\n1. Первый пункт.\n2. Второй пункт.\n1) Вложенный пункт.\n"
|
||
parts = fragments(resource["id"], body)
|
||
article = next(p for p in parts if p["kind"] == "article")
|
||
anchor = article["anchors"][0]
|
||
self.library.documents[resource["id"]] = {"document": {"kind": "code"}, "body": body, "fragments": parts}
|
||
base = "doc:" + resource["id"] + ":article:131"
|
||
nodes = [{"id": base, "kind": "article", "label": article["label"], "resource_id": resource["id"]},
|
||
{"id": base + ":point:1", "kind": "point", "label": "Пункт 1. Первый пункт", "resource_id": resource["id"]}]
|
||
view = GraphView({"nodes": nodes, "edges": [{"source": base, "target": base + ":point:1", "relation": "contains"}]})
|
||
app = App.__new__(App)
|
||
app.library = self.library
|
||
app.graph_views = mock.Mock()
|
||
app.graph_views.get.return_value = view
|
||
result = app.graph_network({"resource_id": resource["id"], "fragment": anchor["id"]})
|
||
self.assertEqual(result["focus_id"], base + ":point:1")
|
||
point = next(n for n in result["nodes"] if n["id"] == result["focus_id"])
|
||
self.assertEqual(point["reader_id"], anchor["id"])
|
||
unsupported = app.graph_network({"resource_id": resource["id"], "fragment": article["anchors"][2]["id"]})
|
||
self.assertEqual(unsupported["status"], "focus_not_found")
|
||
|
||
def test_related_with_node_outside_library_is_not_404(self):
|
||
# Практика 03.10.2026: у ст. 333 ГК РФ соседи из индекса практики (practice:index), а его нет в
|
||
# библиотеке - reader_location бросал KeyError, сервер отвечал 404 на /api/related.
|
||
resource = act(kind="code", title="ГК РФ")
|
||
body = "## Статья 333. Уменьшение неустойки\n1. Первый пункт.\n"
|
||
parts = fragments(resource["id"], body)
|
||
self.library.documents[resource["id"]] = {"document": {"kind": "code"}, "body": body, "fragments": parts}
|
||
article = "doc:" + resource["id"] + ":article:333"
|
||
practice = "doc:practice:index:entry:1"
|
||
nodes = [{"id": article, "kind": "article", "label": "Статья 333. Уменьшение неустойки",
|
||
"resource_id": resource["id"]},
|
||
{"id": practice, "kind": "practice", "label": "Определение ВС", "resource_id": "practice:index"}]
|
||
view = GraphView({"nodes": nodes, "edges": [{"source": practice, "target": article, "relation": "references"}]})
|
||
app = App.__new__(App)
|
||
app.library = self.library
|
||
app.graph_views = mock.Mock()
|
||
app.graph_views.get.return_value = view
|
||
result = app.related_data(resource["id"], article)
|
||
self.assertEqual([edge["source_node"]["reader_id"] for edge in result["related"]], [""])
|
||
self.assertTrue(result["related"][0]["target_node"]["reader_id"])
|
||
|
||
def test_graph_waits_for_reader_index_during_cold_start(self):
|
||
app = App.__new__(App)
|
||
app.library = self.library
|
||
app.graph_views = mock.Mock()
|
||
app.graph_views.ensure.return_value = {"loading": False}
|
||
app.graph_views.get.return_value = GraphView({"nodes": [], "edges": []})
|
||
result = app.graph_network({})
|
||
self.assertTrue(result["loading"])
|
||
self.assertEqual(result["nodes"], [])
|
||
|
||
|
||
if __name__ == "__main__":
|
||
unittest.main()
|