"""Агрегация состояния нормативной базы для админ-панели. Сеть ФГИС замокана.""" import sys from pathlib import Path import pytest sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) import ext_state as es # noqa: E402 import ext_status as est # noqa: E402 @pytest.fixture(autouse=True) def _tmp(monkeypatch, tmp_path): monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path)) est._ref_cache = None # сбросить кэш меток между тестами # доменные метки: 2 субъекта, период 426 = «2 квартал 2026 г.» monkeypatch.setattr(est, "_reference", lambda refresh=False: { "periods": {"426": "2 квартал 2026 г.", "425": "1 квартал 2026 г."}, "subjects": {"323": "город Москва", "50": "Московская область"}, "n_subjects": 2}) return tmp_path def _meta(path: Path): path.mkdir(parents=True, exist_ok=True) (path / "meta.json").write_text("{}", encoding="utf-8") def _seed_prices(zones): with es.update_state() as st: st["sources"]["fgis_split_form"] = { k: {"period_id": p, "pulled_at": "2026-07-18T03:00:00Z"} for k, p in zones.items()} def test_completeness_and_missing_regions(_tmp): _seed_prices({"323/191": 426}) # загружена только Москва из 2 субъектов s = est.normative_status() price = next(x for x in s["sources"] if x["key"] == "fgis_split_form") assert price["regions_loaded"] == 1 and price["regions_total"] == 2 assert price["missing_regions"] == ["Московская область"] # поимённо, чего нет assert price["base_period"] == "2 квартал 2026 г." # доменная метка, не id def test_freshness_thresholds(_tmp, monkeypatch): # свежая загрузка (сегодня) → ok _seed_prices({"323/191": 426}) assert next(x for x in est.normative_status()["sources"] if x["key"] == "fgis_split_form")["freshness"] == "ok" # загрузка полугодовой давности при квартальной каденции → stale with es.update_state() as st: st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426, "pulled_at": "2026-01-01T00:00:00Z"}} assert next(x for x in est.normative_status()["sources"] if x["key"] == "fgis_split_form")["freshness"] == "stale" def test_engine_unset(_tmp): _seed_prices({"323/191": 426}) e = est.normative_status()["engine"] assert e["status"] == "unset" and "дефолтного" in e["message"] def test_engine_ok_and_behind_pulled(_tmp): """Движок применён на 425, а скачано 426 → флаг behind_pulled (скачано≠применено).""" with es.update_state() as st: st["sources"]["fgis_split_form"] = {"323/191": {"period_id": 426, "pulled_at": "2026-07-18T03:00:00Z"}} st.setdefault("active", {})["fgis_split_form"] = { "subject": 323, "zone": 191, "period_id": 425, "activated_at": "2026-07-01T00:00:00Z"} e = est.normative_status()["engine"] assert e["status"] == "ok" and e["applied_period"] == "1 квартал 2026 г." assert e["pulled_period_id"] == 426 and e["behind_pulled"] is True def test_engine_unknown_legacy(_tmp): with es.update_state() as st: st.setdefault("active", {})["fgis_split_form"] = {"target": "/x.xlsx", "sha256": "ab"} assert est.normative_status()["engine"]["status"] == "unknown" def test_doc_sources_counts_and_modes(_tmp): for i in range(3): _meta(_tmp / "snapshots/fgis/bim_letters" / f"g{i}") _meta(_tmp / "snapshots/xsd" / "LSR.zip") es.save_watch_seen({"bim_guids": ["g0", "g1", "g2", "g3"], "xsd_links": ["LSR.zip"], "pravo_eo": ["E1", "E2"]}) s = est.normative_status() bim = next(x for x in s["sources"] if x["key"] == "bim") assert bim["downloaded"] == 3 and bim["known"] == 4 and bim["mode"] == "download" pravo = next(x for x in s["sources"] if x["key"] == "pravo") assert pravo["mode"] == "monitor" and pravo["known"] == 2 # отслеживается, не качается def test_reference_offline_degrades_to_ids(_tmp, monkeypatch): """ФГИС недоступен для меток → период сырым id, полнота по fallback-константе, не падение.""" monkeypatch.setattr(est, "_reference", lambda refresh=False: {"periods": {}, "subjects": {}, "n_subjects": None}) _seed_prices({"323/191": 426}) price = next(x for x in est.normative_status()["sources"] if x["key"] == "fgis_split_form") assert price["base_period"] == "период 426" # деградация к id assert price["regions_total"] == est.TOTAL_SUBJECTS_FALLBACK assert price["missing_regions"] == [] # имён нет — список пуст, не падаем def test_checked_status_from_heartbeat(_tmp): assert est.normative_status()["checked"]["status"] == "never" # heartbeat не писан es.write_heartbeat() assert est.normative_status()["checked"]["status"] == "ok"