"""Real-тест gsfx_deep на НАСТОЯЩИХ .gsfx (сервер). Запуск: GSFX_REAL_DIR=/tmp/gsfx_work python3 tests/test_gsfx_deep_real.py Без GSFX_REAL_DIR — тесты пропускаются (локально реальных файлов нет). Проверяет: ресурсы+состав работ извлекаются массово, суммы позиций бьются с Properties.Total (медианный ratio в мягкой полосе), и в staging-выходе 0 утечек идентификаторов по каждому текстовому полю. """ import json import os import statistics import sys import tempfile from pathlib import Path sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from gsfx_deep import parse_gsfx_full # noqa: E402 from corpus_anon import has_identifier_leak # noqa: E402 REAL_DIR = os.environ.get("GSFX_REAL_DIR", "") def _skip() -> bool: if not REAL_DIR or not Path(REAL_DIR).exists(): print(" skip: GSFX_REAL_DIR не задан или не существует") return True return False def _texts(obj): if isinstance(obj, str): yield obj elif isinstance(obj, dict): for v in obj.values(): yield from _texts(v) elif isinstance(obj, (list, tuple)): for v in obj: yield from _texts(v) def test_real_resources_and_works_extracted(): if _skip(): return files = sorted(Path(REAL_DIR).rglob("*.gsfx")) assert files, REAL_DIR n_ok = n_res = n_works = n_price = 0 for f in files: r = parse_gsfx_full(f) if "error" in r: continue n_ok += 1 for p in r["positions"]: res = p["resources"] if res["workers"] or res["machines"] or res["materials"]: n_res += 1 if any(w["price_cur"] for w in res["workers"]): n_price += 1 if p["works_list"]: n_works += 1 print(f" files_ok={n_ok} pos_with_resources={n_res} " f"pos_with_works={n_works} pos_with_worker_price={n_price}") assert n_ok > 100, n_ok assert n_res > 1000, n_res # ресурсный состав реально извлекается assert n_works > 1000, n_works # состав работ реально извлекается assert n_price > 500, n_price # цены (с запятой) реально парсятся def test_real_totals_match_properties(): if _skip(): return ratios = [] for f in sorted(Path(REAL_DIR).rglob("*.gsfx")): r = parse_gsfx_full(f) if "error" in r: continue tc = r["totals_check"] # сверяем только сметы с итогом и рабочими позициями if tc["ratio"] and r["positions"]: ratios.append(tc["ratio"]) assert len(ratios) > 50, len(ratios) med = statistics.median(ratios) in_band = sum(1 for x in ratios if 0.5 <= x <= 1.5) / len(ratios) print(f" n={len(ratios)} median_ratio={med:.4f} in_band={in_band:.2%}") # медиана в узкой полосе, подавляющее большинство — в мягкой assert 0.85 <= med <= 1.15, med assert in_band >= 0.75, in_band def test_real_staging_zero_leaks(): if _skip(): return sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) from build_gsfx_staging import build # noqa: E402 out = Path(tempfile.mkdtemp()) meta = build(Path(REAL_DIR), out) print(" meta:", json.dumps(meta, ensure_ascii=False)) staging = json.loads((out / "staging_gsfx.json").read_text(encoding="utf-8")) assert meta["unique_items"] > 100, meta leaks = [t for t in _texts({"items": staging["items"], "materials": staging["materials"]}) if has_identifier_leak(t)] assert not leaks, leaks[:10] # у топ-расценок есть состав: ресурсы, работы, НР/СП top = staging["items"][:50] with_res = sum(1 for i in top if i["resources"]["workers"] or i["resources"]["machines"]) with_works = sum(1 for i in top if i["works_list"]) with_nrsp = sum(1 for i in top if i["overhead"]) print(f" top50: with_resources={with_res} with_works={with_works} with_nrsp={with_nrsp}") assert with_res >= 25, with_res assert with_works >= 25, with_works assert with_nrsp >= 25, with_nrsp if __name__ == "__main__": import traceback fns = [v for k, v in sorted(globals().items()) if k.startswith("test_") and callable(v)] failed = 0 for fn in fns: try: print(f"[{fn.__name__}]"); fn(); print(" ok") except Exception: failed += 1; print(" FAIL"); traceback.print_exc() print("ALL PASS" if not failed else f"{failed} FAILED") sys.exit(failed)