"""Real-тест arp_deep + staging на настоящих .arp (гонять на dev2; без корпуса — skip). Якоря — из реального файла 00_02_7_00_01Р (КС, 11900.zip), значения сверены глазами по сырому АРПС-тексту и парной .xls-распечатке (Итого по смете). Запускать ПОСЛЕ scripts/build_arp_staging.py (проверяет и staging-файл). """ import json import sys import zipfile from pathlib import Path import pytest ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT / "scripts")) from arp_deep import parse_arp_text # noqa: E402 from corpus_anon import has_identifier_leak # noqa: E402 from build_arp_staging import _norm_stem, _struct_leaks, _xls_total # noqa: E402 SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/11900.zip") STAGING = ROOT / "data/real_corpus/staging_arp.json" def test_arp_deep_real(): if not SRC.exists(): pytest.skip("нет реальных данных корпуса (гонять на dev2)") z = zipfile.ZipFile(SRC) arp_name = next(n for n in z.namelist() if n.lower().endswith(".arp")) est = parse_arp_text(z.read(arp_name).decode("cp866", "replace"), path="real") # --- шапка + гейт формулы итога --- assert est["code"] == "00-02-7-00-01Р", est["code"] assert abs(est["total"] - 6105760.71) < 0.01, est["total"] assert est["total_check_ok"] is True, (est["total"], est["total_computed"]) assert est["positions_count"] == 70, est["positions_count"] assert est["norm_base"] == "ОСНБЖ", est["norm_base"] assert est["base_year"] == "2014", est["base_year"] print(f" шапка: {est['code']} | итог={est['total']} | формула={est['total_computed']} | позиций={est['positions_count']}") # --- пункт #5: индекс пересчёта с обоснованием --- assert est["recalc"] and est["recalc"]["doc"] == "1288р", est["recalc"] assert est["recalc"]["date"] == "13.05.2022", est["recalc"] assert abs(est["kizp"]["main"] - 8.04) < 1e-9, est["kizp"] print(f" price_level: {est['price_level']} | Кизп={est['kizp']['main']}") # --- реально применённые коэффициенты позиции 1 (Копание ям) --- p0 = est["positions"][0] assert p0["code"] == "01-02-058-03", p0["code"] ks = {(c["kind"], c["target"]): c["value"] for c in p0["coefficients"]} assert abs(ks[("Кзп", "ОТ")] - 1.3) < 1e-9, ks assert abs(ks[("Кнр", "ОТ")] - 0.89) < 1e-9, ks assert abs(ks[("Ксп", "ОТ")] - 0.4) < 1e-9, ks assert abs(ks[("Кизп", "ОТ")] - 8.04) < 1e-9, ks groups = {c["kind"]: c["group"] for c in p0["coefficients"]} assert groups["Кнр"] == "overhead" and groups["Ксп"] == "profit", groups assert groups["Кизп"] == "index" and groups["Кзп"] == "adjust", groups assert abs(p0["quantity"] - 0.00448) < 1e-9, p0["quantity"] # --- ресурсы позиции 2 (Установка опор) --- p1 = est["positions"][1] w = p1["resources"]["workers"] assert abs(w[0]["consumption"] - 38.3364) < 1e-6 and w[0]["grade"] == "3,3", w m = {r["code"]: r for r in p1["resources"]["machines"]} assert abs(m["021312"]["consumption"] - 2.4702) < 1e-6, m assert abs(m["021312"]["price_base"] - 211.94) < 0.01, m mat = {r["code"]: r for r in p1["resources"]["materials"]} assert abs(mat["101-0125"]["consumption"] - 0.0032) < 1e-9, mat print(f" ресурсы поз.2: workers={len(w)} machines={len(m)} materials={len(mat)}") # --- обезличивание: топоним из шапки вырезан, ФИО не извлечены --- dump = json.dumps(est, ensure_ascii=False) assert "Находка" not in dump, "топоним утёк" assert "Антонова" not in dump and "Неверова" not in dump, "ФИО утекли" assert not has_identifier_leak(est["name"]), est["name"] # --- ground truth: итог парной .xls === итог .arp --- stem = _norm_stem(arp_name, "arps?") xls_name = next(n for n in z.namelist() if n.lower().endswith(".xls") and _norm_stem(n, "xls") == stem) xt = _xls_total(z.read(xls_name)) assert xt is not None, "итог из .xls не извлёкся" assert abs(est["total"] - xt) <= 2.0, (est["total"], xt) print(f" сверка с парной .xls: arp={est['total']} xls={xt} — сошлось") # --- staging: счётчики, 0 утечек, живой индекс не тронут по построению --- assert STAGING.exists(), "staging_arp.json не построен — сначала build_arp_staging.py" st = json.loads(STAGING.read_text(encoding="utf-8")) meta = st["meta"] assert meta["staged_files"] > 0 and meta["unique_items"] > 0, meta assert meta["leaks_in_staging"] == 0, meta assert meta["xls_verified"] > 0, meta # арифметика приёмки: staged + duplicates + карантин(файлы, вкл. parse_error) == files_seen quar_files = sum(v for k, v in meta["quarantined"].items() if k not in ("price_outlier", "leak_final_pass")) assert meta["staged_files"] + meta["duplicates"] + quar_files == meta["files_seen"], meta # независимая канарейка утечек: по строковым значениям каждого item leaks = sum(1 for it in st["items"] + st["recalc_index"] if _struct_leaks(it)) assert leaks == 0, f"{leaks} утечек в staging" # записи с реально применёнными коэффициентами и Кнр/Ксп в топе with_coefs = [it for it in st["items"] if it["coef_applications"]] assert with_coefs, "нет ни одной записи с коэффициентами" kinds = {c["kind"] for it in with_coefs for c in it["coef_applications"]["coefs"]} assert "Кнр" in kinds and "Ксп" in kinds, kinds # пункт #5: recalc_index с распоряжением 1288р и Кизп docs = {r["doc"] for r in st["recalc_index"]} assert "1288р" in docs, docs r1288 = next(r for r in st["recalc_index"] if r["doc"] == "1288р") assert "Кизп" in r1288["indices"], r1288["indices"] assert all(it["norm_base"] == "ОСНБЖ" and it["price_level"] for it in st["items"][:50]) print(f" staging: items={meta['unique_items']} staged={meta['staged_files']} " f"dup={meta['duplicates']} quar={dict(meta['quarantined'])} " f"xls_verified={meta['xls_verified']}/{meta['xls_pairs_found']} leaks=0") print("ALL PASS") if __name__ == "__main__": test_arp_deep_real()