Files
smeta-web/tests/test_ext_check.py
T
anor 3a92013600 feat(ext): Фаза 3 — чекер обновлений (только доклад) + watch_seen/heartbeat/дайджест
ext_check: обходит источники (новый период ФГИС по зонам, новые приказы pravo, недоступность),
ТОЛЬКО докладывает — state.json НЕ трогает (инвариант в тесте, red-green). watch_seen (дедуп),
reports/, watch.log, heartbeat. email_service.send_operator_digest — письмо оператору только
при новостях (тишина=норма). 7 тестов.
2026-07-18 01:38:44 +10:00

114 lines
5.1 KiB
Python

"""Срез 3.1: чекер обновлений. Главный инвариант — ЧЕКЕР НЕ МУТИРУЕТ state.json
(его пишут только pull/apply). red-green: тест на неизменность state — первым по важности.
Сеть замокана (fgis_client/pravo_client).
"""
import json
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
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, pages=1, 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_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" # письмо ушло с новостью