A2 ext_check.check_bim_index_gap — рекуррентный сигнал по ПРИМЕНЁННОМУ индексу (не скачанному), только докладывает (state/watch_seen не мутирует), info/update/problem. A3 ext_status.bim_stage — стадия download/parsed/served + счётчики; бейдж в admin.html. docs/PLAN_completion_details.md — планы A1/A4/B1-B5 (adversarial, гейты Юрия). +9 тестов. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
449 lines
26 KiB
Python
449 lines
26 KiB
Python
"""Срез 3.1: чекер обновлений. Главный инвариант — ЧЕКЕР НЕ МУТИРУЕТ state.json
|
||
(его пишут только pull/apply). red-green: тест на неизменность state — первым по важности.
|
||
Сеть замокана (fgis_client/pravo_client).
|
||
"""
|
||
import json
|
||
import os
|
||
import sys
|
||
from pathlib import Path
|
||
|
||
import pytest
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||
import ext_check as ec # noqa: E402
|
||
import ext_state as es # noqa: E402
|
||
import fgis_client as fc # noqa: E402
|
||
import pravo_client as pc # noqa: E402
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def _mock_new_sources(monkeypatch):
|
||
"""По умолчанию opendata/bim/xsd не дают находок (не ходят в сеть). Тесты переопределяют."""
|
||
import xsd_client
|
||
monkeypatch.setattr(fc, "opendata_list", lambda client=None: [])
|
||
monkeypatch.setattr(fc, "bim_leaf_docs", lambda client=None: [])
|
||
monkeypatch.setattr(xsd_client, "schema_links", lambda client=None: [])
|
||
|
||
|
||
@pytest.fixture
|
||
def _tmp(monkeypatch, tmp_path):
|
||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path))
|
||
monkeypatch.delenv("OPERATOR_EMAIL", raising=False)
|
||
return tmp_path
|
||
|
||
|
||
def _mock_fgis(monkeypatch, *, alive=True, latest=426):
|
||
monkeypatch.setattr(fc, "alive", lambda client=None: alive)
|
||
monkeypatch.setattr(fc, "price_zones", lambda s, client=None: [{"id": 191, "name": "город Москва"}])
|
||
monkeypatch.setattr(fc, "latest_period", lambda z, client=None: {"id": latest, "name": f"период {latest}"})
|
||
|
||
|
||
def _mock_pravo(monkeypatch, new_docs):
|
||
monkeypatch.setattr(pc, "new_since", lambda seen, max_pages=8, client=None: new_docs)
|
||
|
||
|
||
def _set_engine(subject=323, zone=191, period=426):
|
||
"""Обозначить движковую зону + применённый период (st['active']). База денежного сигнала."""
|
||
with es.update_state() as st:
|
||
st.setdefault("active", {})["fgis_split_form"] = {
|
||
"subject": subject, "zone": zone, "period_id": period}
|
||
|
||
|
||
def test_new_period_produces_finding_with_action(_tmp, monkeypatch):
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(period=425) # движку применён 425 → latest 426 новее → сигнал «примени»
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
ups = [f for f in rep["findings"] if f["source"] == "fgis_split_form"]
|
||
assert len(ups) == 1 and "426" in ups[0]["message"] and "ext_apply.py" in ups[0]["action"]
|
||
|
||
|
||
def test_no_finding_when_period_is_active(_tmp, monkeypatch):
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(period=426) # движок уже на latest → тишина
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
assert not [f for f in rep["findings"] if f["source"] == "fgis_split_form"]
|
||
|
||
|
||
def test_autopull_does_not_silence_apply_signal(_tmp, monkeypatch):
|
||
"""КЛЮЧ money-safety: авто-закачка обновила ПУЛЛ (sources) до latest, но движок применён на
|
||
старом периоде → сигнал «пора применить» ДОЛЖЕН остаться (иначе движок молча по старым ценам)."""
|
||
_mock_fgis(monkeypatch, latest=430)
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(period=426) # движок на 426
|
||
with es.update_state() as st:
|
||
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 430}} # авто-pull подтянул 430
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
ups = [f for f in rep["findings"] if f["source"] == "fgis_split_form" and f["level"] == "update"]
|
||
assert len(ups) == 1 and "430" in ups[0]["message"] # не заглушено скачанным 430
|
||
|
||
|
||
def test_checker_does_not_mutate_state_json(_tmp, monkeypatch):
|
||
"""КЛЮЧЕВОЙ ИНВАРИАНТ: прогон чекера НЕ меняет state.json ни на байт."""
|
||
_mock_fgis(monkeypatch, latest=999) # заведомо новый период
|
||
_mock_pravo(monkeypatch, [{"eoNumber": "E1", "number": "1/пр", "name": "смета",
|
||
"documentDate": "2026-07-01", "relevant": True, "pdf_url": "u"}])
|
||
with es.update_state() as st:
|
||
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 425}}
|
||
before = (_tmp / "state.json").read_bytes()
|
||
ec.run_check(regions=[323], notify=False)
|
||
after = (_tmp / "state.json").read_bytes()
|
||
assert before == after, "чекер изменил state.json — нарушение контракта"
|
||
|
||
|
||
def test_alive_false_reports_problem_no_crash(_tmp, monkeypatch):
|
||
_mock_fgis(monkeypatch, alive=False)
|
||
_mock_pravo(monkeypatch, [])
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
assert rep["problems"] >= 1
|
||
assert any("недоступен" in f["message"] for f in rep["findings"])
|
||
|
||
|
||
def test_pravo_new_orders_and_seen_dedup(_tmp, monkeypatch):
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
docs = [{"eoNumber": "E1", "number": "1/пр", "name": "Об индексах сметной стоимости",
|
||
"documentDate": "2026-07-01", "relevant": True, "pdf_url": "http://p/E1"}]
|
||
_mock_pravo(monkeypatch, docs)
|
||
with es.update_state() as st:
|
||
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}}
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
pravo = [f for f in rep["findings"] if f["source"] == "pravo"]
|
||
assert len(pravo) == 1 and pravo[0]["level"] == "update" # релевантный → update
|
||
# eoNumber попал в seen (дедуп на следующий прогон)
|
||
assert "E1" in es.load_watch_seen()["pravo_eo"]
|
||
|
||
|
||
def test_heartbeat_written(_tmp, monkeypatch):
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
assert es.heartbeat_age_days() is None
|
||
ec.run_check(regions=[323], notify=False)
|
||
age = es.heartbeat_age_days()
|
||
assert age is not None and age < 1
|
||
|
||
|
||
def test_one_zone_period_failure_does_not_kill_run(_tmp, monkeypatch):
|
||
"""HIGH-фикс Fable: сбой periods по ОДНОЙ зоне → problem-finding, прогон продолжается
|
||
(pravo проверен, heartbeat записан), а не смерть всего."""
|
||
import ext_fetch
|
||
monkeypatch.setattr(fc, "alive", lambda client=None: True)
|
||
monkeypatch.setattr(fc, "price_zones", lambda s, client=None: [{"id": 191, "name": "Москва"}])
|
||
def boom(z, client=None):
|
||
raise ext_fetch.FetchError("timeout periods")
|
||
monkeypatch.setattr(fc, "latest_period", boom)
|
||
_mock_pravo(monkeypatch, [{"eoNumber": "E1", "number": "1", "name": "индекс",
|
||
"documentDate": "2026-07-01", "relevant": True, "pdf_url": "u"}])
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
assert any(f["level"] == "problem" and "периодов" in f["message"] for f in rep["findings"])
|
||
assert any(f["source"] == "pravo" for f in rep["findings"]) # pravo всё равно проверен
|
||
assert es.heartbeat_age_days() is not None # heartbeat записан
|
||
|
||
|
||
def test_notify_failure_keeps_findings_for_retry(_tmp, monkeypatch):
|
||
"""HIGH-фикс: важная находка + письмо НЕ ушло → watch_seen НЕ сохраняется → повтор (не потеря)."""
|
||
_mock_fgis(monkeypatch, latest=430)
|
||
_mock_pravo(monkeypatch, [])
|
||
monkeypatch.setenv("OPERATOR_EMAIL", "") # адреса нет → _notify вернёт False при updates
|
||
_set_engine(period=425) # движок на 425, latest 430 → сигнал «примени»
|
||
rep = ec.run_check(regions=[323], notify=True)
|
||
assert rep["notify_ok"] is False
|
||
# дедуп НЕ сохранён → на следующем прогоне находка повторится
|
||
assert es.load_watch_seen().get("fgis_periods_reported", {}).get("323/191") != 430
|
||
rep2 = ec.run_check(regions=[323], notify=True)
|
||
assert any(f["source"] == "fgis_split_form" for f in rep2["findings"])
|
||
|
||
|
||
def test_rollback_reports_again(_tmp, monkeypatch):
|
||
"""Исполняет ветку reported.pop (Fable: старый тест её не проверял — мутация «убрать pop»
|
||
выживала). Последовательность: gap+доклад (метка ВЫСТАВЛЕНА) → применили latest (pop, метка снята)
|
||
→ откат применения → снова доклад. Мутант без pop даст тишину на 3-м шаге."""
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(period=425) # движок на 425
|
||
rep1 = ec.run_check(regions=[323], notify=False) # gap → доклад, метка=426
|
||
assert any(f["source"] == "fgis_split_form" and "426" in f["message"] for f in rep1["findings"])
|
||
assert es.load_watch_seen()["fgis_periods_reported"].get("323/191") == 426
|
||
_set_engine(period=426) # применили latest → синхронно
|
||
ec.run_check(regions=[323], notify=False) # pop снимает метку
|
||
assert not es.load_watch_seen().get("fgis_periods_reported", {}).get("323/191")
|
||
_set_engine(period=425) # откат применения → 425
|
||
rep3 = ec.run_check(regions=[323], notify=False)
|
||
assert any(f["source"] == "fgis_split_form" and "426" in f["message"] for f in rep3["findings"])
|
||
|
||
|
||
def test_engine_unset_signal_repeats(_tmp, monkeypatch):
|
||
"""Движку ничего не применено → сигнал ПОВТОРЯЕТСЯ каждый прогон (Fable: раньше был one-shot
|
||
навсегда — пропустил письмо, тишина). Денежный риск не рассасывается сам."""
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, []) # engine не задаём → unset
|
||
r1 = ec.run_check(regions=[323], notify=False)
|
||
r2 = ec.run_check(regions=[323], notify=False)
|
||
def sig(rep):
|
||
return [f for f in rep["findings"] if f["source"] == "fgis_split_form"
|
||
and "не применён ни один регион" in f["message"]]
|
||
assert sig(r1) and sig(r2)
|
||
|
||
|
||
def test_legacy_active_without_period_is_reapply_not_silent(_tmp, monkeypatch):
|
||
"""Дефект Fable: active есть, но БЕЗ метаданных (legacy/без --period) → сигнал «перепримени с
|
||
--period» КАЖДЫЙ прогон, а не ложное «ничего не применяли» и не тишина о реальном устаревании."""
|
||
_mock_fgis(monkeypatch, latest=430)
|
||
_mock_pravo(monkeypatch, [])
|
||
with es.update_state() as st: # legacy: только target/sha, без subject/zone/period
|
||
st.setdefault("active", {})["fgis_split_form"] = {"target": "/x.xlsx", "sha256": "ab"}
|
||
r1 = ec.run_check(regions=[323], notify=False)
|
||
r2 = ec.run_check(regions=[323], notify=False)
|
||
def unk(rep):
|
||
return [f for f in rep["findings"] if f["source"] == "fgis_split_form"
|
||
and "период неизвестен" in f["message"]]
|
||
assert unk(r1) and unk(r2) # повторяется, не one-shot
|
||
assert not any("не применён ни один регион" in f["message"] for f in r1["findings"]) # НЕ ложное
|
||
|
||
|
||
def test_engine_gap_signalled_even_if_zone_not_monitored(_tmp, monkeypatch):
|
||
"""Движковая зона вне EXT_REGIONS → apply-gap всё равно проверяется отдельным запросом
|
||
(Fable: ветка была не покрыта). Иначе узкий EXT_REGIONS потерял бы денежный сигнал."""
|
||
monkeypatch.setattr(fc, "alive", lambda client=None: True)
|
||
monkeypatch.setattr(fc, "price_zones", lambda s, client=None: [{"id": 500, "name": "зона корпуса"}])
|
||
monkeypatch.setattr(fc, "latest_period",
|
||
lambda z, client=None: {"id": 430, "name": "п430"} if z == 191 else {"id": 410, "name": "п410"})
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(subject=323, zone=191, period=426) # движок 323/191@426, но мониторим регион 77
|
||
rep = ec.run_check(regions=[77], notify=False)
|
||
assert any(f["source"] == "fgis_split_form" and f["level"] == "update" and "430" in f["message"]
|
||
for f in rep["findings"])
|
||
|
||
|
||
def test_new_sources_seed_then_update_then_dedup(_tmp, monkeypatch):
|
||
"""opendata/bim/xsd: ПРОГОН1 = тихий засев (info-базлайн, НЕ update); ПРОГОН2 = реальные
|
||
изменения → update-ветка; ПРОГОН3 = дедуп. Раньше тест проверял только засев — update-ветка
|
||
не исполнялась ни разу (mutation-тест `if not first_run:`→`if False:` был зелёным)."""
|
||
import xsd_client
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
od = [{"id": 2, "datasetName": "КСР", "lastChangeDate": "2026-05-20"}]
|
||
bim = [{"guid": "G1", "name": "письмо 1", "filePath": "/x.pdf"}]
|
||
xsd = ["/a/LocalEstimateResourceIndexMethod.zip"]
|
||
monkeypatch.setattr(fc, "opendata_list", lambda client=None: od)
|
||
monkeypatch.setattr(fc, "bim_leaf_docs", lambda client=None: bim)
|
||
monkeypatch.setattr(xsd_client, "schema_links", lambda client=None: xsd)
|
||
with es.update_state() as st:
|
||
st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}}
|
||
|
||
rep1 = ec.run_check(regions=[323], notify=False) # ПРОГОН 1 — засев
|
||
lv = {f["source"]: f["level"] for f in rep1["findings"]
|
||
if f["source"] in ("fgis_opendata", "fgis_bim", "xsd_schema")}
|
||
assert lv == {"fgis_opendata": "info", "fgis_bim": "info", "xsd_schema": "info"}
|
||
|
||
od[0]["lastChangeDate"] = "2026-06-05" # ПРОГОН 2 — реальные изменения
|
||
bim.append({"guid": "G2", "name": "письмо 2", "filePath": "/y.pdf"})
|
||
xsd.append("/a/SummaryEstimate.zip")
|
||
rep2 = ec.run_check(regions=[323], notify=False)
|
||
ups = {f["source"] for f in rep2["findings"] if f["level"] == "update"}
|
||
assert {"fgis_opendata", "fgis_bim", "xsd_schema"} <= ups
|
||
|
||
rep3 = ec.run_check(regions=[323], notify=False) # ПРОГОН 3 — дедуп
|
||
assert not [f for f in rep3["findings"]
|
||
if f["source"] in ("fgis_opendata", "fgis_bim", "xsd_schema") and f["level"] == "update"]
|
||
|
||
|
||
def test_checker_bug_becomes_problem_not_crash(_tmp, monkeypatch):
|
||
"""Фаза 4/5: НЕ-FetchError (баг в чекере) в одном источнике → problem-finding source=имя
|
||
чекера, а прогон продолжается (pravo проверен, heartbeat записан). Иначе баг убил бы отчёт."""
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [{"eoNumber": "E1", "number": "1", "name": "смета",
|
||
"documentDate": "2026-07-01", "relevant": True, "pdf_url": "u"}])
|
||
def bug(client=None):
|
||
raise ValueError("нежданный KeyError-класс баг") # НЕ FetchError
|
||
monkeypatch.setattr(fc, "opendata_list", bug)
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
assert any(f["source"] == "check_opendata" and f["level"] == "problem" for f in rep["findings"])
|
||
assert any(f["source"] == "pravo" for f in rep["findings"]) # прогон не умер
|
||
assert es.heartbeat_age_days() is not None # heartbeat записан
|
||
|
||
|
||
def test_crash_midcheck_does_not_mark_undelivered_finding(_tmp, monkeypatch):
|
||
"""КРИТ (репро Fable): чекер падает не-FetchError ПОСЛЕ того как зона A дала находку «новый
|
||
период» и пометила её 'доложено' in-place. Метка не должна осесть в seen — иначе на следующем
|
||
прогоне (когда сбой ушёл) находка потеряется НАВСЕГДА, регион будет считаться по старым
|
||
индексам. Проверяем: сбой ушёл → находка доходит. Падает на старом _safe_check (без deep-copy)."""
|
||
monkeypatch.setattr(fc, "alive", lambda client=None: True)
|
||
monkeypatch.setattr(fc, "price_zones", lambda s, client=None:
|
||
[{"id": 191, "name": "зона A"}, {"id": 999, "name": "зона B"}])
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(subject=323, zone=191, period=426) # 191 — движковая зона, применён 426
|
||
# ключ fgis_periods_reported УЖЕ есть (метка другой зоны) → reported = ссылка ВНУТРЬ seen,
|
||
# значит reported[323/191]=430 мутирует seen in-place ДО краха (иначе баг не воспроизводится).
|
||
es.save_watch_seen({"fgis_periods_reported": {"999/000": 1}})
|
||
flag = {"boom": True}
|
||
def latest(z, client=None):
|
||
if z == 999 and flag["boom"]:
|
||
raise TypeError("нежданный баг в зоне B") # НЕ FetchError — эмулируем баг чекера
|
||
return {"id": 430, "name": "период 430"} if z == 191 else {"id": 300, "name": "стар"}
|
||
monkeypatch.setattr(fc, "latest_period", latest)
|
||
|
||
rep1 = ec.run_check(regions=[323], notify=False) # ПРОГОН 1 — краш в зоне B
|
||
assert any(f["source"] == "check_fgis" and f["level"] == "problem" for f in rep1["findings"])
|
||
assert not [f for f in rep1["findings"] if f["source"] == "fgis_split_form"] # A не доставлена
|
||
|
||
flag["boom"] = False # сбой ушёл
|
||
rep2 = ec.run_check(regions=[323], notify=False) # ПРОГОН 2 — находка A ДОЛЖНА дойти
|
||
assert any(f["source"] == "fgis_split_form" and "430" in f["message"] for f in rep2["findings"])
|
||
|
||
|
||
def test_regions_all_but_unreachable_is_problem(_tmp, monkeypatch):
|
||
"""EXT_REGIONS=all, но список субъектов не получен (сеть/схема) → problem (факт), а не
|
||
тихое 'не задан' — оператор должен видеть, что мониторинг ФГИС фактически не идёт."""
|
||
monkeypatch.setenv("EXT_REGIONS", "all")
|
||
monkeypatch.setattr(fc, "country_subjects",
|
||
lambda client=None: (_ for _ in ()).throw(__import__("ext_fetch").FetchError("down")))
|
||
_mock_pravo(monkeypatch, [])
|
||
rep = ec.run_check(notify=False) # regions=None → _regions() → []
|
||
assert any(f["source"] == "config" and f["level"] == "problem"
|
||
and "all" in f["message"] for f in rep["findings"])
|
||
|
||
|
||
def test_overlapping_run_is_skipped(_tmp, monkeypatch):
|
||
"""Неблокирующий guard: пока один прогон держит .check.lock, второй пропускается (не дубль)."""
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
import fcntl
|
||
lock_path = es.ext_dir() / ".check.lock"
|
||
fd = os.open(str(lock_path), os.O_CREAT | os.O_RDWR, 0o644)
|
||
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) # имитируем идущий прогон
|
||
try:
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
finally:
|
||
os.close(fd)
|
||
assert rep.get("skipped") is True and rep["findings"] == []
|
||
|
||
|
||
# ---------- сигнал «скачано, но НЕ разобрано/применено» по БИМ (по ПРИМЕНЁННОМУ индексу) ----------
|
||
|
||
def _seed_bim_letters(tmp, letters: dict):
|
||
"""Снапшоты писем на диске: {guid: fetched_at}."""
|
||
for guid, fa in letters.items():
|
||
d = tmp / "snapshots/fgis/bim_letters" / guid
|
||
d.mkdir(parents=True, exist_ok=True)
|
||
(d / "letter.pdf").write_bytes(b"%PDF-stub")
|
||
(d / "meta.json").write_text(json.dumps({"fetched_at": fa}), encoding="utf-8")
|
||
|
||
|
||
def _seed_bim_index(tmp, built_at: str | None, guids=("g-old",)):
|
||
idx = {"schema": 1, "quarters": {"2026-Q1": {
|
||
"label": "I квартал 2026",
|
||
"letters": [{"guid": g, "scanned": False} for g in guids],
|
||
"records": [], "partial": False}}}
|
||
if built_at is not None:
|
||
idx["built_at"] = built_at
|
||
p = tmp / "derived/bim/bim_index.json"
|
||
p.parent.mkdir(parents=True, exist_ok=True)
|
||
p.write_text(json.dumps(idx, ensure_ascii=False), encoding="utf-8")
|
||
|
||
|
||
def _bim_gap(rep, level=None):
|
||
return [f for f in rep["findings"] if f["source"] == "fgis_bim_index"
|
||
and (level is None or f["level"] == level)]
|
||
|
||
|
||
def test_bim_index_absent_recurrent_info_not_update(_tmp, monkeypatch):
|
||
"""Письма скачаны, индекс НЕ развёрнут (активация — гейт Юрия B1) → info КАЖДЫЙ прогон
|
||
(видно в отчёте/панели), но НЕ update: ежедневное письмо не должно продавливать гейт."""
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(period=426)
|
||
_seed_bim_letters(_tmp, {"g1": "2026-07-18T03:00:00Z", "g2": "2026-07-18T03:00:00Z",
|
||
"g3": "2026-07-18T03:00:00Z"})
|
||
r1 = ec.run_check(regions=[323], notify=False)
|
||
r2 = ec.run_check(regions=[323], notify=False)
|
||
for rep in (r1, r2): # рекуррентно, не one-shot
|
||
infos = _bim_gap(rep, "info")
|
||
assert len(infos) == 1 and "3" in infos[0]["message"] and "НЕ развёрнут" in infos[0]["message"]
|
||
assert not _bim_gap(rep, "update")
|
||
|
||
|
||
def test_bim_new_letter_after_build_update_recurrent_until_rebuild(_tmp, monkeypatch):
|
||
"""Ядро A2: индекс работает; письмо скачано ПОСЛЕ его сборки → update «нужен разбор+apply»
|
||
КАЖДЫЙ прогон (без дедупа — протухание served-данных не рассасывается само); снимается
|
||
ТОЛЬКО пересборкой индекса (built_at новее). Авто-apply чекер НЕ делает."""
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(period=426)
|
||
_seed_bim_letters(_tmp, {"g-old": "2026-07-18T03:00:00Z"})
|
||
_seed_bim_index(_tmp, "2026-07-23T12:00:00Z", guids=("g-old",))
|
||
|
||
r1 = ec.run_check(regions=[323], notify=False) # всё скачанное разобрано → тишина
|
||
assert not _bim_gap(r1)
|
||
|
||
_seed_bim_letters(_tmp, {"g-new": "2026-07-24T09:00:00Z"}) # новое письмо после сборки
|
||
r2 = ec.run_check(regions=[323], notify=False)
|
||
r3 = ec.run_check(regions=[323], notify=False)
|
||
for rep in (r2, r3): # рекуррентно, без дедупа
|
||
ups = _bim_gap(rep, "update")
|
||
assert len(ups) == 1
|
||
assert "ПОСЛЕ" in ups[0]["message"] and "1" in ups[0]["message"]
|
||
assert "apply" in ups[0]["action"] # команда оператору, не авто-исполнение
|
||
|
||
_seed_bim_index(_tmp, "2026-07-25T00:00:00Z", guids=("g-old", "g-new")) # пересобрали
|
||
r4 = ec.run_check(regions=[323], notify=False)
|
||
assert not _bim_gap(r4) # сигнал снят реальным разбором
|
||
|
||
|
||
def test_bim_index_without_built_at_is_problem(_tmp, monkeypatch):
|
||
"""Индекс без built_at → свежесть не отследить → problem (fail-loud), не тихий ноль."""
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(period=426)
|
||
_seed_bim_letters(_tmp, {"g-old": "2026-07-18T03:00:00Z"})
|
||
_seed_bim_index(_tmp, None, guids=("g-old",))
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
probs = _bim_gap(rep, "problem")
|
||
assert len(probs) == 1 and "built_at" in probs[0]["message"]
|
||
|
||
|
||
def test_bim_parsed_but_tool_unwired_is_problem(_tmp, monkeypatch):
|
||
"""Индекс собран, но инструмент НЕ зарегистрирован на агентном пути (регресс кода) →
|
||
problem: данные «разобраны, но не отдаются» — класс declared-not-delivered."""
|
||
import smeta_mcp
|
||
monkeypatch.setattr(smeta_mcp, "TOOLS", {})
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(period=426)
|
||
_seed_bim_letters(_tmp, {"g-old": "2026-07-18T03:00:00Z"})
|
||
_seed_bim_index(_tmp, "2026-07-23T12:00:00Z", guids=("g-old",))
|
||
rep = ec.run_check(regions=[323], notify=False)
|
||
probs = _bim_gap(rep, "problem")
|
||
assert len(probs) == 1 and "find_recalc_index" in probs[0]["message"]
|
||
|
||
|
||
def test_bim_gap_does_not_mutate_state_or_seen(_tmp, monkeypatch):
|
||
"""Чекер БИМ ТОЛЬКО докладывает: state.json не тронут, дедуп-меток в watch_seen не оставляет
|
||
(иначе сигнал стал бы one-shot и протухание замолчало бы)."""
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
_set_engine(period=426)
|
||
_seed_bim_letters(_tmp, {"g-new": "2026-07-24T09:00:00Z"})
|
||
_seed_bim_index(_tmp, "2026-07-23T12:00:00Z", guids=())
|
||
before = (_tmp / "state.json").read_bytes()
|
||
ec.run_check(regions=[323], notify=False)
|
||
assert (_tmp / "state.json").read_bytes() == before
|
||
seen = es.load_watch_seen()
|
||
assert not any("bim_index" in k for k in seen) # никаких своих меток дедупа
|
||
|
||
|
||
def test_notify_called_only_with_findings(_tmp, monkeypatch):
|
||
_mock_fgis(monkeypatch, latest=426)
|
||
_mock_pravo(monkeypatch, [])
|
||
monkeypatch.setenv("OPERATOR_EMAIL", "op@test")
|
||
calls = []
|
||
import email_service
|
||
monkeypatch.setattr(email_service, "send_operator_digest",
|
||
lambda to, subj, html: calls.append((to, subj)) or True)
|
||
_set_engine(period=426) # движок синхронен с latest → нет новостей
|
||
ec.run_check(regions=[323], notify=True)
|
||
assert calls == []
|
||
_mock_fgis(monkeypatch, latest=430) # latest вырос, движок всё на 426 → «примени»
|
||
ec.run_check(regions=[323], notify=True)
|
||
assert len(calls) == 1 and calls[0][0] == "op@test" # письмо ушло с новостью
|