fix(ext): money-safety фиксы Fable в активации/скачивании (Фаза 1)
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 теста.
This commit is contained in:
+51
-41
@@ -1,6 +1,7 @@
|
||||
"""Срез 1.3: verify + diff + активация. Гейт аномалий (fail-loud) — red-green первым.
|
||||
Синтетические xlsx с кодами в колонке A (без сети, без реального ФГИС-файла).
|
||||
"""Срез 1.3 (+ money-safety фиксы Fable): verify+diff по КОДАМ И ЦЕНАМ, гейт аномалий,
|
||||
temp-verify, пересборка кэша, аудит. red-green на гейтах (удаление кодов И скачок цен).
|
||||
"""
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
@@ -10,13 +11,13 @@ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
import ext_apply as ea # noqa: E402
|
||||
|
||||
|
||||
def _make_xlsx(path, codes):
|
||||
def _make_xlsx(path, codes, price=100.0):
|
||||
import openpyxl
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.append(["Код", "Наименование", "Цена"]) # шапка
|
||||
ws.append(["Код", "Наименование", "Цена"])
|
||||
for c in codes:
|
||||
ws.append([c, "материал", 100.0])
|
||||
ws.append([c, "материал", price])
|
||||
wb.save(str(path))
|
||||
|
||||
|
||||
@@ -24,12 +25,23 @@ def _codes(n, prefix="M"):
|
||||
return [f"{prefix}-{i:05d}" for i in range(n)]
|
||||
|
||||
|
||||
def test_verify_ok_and_too_small(tmp_path):
|
||||
@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))
|
||||
r = ea.verify_snapshot(small)
|
||||
assert r["ok"] is False and "мало" in r["errors"][0]
|
||||
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):
|
||||
@@ -37,52 +49,50 @@ def test_verify_rejects_non_xlsx(tmp_path):
|
||||
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_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(tmp_path):
|
||||
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
|
||||
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_removal_without_force(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
|
||||
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)) # текущий: 2000 кодов
|
||||
snap = tmp_path / "snap.xlsx"; _make_xlsx(snap, _codes(2000)[:1200]) # новый: пропало 40%
|
||||
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"]
|
||||
# целевой файл НЕ тронут (всё ещё 1200 кодов)
|
||||
assert len(ea.read_codes(target)) == 2000
|
||||
assert rep["activated"] is False and "исчезло" in rep["reason"]
|
||||
assert len(ea._read_rows(target)) == 2000 # target цел
|
||||
|
||||
|
||||
def test_gate_overridden_by_force(tmp_path, monkeypatch):
|
||||
monkeypatch.setenv("EXT_SNAPSHOT_DIR", str(tmp_path / "_ext"))
|
||||
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(2000))
|
||||
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
|
||||
assert len(ea.read_codes(target)) == 1200 # применилось
|
||||
# старый забэкаплен в снапшоты (не потерян)
|
||||
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_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()
|
||||
assert backups and len(ea._read_rows(backups[0])) == 2000 # старое не потеряно
|
||||
|
||||
@@ -19,6 +19,8 @@ def _mock_downloads(monkeypatch, content=b"FAKE-XLSX-" + b"x" * 2000):
|
||||
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": "город Москва"}])
|
||||
# _verify_xlsx покрыт отдельно; здесь мок-контент не настоящий xlsx — нейтрализуем
|
||||
monkeypatch.setattr(ep, "_verify_xlsx", lambda p, min_rows: None)
|
||||
|
||||
|
||||
def test_pull_split_form_creates_snapshot_and_state(monkeypatch, tmp_path):
|
||||
|
||||
Reference in New Issue
Block a user