ext_apply: verify+ГЕЙТ теперь по КОДАМ И ЦЕНАМ (файл чужой зоны с теми же кодами, но ценами в разы — ловим по медианному отношению; сдвиг колонок/битые цены — по доле распознанных); activate под ext_lock через temp-copy (нет TOCTOU verify↔подмена); пересборка fgis_cache.pkl НА ХОСТЕ после подмены (иначе Docker-агент падал на ro-записи кэша); аудит активного среза в state; надёжный target (SMETA_PROJECT_DIR, не относительный); чистим служебное поле в отчёте. ext_pull: verify скачанного ДО регистрации (обрезанные HTTP-200), FetchError вместо SystemExit, вежливая пауза между запросами. ext_lock реентрантна. 43 теста.
99 lines
4.4 KiB
Python
99 lines
4.4 KiB
Python
"""Срез 1.3 (+ money-safety фиксы Fable): verify+diff по КОДАМ И ЦЕНАМ, гейт аномалий,
|
||
temp-verify, пересборка кэша, аудит. red-green на гейтах (удаление кодов И скачок цен).
|
||
"""
|
||
import json
|
||
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, price=100.0):
|
||
import openpyxl
|
||
wb = openpyxl.Workbook()
|
||
ws = wb.active
|
||
ws.append(["Код", "Наименование", "Цена"])
|
||
for c in codes:
|
||
ws.append([c, "материал", price])
|
||
wb.save(str(path))
|
||
|
||
|
||
def _codes(n, prefix="M"):
|
||
return [f"{prefix}-{i:05d}" for i in range(n)]
|
||
|
||
|
||
@pytest.fixture(autouse=True)
|
||
def _env(monkeypatch, tmp_path):
|
||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
|
||
# не звать реальный движок в юнит-тестах — проверяем факт вызова отдельно
|
||
monkeypatch.setattr(ea, "_rebuild_host_cache",
|
||
lambda target, report: report.__setitem__("cache_rebuilt", True))
|
||
|
||
|
||
def test_verify_ok_small_and_priceless(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))
|
||
assert ea.verify_snapshot(small)["ok"] is False
|
||
# цены отсутствуют (0) → тоже не ok
|
||
priceless = tmp_path / "pl.xlsx"; _make_xlsx(priceless, _codes(1200), price=0.0)
|
||
r = ea.verify_snapshot(priceless)
|
||
assert r["ok"] is False and any("цен" in e for e in r["errors"])
|
||
|
||
|
||
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_rows_codes_and_prices():
|
||
old = {c: 100.0 for c in _codes(100)}
|
||
new = {c: 100.0 for c in _codes(80)}
|
||
new.update({c: 100.0 for c in _codes(5, "NEW")})
|
||
d = ea.diff_rows(old, new)
|
||
assert d["removed"] == 20 and d["added"] == 5 and d["price_median_ratio"] == 1.0
|
||
|
||
|
||
def test_fresh_activate_creates_target_and_records(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 and rep.get("cache_rebuilt") is True
|
||
assert (tdir / "fgis_split_form.xlsx").exists()
|
||
# аудит активного среза в state
|
||
import ext_state as es
|
||
assert es.load_state()["active"]["fgis_split_form"]["codes"] == 1200
|
||
|
||
|
||
def test_gate_blocks_massive_code_removal(tmp_path):
|
||
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]) # -40% кодов
|
||
rep = ea.activate(snap, target_file=target)
|
||
assert rep["activated"] is False and "исчезло" in rep["reason"]
|
||
assert len(ea._read_rows(target)) == 2000 # target цел
|
||
|
||
|
||
def test_gate_blocks_price_explosion(tmp_path):
|
||
"""Файл с теми же кодами, но ценами в разы — не тот регион/сдвиг колонок (money-safety)."""
|
||
tdir = tmp_path / "railway"; tdir.mkdir()
|
||
target = tdir / "fgis_split_form.xlsx"; _make_xlsx(target, _codes(1500), price=100.0)
|
||
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(1500), price=600.0) # ×6
|
||
rep = ea.activate(snap, target_file=target)
|
||
assert rep["activated"] is False and "цен" in rep["reason"]
|
||
# target не тронут — цена осталась 100
|
||
assert list(ea._read_rows(target).values())[0] == 100.0
|
||
|
||
|
||
def test_gate_overridden_by_force_and_backup(tmp_path):
|
||
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 and len(ea._read_rows(target)) == 1200
|
||
backups = list((tmp_path / "_ext/snapshots/fgis/activated_backup").glob("*.xlsx"))
|
||
assert backups and len(ea._read_rows(backups[0])) == 2000 # старое не потеряно
|