fix(ext): money-safety/надёжность фиксы Fable в мониторинге (Фаза 2/3)
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-тестов.
This commit is contained in:
@@ -96,6 +96,53 @@ def test_heartbeat_written(_tmp, monkeypatch):
|
||||
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, [])
|
||||
|
||||
+43
-14
@@ -1,4 +1,6 @@
|
||||
"""Срез 2.1: мониторинг приказов Минстроя. Мок на реальной фикстуре pravo.gov.ru."""
|
||||
"""Срез 2.1 (+ фиксы Fable): мониторинг приказов. Мок page-aware (пагинация вглубь),
|
||||
фильтр item без eoNumber, дедуп по seen.
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
@@ -13,28 +15,55 @@ import pravo_client as pc # noqa: E402
|
||||
FIX = Path(__file__).resolve().parent / "fixtures" / "ext" / "pravo_documents.json"
|
||||
|
||||
|
||||
def _client():
|
||||
fixture = json.loads(FIX.read_text(encoding="utf-8"))
|
||||
return httpx.Client(transport=httpx.MockTransport(
|
||||
lambda r: httpx.Response(200, json=fixture) if r.url.path == "/api/Documents"
|
||||
else httpx.Response(404)))
|
||||
def _page_aware(pages: dict[int, list]):
|
||||
"""Мок: по index=N отдаёт свою страницу items; pagesTotalCount = число страниц."""
|
||||
total = len(pages)
|
||||
def handler(r):
|
||||
if r.url.path != "/api/Documents":
|
||||
return httpx.Response(404)
|
||||
idx = int(r.url.params.get("index", "1"))
|
||||
return httpx.Response(200, json={"items": pages.get(idx, []), "pagesTotalCount": total})
|
||||
return httpx.Client(transport=httpx.MockTransport(handler))
|
||||
|
||||
|
||||
def _fixture_items():
|
||||
return json.loads(FIX.read_text(encoding="utf-8"))["items"]
|
||||
|
||||
|
||||
def test_recent_normalized():
|
||||
with _client() as c:
|
||||
with _page_aware({1: _fixture_items()}) as c:
|
||||
docs = pc.recent(client=c)
|
||||
assert docs and all("eoNumber" in d and "pdf_url" in d for d in docs)
|
||||
assert docs[0]["number"] == "362/пр"
|
||||
assert docs[0]["pdf_url"].endswith("eoNumber=" + docs[0]["eoNumber"])
|
||||
|
||||
|
||||
def test_new_since_dedup():
|
||||
with _client() as c:
|
||||
first = pc.recent(client=c)
|
||||
seen = {first[0]["eoNumber"]}
|
||||
def test_new_since_paginates_backlog():
|
||||
"""Бэклог >1 страницы (API отдаёт новейшие первыми): новые на стр.1 И стр.2 доложены,
|
||||
стоп на стр.3 (целиком виденная). Раньше брали только стр.1 → бэклог терялся (баг Fable)."""
|
||||
tmpl = _fixture_items()[0]
|
||||
p1 = [{**tmpl, "eoNumber": f"NEW1-{i}"} for i in range(3)] # новые
|
||||
p2 = [{**tmpl, "eoNumber": f"NEW2-{i}"} for i in range(3)] # тоже новые (глубже)
|
||||
p3 = [{**tmpl, "eoNumber": f"OLD-{i}"} for i in range(3)] # виденные
|
||||
with _page_aware({1: p1, 2: p2, 3: p3}) as c:
|
||||
seen = {f"OLD-{i}" for i in range(3)}
|
||||
new = pc.new_since(seen, client=c)
|
||||
assert all(d["eoNumber"] != first[0]["eoNumber"] for d in new)
|
||||
assert len(new) == len(first) - 1
|
||||
got = {d["eoNumber"] for d in new}
|
||||
assert got == {"NEW1-0", "NEW1-1", "NEW1-2", "NEW2-0", "NEW2-1", "NEW2-2"} # обе новые страницы
|
||||
|
||||
|
||||
def test_new_since_stops_when_page_all_seen():
|
||||
items = _fixture_items()
|
||||
with _page_aware({1: items[:3], 2: items[:3]}) as c:
|
||||
seen = {d["eoNumber"] for d in items[:3]} # 1-я страница целиком виденная
|
||||
new = pc.new_since(seen, client=c)
|
||||
assert new == [] # глубже не пошли, дублей нет
|
||||
|
||||
|
||||
def test_item_without_eonumber_skipped():
|
||||
bad = [{"number": "X", "name": "смета"}, {"eoNumber": "OK1", "number": "1", "name": "индекс"}]
|
||||
with _page_aware({1: bad}) as c:
|
||||
docs = pc.recent(client=c)
|
||||
assert [d["eoNumber"] for d in docs] == ["OK1"] # item без eoNumber отброшен (не None в дедупе)
|
||||
|
||||
|
||||
def test_relevance_flag():
|
||||
|
||||
Reference in New Issue
Block a user