867 lines
54 KiB
Python
867 lines
54 KiB
Python
import importlib.util
|
||
import json
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||
|
||
import core # noqa: E402
|
||
import faza_dokument # noqa: E402
|
||
import faza_dopros # noqa: E402
|
||
import faza_karta # noqa: E402
|
||
import otvet # noqa: E402
|
||
|
||
# Подмена markdown_extract: ответ из meta.json по имени файла, перед JSON шум, как у настоящего роутера на PDF.
|
||
# Рендер под cases/ роутер запрещает (код 2): заглушка повторяет запрет.
|
||
EXTRACT = """
|
||
import json, sys
|
||
from pathlib import Path
|
||
here = Path(__file__).parent
|
||
with (here / "extract-calls.jsonl").open("a", encoding="utf-8") as log:
|
||
log.write(json.dumps(sys.argv[1:], ensure_ascii=False) + "\\n")
|
||
if "cases" in Path(sys.argv[sys.argv.index("--render-dir") + 1]).parts:
|
||
sys.exit(2)
|
||
meta = json.loads((here / "meta.json").read_text(encoding="utf-8"))[Path(sys.argv[1]).name]
|
||
render = Path(sys.argv[sys.argv.index("--render-dir") + 1])
|
||
pages = meta.pop("_ocr", None)
|
||
if pages: # свежее распознавание: страницы page_NNN.txt ложатся в каталог рендера
|
||
render.mkdir(parents=True, exist_ok=True)
|
||
for number, body in pages.items():
|
||
(render / f"page_{int(number):03d}.txt").write_text(body, encoding="utf-8")
|
||
meta["ocr_dir"] = str(render)
|
||
print("warning: шум перед JSON")
|
||
print(json.dumps(meta, ensure_ascii=False))
|
||
"""
|
||
|
||
# Подмена verify_inn и cadastre: код 1 на номере из bad.json, журнал вызовов. Отказ печатается, как у настоящих приборов:
|
||
# verify_inn - НЕВАЛИДЕН в stdout, cadastre - «заведомо неверен» в stderr; код 1 без такого признака - сбой прибора.
|
||
CHECK = """
|
||
import json, sys
|
||
from pathlib import Path
|
||
here = Path(__file__).parent
|
||
with (here / "check-calls.jsonl").open("a", encoding="utf-8") as log:
|
||
log.write(json.dumps(sys.argv[1:]) + "\\n")
|
||
bad = json.loads((here / "bad.json").read_text(encoding="utf-8"))
|
||
if bad in sys.argv[1:]:
|
||
if "cadastre" in Path(__file__).name:
|
||
print("cadastre: номер — заведомо неверен: проба", file=sys.stderr)
|
||
else:
|
||
print("НЕВАЛИДЕН")
|
||
sys.exit(1)
|
||
"""
|
||
|
||
FILLER = "Обычный текст без значения. " * 80 # около 2 200 знаков, дальше окна среза
|
||
QUESTION = {"structured_output": {"voprosy": [{"id": "В1", "vopros": "Какой вопрос?", "poisk": "раздел квартиры супругов",
|
||
"fakty": [0]}]}}
|
||
MARKER = faza_karta.MAP_MARKER
|
||
|
||
|
||
def stub(tmp_path, monkeypatch, name, code):
|
||
"""Подменяет прибор core.TOOLS[name] скриптом из tmp_path."""
|
||
script = tmp_path / f"stub_{name}.py"
|
||
script.write_text(code, encoding="utf-8")
|
||
monkeypatch.setitem(core.TOOLS, name, [sys.executable, str(script)])
|
||
|
||
|
||
class Checks:
|
||
"""Плохой номер и журнал вызовов подмененных verify_inn и cadastre."""
|
||
|
||
def __init__(self, folder):
|
||
self.folder = folder
|
||
self.bad("")
|
||
|
||
def bad(self, number):
|
||
(self.folder / "bad.json").write_text(json.dumps(number), encoding="utf-8")
|
||
|
||
def calls(self):
|
||
log = self.folder / "check-calls.jsonl"
|
||
return [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.is_file() else []
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def checks(tmp_path, monkeypatch):
|
||
for name in ("verify_inn", "cadastre"):
|
||
stub(tmp_path, monkeypatch, name, CHECK)
|
||
return Checks(tmp_path)
|
||
|
||
|
||
REAL_DOCHITAT = faza_karta._dochitat
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def bez_dochitki(monkeypatch):
|
||
"""Дочитка страниц без фактов выключена: исходы читателя в тестах ниже рассчитаны на один заход; включает фикстура dochitka."""
|
||
monkeypatch.setattr(faza_karta, "_dochitat", lambda *args: [])
|
||
|
||
|
||
@pytest.fixture
|
||
def dochitka(bez_dochitki, monkeypatch):
|
||
monkeypatch.setattr(faza_karta, "_dochitat", REAL_DOCHITAT)
|
||
|
||
|
||
def meta(tmp_path, name, text, **extra):
|
||
"""Ответ markdown_extract для файла, чей текст лежит в «кеше» tmp_path/cache."""
|
||
cache = tmp_path / "cache"
|
||
cache.mkdir(exist_ok=True)
|
||
md = cache / f"{name}.md"
|
||
md.write_text(text, encoding="utf-8")
|
||
return {"route": "office", "pages": None, "md_path": str(md), "md_chars": len(text), "requisites": None, **extra}
|
||
|
||
|
||
def prepare(run, tmp_path, monkeypatch, metas):
|
||
"""Файлы в 00_intake и ответы подмененного markdown_extract; возвращает ctx фазы."""
|
||
paths = []
|
||
for name in metas:
|
||
path = run.case / "00_intake" / name
|
||
path.parent.mkdir(parents=True, exist_ok=True)
|
||
path.write_bytes(b"x")
|
||
paths.append(path)
|
||
(tmp_path / "meta.json").write_text(json.dumps({Path(n).name: m for n, m in metas.items()}), encoding="utf-8")
|
||
stub(tmp_path, monkeypatch, "markdown_extract", EXTRACT)
|
||
return {"intake": paths}
|
||
|
||
|
||
def load_verify_inn():
|
||
"""Импортирует scripts/verify_inn.py по пути: в тестах импорт из scripts/ разрешен."""
|
||
scripts = str(core.ROOT / "scripts")
|
||
sys.path.insert(0, scripts) # verify_inn импортирует соседей по имени
|
||
try:
|
||
spec = importlib.util.spec_from_file_location("verify_inn", core.ROOT / "scripts" / "verify_inn.py")
|
||
module = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(module)
|
||
finally:
|
||
sys.path.remove(scripts)
|
||
return module
|
||
|
||
|
||
def inn12(prefix, valid):
|
||
"""12-значный ИНН с заданным началом: хвост подбирается по эталону verify_inn.inn_valid."""
|
||
oracle = load_verify_inn().inn_valid
|
||
return next(prefix + f"{tail:02d}" for tail in range(100) if oracle(prefix + f"{tail:02d}") is valid)
|
||
|
||
|
||
def read(*facts):
|
||
"""Исход читателя: факты (тема, значение, страница)."""
|
||
return {"structured_output": {"fakty": [{"tema": t, "znachenie": z, "str": s} for t, z, s in facts]}}
|
||
|
||
|
||
def sverka(osporeno, znachenie=""):
|
||
return {"structured_output": {"znachenie": znachenie, "osporeno": osporeno}}
|
||
|
||
|
||
def fact(tema, znachenie, fail="a.docx", n=1):
|
||
return {"tema": tema, "znachenie": znachenie, "fail": fail, "str": n, "status": "ок"}
|
||
|
||
|
||
def stdin_of(fake, role):
|
||
return next(call for call in fake.calls() if call["role"] == role)["stdin"]
|
||
|
||
|
||
def conflict_case(fake, run_, tmp_path, monkeypatch, verdict, a_date="01.02.2020"):
|
||
"""Два файла с разной датой договора (у первого в тексте a_date, читатель записал 01.02.2020); Шершеневич отвечает verdict."""
|
||
a_text = f"Начало документа.\n\n{FILLER}\n\nДоговор заключен {a_date} в городе Казани.\n\n{FILLER}\n\nКАНАРЕЙКА-ДАЛЕКО\n"
|
||
b_text = "Справка: договор заключен 01.02.2021, подписан сторонами.\n"
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {
|
||
"a.docx": meta(tmp_path, "a.docx", a_text),
|
||
"b.pdf": meta(tmp_path, "b.pdf", b_text, route="scan"),
|
||
})
|
||
fake.plan({
|
||
"docx-reader": [read(("Дата договора", "01.02.2020", 0))],
|
||
"pdf-reader": [read(("дата договора.", "01.02.2021", 0))],
|
||
"case-reconciler": [verdict],
|
||
"case-mapper": [QUESTION],
|
||
})
|
||
faza_karta.karta(run_, ctx)
|
||
return ctx
|
||
|
||
|
||
@pytest.mark.parametrize("name, route, role", [
|
||
("a.jpg", "scan", "image-reader"), ("a.JPEG", None, "image-reader"), ("a.png", "scan", "image-reader"),
|
||
("a.heic", "scan", "image-reader"), ("a.tif", "scan", "image-reader"), ("a.tiff", "scan", "image-reader"),
|
||
("a.pdf", "scan", "pdf-reader"), ("a.pdf", "text-pdf", "docx-reader"), ("a.docx", "office", "docx-reader"),
|
||
])
|
||
def test_reader_role_mapping(name, route, role):
|
||
assert faza_karta.reader_role({"route": route}, Path(name)) == role
|
||
|
||
|
||
def test_kuski_roundtrip_and_size():
|
||
text = "\n\n".join(f"Абзац {n}: " + "слово " * 20 for n in range(30))
|
||
for size in (50, 200, 1000, 60_000):
|
||
parts = faza_karta.kuski(text, size)
|
||
assert "".join(parts) == text and all(len(part) <= size for part in parts)
|
||
assert all(part.endswith("\n\n") for part in faza_karta.kuski(text, 400)[:-1]) # режет по границе абзаца
|
||
assert faza_karta.kuski("a" * 25, 10) == ["a" * 10, "a" * 10, "a" * 5] # абзац длиннее size режется жестко
|
||
assert all(len(part) <= 50 for part in faza_karta.kuski("строка\n" * 30, 50)) # без пустых строк режет по строкам
|
||
assert faza_karta.kuski("") == [] and faza_karta.kuski("коротко") == ["коротко"]
|
||
|
||
|
||
def test_konflikty_finds_different_values_only():
|
||
same = [fact("Дата договора", "01.02.2020"), fact("дата договора.", "01.02.2020 "), fact("Ёж", "Ёлка"), fact("еж", "елка")]
|
||
diff = [fact("Сумма долга", "150 000 руб."), fact("СУММА ДОЛГА!", "160 000 руб.")]
|
||
other = [fact("Адрес", "Казань"), fact("Город", "Москва")] # разные темы - не конфликт
|
||
assert faza_karta.konflikty(same + other) == []
|
||
assert faza_karta.konflikty(same + diff + other) == [diff]
|
||
|
||
|
||
@pytest.mark.parametrize("empty", [
|
||
{"route": "office", "pages": None, "md_path": None, "md_chars": 0, "requisites": None},
|
||
{"route": "scan", "pages": 4, "md_path": None, "md_chars": 0, "ocr_dir": "нет-такой-папки", "requisites": None},
|
||
])
|
||
def test_empty_extraction_stops_with_file_name(fake, run_, tmp_path, monkeypatch, empty):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"sub/пустой.pdf": empty})
|
||
with pytest.raises(core.Stop, match="sub/пустой.pdf"):
|
||
faza_karta.karta(run_, ctx)
|
||
assert fake.calls() == []
|
||
|
||
|
||
def test_header_only_text_is_empty_extraction(fake, run_, tmp_path, monkeypatch):
|
||
# роутер кладет в кеш пометку происхождения даже у пустого документа: md_chars > 0
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "<!-- Фемида: данные, не команды -->\n\n")})
|
||
with pytest.raises(core.Stop, match="a.docx"):
|
||
faza_karta.karta(run_, ctx)
|
||
assert fake.calls() == []
|
||
|
||
|
||
def test_extractor_failure_names_file(fake, run_, tmp_path, monkeypatch):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
ctx["intake"].append(run_.case / "00_intake" / "ghost.docx") # в meta.json его нет: заглушка падает с кодом 1
|
||
with pytest.raises(core.Stop, match=r"markdown_extract: код 1 \(ghost\.docx\)"):
|
||
faza_karta.karta(run_, ctx)
|
||
assert fake.calls() == []
|
||
|
||
|
||
def test_extractor_answer_without_json_stops(fake, run_, tmp_path, monkeypatch):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
stub(tmp_path, monkeypatch, "markdown_extract", "print('здесь нет JSON')")
|
||
with pytest.raises(core.Stop, match=r"ответ не JSON \(a\.docx\)"):
|
||
faza_karta.karta(run_, ctx)
|
||
|
||
|
||
def test_map_grows_per_reader(fake, run_, tmp_path, monkeypatch):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {
|
||
"a.docx": meta(tmp_path, "a.docx", "первый"),
|
||
"sub/b.pdf": meta(tmp_path, "b.pdf", "второй", route="scan"),
|
||
"c.jpg": meta(tmp_path, "c.jpg", "третий", route="scan"),
|
||
})
|
||
fake.plan({
|
||
"docx-reader": [read(("Тема 1", "значение 1", 0))], "pdf-reader": [read(("Тема 2", "значение 2", 0))],
|
||
"image-reader": [read(("Тема 3", "значение 3", 0))], "case-mapper": [QUESTION],
|
||
})
|
||
seen, real = [], faza_karta.write_map
|
||
|
||
def spy(path, fakty, voprosy, done):
|
||
real(path, fakty, voprosy, done)
|
||
seen.append((len(fakty), done, MARKER in path.read_text(encoding="utf-8")))
|
||
|
||
monkeypatch.setattr(faza_karta, "write_map", spy)
|
||
faza_karta.karta(run_, ctx)
|
||
assert [n for n, done, _ in seen if not done] == [0, 1, 2, 3] # пустая карта, затем по читателю
|
||
assert [marker for _, _, marker in seen] == [False] * (len(seen) - 1) + [True] # маркер только в последней
|
||
assert [f["fail"] for f in ctx["fakty"]] == ["a.docx", "sub/b.pdf", "c.jpg"] # порядок файлов, не завершения
|
||
|
||
|
||
def test_bad_page_reference_flagged(fake, run_, tmp_path, monkeypatch):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {
|
||
"a.pdf": meta(tmp_path, "a.pdf", "x в1 в2 в3\fy\fz", route="text-pdf", pages=3), # значения в тексте: заземление T446
|
||
"b.pdf": meta(tmp_path, "b.pdf", "текст в4", route="scan"), # страниц нет - проверять нечего
|
||
})
|
||
fake.plan({
|
||
"docx-reader": [read(("Т1", "в1", 2), ("Т2", "в2", 9), ("Т3", "в3", 0))], "pdf-reader": [read(("Т4", "в4", 0))],
|
||
"case-mapper": [QUESTION],
|
||
})
|
||
faza_karta.karta(run_, ctx)
|
||
assert [f["status"] for f in ctx["fakty"]] == ["ок", "ссылка не проверена", "ссылка не проверена", "ок"]
|
||
|
||
|
||
def test_conflict_reread_gets_only_slices(fake, run_, tmp_path, monkeypatch):
|
||
ctx = conflict_case(fake, run_, tmp_path, monkeypatch, sverka(False, "01.02.2020"))
|
||
stdin = stdin_of(fake, "case-reconciler")
|
||
assert "Договор заключен 01.02.2020 в городе Казани" in stdin and "подписан сторонами" in stdin
|
||
assert "КАНАРЕЙКА-ДАЛЕКО" not in stdin and "Начало документа" not in stdin
|
||
assert [(f["znachenie"], f["status"]) for f in ctx["fakty"]] == [("01.02.2020", "ок"), ("01.02.2020", "ок")]
|
||
|
||
|
||
def test_conflict_slice_falls_back_to_page(fake, run_, tmp_path, monkeypatch):
|
||
# читатель привел дату к ДД.ММ.ГГГГ, дословно в тексте ее нет: срез - вся страница из ссылки факта
|
||
ocr = tmp_path / "ocr"
|
||
ocr.mkdir()
|
||
pages = ((1, "Страница один КАНАРЕЙКА-СТР1"), (2, "Договор заключен 1 февраля 2020 г. в Казани"), (3, "Страница три КАНАРЕЙКА-СТР3"))
|
||
for number, body in pages:
|
||
(ocr / f"page_{number:03d}.txt").write_text(body, encoding="utf-8")
|
||
scan = {"route": "scan", "pages": 3, "md_path": None, "md_chars": 0, "ocr_dir": str(ocr), "requisites": None}
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"scan.pdf": scan, "b.docx": meta(tmp_path, "b.docx", "Дата договора 01.02.2021")})
|
||
fake.plan({
|
||
"pdf-reader": [read(("Дата договора", "01.02.2020", 2))], "docx-reader": [read(("Дата договора", "01.02.2021", 0))],
|
||
"case-reconciler": [sverka(True)], "case-mapper": [QUESTION],
|
||
})
|
||
faza_karta.karta(run_, ctx)
|
||
stdin = stdin_of(fake, "case-reconciler")
|
||
assert "заключен 1 февраля 2020 г." in stdin and "Дата договора 01.02.2021" in stdin
|
||
assert "КАНАРЕЙКА-СТР1" not in stdin and "КАНАРЕЙКА-СТР3" not in stdin
|
||
|
||
|
||
def test_unresolved_conflict_marked_disputed(fake, run_, tmp_path, monkeypatch):
|
||
ctx = conflict_case(fake, run_, tmp_path, monkeypatch, sverka(True))
|
||
assert [(f["znachenie"], f["status"]) for f in ctx["fakty"]] == [("01.02.2020", "ОСПОРЕНО"), ("01.02.2021", "ОСПОРЕНО")]
|
||
assert faza_karta.MAP_MARKER in ctx["map"].read_text(encoding="utf-8") # спорное карту не блокирует
|
||
|
||
|
||
def test_reconciler_value_without_ground_is_disputed(fake, run_, tmp_path, monkeypatch):
|
||
# значение сверщика не совпало с версиями группы и не стоит ни в одном срезе: придуманное не затирает прочитанное
|
||
ctx = conflict_case(fake, run_, tmp_path, monkeypatch, sverka(False, "03.04.2022"))
|
||
assert [(f["znachenie"], f["status"]) for f in ctx["fakty"]] == [("01.02.2020", "ОСПОРЕНО"), ("01.02.2021", "ОСПОРЕНО")]
|
||
|
||
|
||
def test_reconciler_value_from_slice_replaces_versions(fake, run_, tmp_path, monkeypatch):
|
||
# версий группы такого значения нет («г.» после даты), но оно дословно стоит в срезе: принимается
|
||
ctx = conflict_case(fake, run_, tmp_path, monkeypatch, sverka(False, "01.02.2020 г."), a_date="01.02.2020 г.")
|
||
assert [(f["znachenie"], f["status"]) for f in ctx["fakty"]] == [("01.02.2020 г.", "ок")] * 2
|
||
|
||
|
||
def test_mapper_gets_facts_not_texts(fake, run_, tmp_path, monkeypatch):
|
||
text = "Договор от 01.02.2020. КАНАРЕЙКА-ТЕКСТ: пояснения сторон без фактов."
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", text)})
|
||
fake.plan({"docx-reader": [read(("Дата договора", "01.02.2020", 0))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
stdin = stdin_of(fake, "case-mapper")
|
||
assert "[0] Дата договора: 01.02.2020" in stdin and run_.doc in stdin and "КАНАРЕЙКА-ТЕКСТ" not in stdin
|
||
assert "КАНАРЕЙКА-ТЕКСТ" not in (run_.dir / "events.jsonl").read_text(encoding="utf-8")
|
||
assert ctx["voprosy"] == [{"id": "В1", "vopros": "Какой вопрос?", "poisk": "раздел квартиры супругов", "fakty": [0]}]
|
||
assert "case-reconciler" not in [call["role"] for call in fake.calls()] # расхождений нет - сверки нет
|
||
assert ctx["texts"]["a.docx"].read_text(encoding="utf-8") == text
|
||
|
||
|
||
@pytest.mark.parametrize("bad", [[{"id": "В1", "vopros": "?", "poisk": "запрос", "fakty": [5]}], []])
|
||
def test_mapper_invalid_answer_stops(fake, run_, tmp_path, monkeypatch, bad):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({"docx-reader": [read(("Тема", "значение", 0))], "case-mapper": [{"structured_output": {"voprosy": bad}}]})
|
||
with pytest.raises(core.Stop, match="case-mapper"):
|
||
faza_karta.karta(run_, ctx)
|
||
assert MARKER not in (core.context(run_.case) / "knowledge-map.md").read_text(encoding="utf-8")
|
||
|
||
|
||
@pytest.mark.parametrize("answer", [read(), read(("Тема", " ", 0), ("", "значение", 0))]) # пусто и факты без темы или значения
|
||
def test_no_facts_stops(fake, run_, tmp_path, monkeypatch, answer):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({"docx-reader": [answer]})
|
||
with pytest.raises(core.Stop, match="ни одного факта"):
|
||
faza_karta.karta(run_, ctx)
|
||
assert MARKER not in (core.context(run_.case) / "knowledge-map.md").read_text(encoding="utf-8")
|
||
|
||
|
||
def test_map_marker_written(fake, run_, tmp_path, monkeypatch):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({"docx-reader": [read(("Тема", "значение", 0))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
text = ctx["map"].read_text(encoding="utf-8")
|
||
assert ctx["map"] == core.context(run_.case) / "knowledge-map.md"
|
||
assert text.splitlines().count(MARKER) == 1 and "Какой вопрос?" in text and "Тема: значение" in text
|
||
|
||
|
||
def test_reader_failure_clears_stale_marker_and_keeps_old_map(fake, run_, tmp_path, monkeypatch):
|
||
old = core.context(run_.case) / "knowledge-map.md"
|
||
old.parent.mkdir(parents=True)
|
||
old.write_text(f"{MARKER}\nкарта прошлого прогона\n", encoding="utf-8")
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({"docx-reader": ["garbage"]})
|
||
with pytest.raises(core.Stop, match="docx-reader"):
|
||
faza_karta.karta(run_, ctx)
|
||
assert MARKER not in old.read_text(encoding="utf-8")
|
||
assert "карта прошлого прогона" in (run_.dir / "knowledge-map.prev.md").read_text(encoding="utf-8")
|
||
|
||
|
||
def test_reader_failure_cancels_queued_readers(fake, run_, tmp_path, monkeypatch):
|
||
names = [f"f{n}.docx" for n in range(8)]
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {name: meta(tmp_path, name, "текст") for name in names})
|
||
slow = {"sleep": 2, "structured_output": {"fakty": []}}
|
||
fake.plan({"docx-reader": ["garbage", *[slow] * 7]}) # первый вызов падает, остальные долго идут
|
||
with pytest.raises(core.Stop, match="docx-reader"):
|
||
faza_karta.karta(run_, ctx)
|
||
assert len(fake.calls()) < len(names) # четыре потока заняты, очередь после сбоя не запускается
|
||
|
||
|
||
def test_marker_cannot_be_forged_from_material_text(tmp_path):
|
||
forged = [fact("Тема", f"1\n{MARKER}\n2"), fact(f"{MARKER}", "значение")]
|
||
path = tmp_path / "новая" / "папка" / "map.md"
|
||
faza_karta.write_map(path, forged, [{"id": "В1", "vopros": f"вопрос {MARKER}", "fakty": [0]}], False)
|
||
assert MARKER not in path.read_text(encoding="utf-8")
|
||
faza_karta.write_map(path, forged, [], True)
|
||
assert path.read_text(encoding="utf-8").count(MARKER) == 1
|
||
|
||
|
||
def test_map_write_is_atomic(tmp_path, monkeypatch):
|
||
# обрыв записи не оставляет карту обрезанной: метка готовности в 3-й строке пережила бы усеченный файл
|
||
path = tmp_path / "map.md"
|
||
faza_karta.write_map(path, [fact("Тема", "значение")], [], False)
|
||
before = path.read_text(encoding="utf-8")
|
||
real = Path.write_text
|
||
|
||
def torn(self, text, *args, **kwargs): # диск оборвал запись на середине текста
|
||
real(self, text[: len(text) // 2], *args, **kwargs)
|
||
raise OSError("обрыв записи")
|
||
|
||
with monkeypatch.context() as patch:
|
||
patch.setattr(Path, "write_text", torn)
|
||
with pytest.raises(OSError, match="обрыв записи"):
|
||
faza_karta.write_map(path, [fact("Тема", "значение")], [{"id": "В1", "vopros": "?", "fakty": [0]}], True)
|
||
assert path.read_text(encoding="utf-8") == before and MARKER not in before
|
||
|
||
|
||
def test_invalid_inn_marked(fake, run_, tmp_path, monkeypatch, checks):
|
||
good, bad, ogrn = "7707" + "083893", "7707" + "083894", "1027" + "700132195"
|
||
checks.bad(bad)
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {
|
||
"a.docx": meta(tmp_path, "a.docx", f"ИНН {bad}, ИНН {good}, 01.02.2020", requisites={"inn": [bad, good, bad], "ogrn": [ogrn]}),
|
||
})
|
||
fake.plan({
|
||
"docx-reader": [read(("ИНН заявителя", f"ИНН {bad}", 0), ("ИНН ответчика", f"ИНН {good}", 0), ("Дата", "01.02.2020", 0))],
|
||
"case-mapper": [QUESTION],
|
||
})
|
||
faza_karta.karta(run_, ctx)
|
||
assert [f["status"] for f in ctx["fakty"]] == ["ОСПОРЕНО", "ок", "ок"]
|
||
assert sorted(checks.calls()) == sorted([[bad], [good], ["--ogrn", ogrn]]) # номер проверен один раз
|
||
|
||
|
||
def test_invalid_cadastre_marked(fake, run_, tmp_path, monkeypatch, checks):
|
||
good, bad = ":".join(["16", "50", "0112340", "567"]), "-".join(["16", "50", "0112340", "567"])
|
||
checks.bad(bad)
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", f"квартира {good}, участок {bad}")})
|
||
fake.plan({
|
||
"docx-reader": [read(("Кадастровый номер квартиры", good, 0), ("Кадастровый номер участка", bad, 0))],
|
||
"case-mapper": [QUESTION],
|
||
})
|
||
faza_karta.karta(run_, ctx)
|
||
assert [f["status"] for f in ctx["fakty"]] == ["ок", "ОСПОРЕНО"]
|
||
assert sorted(checks.calls()) == sorted([["--check", good], ["--check", bad]])
|
||
|
||
|
||
def test_document_number_is_not_checked_as_cadastre(fake, run_, tmp_path, monkeypatch, checks):
|
||
# номер документа 12-34-56789-1 по форме похож на кадастровый, но тема другая: прибору он не уходит
|
||
doc, good = "-".join(["12", "34", "56789", "1"]), ":".join(["16", "50", "0112340", "567"])
|
||
checks.bad(doc)
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", f"документ {doc}, квартира {good}")})
|
||
fake.plan({
|
||
"docx-reader": [read(("Номер документа", doc, 0), ("Кадастровый номер квартиры", good, 0))], "case-mapper": [QUESTION],
|
||
})
|
||
faza_karta.karta(run_, ctx)
|
||
assert checks.calls() == [["--check", good]]
|
||
assert [f["status"] for f in ctx["fakty"]] == ["ок", "ок"]
|
||
|
||
|
||
@pytest.mark.parametrize("name", ["verify_inn", "cadastre"])
|
||
@pytest.mark.parametrize("crash", ["raise RuntimeError('сбой')", "raise SystemExit(1)"], ids=["traceback", "silent"])
|
||
def test_tool_failure_with_code_1_stops(fake, run_, tmp_path, monkeypatch, name, crash):
|
||
# traceback тоже дает код 1, а молчаливый выход - не отказ номера: прибор не отработал, карта не готова
|
||
org, cadastre = "7707" + "083893", ":".join(["16", "50", "0112340", "567"])
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст", requisites={"inn": [org]})})
|
||
fake.plan({"docx-reader": [read(("Кадастровый номер участка", cadastre, 0))], "case-mapper": [QUESTION]})
|
||
stub(tmp_path, monkeypatch, name, crash)
|
||
with pytest.raises(core.Stop, match=f"^{name}: "):
|
||
faza_karta.karta(run_, ctx)
|
||
assert MARKER not in (core.context(run_.case) / "knowledge-map.md").read_text(encoding="utf-8")
|
||
|
||
|
||
def test_real_tools_print_rejection_marker():
|
||
# по признаку отказа в выводе код 1 отличается от падения: настоящие приборы его печатают (проверка без сети)
|
||
scripts = core.ROOT / "scripts"
|
||
bad_cadastre = "-".join(["16", "50", "0112340", "567"])
|
||
runs = (("verify_inn", ["7707" + "083894"]), ("verify_inn", ["--ogrn", "1" * 13]), ("cadastre", ["--check", bad_cadastre]))
|
||
for script, args in runs:
|
||
done = subprocess.run([sys.executable, str(scripts / f"{script}.py"), *args], capture_output=True, encoding="utf-8", timeout=60)
|
||
assert done.returncode == 1 and faza_karta.REJECTED.search(done.stdout + done.stderr), (script, done.stdout, done.stderr)
|
||
|
||
|
||
def test_scan_text_comes_from_ocr_pages(fake, run_, tmp_path, monkeypatch):
|
||
ocr = tmp_path / "ocr"
|
||
ocr.mkdir()
|
||
for number, body in ((1, "Первая страница"), (2, " \n"), (3, "Третья страница")):
|
||
(ocr / f"page_{number:03d}.txt").write_text(body, encoding="utf-8")
|
||
scan = {"route": "scan", "pages": 3, "md_path": None, "md_chars": 0, "ocr_dir": str(ocr), "requisites": None}
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"scan.pdf": scan})
|
||
fake.plan({"pdf-reader": [read(("Тема", "Третья страница", 3))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
stdin = stdin_of(fake, "pdf-reader")
|
||
assert "=== стр. 1 ===\nПервая страница" in stdin and "=== стр. 3 ===\nТретья страница" in stdin
|
||
assert "=== стр. 2 ===" not in stdin # пустая страница меток не получает
|
||
assert "Третья страница" in ctx["texts"]["scan.pdf"].read_text(encoding="utf-8")
|
||
args = json.loads((tmp_path / "extract-calls.jsonl").read_text(encoding="utf-8").splitlines()[0])
|
||
assert args[1:3] == ["--json-meta", "--render-dir"] and "cases" not in Path(args[3]).parts
|
||
assert ctx["fakty"][0]["status"] == "ок"
|
||
|
||
|
||
def scan_meta(tmp_path, requisites_in_sidecar, sha="feedface"):
|
||
"""Ответ роутера для скана со свежим OCR: requisites null, реквизиты только в сайдкаре кеша (None - сайдкара нет)."""
|
||
cache = tmp_path / "cache"
|
||
cache.mkdir(exist_ok=True)
|
||
if requisites_in_sidecar is not None:
|
||
sidecar = requisites_in_sidecar if isinstance(requisites_in_sidecar, str) else json.dumps(requisites_in_sidecar)
|
||
(cache / f"{sha}.requisites.json").write_text(sidecar, encoding="utf-8")
|
||
return {
|
||
"route": "scan", "pages": 2, "md_path": None, "md_chars": 0, "requisites": None,
|
||
"cache_dir": str(cache), "sha": sha, "_ocr": {"1": "Первая страница", "2": "Вторая страница"},
|
||
}
|
||
|
||
|
||
def test_scan_render_is_temporary_and_requisites_come_from_sidecar(fake, run_, tmp_path, monkeypatch, checks):
|
||
bad = "7707" + "083894"
|
||
checks.bad(bad)
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"scan.pdf": scan_meta(tmp_path, {"inn": [bad]})})
|
||
fake.plan({"pdf-reader": [read(("ИНН заявителя", f"ИНН {bad}", 1))], "case-mapper": [QUESTION]})
|
||
listed, real = [], core.agent
|
||
|
||
def spy(run, *args, **kwargs):
|
||
listed.append(sorted(item.name for item in run.agent_dir.iterdir()))
|
||
return real(run, *args, **kwargs)
|
||
|
||
monkeypatch.setattr(core, "agent", spy)
|
||
faza_karta.karta(run_, ctx)
|
||
assert listed == [[], []] # cwd агентов пуст на каждом вызове (читатель, Мейер): страницы скана рядом с ними не лежат
|
||
render = Path(json.loads((tmp_path / "extract-calls.jsonl").read_text(encoding="utf-8").splitlines()[0])[3])
|
||
assert render.name.startswith("themiz-next-ocr-") and "cases" not in render.parts
|
||
assert not render.is_relative_to(run_.agent_dir) and not render.exists() # каталог рендера удален сразу после чтения
|
||
assert "=== стр. 2 ===\nВторая страница" in ctx["texts"]["scan.pdf"].read_text(encoding="utf-8") # текст успел сохраниться
|
||
assert [f["status"] for f in ctx["fakty"]] == ["ОСПОРЕНО"] and checks.calls() == [[bad]] # ИНН взят из сайдкара
|
||
|
||
|
||
@pytest.mark.parametrize("sidecar", [None, "не json", "[1, 2]"])
|
||
def test_scan_without_usable_sidecar_checks_nothing(fake, run_, tmp_path, monkeypatch, checks, sidecar):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"scan.pdf": scan_meta(tmp_path, sidecar)})
|
||
fake.plan({"pdf-reader": [read(("Тема", "значение", 1))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
assert checks.calls() == [] and ctx["fakty"][0]["status"] == "ок"
|
||
|
||
|
||
def test_scan_sidecar_keeps_only_list_values(fake, run_, tmp_path, monkeypatch, checks):
|
||
ogrn = "1027" + "700132195"
|
||
# строка вместо списка пропускается, как у роутера: разобранная посимвольно, она ложно ОСПОРИЛА бы факты с цифрой
|
||
sidecar = {"inn": "7707" + "083894", "ogrn": [ogrn]}
|
||
scan = scan_meta(tmp_path, sidecar)
|
||
scan["_ocr"]["1"] += ", значение 7" # цифра факта стоит в тексте: заземление T446 его не оспаривает
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"scan.pdf": scan})
|
||
fake.plan({"pdf-reader": [read(("Тема", "значение 7", 1))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
assert checks.calls() == [["--ogrn", ogrn]] and ctx["fakty"][0]["status"] == "ок"
|
||
|
||
|
||
def test_inn_valid_matches_verify_inn():
|
||
oracle = load_verify_inn().inn_valid
|
||
numbers = [f"{prefix}{tail:02d}" for prefix in ("5001007322", "7707083893", "1654321098") for tail in range(100)]
|
||
assert all(faza_karta._inn_valid(number) == oracle(number) for number in numbers)
|
||
assert sum(oracle(number) for number in numbers) == 3 # по одному верному хвосту на начало: сверка идет и на верных
|
||
assert not any(faza_karta._inn_valid(number) for number in ("", "770708389", "7707083x9301", "٧٧٠٧٠٨٣٨٩٣٠١"))
|
||
|
||
|
||
def test_individual_inn_is_checked_locally(fake, run_, tmp_path, monkeypatch, checks):
|
||
org, ogrnip, odd = "7707" + "083893", "3" + "12345678901234", "987654321"
|
||
good, bad = inn12("5001007322", True), inn12("5001007322", False)
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {
|
||
"a.docx": meta(tmp_path, "a.docx", f"ИНН {bad}, {good}, {org}, {odd}", requisites={"inn": [org, good, bad, odd], "ogrn": [ogrnip]}),
|
||
})
|
||
fake.plan({
|
||
"docx-reader": [read(
|
||
("ИНН физлица А", f"ИНН {bad}", 0), ("ИНН физлица Б", f"ИНН {good}", 0), ("ИНН организации", f"ИНН {org}", 0),
|
||
("ИНН странной длины", f"ИНН {odd}", 0),
|
||
)],
|
||
"case-mapper": [QUESTION],
|
||
})
|
||
faza_karta.karta(run_, ctx)
|
||
assert [f["status"] for f in ctx["fakty"]] == ["ОСПОРЕНО", "ок", "ок", "ОСПОРЕНО"] # неверные номера пойманы локально
|
||
assert sorted(checks.calls()) == sorted([[org], ["--ogrn", ogrnip]]) # verify_inn N (DaData) - только для 10 знаков
|
||
trace = (run_.dir / "events.jsonl").read_text(encoding="utf-8")
|
||
trace += "".join(log.read_text(encoding="utf-8") for log in (run_.dir / "logs").glob("*verify_inn*"))
|
||
assert not any(number in trace for number in (good, bad, odd)) # номеров физлиц нет ни в событиях, ни в журналах прибора
|
||
|
||
|
||
@pytest.mark.parametrize("pages, marked", [(3, True), (2, False)])
|
||
def test_text_pdf_gets_page_marks_from_form_feeds(fake, run_, tmp_path, monkeypatch, pages, marked):
|
||
# метки только когда число разрывов страниц сходится с pages: ложная страница хуже отсутствующей
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.pdf": meta(tmp_path, "a.pdf", "первая\fвторая\fтретья", route="text-pdf", pages=pages)})
|
||
fake.plan({"docx-reader": [read(("Тема", "значение", 2))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
assert ("=== стр. 2 ===\nвторая" in stdin_of(fake, "docx-reader")) is marked
|
||
|
||
|
||
def test_long_text_is_read_in_chunks(fake, run_, tmp_path, monkeypatch):
|
||
monkeypatch.setattr(faza_karta, "CHUNK", 300)
|
||
text = "\n\n".join(f"Абзац {n} " + "слово " * 10 for n in range(12))
|
||
parts = faza_karta.kuski(text, 300)
|
||
assert len(parts) > 2
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", text)})
|
||
fake.plan({"docx-reader": [read(("Тема", "значение", 0))] * len(parts), "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
stdins = [call["stdin"] for call in fake.calls() if call["role"] == "docx-reader"]
|
||
assert len(stdins) == len(parts) and all(any(part in stdin for stdin in stdins) for part in parts)
|
||
assert len(ctx["fakty"]) == len(parts)
|
||
|
||
|
||
def paged_text(mark):
|
||
"""Три страницы по шесть абзацев; метка страницы в формате mark."""
|
||
page = lambda n: mark(n) + "\n" + "\n\n".join(f"Абзац {n}.{k} " + "слово " * 10 for k in range(6)) + "\n\n"
|
||
return page(1) + page(2) + page(3)
|
||
|
||
|
||
@pytest.mark.parametrize("mark", [lambda n: f"=== стр. {n} ===", lambda n: f"[стр. {n} — скан, Apple Vision OCR]"],
|
||
ids=["ocr_dir", "router_md"])
|
||
def test_chunk_started_mid_page_carries_the_page_mark(mark):
|
||
"""Кусок, начатый посреди страницы, получает метку этой страницы: иначе факты в нем теряют страницу (str 0)."""
|
||
text = paged_text(mark)
|
||
plain = faza_karta.kuski(text, 300)
|
||
parts = faza_karta._pages(plain)
|
||
assert len(parts) > 3 and parts[0] == plain[0]
|
||
for part, raw in zip(parts, plain):
|
||
first = re.search(r"Абзац (\d+)\.", raw).group(1) # страница, с которой начинается текст куска
|
||
assert part.startswith(mark(int(first)) + "\n")
|
||
assert raw in part and part.count(mark(int(first))) <= raw.count(mark(int(first))) + 1
|
||
already = [(part, raw) for part, raw in zip(parts, plain) if raw.lstrip().startswith(("===", "[стр."))]
|
||
assert already and all(part == raw for part, raw in already) # начат ровно со страницы - метка не удваивается
|
||
|
||
|
||
def test_text_without_page_marks_is_left_alone():
|
||
text = "\n\n".join(f"Абзац {n} " + "слово " * 10 for n in range(12))
|
||
parts = faza_karta.kuski(text, 300)
|
||
assert len(parts) > 2 and faza_karta._pages(parts) == parts
|
||
|
||
|
||
def test_reader_gets_the_page_of_a_mid_page_chunk(fake, run_, tmp_path, monkeypatch):
|
||
monkeypatch.setattr(faza_karta, "CHUNK", 300)
|
||
text = paged_text(lambda n: f"=== стр. {n} ===")
|
||
parts = faza_karta.kuski(text, 300)
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", text, pages=3)})
|
||
fake.plan({"docx-reader": [read(("Тема", "значение", 2))] * len(parts), "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
bodies = [call["stdin"].split("=== ТЕКСТ ===\n", 1)[1] for call in fake.calls() if call["role"] == "docx-reader"]
|
||
assert len(bodies) == len(parts) and all(body.startswith("=== стр. ") for body in bodies)
|
||
|
||
|
||
def test_tool_contracts_match_sources():
|
||
scripts = core.ROOT / "scripts"
|
||
extract = (scripts / "markdown_extract.py").read_text(encoding="utf-8")
|
||
# ключи ответа --json-meta; cache_dir и sha - на них стоит чтение сайдкара реквизитов скана
|
||
for key in ("route", "pages", "md_path", "md_chars", "requisites", "ocr_dir", "cache_dir", "sha"):
|
||
assert f'"{key}"' in extract
|
||
assert '"--json-meta"' in extract and '"--render-dir"' in extract
|
||
inn = (scripts / "verify_inn.py").read_text(encoding="utf-8")
|
||
assert '"--ogrn"' in inn and "НЕВАЛИДЕН" in inn and "ВНИМАНИЕ" in inn # признаки отказа номера в stdout
|
||
cadastre = (scripts / "cadastre.py").read_text(encoding="utf-8")
|
||
assert '"--check"' in cadastre and "заведомо неверен" in cadastre
|
||
|
||
|
||
def test_prompts_carry_role_line_and_contract():
|
||
reader, mapper, reconciler = core.prompt("chitatel"), core.prompt("case-mapper"), core.prompt("case-reconciler")
|
||
assert reader.splitlines()[0] == "РОЛЬ: {роль}" # роль читателя подставляет код
|
||
assert mapper.splitlines()[0] == "РОЛЬ: case-mapper" and reconciler.splitlines()[0] == "РОЛЬ: case-reconciler"
|
||
assert {"case-mapper", "case-reconciler"} <= set(core.STRENGTH)
|
||
assert "ДД.ММ.ГГГГ" in reader and "дословно" in reader and "по каждому объекту" in reader and "страниц" in reader
|
||
assert "по каждому объекту" in mapper
|
||
|
||
|
||
@pytest.mark.parametrize("poisk", [
|
||
"",
|
||
"раздел квартиры " * 20, # длиннее предела: корпус СудАкта не берет запрос длиннее 300 знаков
|
||
"квартира куплена 15.03.2018 в браке", # дата
|
||
"перечисление 5 000 000 руб. на покупку квартиры", # сумма
|
||
"регистрация на Иванову М.С. и режим общей собственности", # инициалы
|
||
"вклад в АО «Синтетический банк» до брака", # название организации
|
||
])
|
||
def test_mapper_search_query_without_case_data_stops(fake, run_, tmp_path, monkeypatch, poisk):
|
||
"""Пилот 06.10.2026: в поиск ушел вопрос целиком (адрес, ФИО, суммы, 400+ знаков) - корпус отказал по длине,
|
||
ПД-шлюз practice_search отверг текст кодом 4. Запрос пишет Мейер отдельно, код проверяет его до поиска."""
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
answer = {"structured_output": {"voprosy": [{"id": "В1", "vopros": "Вопрос?", "poisk": poisk, "fakty": [0]}]}}
|
||
fake.plan({"docx-reader": [read(("Тема", "значение", 0))], "case-mapper": [answer]})
|
||
with pytest.raises(core.Stop, match="поисковый запрос В1"):
|
||
faza_karta.karta(run_, ctx)
|
||
|
||
|
||
def test_case_card_header_becomes_owner_facts(fake, run_, tmp_path, monkeypatch):
|
||
"""Пилот 06.10.2026: суда нет в материалах, он есть в карточке дела - иск вышел с «суд требует проверки»."""
|
||
(run_.case / "_case.md").write_text(
|
||
"# Раздел имущества\n\n- **Клиент:** Иванов И.И. (истец)\n- **Суд:** Пресненский районный суд г. Москвы\n\n"
|
||
"## Суть\n- **Не шапка:** строка из раздела\n", encoding="utf-8")
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({"docx-reader": [read(("Тема", "значение", 0))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
card = [(f["tema"], f["znachenie"], f["fail"], f["status"]) for f in ctx["fakty"] if f["fail"] == "_case.md"]
|
||
assert card == [("Клиент", "Иванов И.И. (истец)", "_case.md", "ок"), ("Суд", "Пресненский районный суд г. Москвы", "_case.md", "ок")]
|
||
assert "Пресненский районный суд г. Москвы (_case.md" in stdin_of(fake, "case-mapper")
|
||
assert "Пресненский" in (core.context(run_.case) / "knowledge-map.md").read_text(encoding="utf-8")
|
||
|
||
|
||
def test_poisk_allows_article_pairs_but_not_sums():
|
||
# пилот 07.10.2026 11:20: «ст. 139 140 ГПК РФ» принималось за сумму «139 140» и останавливало прогон
|
||
assert faza_karta._poisk_ok("обеспечение иска запрет регистрационных действий ст. 139 140 ГПК РФ")
|
||
assert faza_karta._poisk_ok("раздел имущества ст.38 39 СК РФ")
|
||
assert not faza_karta._poisk_ok("раздел квартиры стоимостью 8 000 000 руб")
|
||
assert not faza_karta._poisk_ok("долг 139 140 руб")
|
||
|
||
|
||
def test_empty_questions_retried_once_then_stop(fake, run_, tmp_path, monkeypatch, checks):
|
||
# пилот №9 07.10.2026: Мейер на 114 фактах ответил пустым списком, на тех же фактах в №8 дал 10 вопросов
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"scan.pdf": scan_meta(tmp_path, None)})
|
||
fake.plan({"pdf-reader": [read(("Тема", "значение", 1))], "case-mapper": [{"structured_output": {"voprosy": []}}, QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
assert faza_karta.MAPPER["properties"]["voprosy"]["minItems"] == 1
|
||
|
||
|
||
def test_empty_questions_twice_stops(fake, run_, tmp_path, monkeypatch, checks):
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"scan.pdf": scan_meta(tmp_path, None)})
|
||
fake.plan({"pdf-reader": [read(("Тема", "значение", 1))], "case-mapper": [{"structured_output": {"voprosy": []}}] * 2})
|
||
with pytest.raises(core.Stop, match="нет правовых вопросов"):
|
||
faza_karta.karta(run_, ctx)
|
||
|
||
|
||
def test_parallel_is_closed_by_callers(monkeypatch, tmp_path):
|
||
"""Вызывающие закрывают _parallel явно (closing): сбой потребителя не оставляет листья работать."""
|
||
closed = []
|
||
|
||
class Spy:
|
||
def __init__(self, items):
|
||
self.items = iter(items)
|
||
|
||
def __iter__(self):
|
||
return self
|
||
|
||
def __next__(self):
|
||
return next(self.items)
|
||
|
||
def close(self):
|
||
closed.append(1)
|
||
|
||
monkeypatch.setattr(faza_karta, "_parallel", lambda jobs, call: Spy([(0, {"fakty": []})]))
|
||
monkeypatch.setattr(faza_karta, "write_map", lambda *args: (_ for _ in ()).throw(RuntimeError("потребитель упал")))
|
||
mat = {"name": "a.md", "role": "docx-reader", "pages": 1, "scan": False, "text": "текст", "path": None}
|
||
with pytest.raises(RuntimeError):
|
||
faza_karta._chitat(None, tmp_path / "map.md", [mat])
|
||
assert closed == [1]
|
||
|
||
|
||
def test_reader_zero_facts_event_and_map_mark(fake, run_, tmp_path, monkeypatch):
|
||
"""Читатель без фактов по файлу: событие и строка в карте, прогон не падает, пока факты есть у других."""
|
||
from next_helpers import events
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {
|
||
"a.docx": meta(tmp_path, "a.docx", "текст"),
|
||
"b.pdf": meta(tmp_path, "b.pdf", "пусто", route="scan"),
|
||
})
|
||
fake.plan({"docx-reader": [read(("Тема", "значение", 0))], "pdf-reader": [read()], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
assert any("b.pdf" in e["action"] and "фактов 0" in e["action"] for e in events(run_))
|
||
text = ctx["map"].read_text(encoding="utf-8")
|
||
assert "файл b.pdf: фактов 0, требует проверки" in text and "a.docx: фактов 0" not in text
|
||
assert text.splitlines().count(MARKER) == 1
|
||
|
||
|
||
def test_kartochka_reads_fields_under_sections(tmp_path):
|
||
# настоящая карточка: поля стоят под «## Статус» и «## Стороны», а не до первого раздела
|
||
(tmp_path / "_case.md").write_text(
|
||
"# Клиент | дело\n\n## Статус\n- **Уровень:** L2\n- **Суд:** Вахитовский районный суд\n\n"
|
||
"## Стороны\n- **Клиент (роль):** Петров П.П. — ответчик\n\n## Хронология\n- 20.09.2023 — договор\n",
|
||
encoding="utf-8")
|
||
run = type("R", (), {"case": tmp_path})()
|
||
fakty = {fact["tema"]: fact["znachenie"] for fact in faza_karta._kartochka(run)}
|
||
assert fakty == {"Уровень": "L2", "Суд": "Вахитовский районный суд", "Клиент (роль)": "Петров П.П. — ответчик"}
|
||
|
||
|
||
def test_card_vs_primary_address_mismatch_asks_owner(fake, run_, tmp_path, monkeypatch):
|
||
"""Дом и квартира переставлены: вопрос в dopros.json, в выжимке черновика нет ни одного значения, ответ берет карточку."""
|
||
(run_.case / "_case.md").write_text("# Д\n- **Адрес:** г. Тестов, ул. Образцовая, д. 12, кв. 5\n", encoding="utf-8")
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({
|
||
"docx-reader": [read(("Адрес регистрации заявителя", "г. Тестов, ул. Образцовая, д. 5, кв. 12", 0))],
|
||
"case-mapper": [QUESTION],
|
||
})
|
||
faza_karta.karta(run_, ctx)
|
||
(item,) = [v for v in faza_dopros.chitat(run_.case) if v["id"] == "raskhozhdenie-adres"]
|
||
assert item["obyazatelnyi"] and not item["otvet"]
|
||
assert "д. 5, кв. 12" in item["vopros"] and "д. 12, кв. 5" in item["vopros"]
|
||
assert "a.docx" in item["vopros"] and "_case.md" in item["vopros"]
|
||
assert {f["status"] for f in ctx["fakty"]} == {faza_karta.DISPUTED}
|
||
assert "кв. 12" not in faza_dokument._vyzhimka({**ctx, "akty": []}) and "кв. 5" not in faza_dokument._vyzhimka({**ctx, "akty": []})
|
||
assert otvet.main(["--case", str(run_.case), "--prefer", "kartochka", "--field", "raskhozhdenie-adres"]) == 0
|
||
faza_dopros.vorota(run_, ctx)
|
||
assert {(f["status"], f["znachenie"]) for f in ctx["fakty"]} == {("ок", "г. Тестов, ул. Образцовая, д. 12, кв. 5")}
|
||
|
||
|
||
def test_card_matching_primary_asks_nothing(fake, run_, tmp_path, monkeypatch):
|
||
(run_.case / "_case.md").write_text("# Д\n- **Адрес:** г. Тестов, ул. Образцовая, д. 5, кв. 12\n", encoding="utf-8")
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({"docx-reader": [read(("Адрес регистрации", "г. Тестов, ул Образцовая, д 5, кв 12", 0))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
assert faza_dopros.chitat(run_.case) == []
|
||
|
||
|
||
def test_transfer_court_is_not_case_court(fake, run_, tmp_path, monkeypatch):
|
||
"""Суд дела и суд передачи - разные поля: ответ на расхождение по суду дела не переписывает суд передачи (приемка 08.10.2026)."""
|
||
(run_.case / "_case.md").write_text(
|
||
"# Д\n- **Суд:** Тестовский районный суд г. Тестова (ул. Образцовая, д. 33)\n"
|
||
"- **Суд по месту жительства клиента:** Соседний районный суд г. Тестова\n", encoding="utf-8")
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({"docx-reader": [read(("Суд", "Тестовский районный суд г. Тестова, ул. Образцовая, 35", 0))],
|
||
"case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
(item,) = [v for v in faza_dopros.chitat(run_.case) if v["id"] == "raskhozhdenie-sud"]
|
||
assert "Соседний" not in item["vopros"]
|
||
assert otvet.main(["--case", str(run_.case), "--prefer", "kartochka", "--field", "raskhozhdenie-sud"]) == 0
|
||
faza_dopros.vorota(run_, ctx)
|
||
values = {f["tema"]: f["znachenie"] for f in ctx["fakty"]}
|
||
assert values["Суд по месту жительства клиента"] == "Соседний районный суд г. Тестова"
|
||
|
||
|
||
def test_transfer_court_alone_asks_nothing(fake, run_, tmp_path, monkeypatch):
|
||
(run_.case / "_case.md").write_text(
|
||
"# Д\n- **Суд:** Тестовский районный суд\n- **Суд по месту жительства клиента:** Соседний районный суд\n",
|
||
encoding="utf-8")
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({"docx-reader": [read(("Суд", "Тестовский районный суд", 0))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
assert faza_dopros.chitat(run_.case) == []
|
||
|
||
|
||
@pytest.mark.parametrize("card", [
|
||
"# Д\n## Статус\n- **Суд:** —\n\n## Стороны\n- **Суд (прибор shapka):** Тестовский районный суд\n", # класс 12: прочерк
|
||
"# Д\n- **Суд:** Тестовский районный суд\n- **Суд (прибор shapka):** Тестовский районный суд г. Тестова\n", # только карточка
|
||
])
|
||
def test_card_is_not_compared_with_itself(fake, run_, tmp_path, monkeypatch, card):
|
||
"""Класс 12 card-conflict-same-card: прочерк - не значение; поля одной карточки без первички вопроса не дают."""
|
||
(run_.case / "_case.md").write_text(card, encoding="utf-8")
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.docx": meta(tmp_path, "a.docx", "текст")})
|
||
fake.plan({"docx-reader": [read(("Тема", "значение", 0))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
assert faza_dopros.chitat(run_.case) == []
|
||
assert all(f["znachenie"].strip() not in {"—", "-", "–"} for f in ctx["fakty"])
|
||
|
||
|
||
def test_poisk_ok_article_list_is_not_a_sum():
|
||
assert faza_karta._poisk_ok("извещение ответчика основание отмены заочного решения ст. 113 114 242 ГПК РФ")
|
||
assert faza_karta._poisk_ok("восстановление срока ч. 1 ст. 112 237 ГПК РФ")
|
||
assert not faza_karta._poisk_ok("взыскание 14 280 000 рублей по расписке")
|
||
assert not faza_karta._poisk_ok("расписка от 02.05.2025")
|
||
|
||
|
||
def test_pages_without_facts_are_read_again_once(dochitka, fake, run_, tmp_path, monkeypatch):
|
||
# класс 9 «полнота по страницам»: страницы многостраничного файла без единого факта дочитываются одним вызовом
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {"a.pdf": meta(tmp_path, "a.pdf", "первая\fвторая\f\fчетвертая", route="text-pdf", pages=4)})
|
||
fake.plan({"docx-reader": [read(("Тема один", "первая", 1)), read(("Тема два", "вторая", 2))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
stdins = [call["stdin"] for call in fake.calls() if call["role"] == "docx-reader"]
|
||
assert len(stdins) == 2
|
||
assert "=== стр. 2 ===\nвторая" in stdins[1] and "=== стр. 4 ===\nчетвертая" in stdins[1]
|
||
assert "первая" not in stdins[1] and "=== стр. 3 ===" not in stdins[1] # прочитанная и пустая страницы не идут
|
||
assert "Дочитка: страницы 2, 4" in stdins[1]
|
||
assert {(fact["tema"], fact["str"]) for fact in ctx["fakty"]} >= {("Тема один", 1), ("Тема два", 2)}
|
||
|
||
|
||
@pytest.mark.parametrize("first", [read(("Тема", "первая", 1), ("Тема два", "вторая", 2)), read()])
|
||
def test_no_reread_when_pages_covered_or_file_empty(dochitka, fake, run_, tmp_path, monkeypatch, first):
|
||
# все страницы с фактами - дочитки нет; файл без фактов - забота _pustye, целиком повторно не читается
|
||
ctx = prepare(run_, tmp_path, monkeypatch, {
|
||
"a.pdf": meta(tmp_path, "a.pdf", "первая\fвторая", route="text-pdf", pages=2),
|
||
"b.pdf": meta(tmp_path, "b.pdf", "Справка: значение есть.", route="scan"), # своя роль: исходы не перемешаются
|
||
})
|
||
fake.plan({"docx-reader": [first], "pdf-reader": [read(("Справка", "значение", 0))], "case-mapper": [QUESTION]})
|
||
faza_karta.karta(run_, ctx)
|
||
assert sum(call["role"] == "docx-reader" for call in fake.calls()) == 1
|