feat(ext): Фаза 1 — скачивание и активация данных ФГИС ЦС
fgis_client: download_split_form/indices/salary (endpoints сняты с сервера). ext_pull: скачивание в снапшоты по региону+кварталу (осознанный шаг, EXT_REGIONS, не все 85). ext_apply: verify (openpyxl+кодов≥1000) → diff по кодам колонки A → ГЕЙТ аномалий (>30% удалено → отказ без --force) → бэкап старого → атомарная подмена fgis_split_form.xlsx → предупреждение о fgis_cache.pkl (удаление только --yes) → напоминание рестарта (сам НЕ рестартит). 11 тестов (гейт red-green).
This commit is contained in:
+151
@@ -0,0 +1,151 @@
|
||||
"""ext_apply — осознанная активация снапшота ФГИС для движка (срез 1.3).
|
||||
|
||||
Заменяет рабочий fgis_split_form.xlsx (его ест estimate_contract) новым снапшотом ТОЛЬКО
|
||||
после проверок, с диффом на экране и защитой от аномалий (fail-loud). Никаких тихих
|
||||
перезаписей денежных данных. НЕ рестартит сервис — только напоминает.
|
||||
|
||||
Порядок: verify(new) → если есть текущий: verify(old)+diff+гейт → бэкап старого в снапшот
|
||||
→ атомарная подмена target → (по --yes) удалить fgis_cache.pkl → напомнить рестарт.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import ext_state
|
||||
|
||||
MIN_CODES = 1000 # реальная сплит-форма ~43k строк; <1000 = явно битый файл
|
||||
REMOVED_RATIO_GATE = 0.30 # исчезло >30% кодов → аномалия, требуется --force
|
||||
|
||||
|
||||
def _target_file() -> Path:
|
||||
"""Куда активируем: fgis_split_form.xlsx рядом с движком (estimate_contract._SR_ROOT)."""
|
||||
try:
|
||||
import estimate_contract as ec
|
||||
return Path(ec._SR_ROOT) / "fgis_split_form.xlsx"
|
||||
except Exception:
|
||||
return Path(os.environ.get("SMETA_RAILWAY", "../smeta-railway")) / "fgis_split_form.xlsx"
|
||||
|
||||
|
||||
def read_codes(xlsx_path: os.PathLike | str) -> set[str]:
|
||||
"""Множество кодов ресурсов из первой колонки (read-only, для больших файлов)."""
|
||||
import openpyxl
|
||||
wb = openpyxl.load_workbook(str(xlsx_path), read_only=True, data_only=True)
|
||||
try:
|
||||
ws = wb.active
|
||||
codes: set[str] = set()
|
||||
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True)):
|
||||
if i == 0:
|
||||
continue # шапка
|
||||
v = row[0]
|
||||
if v is not None and str(v).strip():
|
||||
codes.add(str(v).strip())
|
||||
return codes
|
||||
finally:
|
||||
wb.close()
|
||||
|
||||
|
||||
def verify_snapshot(xlsx_path: os.PathLike | str) -> dict:
|
||||
"""Структурная проверка: openpyxl открывает, кодов ≥ порога. Возвращает {ok, codes, errors}."""
|
||||
errors = []
|
||||
try:
|
||||
codes = read_codes(xlsx_path)
|
||||
except Exception as e: # noqa: BLE001 — битый xlsx не должен доехать до движка
|
||||
return {"ok": False, "codes": 0, "errors": [f"не открывается как xlsx: {type(e).__name__}: {e}"]}
|
||||
if len(codes) < MIN_CODES:
|
||||
errors.append(f"кодов {len(codes)} < {MIN_CODES} — подозрительно мало (битый/частичный?)")
|
||||
return {"ok": not errors, "codes": len(codes), "errors": errors, "_codes": codes}
|
||||
|
||||
|
||||
def diff_codes(old_codes: set[str], new_codes: set[str]) -> dict:
|
||||
added = new_codes - old_codes
|
||||
removed = old_codes - new_codes
|
||||
removed_ratio = (len(removed) / len(old_codes)) if old_codes else 0.0
|
||||
return {
|
||||
"added": len(added), "removed": len(removed), "common": len(old_codes & new_codes),
|
||||
"removed_ratio": round(removed_ratio, 4),
|
||||
"sample_removed": sorted(list(removed))[:10],
|
||||
"sample_added": sorted(list(added))[:10],
|
||||
}
|
||||
|
||||
|
||||
def activate(snapshot_xlsx: os.PathLike | str, *, target_file: Path | None = None,
|
||||
force: bool = False, drop_cache: bool = False) -> dict:
|
||||
"""Активировать снапшот. Возвращает отчёт. При аномалии без force — {activated: False}."""
|
||||
snapshot_xlsx = Path(snapshot_xlsx)
|
||||
target = Path(target_file) if target_file else _target_file()
|
||||
|
||||
v_new = verify_snapshot(snapshot_xlsx)
|
||||
if not v_new["ok"]:
|
||||
return {"activated": False, "reason": "новый снапшот не прошёл verify", "verify_new": v_new}
|
||||
|
||||
report = {"target": str(target), "verify_new": {k: v for k, v in v_new.items() if k != "_codes"}}
|
||||
|
||||
if target.exists():
|
||||
v_old = verify_snapshot(target)
|
||||
d = diff_codes(v_old.get("_codes", set()), v_new["_codes"])
|
||||
report["diff"] = d
|
||||
report["verify_old"] = {k: v for k, v in v_old.items() if k != "_codes"}
|
||||
if d["removed_ratio"] > REMOVED_RATIO_GATE and not force:
|
||||
report["activated"] = False
|
||||
report["reason"] = (f"АНОМАЛИЯ: исчезло {d['removed']} кодов "
|
||||
f"({d['removed_ratio']*100:.0f}% > {REMOVED_RATIO_GATE*100:.0f}%). "
|
||||
f"Примеры: {d['sample_removed']}. Нужен --force, если это ожидаемо.")
|
||||
return report
|
||||
# бэкап текущего рядом (в снапшоты), чтобы не потерять то, что реально стояло
|
||||
_backup_current(target)
|
||||
|
||||
# атомарная подмена (staging в каталоге движка + os.replace)
|
||||
ext_state._atomic_copy(snapshot_xlsx, target)
|
||||
report["activated"] = True
|
||||
|
||||
cache = target.parent / "fgis_cache.pkl"
|
||||
if cache.exists():
|
||||
if drop_cache:
|
||||
cache.unlink()
|
||||
report["cache_dropped"] = True
|
||||
else:
|
||||
report["cache_warning"] = (f"fgis_cache.pkl не удалён — движок продолжит читать СТАРЫЙ "
|
||||
f"кэш! Перезапусти с --yes или удали вручную: {cache}")
|
||||
report["restart_reminder"] = "Данные заменены. Перезапусти сервис, чтобы движок перечитал файл."
|
||||
return report
|
||||
|
||||
|
||||
def _backup_current(target: Path) -> None:
|
||||
"""Сохранить текущий рабочий файл в снапшоты как «что реально стояло» (не потерять)."""
|
||||
dest_dir = ext_state.ext_dir() / "snapshots/fgis/activated_backup"
|
||||
ext_state.register_snapshot(dest_dir, target, source="activated_backup",
|
||||
key="fgis_split_form.xlsx", url="(local active file)")
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description="Активировать снапшот ФГИС для движка (с диффом и защитой).")
|
||||
ap.add_argument("--subject", type=int, required=True)
|
||||
ap.add_argument("--zone", type=int, required=True)
|
||||
ap.add_argument("--period", type=int, required=True)
|
||||
ap.add_argument("--target-dir", help="куда активировать (по умолч. каталог движка); для теста — копия")
|
||||
ap.add_argument("--force", action="store_true", help="активировать несмотря на аномалию диффа")
|
||||
ap.add_argument("--yes", action="store_true", help="разрешить удаление fgis_cache.pkl")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
snap = (ext_state.ext_dir() / "snapshots/fgis/split_form"
|
||||
/ str(args.subject) / str(args.zone) / str(args.period) / "fgis_split_form.xlsx")
|
||||
if not snap.exists():
|
||||
print(f"снапшот не найден: {snap}\nсначала: python3 ext_pull.py --source split_form "
|
||||
f"--subject {args.subject} --zone {args.zone} --period {args.period}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
target_file = None
|
||||
if args.target_dir:
|
||||
target_file = Path(args.target_dir) / "fgis_split_form.xlsx"
|
||||
|
||||
rep = activate(snap, target_file=target_file, force=args.force, drop_cache=args.yes)
|
||||
import json as _json
|
||||
print(_json.dumps(rep, ensure_ascii=False, indent=2))
|
||||
return 0 if rep.get("activated") else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
"""ext_pull — скачивание внешних данных ФГИС ЦС в версионированные снапшоты (срез 1.2).
|
||||
|
||||
ОСОЗНАННЫЙ шаг (не чекер): качает сплит-форму / индексы ГОСР / оплату труда по региону+
|
||||
кварталу, кладёт в снапшот (ext_state.register_snapshot — crash-safe, версионирование),
|
||||
отмечает в state. НЕ активирует данные для движка (это ext_apply). НЕ рестартит сервис.
|
||||
|
||||
Объёмы: сплит-форма ~13.7МБ × регион × квартал. По умолчанию только EXT_REGIONS
|
||||
(id регионов через запятую) — НЕ все 85. Периоды: latest, если не задан.
|
||||
|
||||
CLI: python3 ext_pull.py --source split_form --subject 323 [--zone 191] [--period 426]
|
||||
python3 ext_pull.py --source all --regions 323 # split+indices+salary
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
import ext_state
|
||||
import fgis_client as fc
|
||||
|
||||
SNAP = "snapshots/fgis"
|
||||
|
||||
|
||||
def _snap_dir(kind: str, subject_id: int, zone_id: int, period_id: int) -> Path:
|
||||
return ext_state.ext_dir() / SNAP / kind / str(subject_id) / str(zone_id) / str(period_id)
|
||||
|
||||
|
||||
def _record_state(kind: str, subject_id: int, zone_id: int, period_id: int, meta: dict) -> None:
|
||||
with ext_state.update_state() as st:
|
||||
srcs = st["sources"].setdefault(f"fgis_{kind}", {})
|
||||
srcs[f"{subject_id}/{zone_id}"] = {
|
||||
"period_id": period_id, "sha256": meta["sha256"],
|
||||
"rev": meta["rev"], "pulled_at": meta["fetched_at"],
|
||||
"reuploaded": meta.get("reuploaded", False),
|
||||
}
|
||||
|
||||
|
||||
def _resolve_period(zone_id: int, period_id: int | None) -> int:
|
||||
if period_id:
|
||||
return period_id
|
||||
lp = fc.latest_period(zone_id)
|
||||
if not lp:
|
||||
raise SystemExit(f"нет периодов для зоны {zone_id}")
|
||||
return lp["id"]
|
||||
|
||||
|
||||
def pull_split_form(subject_id: int, zone_id: int, period_id: int | None = None) -> dict:
|
||||
period_id = _resolve_period(zone_id, period_id)
|
||||
dest_dir = _snap_dir("split_form", subject_id, zone_id, period_id)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tmp = Path(td) / "fgis_split_form.xlsx"
|
||||
res = fc.download_split_form(period_id, zone_id, tmp)
|
||||
meta = ext_state.register_snapshot(
|
||||
dest_dir, tmp, source="fgis_split_form", key=f"{subject_id}/{zone_id}/{period_id}",
|
||||
url=fc.BASE + "/api/EstimatedPrice/BuildingResources/ExportSplitForm",
|
||||
params={"periodId": period_id, "priceZoneId": zone_id})
|
||||
_record_state("split_form", subject_id, zone_id, period_id, meta)
|
||||
return {**meta, "downloaded_size": res["size"]}
|
||||
|
||||
|
||||
def pull_indices(subject_id: int, zone_id: int, period_id: int | None = None) -> dict:
|
||||
period_id = _resolve_period(zone_id, period_id)
|
||||
dest_dir = _snap_dir("indices_gosr", subject_id, zone_id, period_id)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tmp = Path(td) / "fgis_indices_gosr.xlsx"
|
||||
fc.download_indices(period_id, zone_id, tmp)
|
||||
meta = ext_state.register_snapshot(
|
||||
dest_dir, tmp, source="fgis_indices_gosr", key=f"{subject_id}/{zone_id}/{period_id}",
|
||||
url=fc.BASE + "/api/IndicesForResourcesGroups/GenerateCustomReport",
|
||||
params={"periodId": period_id, "priceZoneId": zone_id})
|
||||
_record_state("indices_gosr", subject_id, zone_id, period_id, meta)
|
||||
return meta
|
||||
|
||||
|
||||
def pull_salary(subject_id: int, zone_id: int, period_id: int | None = None) -> dict:
|
||||
period_id = _resolve_period(zone_id, period_id)
|
||||
dest_dir = _snap_dir("salary", subject_id, zone_id, period_id)
|
||||
data = fc.salary_registry(zone_id, period_id)
|
||||
with tempfile.TemporaryDirectory() as td:
|
||||
tmp = Path(td) / "salary_registry.json"
|
||||
tmp.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
|
||||
meta = ext_state.register_snapshot(
|
||||
dest_dir, tmp, source="fgis_salary", key=f"{subject_id}/{zone_id}/{period_id}",
|
||||
url=fc.BASE + "/api/EstimatedPrice/RimWorkerSalaryRegistry",
|
||||
params={"priceZoneId": zone_id, "periodId": period_id})
|
||||
_record_state("salary", subject_id, zone_id, period_id, meta)
|
||||
return {**meta, "items": data.get("total")}
|
||||
|
||||
|
||||
def _zones_of(subject_id: int) -> list[int]:
|
||||
return [z["id"] for z in fc.price_zones(subject_id)]
|
||||
|
||||
|
||||
def pull_all_for_subject(subject_id: int, period_id: int | None = None) -> list[dict]:
|
||||
out = []
|
||||
for zone_id in _zones_of(subject_id):
|
||||
out.append(pull_split_form(subject_id, zone_id, period_id))
|
||||
out.append(pull_indices(subject_id, zone_id, period_id))
|
||||
out.append(pull_salary(subject_id, zone_id, period_id))
|
||||
return out
|
||||
|
||||
|
||||
def _regions_from_env(cli_regions: str | None) -> list[int]:
|
||||
raw = cli_regions or os.environ.get("EXT_REGIONS", "")
|
||||
return [int(x) for x in raw.replace(";", ",").split(",") if x.strip().isdigit()]
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
ap = argparse.ArgumentParser(description="Скачать данные ФГИС ЦС в снапшоты (осознанный шаг).")
|
||||
ap.add_argument("--source", choices=["split_form", "indices", "salary", "all"], required=True)
|
||||
ap.add_argument("--subject", type=int, help="id региона")
|
||||
ap.add_argument("--zone", type=int, help="id ценовой зоны (если не задан — все зоны региона)")
|
||||
ap.add_argument("--period", type=int, help="id периода (по умолчанию последний)")
|
||||
ap.add_argument("--regions", help="id регионов через запятую (или env EXT_REGIONS) для --source all")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if not fc.alive():
|
||||
print("ФГИС ЦС недоступен (/api/alive). Прервано.", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
if args.source == "all":
|
||||
subjects = [args.subject] if args.subject else _regions_from_env(args.regions)
|
||||
if not subjects:
|
||||
print("не заданы регионы: --subject, --regions или env EXT_REGIONS", file=sys.stderr)
|
||||
return 2
|
||||
for sid in subjects:
|
||||
for r in pull_all_for_subject(sid, args.period):
|
||||
print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}"
|
||||
+ (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else ""))
|
||||
return 0
|
||||
|
||||
if not args.subject:
|
||||
print("--subject обязателен", file=sys.stderr)
|
||||
return 2
|
||||
zones = [args.zone] if args.zone else _zones_of(args.subject)
|
||||
fn = {"split_form": pull_split_form, "indices": pull_indices, "salary": pull_salary}[args.source]
|
||||
for zone_id in zones:
|
||||
r = fn(args.subject, zone_id, args.period)
|
||||
print(f" ✓ {r['source']} {r['key']} rev={r['rev']} sha={r['sha256'][:12]}"
|
||||
+ (" ⚠ПЕРЕЗАЛИВ" if r.get("reuploaded") else ""))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -76,3 +76,34 @@ def subject_id_by_name(name_substr: str, client: httpx.Client | None = None) ->
|
||||
if name_substr.lower() in s["name"].lower():
|
||||
return s["id"]
|
||||
return None
|
||||
|
||||
|
||||
# --- Выгрузки (проверено на сервере 2026-07: content-type spreadsheet, размеры реальны) ---
|
||||
_SPREADSHEET = "spreadsheet" # часть application/vnd.openxmlformats-...spreadsheetml.sheet
|
||||
|
||||
|
||||
def download_split_form(period_id: int, price_zone_id: int, dest, client=None) -> dict:
|
||||
"""Сплит-форма: полный каталог текущих цен ресурсов зоны за квартал (~13.7 МБ xlsx).
|
||||
Это то, чем питается движок (fgis_split_form.xlsx)."""
|
||||
return ext_fetch.fetch_file(
|
||||
f"{BASE}/api/EstimatedPrice/BuildingResources/ExportSplitForm", dest,
|
||||
params={"periodId": period_id, "priceZoneId": price_zone_id},
|
||||
expect_min_size=1_000_000, expected_content_type=_SPREADSHEET, client=client)
|
||||
|
||||
|
||||
def download_indices(period_id: int, price_zone_id: int, dest, client=None) -> dict:
|
||||
"""Индексы к группам однородных ресурсов (ГОСР) зоны за квартал (~2.2 МБ xlsx, РИМ)."""
|
||||
return ext_fetch.fetch_file(
|
||||
f"{BASE}/api/IndicesForResourcesGroups/GenerateCustomReport", dest,
|
||||
params={"periodId": period_id, "priceZoneId": price_zone_id, "authorityId": "null"},
|
||||
expect_min_size=50_000, expected_content_type=_SPREADSHEET, client=client)
|
||||
|
||||
|
||||
def salary_registry(price_zone_id: int, period_id: int, client=None) -> dict:
|
||||
"""Реестр оплаты труда рабочих по разрядам (JSON: {total, items:[...]})."""
|
||||
data = ext_fetch.fetch_json(f"{BASE}/api/EstimatedPrice/RimWorkerSalaryRegistry",
|
||||
params={"priceZoneId": price_zone_id, "periodId": period_id},
|
||||
client=client)
|
||||
if not (isinstance(data, dict) and "items" in data):
|
||||
raise FgisFormatError("RimWorkerSalaryRegistry: нет ключа items")
|
||||
return data
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
"""Срез 1.3: verify + diff + активация. Гейт аномалий (fail-loud) — red-green первым.
|
||||
Синтетические xlsx с кодами в колонке A (без сети, без реального ФГИС-файла).
|
||||
"""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
import ext_apply as ea # noqa: E402
|
||||
|
||||
|
||||
def _make_xlsx(path, codes):
|
||||
import openpyxl
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.append(["Код", "Наименование", "Цена"]) # шапка
|
||||
for c in codes:
|
||||
ws.append([c, "материал", 100.0])
|
||||
wb.save(str(path))
|
||||
|
||||
|
||||
def _codes(n, prefix="M"):
|
||||
return [f"{prefix}-{i:05d}" for i in range(n)]
|
||||
|
||||
|
||||
def test_verify_ok_and_too_small(tmp_path):
|
||||
big = tmp_path / "big.xlsx"; _make_xlsx(big, _codes(1200))
|
||||
assert ea.verify_snapshot(big)["ok"] is True
|
||||
small = tmp_path / "small.xlsx"; _make_xlsx(small, _codes(10))
|
||||
r = ea.verify_snapshot(small)
|
||||
assert r["ok"] is False and "мало" in r["errors"][0]
|
||||
|
||||
|
||||
def test_verify_rejects_non_xlsx(tmp_path):
|
||||
bad = tmp_path / "bad.xlsx"; bad.write_bytes(b"not really xlsx")
|
||||
assert ea.verify_snapshot(bad)["ok"] is False
|
||||
|
||||
|
||||
def test_diff_codes_ratio():
|
||||
d = ea.diff_codes(set(_codes(100)), set(_codes(80)) | set(_codes(5, "NEW")))
|
||||
assert d["removed"] == 20 and d["added"] == 5
|
||||
assert d["removed_ratio"] == 0.2
|
||||
|
||||
|
||||
def test_fresh_activate_creates_target(tmp_path):
|
||||
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(1200))
|
||||
tdir = tmp_path / "railway"; tdir.mkdir()
|
||||
rep = ea.activate(snap, target_file=tdir / "fgis_split_form.xlsx")
|
||||
assert rep["activated"] is True
|
||||
assert (tdir / "fgis_split_form.xlsx").exists()
|
||||
|
||||
|
||||
def test_gate_blocks_massive_removal_without_force(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
|
||||
tdir = tmp_path / "railway"; tdir.mkdir()
|
||||
target = tdir / "fgis_split_form.xlsx"
|
||||
_make_xlsx(target, _codes(2000)) # текущий: 2000 кодов
|
||||
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(2000)[:1200]) # новый: пропало 40%
|
||||
rep = ea.activate(snap, target_file=target)
|
||||
assert rep["activated"] is False and "АНОМАЛИЯ" in rep["reason"]
|
||||
# целевой файл НЕ тронут (всё ещё 1200 кодов)
|
||||
assert len(ea.read_codes(target)) == 2000
|
||||
|
||||
|
||||
def test_gate_overridden_by_force(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
|
||||
tdir = tmp_path / "railway"; tdir.mkdir()
|
||||
target = tdir / "fgis_split_form.xlsx"
|
||||
_make_xlsx(target, _codes(2000))
|
||||
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(2000)[:1200])
|
||||
rep = ea.activate(snap, target_file=target, force=True)
|
||||
assert rep["activated"] is True
|
||||
assert len(ea.read_codes(target)) == 1200 # применилось
|
||||
# старый забэкаплен в снапшоты (не потерян)
|
||||
backups = list((tmp_path / "_ext/snapshots/fgis/activated_backup").glob("*.xlsx"))
|
||||
assert backups and len(ea.read_codes(backups[0])) == 2000
|
||||
|
||||
|
||||
def test_cache_warning_without_yes(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
|
||||
tdir = tmp_path / "railway"; tdir.mkdir()
|
||||
(tdir / "fgis_cache.pkl").write_bytes(b"cache")
|
||||
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(1200))
|
||||
rep = ea.activate(snap, target_file=tdir / "fgis_split_form.xlsx")
|
||||
assert "cache_warning" in rep and (tdir / "fgis_cache.pkl").exists() # не удалён без --yes
|
||||
rep2 = ea.activate(snap, target_file=tdir / "fgis_split_form.xlsx", drop_cache=True)
|
||||
assert rep2.get("cache_dropped") is True and not (tdir / "fgis_cache.pkl").exists()
|
||||
@@ -0,0 +1,62 @@
|
||||
"""Срез 1.2: скачивание ФГИС в снапшоты. Сетевые вызовы fgis_client замоканы (без сети)."""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
import ext_pull as ep # noqa: E402
|
||||
import ext_state as es # noqa: E402
|
||||
import fgis_client as fc # noqa: E402
|
||||
|
||||
|
||||
def _mock_downloads(monkeypatch, content=b"FAKE-XLSX-" + b"x" * 2000):
|
||||
def dl_split(period_id, zone_id, dest, client=None):
|
||||
Path(dest).write_bytes(content)
|
||||
return {"path": str(dest), "size": len(content), "sha256": es.sha256_file(dest)}
|
||||
monkeypatch.setattr(fc, "download_split_form", dl_split)
|
||||
monkeypatch.setattr(fc, "download_indices",
|
||||
lambda p, z, d, client=None: (Path(d).write_bytes(content), {"size": len(content)})[1])
|
||||
monkeypatch.setattr(fc, "salary_registry", lambda z, p, client=None: {"total": 3, "items": [{"code": "1-100-1"}]})
|
||||
monkeypatch.setattr(fc, "latest_period", lambda z, client=None: {"id": 426, "name": "2 кв 2026"})
|
||||
monkeypatch.setattr(fc, "price_zones", lambda s, client=None: [{"id": 191, "name": "город Москва"}])
|
||||
|
||||
|
||||
def test_pull_split_form_creates_snapshot_and_state(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path))
|
||||
_mock_downloads(monkeypatch)
|
||||
meta = ep.pull_split_form(323, 191) # period → latest (426)
|
||||
snap = tmp_path / "snapshots/fgis/split_form/323/191/426/fgis_split_form.xlsx"
|
||||
assert snap.exists() and meta["rev"] == 1
|
||||
st = es.load_state()
|
||||
assert st["sources"]["fgis_split_form"]["323/191"]["period_id"] == 426
|
||||
assert st["sources"]["fgis_split_form"]["323/191"]["sha256"] == meta["sha256"]
|
||||
|
||||
|
||||
def test_repull_same_content_no_new_revision(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path))
|
||||
_mock_downloads(monkeypatch)
|
||||
ep.pull_split_form(323, 191, 426)
|
||||
m2 = ep.pull_split_form(323, 191, 426)
|
||||
assert m2["rev"] == 1 and m2["reuploaded"] is False
|
||||
snapdir = tmp_path / "snapshots/fgis/split_form/323/191/426"
|
||||
assert not list(snapdir.glob("rev-*")) # ревизий не создано
|
||||
|
||||
|
||||
def test_repull_changed_content_creates_revision(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path))
|
||||
_mock_downloads(monkeypatch, content=b"OLD-" + b"x" * 2000)
|
||||
ep.pull_split_form(323, 191, 426)
|
||||
_mock_downloads(monkeypatch, content=b"NEW-REUPLOADED-" + b"y" * 2000) # ФГИС перезалил
|
||||
m2 = ep.pull_split_form(323, 191, 426)
|
||||
assert m2["reuploaded"] is True and m2["rev"] == 2
|
||||
snapdir = tmp_path / "snapshots/fgis/split_form/323/191/426"
|
||||
assert len(list(snapdir.glob("rev-1_*"))) == 1 # старый уехал в архив
|
||||
|
||||
|
||||
def test_pull_salary_saves_json(monkeypatch, tmp_path):
|
||||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path))
|
||||
_mock_downloads(monkeypatch)
|
||||
meta = ep.pull_salary(323, 191, 426)
|
||||
snap = tmp_path / "snapshots/fgis/salary/323/191/426/salary_registry.json"
|
||||
assert snap.exists()
|
||||
assert json.loads(snap.read_text())["items"][0]["code"] == "1-100-1"
|
||||
Reference in New Issue
Block a user