151 lines
7.1 KiB
Python
151 lines
7.1 KiB
Python
#!/usr/bin/env python3
|
|
"""Контракт скорости reader без сети загрузки корпуса."""
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import json
|
|
import sys
|
|
import tempfile
|
|
import time
|
|
import unittest
|
|
import urllib.parse
|
|
import urllib.request
|
|
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))
|
|
from eunomia.library import Library # noqa: E402
|
|
|
|
|
|
def resource():
|
|
return {
|
|
"id": "legal-corpus:code:gpk-rf",
|
|
"kind": "code",
|
|
"parser": "synthetic",
|
|
"url": "https://example.test/gpk-rf",
|
|
"output": "knowledge/kodeksy/gpk-rf.md",
|
|
"title": "ГПК РФ",
|
|
"entry": {"slug": "gpk-rf"},
|
|
}
|
|
|
|
|
|
class ReaderPerformanceTests(unittest.TestCase):
|
|
def test_article_reader_payload_is_compact_and_has_toc(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
root = Path(directory)
|
|
item = resource()
|
|
body = "# ГПК РФ\n\n" + "\n\n".join(
|
|
f"## Статья {n}. Норма\nТекст пункта {n}." for n in range(1, 80)
|
|
)
|
|
path = root / item["output"]
|
|
path.parent.mkdir(parents=True)
|
|
path.write_text(
|
|
"---\n"
|
|
f'дата_редакции: "08.09.2026"\ncoverage: "full"\n'
|
|
f'last_checked: "2026-09-08T10:00:00Z"\nsha256: "{hashlib.sha256(body.encode()).hexdigest()}"\n'
|
|
"---\n" + body,
|
|
encoding="utf-8",
|
|
)
|
|
with mock.patch("corpus_registry.registry", return_value=[item]):
|
|
library = Library(root)
|
|
self.assertTrue(library.refresh())
|
|
article = next(part for part in library.documents[item["id"]]["fragments"] if "article_40" in part["id"])
|
|
full = library.document(item["id"])
|
|
initial = library.reader(item["id"])
|
|
self.assertEqual(initial["selected_id"], full["fragments"][0]["id"])
|
|
self.assertEqual(initial["fragment"]["id"], full["fragments"][0]["id"])
|
|
compact = library.reader(item["id"], article["id"])
|
|
self.assertEqual(compact["fragment"]["id"], article["id"])
|
|
self.assertEqual(compact["selected_id"], article["id"])
|
|
self.assertEqual(len(compact["toc"]), 80)
|
|
self.assertNotIn("body", compact)
|
|
self.assertLess(len(json.dumps(compact, ensure_ascii=False)), len(json.dumps(full, ensure_ascii=False)))
|
|
|
|
def test_reader_resolves_nested_anchor_and_unknown_location(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
root = Path(directory)
|
|
item = resource()
|
|
body = "# ГПК РФ\n\n## Статья 131. Заявление\n1. Первый пункт.\n2. Второй пункт.\n"
|
|
path = root / item["output"]
|
|
path.parent.mkdir(parents=True)
|
|
path.write_text(
|
|
"---\ncoverage: full\n"
|
|
f'sha256: "{hashlib.sha256(body.encode()).hexdigest()}"\n---\n{body}',
|
|
encoding="utf-8",
|
|
)
|
|
with mock.patch("corpus_registry.registry", return_value=[item]):
|
|
library = Library(root)
|
|
self.assertTrue(library.refresh())
|
|
article = next(p for p in library.documents[item["id"]]["fragments"] if p["kind"] == "article")
|
|
anchor = article["anchors"][1]
|
|
selected = library.reader(item["id"], anchor["id"])
|
|
self.assertEqual(selected["selected_id"], anchor["id"])
|
|
self.assertEqual(selected["fragment"]["id"], article["id"])
|
|
self.assertEqual(selected["toc"][1]["anchors"][1], {"id": anchor["id"], "label": anchor["label"]})
|
|
unknown = library.reader(item["id"], "opaque-missing-location")
|
|
self.assertIsNone(unknown["fragment"])
|
|
self.assertIsNone(unknown["selected_id"])
|
|
|
|
def test_plenum_n10_plain_point_anchor_and_source_line_disambiguation(self):
|
|
with tempfile.TemporaryDirectory() as directory:
|
|
root = Path(directory)
|
|
item = resource()
|
|
item.update({
|
|
"id": "legal-corpus:plenum:n10",
|
|
"output": "knowledge/plenumy/n10.md",
|
|
"title": "Постановление Пленума ВС РФ № 10",
|
|
"kind": "plenum",
|
|
})
|
|
body = (
|
|
"# Постановление Пленума ВС РФ № 10\n\n"
|
|
"65. Первый пункт по вопросам практики.\n\n"
|
|
"65. Второй пункт в приложении.\n"
|
|
)
|
|
path = root / item["output"]
|
|
path.parent.mkdir(parents=True)
|
|
path.write_text(
|
|
"---\ncoverage: full\n"
|
|
f'sha256: "{hashlib.sha256(body.encode()).hexdigest()}"\n---\n{body}',
|
|
encoding="utf-8",
|
|
)
|
|
with mock.patch("corpus_registry.registry", return_value=[item]):
|
|
library = Library(root)
|
|
self.assertTrue(library.refresh())
|
|
parts = library.documents[item["id"]]["fragments"]
|
|
self.assertEqual(len(parts[0]["anchors"]), 2)
|
|
self.assertEqual(parts[0]["anchors"][0]["label"], "65.")
|
|
self.assertIsNone(library.reader_location(item["id"], "Пункт 65"))
|
|
first_offset = body.index("65.")
|
|
source_line = f"L{body[:first_offset].count(chr(10)) + 1}"
|
|
resolved = library.reader_location(item["id"], "Пункт 65", source_line)
|
|
self.assertEqual(resolved, parts[0]["anchors"][0]["id"])
|
|
|
|
def test_live_search_and_document_for_gpk131_gk395(self):
|
|
base = "http://127.0.0.1:18765"
|
|
try:
|
|
urllib.request.urlopen(base + "/api/status", timeout=1).close()
|
|
except OSError as exc:
|
|
self.skipTest(f"live Eunomia server unavailable: {exc}")
|
|
for query, resource_id in (("ст. 131 ГПК", "legal-corpus:code:gpk-rf"), ("ст. 395 ГК", "legal-corpus:code:gk-rf")):
|
|
with self.subTest(query=query):
|
|
start = time.perf_counter()
|
|
with urllib.request.urlopen(base + "/api/search?q=" + urllib.parse.quote(query), timeout=5) as response:
|
|
result = json.load(response)
|
|
elapsed = time.perf_counter() - start
|
|
self.assertTrue(result["total"], result)
|
|
self.assertLess(elapsed, 2.0, f"{query} search took {elapsed:.3f}s")
|
|
start = time.perf_counter()
|
|
with urllib.request.urlopen(base + "/api/document?id=" + urllib.parse.quote(resource_id), timeout=15) as response:
|
|
document = json.load(response)
|
|
elapsed = time.perf_counter() - start
|
|
self.assertTrue(document["fragments"])
|
|
# Current compatibility endpoint still serializes the complete
|
|
# text; keep a generous ceiling while reader endpoint is rolled out.
|
|
self.assertLess(elapsed, 15.0, f"{resource_id} document took {elapsed:.3f}s")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|