Files
smeta-web/tests/test_fgis_zone_scan.py
anorandClaude Code 6a6627ee1b fix(обход): сбой сети не снимает ожидания, здоровье краснеет при сбоях
Уход зоны доказывается только успешно прочитанным списком зон субъекта:
при сбое списка зон или периодов ожидания остаются. last_success пишется
только при пустом списке сбоев, попытка отмечается отдельно. Health-проверка
zone_scan краснеет от сбоев и от возраста свыше 36 часов, в журнале сторожа
виден возраст обхода. Проверки: три ветки на выдуманных данных, мутации
ловятся.

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-11-22 17:03:03 +10:00

136 lines
6.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Планировщик ожиданий ежедневного обхода зон (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
def p(i, name): return {"id": i, "name": name}
PORTAL = {(320, 245): [p(421, "1 квартал 2025 г."), p(422, "2 квартал 2025 г."),
p(423, "3 квартал 2025 г."), p(424, "4 квартал 2025 г."),
p(425, "1 квартал 2026 г."), p(426, "2 квартал 2026 г.")]}
def test_new_period_added_when_not_loaded():
adds, rem = z.plan([], PORTAL, known={(320, 245, 425)}, horizon=2)
assert any(a["period"] == "2026-Q2" for a in adds)
assert not any(a["period"] == "2026-Q1" for a in adds)
def test_expectation_not_duplicated():
ex = [{"subject_id": 320, "zone_id": 245, "period": "2026-Q2"}]
adds, _ = z.plan(ex, PORTAL, known={(320, 245, 425)}, horizon=2)
assert not [a for a in adds if a["period"] == "2026-Q2"]
def test_old_expectation_removed_by_horizon():
ex = [{"subject_id": 320, "zone_id": 245, "period": "2024-Q4"}]
_, rem = z.plan(ex, PORTAL, known=set(), horizon=2)
assert ex[0] in rem
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, 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"]