"""Планировщик ожиданий ежедневного обхода зон (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"]