199 lines
14 KiB
Python
199 lines
14 KiB
Python
"""Acceptance checks for exact article/point knowledge graphs."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import re
|
|
import urllib.parse
|
|
import urllib.request
|
|
import urllib.error
|
|
import time
|
|
from pathlib import Path
|
|
from typing import Any
|
|
|
|
from playwright.sync_api import sync_playwright
|
|
|
|
BASE = os.environ.get("EUNOMIA_URL", "http://127.0.0.1:18765")
|
|
OUT = Path(__file__).parents[1] / "qa" / "atomic"
|
|
OUT.mkdir(parents=True, exist_ok=True)
|
|
GPK = "legal-corpus:code:gpk-rf"
|
|
GPK131 = "doc:legal-corpus:code:gpk-rf:article:131"
|
|
GK = "legal-corpus:code:gk-rf"
|
|
GK395 = "doc:legal-corpus:code:gk-rf:article:395"
|
|
|
|
|
|
def get_json(path: str) -> dict[str, Any]:
|
|
last: Exception | None = None
|
|
for _ in range(4):
|
|
try:
|
|
with urllib.request.urlopen(BASE + "/api" + path, timeout=30) as response:
|
|
return json.load(response)
|
|
except urllib.error.HTTPError as error:
|
|
last = error
|
|
time.sleep(0.4)
|
|
raise last or RuntimeError("API request failed")
|
|
|
|
|
|
def graph(resource: str, fragment: str = "", **extra: str) -> dict[str, Any]:
|
|
params = {"level": "atoms", "resource_id": resource, "limit": "1000", **extra}
|
|
if fragment:
|
|
params["fragment"] = fragment
|
|
last: dict[str, Any] = {}
|
|
for _ in range(120):
|
|
last = get_json("/graph/network?" + urllib.parse.urlencode(params))
|
|
if not last.get("loading") or last.get("nodes"):
|
|
return last
|
|
time.sleep(1)
|
|
return last
|
|
|
|
|
|
def check(report: dict[str, Any], name: str, ok: bool, detail: Any = "") -> None:
|
|
report["checks"].append({"name": name, "ok": bool(ok), "detail": detail})
|
|
|
|
|
|
def ids_and_edges(data: dict[str, Any]) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
|
|
return {node["id"]: node for node in data.get("nodes", [])}, data.get("edges", [])
|
|
|
|
|
|
def assert_focus(report: dict[str, Any], data: dict[str, Any], focus: str, resource: str) -> None:
|
|
nodes, edges = ids_and_edges(data)
|
|
check(report, f"{focus} has exact focus id", data.get("focus_id") == focus, data.get("focus_id"))
|
|
check(report, f"{focus} has no document nodes", not any(node.get("kind") == "document" for node in nodes.values()), [node.get("kind") for node in nodes.values() if node.get("kind") == "document"])
|
|
check(report, f"{focus} is represented as an article/point", nodes.get(focus, {}).get("kind") in {"article", "point"}, nodes.get(focus, {}).get("kind"))
|
|
check(report, f"{focus} graph is bounded", len(nodes) <= 1000 and len(edges) <= 1000, {"nodes": len(nodes), "edges": len(edges)})
|
|
check(report, f"{focus} nodes stay in graph resources", all(node.get("resource_id") for node in nodes.values()), resource)
|
|
|
|
|
|
def route(**params: str) -> str:
|
|
return "#" + urllib.parse.urlencode({"view": "graph", **params})
|
|
|
|
|
|
def reader_hash(resource: str, fragment: str) -> str:
|
|
return "#" + urllib.parse.urlencode({"doc": resource, "fragment": fragment})
|
|
|
|
|
|
def edge_set(data: dict[str, Any], relation: str = "references") -> set[tuple[str, str, str]]:
|
|
return {(edge["source"], edge["target"], edge.get("relation", "")) for edge in data.get("edges", []) if edge.get("relation") == relation}
|
|
|
|
|
|
def main() -> int:
|
|
report: dict[str, Any] = {"base": BASE, "checks": []}
|
|
gpk0 = graph(GPK, GPK131, include_contains="0")
|
|
gpk1 = graph(GPK, GPK131, include_contains="1")
|
|
gk0 = graph(GK, GK395, include_contains="0")
|
|
gk1 = graph(GK, GK395, include_contains="1")
|
|
report["api"] = {"gpk131_no_structure": {"nodes": len(gpk0.get("nodes", [])), "edges": len(gpk0.get("edges", []))}, "gpk131_structure": {"nodes": len(gpk1.get("nodes", [])), "edges": len(gpk1.get("edges", []))}, "gk395_no_structure": {"nodes": len(gk0.get("nodes", [])), "edges": len(gk0.get("edges", []))}, "gk395_structure": {"nodes": len(gk1.get("nodes", [])), "edges": len(gk1.get("edges", []))}}
|
|
for data, focus, resource in [(gpk0, GPK131, GPK), (gk0, GK395, GK)]:
|
|
assert_focus(report, data, focus, resource)
|
|
gpk_nodes, gpk_edges = ids_and_edges(gpk1)
|
|
gpk_inc = [edge for edge in gpk_edges if edge["target"] == GPK131]
|
|
gpk_out = [edge for edge in gpk_edges if edge["source"] == GPK131]
|
|
check(report, "GPK 131 has incoming plenum point", any(gpk_nodes.get(edge["source"], {}).get("document_kind") == "plenum" and gpk_nodes.get(edge["source"], {}).get("kind") == "point" for edge in gpk_inc), [(gpk_nodes.get(edge["source"], {}).get("kind"), gpk_nodes.get(edge["source"], {}).get("document_kind")) for edge in gpk_inc])
|
|
check(report, "GPK 131 has outbound article/point relation", any(gpk_nodes.get(edge["target"], {}).get("kind") in {"article", "point"} for edge in gpk_out), len(gpk_out))
|
|
check(report, "structure toggle adds contains edges", len(gpk1.get("edges", [])) > len(gpk0.get("edges", [])) and any(edge.get("relation") == "contains" for edge in gpk1.get("edges", [])), report["api"])
|
|
check(report, "structure toggle preserves exact citation edge set", edge_set(gpk0) == edge_set(gpk1), {"without": len(edge_set(gpk0)), "with": len(edge_set(gpk1))})
|
|
gk_query = graph(GK, q="ст. 395 ГК")
|
|
qnodes = {node["id"]: node for node in gk_query.get("nodes", [])}
|
|
check(report, "query 395 returns exact article focus", any(node.get("label", "").startswith("Статья 395.") for node in qnodes.values()), [node.get("label") for node in qnodes.values() if node.get("kind") == "article"][:5])
|
|
seed_1395 = [node for node in qnodes.values() if re.search(r"article:1395(?:$|_)", node.get("id", ""))]
|
|
check(report, "query 395 does not seed article 1395", not seed_1395, [node.get("id") for node in seed_1395])
|
|
check(report, "query graph stays bounded", len(qnodes) <= 1000 and len(gk_query.get("edges", [])) <= 1000, {"nodes": len(qnodes), "edges": len(gk_query.get("edges", []))})
|
|
|
|
with sync_playwright() as playwright:
|
|
browser = playwright.chromium.launch(headless=True)
|
|
page = browser.new_page(viewport={"width": 1440, "height": 1000})
|
|
page.goto(BASE + "/" + route(level="atoms", resource_id=GPK, fragment=GPK131, include_contains="1"), wait_until="domcontentloaded")
|
|
page.locator(".p-network-toolbar").wait_for(timeout=120000)
|
|
try:
|
|
page.get_by_role("button", name="Оживить").wait_for(timeout=120000)
|
|
except Exception:
|
|
pass
|
|
body = page.locator("body").inner_text()
|
|
check(report, "browser focus identifies article 131", "Статья 131" in body and "Связи выбранной нормы" in body, body[:1500])
|
|
relations = page.locator(".p-atomic-relation")
|
|
relation_text = " ".join(relations.all_inner_texts())
|
|
relation_lower = relation_text.lower()
|
|
check(report, "browser renders concrete atomic relation labels", all(label in relation_lower for label in ("ссылка из", "ссылается на", "содержит")), relation_text[:1200])
|
|
check(report, "browser relations expose concrete reader links", relations.locator("a.p-atomic-read").count() > 0 and all((href := link.get_attribute("href")) and href.startswith("#doc=") for link in relations.locator("a.p-atomic-read").all()), relations.locator("a.p-atomic-read").count())
|
|
center = page.get_by_role("link", name="В центре — эта норма")
|
|
check(report, "recenter link preserves exact node", center.count() == 1 and "node_id=" in (center.get_attribute("href") or ""), center.get_attribute("href") if center.count() else "")
|
|
first_relation = page.locator(".p-atomic-relation").first
|
|
if first_relation.count():
|
|
first_relation.locator(".p-related-node").click()
|
|
page.wait_for_timeout(300)
|
|
recenter = page.get_by_role("link", name="В центре — эта норма")
|
|
recenter_href = recenter.get_attribute("href") if recenter.count() else ""
|
|
recenter_params = urllib.parse.parse_qs(recenter_href.lstrip("#")) if recenter_href else {}
|
|
expected_node = recenter_params.get("node_id", [""])[0]
|
|
check(report, "related node offers exact recenter action", recenter.count() == 1 and bool(expected_node), recenter_href)
|
|
if recenter.count():
|
|
recenter.click(); page.locator(".p-network-toolbar").wait_for(timeout=120000)
|
|
route_params = urllib.parse.parse_qs(urllib.parse.urlparse(page.url).fragment)
|
|
check(report, "recenter action navigates to selected exact node", route_params.get("node_id", [""])[0] == expected_node, {"url": page.url, "expected": expected_node})
|
|
neighbor_graph = graph(GPK, "", node_id=expected_node, include_contains="1")
|
|
check(report, "recentered related node becomes API focus", neighbor_graph.get("focus_id") == expected_node, neighbor_graph.get("focus_id"))
|
|
page.screenshot(path=str(OUT / "atomic-gpk-131.png"), full_page=True)
|
|
toggle = page.get_by_role("checkbox", name="Показывать состав статьи и вложенные пункты")
|
|
check(report, "browser exposes structure toggle", toggle.count() == 1, toggle.count())
|
|
if toggle.count():
|
|
before = page.locator(".p-network-toolbar").inner_text()
|
|
toggle.click(force=True); page.wait_for_timeout(1200)
|
|
after = page.locator(".p-network-toolbar").inner_text()
|
|
check(report, "structure toggle changes graph payload", before != after or page.url.find("include_contains=0") >= 0, {"before": before, "after": after, "url": page.url})
|
|
page.goto(BASE + "/" + route(level="atoms", q="ст. 395 ГК"), wait_until="domcontentloaded")
|
|
page.locator(".p-network-toolbar").wait_for(timeout=120000)
|
|
check(report, "browser query 395 excludes 1395 as seed", "Статья 1395." not in page.locator("body").inner_text().split("Граф знаний", 1)[-1], page.locator("body").inner_text()[-1000:])
|
|
page.set_viewport_size({"width": 390, "height": 844}); page.wait_for_timeout(500)
|
|
check(report, "atomic graph has no mobile overflow", page.evaluate("document.documentElement.scrollWidth - document.documentElement.clientWidth") == 0, page.evaluate("[document.documentElement.scrollWidth, document.documentElement.clientWidth]"))
|
|
page.screenshot(path=str(OUT / "atomic-mobile.png"), full_page=True)
|
|
|
|
# Real user path: reader article -> exact graph, for both requested articles.
|
|
for resource, reader_fragment, canonical in ((GPK, "doc:legal-corpus:code:gpk-rf_article_131", GPK131), (GK, "doc:legal-corpus:code:gk-rf_article_395", GK395)):
|
|
page.set_viewport_size({"width": 1440, "height": 1000})
|
|
page.goto(BASE + "/" + reader_hash(resource, reader_fragment), wait_until="domcontentloaded")
|
|
page.locator(".p-document").wait_for(timeout=120000)
|
|
page.locator(".p-fragment-graph").first.wait_for(timeout=120000)
|
|
graph_link = None
|
|
graph_href = ""
|
|
for candidate in page.locator(".p-fragment-graph").all():
|
|
candidate_href = candidate.get_attribute("href") or ""
|
|
candidate_params = urllib.parse.parse_qs(candidate_href.lstrip("#"))
|
|
if candidate_params.get("fragment", [""])[0] == reader_fragment:
|
|
graph_link, graph_href = candidate, candidate_href
|
|
break
|
|
check(report, f"reader exposes exact graph link for {reader_fragment}", graph_link is not None, graph_href)
|
|
if graph_link is not None:
|
|
graph_link.click()
|
|
page.locator(".p-network-toolbar").wait_for(timeout=120000)
|
|
parsed = urllib.parse.urlparse(page.url)
|
|
route_params = urllib.parse.parse_qs(parsed.fragment)
|
|
graph_data = graph(resource, reader_fragment, include_contains="1")
|
|
check(report, f"reader graph link centers {canonical}", graph_data.get("focus_id") == canonical and route_params.get("fragment", [""])[0] == reader_fragment, {"focus_id": graph_data.get("focus_id"), "url": page.url})
|
|
relation_link = page.locator(".p-atomic-read").first
|
|
if relation_link.count():
|
|
target_href = relation_link.get_attribute("href") or ""
|
|
target_params = urllib.parse.parse_qs(target_href.lstrip("#"))
|
|
relation_link.click()
|
|
page.locator(".p-document").wait_for(timeout=120000)
|
|
try:
|
|
target_reader = get_json("/reader?" + urllib.parse.urlencode({"id": target_params.get("doc", [""])[0], "fragment": target_params.get("fragment", [""])[0]}))
|
|
except Exception as error:
|
|
target_reader = {}
|
|
check(report, f"atomic relation opens exact reader for {canonical}", False, {"href": target_href, "error": str(error)})
|
|
if target_reader:
|
|
requested_fragment = target_params.get("fragment", [""])[0]
|
|
check(report, f"atomic relation opens exact reader for {canonical}", bool(requested_fragment) and target_reader.get("selected_id") == requested_fragment, {"href": target_href, "selected_id": target_reader.get("selected_id")})
|
|
|
|
unknown = graph(GPK, "doc:legal-corpus:code:gpk-rf_article_999999", include_contains="1")
|
|
check(report, "unknown fragment stays empty instead of falling back to document", unknown.get("status") == "focus_not_found" and not unknown.get("nodes"), {"status": unknown.get("status"), "nodes": len(unknown.get("nodes", []))})
|
|
browser.close()
|
|
(OUT / "atomic-check.json").write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n")
|
|
failures = [item for item in report["checks"] if not item["ok"]]
|
|
print(json.dumps({"checks": len(report["checks"]), "failures": failures}, ensure_ascii=False, indent=2))
|
|
return 1 if failures else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|