"""Срез 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 test_new_period_produces_finding_with_action(_tmp, monkeypatch): _mock_fgis(monkeypatch, latest=426) _mock_pravo(monkeypatch, []) # активен период 425 → 426 новее with es.update_state() as st: st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 425}} 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_pull.py" in ups[0]["action"] def test_no_finding_when_period_is_active(_tmp, monkeypatch): _mock_fgis(monkeypatch, latest=426) _mock_pravo(monkeypatch, []) with es.update_state() as st: st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} rep = ec.run_check(regions=[323], notify=False) assert not [f for f in rep["findings"] if f["source"] == "fgis_split_form"] 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 with es.update_state() as st: st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 425}} 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): """MEDIUM-фикс: применили период → синхронно (нет доклада, метка снята) → откат → снова доклад.""" _mock_fgis(monkeypatch, latest=426) _mock_pravo(monkeypatch, []) with es.update_state() as st: st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} # активен = latest ec.run_check(regions=[323], notify=False) # синхронно → нет находки assert not es.load_watch_seen().get("fgis_periods_reported", {}).get("323/191") # откат: активным стал 425 (а latest всё ещё 426) with es.update_state() as st: st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 425}} rep = ec.run_check(regions=[323], notify=False) assert any(f["source"] == "fgis_split_form" and "426" 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, []) with es.update_state() as st: st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} # активен 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 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) with es.update_state() as st: st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426}} ec.run_check(regions=[323], notify=True) # нет новостей assert calls == [] _mock_fgis(monkeypatch, latest=430) # теперь новый период ec.run_check(regions=[323], notify=True) assert len(calls) == 1 and calls[0][0] == "op@test" # письмо ушло с новостью