fix(обход): сбой сети не снимает ожидания, здоровье краснеет при сбоях
Уход зоны доказывается только успешно прочитанным списком зон субъекта: при сбое списка зон или периодов ожидания остаются. last_success пишется только при пустом списке сбоев, попытка отмечается отдельно. Health-проверка zone_scan краснеет от сбоев и от возраста свыше 36 часов, в журнале сторожа виден возраст обхода. Проверки: три ветки на выдуманных данных, мутации ловятся. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
"""Планировщик ожиданий ежедневного обхода зон (22.11.2026)."""
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts"))
|
||||
import fgis_zone_scan as z # noqa: E402
|
||||
@@ -26,5 +29,107 @@ def test_old_expectation_removed_by_horizon():
|
||||
|
||||
def test_zone_gone_removes_all_its_expectations():
|
||||
ex = [{"subject_id": 999, "zone_id": 1, "period": "2025-Q1"}]
|
||||
_, rem = z.plan(ex, PORTAL, known=set(), horizon=2)
|
||||
_, rem = z.plan(ex, PORTAL, known=set(), horizon=2, zones_by_subject={999: set()})
|
||||
assert ex[0] in rem
|
||||
|
||||
|
||||
def test_network_failure_keeps_expectations():
|
||||
"""Сбой периодов не доказывает уход зоны: ожидание остаётся."""
|
||||
ex = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1"}]
|
||||
_, rem = z.plan(ex, {}, known=set(), horizon=2, zones_by_subject={1: {7}})
|
||||
assert rem == []
|
||||
|
||||
|
||||
def test_unknown_subject_keeps_expectations():
|
||||
"""Список зон субъекта не прочитан — трогать его ожидания нельзя."""
|
||||
ex = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1"}]
|
||||
_, rem = z.plan(ex, {}, known=set(), horizon=2, zones_by_subject={})
|
||||
assert rem == []
|
||||
|
||||
|
||||
def _scan_stand(tmp_path, monkeypatch, periods, known=(), expect=None,
|
||||
pull_error=None, fail_periods=False, fail_subjects=False):
|
||||
db = tmp_path / "fgis.sqlite"
|
||||
con = sqlite3.connect(db)
|
||||
con.execute("create table zone_snapshots(subject_id int, zone_id int, period_id int)")
|
||||
con.executemany("insert into zone_snapshots values (?,?,?)", known)
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
class Client:
|
||||
def country_subjects(self):
|
||||
if fail_subjects:
|
||||
raise RuntimeError("сеть недоступна")
|
||||
return [{"id": 1}]
|
||||
|
||||
def price_zones(self, sid):
|
||||
return [{"id": 7}]
|
||||
|
||||
def periods(self, zid):
|
||||
if fail_periods:
|
||||
raise RuntimeError("таймаут")
|
||||
return periods
|
||||
|
||||
def pull_split_form(sid, zid, pid):
|
||||
if pull_error:
|
||||
raise RuntimeError(pull_error)
|
||||
|
||||
monkeypatch.setitem(sys.modules, "fgis_client", Client())
|
||||
monkeypatch.setitem(sys.modules, "ext_pull",
|
||||
types.SimpleNamespace(pull_split_form=pull_split_form))
|
||||
expect_path = tmp_path / "expect.json"
|
||||
if expect is not None:
|
||||
expect_path.write_text(json.dumps(expect, ensure_ascii=False), encoding="utf-8")
|
||||
state_path = tmp_path / "state.json"
|
||||
log_path = tmp_path / "scan.log"
|
||||
monkeypatch.setenv("SCAN_LOCK", str(tmp_path / "scan.lock"))
|
||||
monkeypatch.delenv("OPERATOR_EMAIL", raising=False)
|
||||
monkeypatch.setattr(sys, "argv", [
|
||||
"fgis_zone_scan.py", "--expect", str(expect_path), "--state", str(state_path),
|
||||
"--log", str(log_path), "--db", str(db)])
|
||||
code = z.main()
|
||||
return code, expect_path, state_path, log_path
|
||||
|
||||
|
||||
def test_new_period_is_added_and_run_marked_success(tmp_path, monkeypatch):
|
||||
periods = [p(1, "1 квартал 2025"), p(2, "2 квартал 2025"), p(3, "3 квартал 2025"),
|
||||
p(4, "4 квартал 2025 г."), p(5, "1 квартал 2026 г.")]
|
||||
code, expect, state, log = _scan_stand(
|
||||
tmp_path, monkeypatch, periods, known={(1, 7, 4)}, expect=[])
|
||||
assert code == 0
|
||||
assert "добавлено=1" in log.read_text(encoding="utf-8")
|
||||
data = json.loads(state.read_text(encoding="utf-8"))
|
||||
assert data["failures"] == [] and data["last_success"]
|
||||
|
||||
|
||||
def test_expired_expectation_is_removed(tmp_path, monkeypatch):
|
||||
periods = [p(1, "1 квартал 2025"), p(2, "2 квартал 2025"), p(3, "3 квартал 2025"),
|
||||
p(4, "4 квартал 2025 г."), p(5, "1 квартал 2026 г.")]
|
||||
old = [{"subject_id": 1, "zone_id": 7, "period": "2024-Q1", "reason": "старое"}]
|
||||
code, expect, state, log = _scan_stand(
|
||||
tmp_path, monkeypatch, periods, known={(1, 7, 3), (1, 7, 4), (1, 7, 5)}, expect=old)
|
||||
assert code == 0
|
||||
assert "снято=1" in log.read_text(encoding="utf-8")
|
||||
assert json.loads(expect.read_text(encoding="utf-8")) == []
|
||||
|
||||
|
||||
def test_network_failure_keeps_files_and_marks_no_success(tmp_path, monkeypatch):
|
||||
old = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1", "reason": "нет форм"}]
|
||||
before = json.dumps(old, ensure_ascii=False)
|
||||
code, expect, state, log = _scan_stand(
|
||||
tmp_path, monkeypatch, [], expect=old, fail_periods=True)
|
||||
assert code == 1
|
||||
assert expect.read_text(encoding="utf-8") == before
|
||||
data = json.loads(state.read_text(encoding="utf-8"))
|
||||
assert data["failures"] and not data.get("last_success")
|
||||
assert "сбоев=1" in log.read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def test_country_list_failure_keeps_expectations(tmp_path, monkeypatch):
|
||||
old = [{"subject_id": 1, "zone_id": 7, "period": "2025-Q1"}]
|
||||
before = json.dumps(old, ensure_ascii=False)
|
||||
code, expect, state, log = _scan_stand(
|
||||
tmp_path, monkeypatch, [], expect=old, fail_subjects=True)
|
||||
assert code == 1
|
||||
assert expect.read_text(encoding="utf-8") == before
|
||||
assert json.loads(state.read_text(encoding="utf-8"))["failures"]
|
||||
|
||||
@@ -715,3 +715,41 @@ def test_old_canaries_are_marked_as_retired():
|
||||
head = open(os.path.join(ROOT, "scripts", name), encoding="utf-8").read()[:1500]
|
||||
assert "снят с расписания" in head, name
|
||||
assert "health_checks.py" in head, name
|
||||
|
||||
|
||||
# --- Д. Свежесть ежедневного обхода зон ФГИС -----------------------------------
|
||||
|
||||
def _zone_state(tmp_path, monkeypatch, **state):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
now = datetime.now(timezone.utc)
|
||||
state.setdefault("last_success", (now - timedelta(hours=1)).strftime("%Y-%m-%dT%H:%M:%SZ"))
|
||||
path = tmp_path / "zone_state.json"
|
||||
path.write_text(json.dumps(state, ensure_ascii=False), encoding="utf-8")
|
||||
monkeypatch.setenv("ZONE_SCAN_STATE", str(path))
|
||||
return path
|
||||
|
||||
|
||||
def test_zone_scan_fresh_success_is_green(env, tmp_path, monkeypatch):
|
||||
_, h, _ = env
|
||||
_zone_state(tmp_path, monkeypatch, last_attempt="2026-11-22T06:00:00Z", failures=[])
|
||||
c = h.check_zone_scan()
|
||||
assert c.ok and c.name == "zone_scan"
|
||||
assert "возраст" in c.detail
|
||||
|
||||
|
||||
def test_zone_scan_stale_success_is_red(env, tmp_path, monkeypatch):
|
||||
from datetime import datetime, timedelta, timezone
|
||||
_, h, _ = env
|
||||
old = (datetime.now(timezone.utc) - timedelta(hours=40)).strftime("%Y-%m-%dT%H:%M:%SZ")
|
||||
_zone_state(tmp_path, monkeypatch, last_success=old, failures=[])
|
||||
c = h.check_zone_scan()
|
||||
assert not c.ok and "возраст" in c.detail
|
||||
|
||||
|
||||
def test_zone_scan_failed_last_run_is_red(env, tmp_path, monkeypatch):
|
||||
_, h, _ = env
|
||||
_zone_state(tmp_path, monkeypatch, last_attempt="2026-11-22T06:00:00Z",
|
||||
failures=["periods 1/7: Timeout"])
|
||||
c = h.check_zone_scan()
|
||||
assert not c.ok
|
||||
assert "сбоями" in c.detail and "periods 1/7" in c.detail
|
||||
|
||||
Reference in New Issue
Block a user