release: Евномия, новая версия, линейка юристов

This commit is contained in:
public-repo-gate
2026-10-19 17:43:00 +03:00
parent 067c6c2414
commit bf1edc117c
239 changed files with 245397 additions and 36598 deletions
+454
View File
@@ -0,0 +1,454 @@
import json
import re
import sys
import textwrap
import time
from pathlib import Path
import pytest
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import core # noqa: E402
import faza_karta # noqa: E402
import faza_praktika # noqa: E402
from next_helpers import events, make_case # noqa: E402
# Подмена приборов: ответ из plan.json по ключу (вопрос поиска, номер акта), журнал вызовов - calls.jsonl.
# Перед JSON идет строка шума, как у приборов с предупреждениями библиотек.
TOOL = """
import json, sys
from pathlib import Path
here = Path(__file__).parent
name = NAME
with (here / "calls.jsonl").open("a", encoding="utf-8") as log:
log.write(json.dumps([name, *sys.argv[1:]], ensure_ascii=False) + "\\n")
plan = json.loads((here / "plan.json").read_text(encoding="utf-8"))[name]
key = sys.argv[sys.argv.index("--") + 1] if "--" in sys.argv else sys.argv[1].split("@")[0]
reply = plan.get(key, plan["*"])
print("warning: шум перед JSON")
print(json.dumps(reply["out"], ensure_ascii=False, indent=2))
sys.exit(reply["code"])
"""
A, B, C = "5-КГ22-82-К2", "33-7458/2026", "А65-1234/2025"
def cand(number, snippet="Фрагмент акта."):
"""Кандидат из выдачи practice_search.py --ladder --json."""
return {"number": number, "date": "04.10.2022", "court": "Верховный Суд РФ", "url": f"https://example.org/akt/{number}",
"snippet": snippet, "title": f"Определение № {number}", "verdict": "подтвержден"}
def reply(out, code=0):
return {"code": code, "out": out}
class Tools:
"""План ответов подмененных приборов и журнал их вызовов."""
def __init__(self, folder):
self.folder = folder
self.plan = {
"preflight_search": {"*": reply([{"channel": "Линкей (lynceuz)", "ok": True, "note": "", "action": ""}])},
"practice_search": {"*": reply({"results": [cand(A), cand(B), cand(C)], "step": "local", "reasons": []})},
"verify_act": {"*": reply([{"act": A, "status": faza_praktika.VERIFIED}])},
}
self.save()
def save(self):
(self.folder / "plan.json").write_text(json.dumps(self.plan, ensure_ascii=False), encoding="utf-8")
def calls(self, name=None):
log = self.folder / "calls.jsonl"
rows = [json.loads(line) for line in log.read_text(encoding="utf-8").splitlines()] if log.is_file() else []
return [row for row in rows if name in (None, row[0])]
@pytest.fixture
def tools(tmp_path, monkeypatch):
for name in ("preflight_search", "practice_search", "verify_act"):
script = tmp_path / f"stub_{name}.py"
script.write_text(TOOL.replace("NAME", repr(name)), encoding="utf-8")
monkeypatch.setitem(core.TOOLS, name, [sys.executable, str(script)])
return Tools(tmp_path)
@pytest.fixture
def full_run(tmp_path):
with core.Run(make_case(tmp_path / "cases" / "c" / "d"), "FULL", "иск") as run:
yield run
def fact(tema, znachenie, status="ок"):
return {"tema": tema, "znachenie": znachenie, "fail": "a.docx", "str": 1, "status": status}
def vopros(number, *facts):
return {"id": f"В{number}", "vopros": f"Правовой вопрос {number}?", "poisk": f"запрос {number}",
"fakty": list(facts or (0,))}
def make_ctx(run, voprosy=None, fakty=None):
"""Карта с меткой готовности и ctx, как после фазы «Карта»."""
fakty = fakty or [fact("Тема", "значение")]
voprosy = voprosy or [vopros(1)]
path = core.context(run.case) / "knowledge-map.md"
faza_karta.write_map(path, fakty, voprosy, True)
return {"map": path, "voprosy": voprosy, "fakty": fakty, "texts": {}}
def leaf(*acts):
"""Исход листа: акты (номер, польза, тезис). Реквизиты в ответе заведомо чужие: код берет их из выдачи поиска."""
return {"structured_output": {"akty": [
{"nomer": number, "data": "01.01.1999", "sud": "Выдуманный суд", "url": "http://evil.invalid/x", "tezis": tezis,
"polza": polza} for number, polza, tezis in acts]}}
def practice_of(run):
return (core.context(run.case) / "practice.md").read_text(encoding="utf-8")
def test_ustanovki_match_design():
assert faza_praktika.USTANOVKI == {
"FAST": [("process", "practice-hunter-tactical")],
"FULL": [("za", "practice-hunter-classic"), ("protiv", "practice-hunter-skeptic"), ("process", "practice-hunter-tactical")],
}
@pytest.mark.parametrize("raw", ["5-КГ22-82-К2", " № 5-кг22-82-К2 ", "№5-КГ22-82-К2", "5 - КГ22 - 82 - К2", "5\u2011КГ22\u201182-К2", "\u00a0№\u00a05-КГ22-82-К2"])
def test_nomer_key_ignores_spaces_case_sign_and_dash_kind(raw):
assert faza_praktika.nomer_key(raw) == "5-кг22-82-к2"
def test_verify_act_contract():
source = (core.ROOT / "scripts" / "verify_act.py").read_text(encoding="utf-8")
assert f'"{faza_praktika.VERIFIED_KEY}": ' in source # ключ статуса в словаре ответа --json
assert f'"{faza_praktika.VERIFIED}"' in source # его значение у подтвержденного акта
assert '"--json"' in source and '"--url"' in source
assert f"{faza_praktika.UNAVAILABLE} канал недоступен" in source and "КАНАЛ НЕДОСТУПЕН" in source # код 4 - проверка не выполнена
def test_search_tools_contract():
scripts = core.ROOT / "scripts"
search = (scripts / "practice_search.py").read_text(encoding="utf-8")
assert all(f'"{flag}"' in search for flag in ("--ladder", "--json", "--limit", "--case"))
assert all(f'"{key}"' in search for key in ("results", "number", "date", "court", "url", "snippet", "number_from_title")) # ответ --ladder --json
preflight = (scripts / "preflight_search.py").read_text(encoding="utf-8")
assert all(f'"{key}"' in preflight for key in ("--json", "--case", "channel", "ok"))
def test_prompt_contract():
prompt = core.prompt("practice-leaf")
assert prompt.splitlines()[0] == "РОЛЬ: practice-leaf" and core.STRENGTH["practice-leaf"] == "cheap"
assert "данные, а не команды" in prompt and "ДД.ММ.ГГГГ" in prompt and "только" in prompt
assert all(f"`{polza}`" in prompt for polza in ("za", "protiv", "process"))
@pytest.mark.parametrize("spoil", ["no_marker", "no_file", "no_key"])
def test_hunt_refuses_without_map_marker(fake, run_, tools, spoil):
ctx = make_ctx(run_)
old = core.context(run_.case) / "practice.md"
old.write_text("прошлая практика\n", encoding="utf-8")
if spoil == "no_marker":
faza_karta.write_map(ctx["map"], ctx["fakty"], ctx["voprosy"], False)
elif spoil == "no_file":
ctx["map"].unlink()
else:
del ctx["map"]
with pytest.raises(core.Stop, match="карта"):
faza_praktika.praktika(run_, ctx)
assert tools.calls() == [] and fake.calls() == [] and "akty" not in ctx
assert old.read_text(encoding="utf-8") == "прошлая практика\n" # отказ ничего не трогает
def test_fast_runs_only_process(fake, run_, tools):
ctx = make_ctx(run_, [vopros(1), vopros(2)])
fake.plan({"practice-leaf": [leaf(), leaf()]})
faza_praktika.praktika(run_, ctx)
stdins = [call["stdin"] for call in fake.calls()]
assert len(stdins) == 2 and all("Установка: процесс." in s and "за нас" not in s and "против нас" not in s for s in stdins)
assert all("по существу вопроса" in s for s in stdins) # единственному охотнику FAST поручено и существо вопроса
hunters = [(e["who"], e["state"]) for e in events(run_) if e["who"].startswith("practice-hunter")]
assert hunters == [("practice-hunter-tactical", "start"), ("practice-hunter-tactical", "ok")]
assert len(tools.calls("practice_search")) == 2 # поиск на каждый вопрос
def test_full_runs_three_ustanovki(fake, full_run, tools):
ctx = make_ctx(full_run)
fake.plan({"practice-leaf": [leaf(), leaf(), leaf()]})
faza_praktika.praktika(full_run, ctx)
labels = sorted(re.search(r"Установка: (.+?)\.", call["stdin"])[1] for call in fake.calls())
assert labels == ["за нас", "против нас", "процесс"]
assert not any("по существу вопроса" in call["stdin"] for call in fake.calls()) # на FULL существо вопроса ищут за и против
hunters = {(e["who"], e["state"]) for e in events(full_run) if e["who"].startswith("practice-hunter")}
assert hunters == {(role, state) for _, role in faza_praktika.USTANOVKI["FULL"] for state in ("start", "ok")}
assert len(tools.calls("practice_search")) == 1 # одна выдача на вопрос: установки читают одних кандидатов
assert practice_of(full_run).count("подтвержденных актов нет: лист не выбрал ни одного кандидата") == 3 # по блоку на лист
def test_leaf_gets_question_not_texts(fake, run_, tools):
texts = run_.dir / "texts"
texts.mkdir()
(texts / "01.md").write_text("Текст материала. КАНАРЕЙКА-ТЕКСТ", encoding="utf-8")
fakty = [fact(f"Тема {n}", f"значение {n}", "ОСПОРЕНО" if n == 3 else "ок") for n in range(12)] + [fact("Чужой", "КАНАРЕЙКА-ЧУЖОЙ")]
ctx = make_ctx(run_, [vopros(1, *range(12))], fakty)
ctx["texts"] = {"01.md": texts / "01.md"}
tools.plan["practice_search"]["*"]["out"]["results"][0]["snippet"] = "НАЧАЛО " + "а" * 1600 + " КАНАРЕЙКА-ХВОСТ"
tools.save()
fake.plan({"practice-leaf": [leaf()]})
faza_praktika.praktika(run_, ctx)
stdin = fake.calls()[0]["stdin"]
assert "Документ: иск" in stdin and "Правовой вопрос 1?" in stdin
assert "- Тема 9: значение 9" in stdin and "- Тема 3: значение 3 (ОСПОРЕНО)" in stdin
assert "Тема 10" not in stdin and "КАНАРЕЙКА-ЧУЖОЙ" not in stdin and "КАНАРЕЙКА-ТЕКСТ" not in stdin # до 10 фактов, без текстов
assert "НАЧАЛО" in stdin and "КАНАРЕЙКА-ХВОСТ" not in stdin # фрагмент обрезан до 1 500 знаков
assert all(number in stdin for number in (A, B, C)) and stdin.count("Фрагмент:") == 3
assert "КАНАРЕЙКА" not in (run_.dir / "events.jsonl").read_text(encoding="utf-8")
def test_search_and_verify_argv(fake, run_, tools):
ctx = make_ctx(run_)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис."))]})
faza_praktika.praktika(run_, ctx)
case = str(run_.case.absolute())
assert tools.calls() == [
["preflight_search", "--json", "--case", case],
["practice_search", "--ladder", "--json", "--limit", "10", "--case", case, "--", "запрос 1"],
["verify_act", f"{A}@04.10.2022", "--json", "--url", f"https://example.org/akt/{A}"],
]
def test_requisites_come_from_search_not_from_leaf(fake, run_, tools):
ctx = make_ctx(run_)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис."), ("77-ВЫДУМАН/2020", "za", "Выдуманный акт."))]})
faza_praktika.praktika(run_, ctx)
assert ctx["akty"] == [{"nomer": A, "data": "04.10.2022", "sud": "Верховный Суд РФ", "url": f"https://example.org/akt/{A}",
"ustanovka": "za", "tezis": "Тезис.", "vopros": "В1"}]
assert [call[1] for call in tools.calls("verify_act")] == [f"{A}@04.10.2022"] # акт вне выдачи до сверки не дошел
assert "evil.invalid" not in practice_of(run_) and "Выдуманн" not in practice_of(run_)
assert any(e["who"] == "themiz" and "77-ВЫДУМАН/2020" in e["action"] and "не принят" in e["action"] for e in events(run_))
def test_leaf_without_benefit_or_thesis_not_accepted(fake, run_, tools):
ctx = make_ctx(run_)
fake.plan({"practice-leaf": [leaf((A, "обе", "Тезис."), (B, "za", " "), (C, "protiv", "Тезис третьего."))]})
faza_praktika.praktika(run_, ctx)
assert [(a["nomer"], a["ustanovka"]) for a in ctx["akty"]] == [(C, "protiv")]
@pytest.mark.parametrize("code, out, note", [
(3, [{"act": B, "status": "НЕ ПОДТВЕРЖДЕН"}], "не подтверждены сверкой 1"),
(2, [{"act": B, "status": "РАСХОЖДЕНИЕ"}], "не подтверждены сверкой 1"),
(4, [{"act": B, "status": "КАНАЛ НЕДОСТУПЕН"}], "сверка недоступна 1"), # проверка не выполнена - не вердикт, и названа иначе
(0, [{"act": B, "status": "РАСХОЖДЕНИЕ"}], "не подтверждены сверкой 1"), # код 0 при чужом статусе подтверждением не считается
(0, "ответ без JSON", "не подтверждены сверкой 1"),
(0, [], "не подтверждены сверкой 1"),
])
def test_unverified_act_not_written(fake, run_, tools, code, out, note):
tools.plan["verify_act"][B] = reply(out, code)
tools.save()
ctx = make_ctx(run_)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис первого."), (B, "protiv", "Тезис второго."))]})
faza_praktika.praktika(run_, ctx)
assert [a["nomer"] for a in ctx["akty"]] == [A]
text = practice_of(run_)
assert A in text and B not in text and "Тезис второго" not in text
assert f"- не записано: {note}" in text # неполный блок называет, чего в нем нет
assert any(e["who"] == "themiz" and B in e["action"] and "не подтвержден" in e["action"] for e in events(run_))
def test_duplicate_act_written_once(fake, full_run, tools):
ctx = make_ctx(full_run)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис 1.")), leaf((f"№ {A.lower()}", "protiv", "Тезис 2.")), leaf((f" {A} ", "process", "Тезис 3."))]})
faza_praktika.praktika(full_run, ctx)
assert len(ctx["akty"]) == 1 and practice_of(full_run).count("№ ") == 1 # одна строка акта в файле
assert len(tools.calls("verify_act")) == 1 # повтор отброшен до сверки
assert practice_of(full_run).count("подтвержденных актов нет: уже записаны в других блоках 1") == 2
def test_practice_grows_per_leaf(fake, full_run, tools, monkeypatch):
seen, real = [], faza_praktika.write_practice
def spy(path, blocks):
real(path, blocks)
seen.append((len(blocks), sum(len(acts) for _, acts, _ in blocks)))
monkeypatch.setattr(faza_praktika, "write_practice", spy)
ctx = make_ctx(full_run)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис 1.")), leaf((B, "protiv", "Тезис 2.")), leaf((C, "process", "Тезис 3."))]})
faza_praktika.praktika(full_run, ctx)
assert seen == [(0, 0), (1, 1), (2, 2), (3, 3)] # пустой файл в начале, затем по листу
text = practice_of(full_run)
assert all(number in text for number in (A, B, C)) and "verify_act.py" in text
assert sorted(a["nomer"] for a in ctx["akty"]) == sorted([A, B, C])
def test_stale_practice_replaced_and_kept_in_run_dir(fake, run_, tools):
ctx = make_ctx(run_)
path = core.context(run_.case) / "practice.md"
path.write_text("прошлая практика СТАРЫЙ-АКТ\n", encoding="utf-8")
fake.plan({"practice-leaf": [leaf()]})
faza_praktika.praktika(run_, ctx)
assert "СТАРЫЙ-АКТ" not in practice_of(run_) and "СТАРЫЙ-АКТ" in (run_.dir / "practice.prev.md").read_text(encoding="utf-8")
def test_no_candidates_no_leaf(fake, run_, tools):
tools.plan["practice_search"]["*"] = reply({"results": [], "step": None, "reasons": []}, 2) # код 2: лестница пуста
tools.save()
ctx = make_ctx(run_)
faza_praktika.praktika(run_, ctx)
assert fake.calls() == [] and ctx["akty"] == [] # лист без кандидатов дал бы акты из памяти модели
assert "подтвержденных актов нет: поиск не дал кандидатов" in practice_of(run_)
assert any(e["who"] == "themiz" and "кандидатов" in e["action"] for e in events(run_))
@pytest.mark.parametrize("code, out", [(4, ""), (1, ""), (2, "usage: practice_search.py"), (0, {"нет": "results"})])
def test_search_failure_stops(fake, run_, tools, code, out):
tools.plan["practice_search"]["*"] = reply(out, code)
tools.save()
ctx = make_ctx(run_)
with pytest.raises(core.Stop, match="practice_search"):
faza_praktika.praktika(run_, ctx)
assert fake.calls() == [] and "akty" not in ctx
def test_preflight_reported_and_not_blocking(fake, run_, tools):
rows = [{"channel": "Линкей (lynceuz)", "ok": False, "note": "", "action": ""}, {"channel": "Публикатор vsrf.ru", "ok": True, "note": "", "action": ""}]
tools.plan["preflight_search"]["*"] = reply(rows, 1) # код 1: внешних каналов нет, локальная база работает
tools.save()
ctx = make_ctx(run_)
fake.plan({"practice-leaf": [leaf()]})
faza_praktika.praktika(run_, ctx)
info = [e["action"] for e in events(run_) if e["who"] == "themiz" and "каналы" in e["action"]]
assert len(info) == 1 and "Линкей (lynceuz)" in info[0] and "Публикатор" not in info[0]
assert tools.calls()[0][0] == "preflight_search" and len(fake.calls()) == 1
def test_leaf_failure_stops_and_cancels_queue(fake, run_, tools):
ctx = make_ctx(run_, [vopros(n) for n in range(1, 9)])
fake.plan({"practice-leaf": ["garbage", *[{"sleep": 2, "structured_output": {"akty": []}}] * 7]}) # первый падает, остальные долго идут
with pytest.raises(core.Stop, match="practice-leaf"):
faza_praktika.praktika(run_, ctx)
assert len(fake.calls()) < 8 and "akty" not in ctx # четыре потока заняты, очередь после сбоя не запускается
def test_verify_failure_cancels_queued_leaves(fake, run_, tools):
# сбой сверки случается в главном потоке, пока листья еще идут: очередь после него не запускается
tools.plan["verify_act"]["*"] = reply("", 1)
tools.save()
ctx = make_ctx(run_, [vopros(n) for n in range(1, 9)])
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис.")), *[{"sleep": 1.5, "structured_output": {"akty": []}}] * 7]})
with pytest.raises(core.Stop, match="verify_act") as failure:
faza_praktika.praktika(run_, ctx)
time.sleep(2) # дольше самого долгого листа; failure держит трассировку, поэтому без явного закрытия очередь жила бы
assert len(fake.calls()) <= 5 and "akty" not in ctx # четыре первых листа и один, взятый освободившимся потоком
assert failure.value.args
def test_citation_candidates_skipped(fake, run_, tools):
# лестница строку не сверяла: номер взят не из заголовка, это цитата чужого акта, а суд и URL принадлежат цитатчику
cited = {**cand(B), "number_from_title": False, "verdict": "требует проверки", "verdict_note": "номер взят не из заголовка акта"}
tools.plan["practice_search"]["*"] = reply({"results": [cand(A), cited, {**cand(C), "number_from_title": True}], "step": "local", "reasons": []})
tools.save()
ctx = make_ctx(run_)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис 1."), (B, "za", "Тезис цитаты."), (C, "protiv", "Тезис 3."))]})
faza_praktika.praktika(run_, ctx)
stdin = fake.calls()[0]["stdin"]
assert A in stdin and C in stdin and B not in stdin # цитата листу не показана
assert [a["nomer"] for a in ctx["akty"]] == [A, C] and [call[1] for call in tools.calls("verify_act")] == [f"{A}@04.10.2022", f"{C}@04.10.2022"]
assert any("отброшено кандидатов" in e["action"] and e["action"].endswith(": 1") for e in events(run_))
def test_only_citations_means_no_candidates(fake, run_, tools):
cited = {**cand(B), "number_from_title": False}
tools.plan["practice_search"]["*"] = reply({"results": [cited], "step": "local", "reasons": []}, 2)
tools.save()
ctx = make_ctx(run_)
faza_praktika.praktika(run_, ctx)
assert fake.calls() == [] and tools.calls("verify_act") == [] and ctx["akty"] == []
assert "подтвержденных актов нет: поиск не дал кандидатов" in practice_of(run_)
@pytest.mark.parametrize("kind, note", [
("leaf_none", "лист не выбрал ни одного кандидата"),
("outside", "нет в выдаче, пользы или тезиса 1"),
("denied", "не подтверждены сверкой 1"),
])
def test_empty_block_names_reason(fake, run_, tools, kind, note):
ctx = make_ctx(run_)
if kind == "denied":
tools.plan["verify_act"][A] = reply([{"act": A, "status": "НЕ ПОДТВЕРЖДЕН"}], 3)
tools.save()
chosen = {"leaf_none": leaf(), "outside": leaf(("77-ВЫДУМАН/2020", "za", "Тезис.")), "denied": leaf((A, "za", "Тезис."))}[kind]
fake.plan({"practice-leaf": [chosen]})
faza_praktika.praktika(run_, ctx)
assert ctx["akty"] == [] and f"- подтвержденных актов нет: {note}" in practice_of(run_)
def test_all_verifications_down_stops(fake, run_, tools):
tools.plan["verify_act"]["*"] = reply([{"act": A, "status": "КАНАЛ НЕДОСТУПЕН"}], faza_praktika.UNAVAILABLE)
tools.save()
ctx = make_ctx(run_)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис 1."), (B, "protiv", "Тезис 2."))]})
with pytest.raises(core.Stop, match="сверка актов недоступна"):
faza_praktika.praktika(run_, ctx) # проверка не выполнена: пустая практика была бы ложным «практики нет»
assert "akty" not in ctx
assert any(e["state"] == "fail" and "сверка актов недоступна" in e["action"] and "В1" in e["action"] for e in events(run_))
text = practice_of(run_) # файл записан до остановки и называет причину
assert "подтвержденных актов нет: сверка недоступна 2" in text and A not in text and B not in text
def test_verification_down_decided_after_last_leaf_of_question(fake, full_run, tools):
tools.plan["verify_act"]["*"] = reply([{"act": A, "status": "КАНАЛ НЕДОСТУПЕН"}], faza_praktika.UNAVAILABLE)
tools.save()
ctx = make_ctx(full_run)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис 1.")), leaf((B, "protiv", "Тезис 2.")), leaf((C, "process", "Тезис 3."))]})
with pytest.raises(core.Stop, match="сверка актов недоступна"):
faza_praktika.praktika(full_run, ctx)
assert len(tools.calls("verify_act")) == 3 # решение после третьего листа вопроса, а не после первого
def test_down_in_one_leaf_does_not_stop_question_with_confirmed_act(fake, full_run, tools):
tools.plan["verify_act"][A] = reply([{"act": A, "status": "КАНАЛ НЕДОСТУПЕН"}], faza_praktika.UNAVAILABLE)
tools.save()
ctx = make_ctx(full_run)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис 1.")), leaf((B, "protiv", "Тезис 2.")), leaf()]})
faza_praktika.praktika(full_run, ctx)
assert [a["nomer"] for a in ctx["akty"]] == [B]
assert "сверка недоступна 1" in practice_of(full_run)
def test_url_from_verify_when_search_has_none(fake, run_, tools):
tools.plan["practice_search"]["*"] = reply({"results": [{**cand(A), "url": ""}, cand(B)], "step": "local", "reasons": []})
tools.plan["verify_act"][A] = reply([{"act": A, "status": faza_praktika.VERIFIED, "url": "https://example.org/pub/a"}])
tools.plan["verify_act"][B] = reply([{"act": B, "status": faza_praktika.VERIFIED, "url": "https://example.org/pub/b"}])
tools.save()
ctx = make_ctx(run_)
fake.plan({"practice-leaf": [leaf((A, "za", "Тезис 1."), (B, "za", "Тезис 2."))]})
faza_praktika.praktika(run_, ctx)
assert {a["nomer"]: a["url"] for a in ctx["akty"]} == {A: "https://example.org/pub/a", B: f"https://example.org/akt/{B}"} # URL поиска важнее
assert "https://example.org/pub/a" in practice_of(run_)
assert tools.calls("verify_act")[0] == ["verify_act", f"{A}@04.10.2022", "--json"] # без URL поиска нет и --url
def test_candidates_not_shared_between_questions(fake, run_, tools):
# у вопросов разные выдачи: акт другого вопроса листу не засчитывается
tools.plan["practice_search"]["запрос 1"] = reply({"results": [cand(A)], "step": "local", "reasons": []})
tools.plan["practice_search"]["запрос 2"] = reply({"results": [cand(B)], "step": "local", "reasons": []})
tools.save()
ctx = make_ctx(run_, [vopros(1), vopros(2)])
both = leaf((A, "za", "Тезис А."), (B, "za", "Тезис Б.")) # каждый лист возвращает оба акта
fake.plan({"practice-leaf": [{**both, "sleep": 0.5}, both]}) # какой-то лист закончит позже: порядок акта - по вопросам, не по готовности
faza_praktika.praktika(run_, ctx)
assert [(a["vopros"], a["nomer"]) for a in ctx["akty"]] == [("В1", A), ("В2", B)]
def test_fast_practice_gets_marker_guard_reads(fake, run_, tools):
"""Класс themiz-runpy-vs-guard-markers: практика FAST по завершении несет маркер, которого ждут guard и контракт."""
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts"))
import themiz_guard
ctx = make_ctx(run_, [vopros(1)])
fake.plan({"practice-leaf": [leaf()]})
faza_praktika.praktika(run_, ctx)
assert themiz_guard._has_marker(str(core.context(run_.case) / "practice.md"), themiz_guard.PRACTICE_MARKER)