Fable: контракт «чекер не мутирует state» — чисто. Исправлено: (HIGH) сбой периодов ОДНОЙ зоны роняет весь прогон → try/except+problem+continue; (HIGH) находки доставлялись оператору ровно раз и молча терялись при сбое SMTP → watch_seen сохраняется только после доставки (at-least-once), _notify возвращает bool, warning в log; (MEDIUM) бэклог >30 приказов терялся → пагинация вглубь до виденной страницы; item без eoNumber ронял прогон → фильтр; откат периода → вечное молчание → сброс метки при синхроне; html.escape в письме + https pravo; grep-якорь в cron (не снести dev2); warning при пустом EXT_REGIONS. 30 ext-тестов.
161 lines
8.2 KiB
Python
161 lines
8.2 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_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_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" # письмо ушло с новостью
|