test: script-probe тесты собираются pytest'ом — skip без данных вместо 7 collection-errors

Тела 7 серверных probe-скриптов обёрнуты в тест-функции с гейтом:
skip при отсутствии корпуса (/home/mcp-user/…), для mask_integration —
при отсутствии живой БД (файл+схема, гейт ДО import main); модуль-левел
sys.exit заменён на assert fails==0. Гейт formats стоит до импорта
claude_bridge_glm (цепочка тянет pymorphy2). __main__-гвард сохраняет
запуск скриптом на dev2; на сервере с корпусом проверки едут как раньше
(доказано на mask_integration с инициализированной БД: 1 passed).
Полный прогон: 373→374 passed, errors 12→5.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
anor
2026-07-20 23:09:08 +10:00
co-authored by Claude Opus 4.8
parent 1590bf2e21
commit 99e46407a1
7 changed files with 392 additions and 302 deletions
+72 -61
View File
@@ -1,78 +1,89 @@
"""Real-data тест обезличивания: гонит scrub по НАСТОЯЩИМ наименованиям позиций из """Real-data тест обезличивания: гонит scrub по НАСТОЯЩИМ наименованиям позиций из
.arp/.gsfx и ячейкам реестра замечаний. Метрика: утечки ДО vs остаточные ПОСЛЕ scrub .arp/.gsfx и ячейкам реестра замечаний. Метрика: утечки ДО vs остаточные ПОСЛЕ scrub
(остаточные → карантин, в корпус НЕ идут). Гонять на dev2.""" (остаточные → карантин, в корпус НЕ идут). Гонять на dev2; без корпуса — skip."""
import tempfile import tempfile
import zipfile import zipfile
from pathlib import Path from pathlib import Path
import pytest
import corpus_anon as ca import corpus_anon as ca
from gge_tools import parse_arp_file, parse_gsfx_file from gge_tools import parse_arp_file, parse_gsfx_file
BASE = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100") BASE = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100")
tmp = Path(tempfile.mkdtemp())
names: list[str] = []
# .arp — наименования позиций + шапки
with zipfile.ZipFile(BASE / "11900.zip") as z:
for n in [x for x in z.namelist() if x.lower().endswith(".arp")][:8]:
p = tmp / "a.arp"; p.write_bytes(z.read(n))
r = parse_arp_file(p)
names.append(r["name"])
names += [pos["name"] for pos in r["positions"]]
# .gsfx — наименования позиций + шапка + регион def test_anon_realdata():
with zipfile.ZipFile(BASE / "АРХИВ ОБЩИЙ_Гранд-смета.zip") as z: if not BASE.exists():
for n in [x for x in z.namelist() if x.lower().endswith(".gsfx")][:8]: pytest.skip("нет реальных данных корпуса (гонять на dev2)")
p = tmp / "g.gsfx"; p.write_bytes(z.read(n)) tmp = Path(tempfile.mkdtemp())
r = parse_gsfx_file(p) names: list[str] = []
if "error" in r:
continue
names += [r.get("name", ""), r.get("region", "")]
names += [pos["name"] for pos in r.get("positions", [])]
# реестр замечаний — свободный текст ячеек # .arp — наименования позиций + шапки
try: with zipfile.ZipFile(BASE / "11900.zip") as z:
import openpyxl for n in [x for x in z.namelist() if x.lower().endswith(".arp")][:8]:
reestr = next(BASE.glob("*Локальные замечания*.xlsx"), None) p = tmp / "a.arp"; p.write_bytes(z.read(n))
if reestr: r = parse_arp_file(p)
wb = openpyxl.load_workbook(str(reestr), data_only=True, read_only=True) names.append(r["name"])
ws = wb.worksheets[0] names += [pos["name"] for pos in r["positions"]]
for i, row in enumerate(ws.iter_rows(values_only=True)):
if i > 200: # .gsfx — наименования позиций + шапка + регион
with zipfile.ZipFile(BASE / "АРХИВ ОБЩИЙ_Гранд-смета.zip") as z:
for n in [x for x in z.namelist() if x.lower().endswith(".gsfx")][:8]:
p = tmp / "g.gsfx"; p.write_bytes(z.read(n))
r = parse_gsfx_file(p)
if "error" in r:
continue
names += [r.get("name", ""), r.get("region", "")]
names += [pos["name"] for pos in r.get("positions", [])]
# реестр замечаний — свободный текст ячеек
try:
import openpyxl
reestr = next(BASE.glob("*Локальные замечания*.xlsx"), None)
if reestr:
wb = openpyxl.load_workbook(str(reestr), data_only=True, read_only=True)
ws = wb.worksheets[0]
for i, row in enumerate(ws.iter_rows(values_only=True)):
if i > 200:
break
for v in row:
if isinstance(v, str) and len(v.strip()) > 8:
names.append(v.strip())
except Exception as e:
print("реестр пропущен:", e)
names = [x for x in names if x and x.strip()]
scrubbed = [ca.scrub(x) for x in names]
leak_before = sum(1 for x in names if ca.has_identifier_leak(x))
residual = [(names[i], scrubbed[i]) for i in range(len(names))
if ca.has_identifier_leak(scrubbed[i])]
print(f"всего строк: {len(names)}")
print(f"с идентификатором ДО scrub: {leak_before}")
print(f"остаточная утечка ПОСЛЕ scrub (→ КАРАНТИН, не в корпус): {len(residual)}")
print("--- примеры успешного скраба (идентификатор убран, работа цела) ---")
shown = 0
for i in range(len(names)):
if ca.has_identifier_leak(names[i]) and not ca.has_identifier_leak(scrubbed[i]):
print(" ", repr(names[i][:75]), "→", repr(scrubbed[i][:75]))
shown += 1
if shown >= 8:
break break
for v in row: if residual:
if isinstance(v, str) and len(v.strip()) > 8: print("--- ОСТАТОЧНЫЕ (пойдут в карантин) ---")
names.append(v.strip()) for orig, sc in residual[:8]:
except Exception as e: print(" ", repr(sc[:80]))
print("реестр пропущен:", e)
names = [x for x in names if x and x.strip()] import shutil
scrubbed = [ca.scrub(x) for x in names] shutil.rmtree(tmp, ignore_errors=True)
leak_before = sum(1 for x in names if ca.has_identifier_leak(x)) # Гейт: остаточные утечки допустимы (→ карантин), но их доля не должна быть большой,
residual = [(names[i], scrubbed[i]) for i in range(len(names)) # иначе скраб слишком дырявый. Порог: < 5% остаточных.
if ca.has_identifier_leak(scrubbed[i])] rate = len(residual) / max(1, len(names))
print(f"доля остаточных: {rate:.1%}")
assert rate < 0.05, f"слишком много остаточных утечек ({rate:.1%}) — скраб дырявый"
print("REALDATA OK")
print(f"всего строк: {len(names)}")
print(f"с идентификатором ДО scrub: {leak_before}")
print(f"остаточная утечка ПОСЛЕ scrub (→ КАРАНТИН, не в корпус): {len(residual)}")
print("--- примеры успешного скраба (идентификатор убран, работа цела) ---")
shown = 0
for i in range(len(names)):
if ca.has_identifier_leak(names[i]) and not ca.has_identifier_leak(scrubbed[i]):
print(" ", repr(names[i][:75]), "→", repr(scrubbed[i][:75]))
shown += 1
if shown >= 8:
break
if residual:
print("--- ОСТАТОЧНЫЕ (пойдут в карантин) ---")
for orig, sc in residual[:8]:
print(" ", repr(sc[:80]))
import shutil if __name__ == "__main__":
shutil.rmtree(tmp, ignore_errors=True) test_anon_realdata()
# Гейт: остаточные утечки допустимы (→ карантин), но их доля не должна быть большой,
# иначе скраб слишком дырявый. Порог: < 5% остаточных.
rate = len(residual) / max(1, len(names))
print(f"доля остаточных: {rate:.1%}")
assert rate < 0.05, f"слишком много остаточных утечек ({rate:.1%}) — скраб дырявый"
print("REALDATA OK")
+91 -81
View File
@@ -1,4 +1,4 @@
"""Real-тест arp_deep + staging на настоящих .arp (гонять на dev2). """Real-тест arp_deep + staging на настоящих .arp (гонять на dev2; без корпуса — skip).
Якоря — из реального файла 00_02_7_00_01Р (КС, 11900.zip), значения сверены Якоря — из реального файла 00_02_7_00_01Р (КС, 11900.zip), значения сверены
глазами по сырому АРПС-тексту и парной .xls-распечатке (Итого по смете). глазами по сырому АРПС-тексту и парной .xls-распечатке (Итого по смете).
@@ -9,6 +9,8 @@ import sys
import zipfile import zipfile
from pathlib import Path from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parent.parent ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT)) sys.path.insert(0, str(ROOT))
sys.path.insert(0, str(ROOT / "scripts")) sys.path.insert(0, str(ROOT / "scripts"))
@@ -19,90 +21,98 @@ from build_arp_staging import _norm_stem, _struct_leaks, _xls_total # noqa: E40
SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/11900.zip") SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/11900.zip")
STAGING = ROOT / "data/real_corpus/staging_arp.json" STAGING = ROOT / "data/real_corpus/staging_arp.json"
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")
# --- шапка + гейт формулы итога --- def test_arp_deep_real():
assert est["code"] == "00-02-7-00-01Р", est["code"] if not SRC.exists():
assert abs(est["total"] - 6105760.71) < 0.01, est["total"] pytest.skip("нет реальных данных корпуса (гонять на dev2)")
assert est["total_check_ok"] is True, (est["total"], est["total_computed"]) z = zipfile.ZipFile(SRC)
assert est["positions_count"] == 70, est["positions_count"] arp_name = next(n for n in z.namelist() if n.lower().endswith(".arp"))
assert est["norm_base"] == "ОСНБЖ", est["norm_base"] est = parse_arp_text(z.read(arp_name).decode("cp866", "replace"), path="real")
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["code"] == "00-02-7-00-01Р", est["code"]
assert est["recalc"]["date"] == "13.05.2022", est["recalc"] assert abs(est["total"] - 6105760.71) < 0.01, est["total"]
assert abs(est["kizp"]["main"] - 8.04) < 1e-9, est["kizp"] assert est["total_check_ok"] is True, (est["total"], est["total_computed"])
print(f" price_level: {est['price_level']} | Кизп={est['kizp']['main']}") 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']}")
# --- реально применённые коэффициенты позиции 1 (Копание ям) --- # --- пункт #5: индекс пересчёта с обоснованием ---
p0 = est["positions"][0] assert est["recalc"] and est["recalc"]["doc"] == "1288р", est["recalc"]
assert p0["code"] == "01-02-058-03", p0["code"] assert est["recalc"]["date"] == "13.05.2022", est["recalc"]
ks = {(c["kind"], c["target"]): c["value"] for c in p0["coefficients"]} assert abs(est["kizp"]["main"] - 8.04) < 1e-9, est["kizp"]
assert abs(ks[("Кзп", "ОТ")] - 1.3) < 1e-9, ks print(f" price_level: {est['price_level']} | Кизп={est['kizp']['main']}")
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 (Установка опор) --- # --- реально применённые коэффициенты позиции 1 (Копание ям) ---
p1 = est["positions"][1] p0 = est["positions"][0]
w = p1["resources"]["workers"] assert p0["code"] == "01-02-058-03", p0["code"]
assert abs(w[0]["consumption"] - 38.3364) < 1e-6 and w[0]["grade"] == "3,3", w ks = {(c["kind"], c["target"]): c["value"] for c in p0["coefficients"]}
m = {r["code"]: r for r in p1["resources"]["machines"]} assert abs(ks[("Кзп", "ОТ")] - 1.3) < 1e-9, ks
assert abs(m["021312"]["consumption"] - 2.4702) < 1e-6, m assert abs(ks[("Кнр", "ОТ")] - 0.89) < 1e-9, ks
assert abs(m["021312"]["price_base"] - 211.94) < 0.01, m assert abs(ks[("Ксп", "ОТ")] - 0.4) < 1e-9, ks
mat = {r["code"]: r for r in p1["resources"]["materials"]} assert abs(ks[("Кизп", "ОТ")] - 8.04) < 1e-9, ks
assert abs(mat["101-0125"]["consumption"] - 0.0032) < 1e-9, mat groups = {c["kind"]: c["group"] for c in p0["coefficients"]}
print(f" ресурсы поз.2: workers={len(w)} machines={len(m)} materials={len(mat)}") 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 (Установка опор) ---
dump = json.dumps(est, ensure_ascii=False) p1 = est["positions"][1]
assert "Находка" not in dump, "топоним утёк" w = p1["resources"]["workers"]
assert "Антонова" not in dump and "Неверова" not in dump, "ФИО утекли" assert abs(w[0]["consumption"] - 38.3364) < 1e-6 and w[0]["grade"] == "3,3", w
assert not has_identifier_leak(est["name"]), est["name"] 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)}")
# --- ground truth: итог парной .xls === итог .arp --- # --- обезличивание: топоним из шапки вырезан, ФИО не извлечены ---
stem = _norm_stem(arp_name, "arps?") dump = json.dumps(est, ensure_ascii=False)
xls_name = next(n for n in z.namelist() assert "Находка" not in dump, "топоним утёк"
if n.lower().endswith(".xls") and _norm_stem(n, "xls") == stem) assert "Антонова" not in dump and "Неверова" not in dump, "ФИО утекли"
xt = _xls_total(z.read(xls_name)) assert not has_identifier_leak(est["name"]), est["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 утечек, живой индекс не тронут по построению --- # --- ground truth: итог парной .xls === итог .arp ---
assert STAGING.exists(), "staging_arp.json не построен — сначала build_arp_staging.py" stem = _norm_stem(arp_name, "arps?")
st = json.loads(STAGING.read_text(encoding="utf-8")) xls_name = next(n for n in z.namelist()
meta = st["meta"] if n.lower().endswith(".xls") and _norm_stem(n, "xls") == stem)
assert meta["staged_files"] > 0 and meta["unique_items"] > 0, meta xt = _xls_total(z.read(xls_name))
assert meta["leaks_in_staging"] == 0, meta assert xt is not None, "итог из .xls не извлёкся"
assert meta["xls_verified"] > 0, meta assert abs(est["total"] - xt) <= 2.0, (est["total"], xt)
# арифметика приёмки: staged + duplicates + карантин(файлы, вкл. parse_error) == files_seen print(f" сверка с парной .xls: arp={est['total']} xls={xt} — сошлось")
quar_files = sum(v for k, v in meta["quarantined"].items()
if k not in ("price_outlier", "leak_final_pass")) # --- staging: счётчики, 0 утечек, живой индекс не тронут по построению ---
assert meta["staged_files"] + meta["duplicates"] + quar_files == meta["files_seen"], meta assert STAGING.exists(), "staging_arp.json не построен — сначала build_arp_staging.py"
# независимая канарейка утечек: по строковым значениям каждого item st = json.loads(STAGING.read_text(encoding="utf-8"))
leaks = sum(1 for it in st["items"] + st["recalc_index"] if _struct_leaks(it)) meta = st["meta"]
assert leaks == 0, f"{leaks} утечек в staging" assert meta["staged_files"] > 0 and meta["unique_items"] > 0, meta
# записи с реально применёнными коэффициентами и Кнр/Ксп в топе assert meta["leaks_in_staging"] == 0, meta
with_coefs = [it for it in st["items"] if it["coef_applications"]] assert meta["xls_verified"] > 0, meta
assert with_coefs, "нет ни одной записи с коэффициентами" # арифметика приёмки: staged + duplicates + карантин(файлы, вкл. parse_error) == files_seen
kinds = {c["kind"] for it in with_coefs for c in it["coef_applications"]["coefs"]} quar_files = sum(v for k, v in meta["quarantined"].items()
assert "Кнр" in kinds and "Ксп" in kinds, kinds if k not in ("price_outlier", "leak_final_pass"))
# пункт #5: recalc_index с распоряжением 1288р и Кизп assert meta["staged_files"] + meta["duplicates"] + quar_files == meta["files_seen"], meta
docs = {r["doc"] for r in st["recalc_index"]} # независимая канарейка утечек: по строковым значениям каждого item
assert "1288р" in docs, docs leaks = sum(1 for it in st["items"] + st["recalc_index"] if _struct_leaks(it))
r1288 = next(r for r in st["recalc_index"] if r["doc"] == "1288р") assert leaks == 0, f"{leaks} утечек в staging"
assert "Кизп" in r1288["indices"], r1288["indices"] # записи с реально применёнными коэффициентами и Кнр/Ксп в топе
assert all(it["norm_base"] == "ОСНБЖ" and it["price_level"] for it in st["items"][:50]) with_coefs = [it for it in st["items"] if it["coef_applications"]]
print(f" staging: items={meta['unique_items']} staged={meta['staged_files']} " assert with_coefs, "нет ни одной записи с коэффициентами"
f"dup={meta['duplicates']} quar={dict(meta['quarantined'])} " kinds = {c["kind"] for it in with_coefs for c in it["coef_applications"]["coefs"]}
f"xls_verified={meta['xls_verified']}/{meta['xls_pairs_found']} leaks=0") assert "Кнр" in kinds and "Ксп" in kinds, kinds
print("ALL PASS") # пункт #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()
+28 -19
View File
@@ -1,29 +1,38 @@
"""Real-тест parse_arp_file на настоящем .arp (гонять на dev2).""" """Real-тест parse_arp_file на настоящем .arp (гонять на dev2; без корпуса — skip)."""
import shutil import shutil
import sys
import tempfile import tempfile
import zipfile import zipfile
from pathlib import Path from pathlib import Path
import pytest
from gge_tools import parse_arp_file from gge_tools import parse_arp_file
SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/11900.zip") SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/11900.zip")
tmp = Path(tempfile.mkdtemp())
with zipfile.ZipFile(SRC) as z:
name = next(n for n in z.namelist() if n.lower().endswith(".arp"))
p = tmp / "s.arp"
p.write_bytes(z.read(name))
r = parse_arp_file(p) def test_arp_real():
assert "error" not in r, r if not SRC.exists():
print(f" code={r['code']} | total={r['total']} | positions={r['positions_count']}") pytest.skip("нет реальных данных корпуса (гонять на dev2)")
assert r["code"] == "00-02-7-00-01Р", r["code"] # реальный якорь (не только непустота) tmp = Path(tempfile.mkdtemp())
assert abs(r["total"] - 6105760.71) < 0.01, r["total"] # ловит съезд индекса поля итога with zipfile.ZipFile(SRC) as z:
assert r["positions_count"] > 0, r name = next(n for n in z.namelist() if n.lower().endswith(".arp"))
p0 = r["positions"][0] p = tmp / "s.arp"
assert p0["code"] and p0["name"] and p0["unit"], p0 p.write_bytes(z.read(name))
assert p0["total"] > 0, p0 # ловит съезд индекса стоимости позиции
print(f" пример: {p0}") r = parse_arp_file(p)
shutil.rmtree(tmp, ignore_errors=True) assert "error" not in r, r
print("ALL PASS") print(f" code={r['code']} | total={r['total']} | positions={r['positions_count']}")
assert r["code"] == "00-02-7-00-01Р", r["code"] # реальный якорь (не только непустота)
assert abs(r["total"] - 6105760.71) < 0.01, r["total"] # ловит съезд индекса поля итога
assert r["positions_count"] > 0, r
p0 = r["positions"][0]
assert p0["code"] and p0["name"] and p0["unit"], p0
assert p0["total"] > 0, p0 # ловит съезд индекса стоимости позиции
print(f" пример: {p0}")
shutil.rmtree(tmp, ignore_errors=True)
print("ALL PASS")
if __name__ == "__main__":
test_arp_real()
+66 -50
View File
@@ -1,15 +1,21 @@
"""Real-тест чтения форматов в GLM-пути (_read_work_dir_files) на НАСТОЯЩИХ файлах """Real-тест чтения форматов в GLM-пути (_read_work_dir_files) на НАСТОЯЩИХ файлах
из загруженных архивов (гонять на dev2, где стоят xlrd/catdoc/tesseract/docx). из загруженных архивов (гонять на dev2, где стоят xlrd/catdoc/tesseract/docx).
Вытаскивает по одному образцу .xls/.doc/.docx/.gsfx/.esw и проверяет вывод.""" Вытаскивает по одному образцу .xls/.doc/.docx/.gsfx/.esw и проверяет вывод.
Без корпуса — skip всего модуля (гейт стоит ДО импорта claude_bridge_glm:
его цепочка тянет pymorphy2, которого нет вне сервера)."""
import shutil import shutil
import sys
import tempfile import tempfile
import zipfile import zipfile
from pathlib import Path from pathlib import Path
from claude_bridge_glm import _read_work_dir_files import pytest
BASE = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100") BASE = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100")
if not BASE.exists():
pytest.skip("нет реальных данных корпуса (гонять на dev2)", allow_module_level=True)
from claude_bridge_glm import _read_work_dir_files # noqa: E402
# (архив, расширение, имя-образца) # (архив, расширение, имя-образца)
SAMPLES = [ SAMPLES = [
("40_Калинина.zip", ".xls", "sample.xls"), ("40_Калинина.zip", ".xls", "sample.xls"),
@@ -19,59 +25,69 @@ SAMPLES = [
("очистные тумнин.zip", ".esw", "sample.esw"), ("очистные тумнин.zip", ".esw", "sample.esw"),
] ]
tmp = Path(tempfile.mkdtemp())
got = {}
for arch, ext, outname in SAMPLES:
ap = BASE / arch
if not ap.exists():
print(f" ПРОПУСК {arch} (нет)")
continue
with zipfile.ZipFile(ap) as z:
entry = next((n for n in z.namelist()
if n.lower().endswith(ext) and not n.endswith("/")), None)
if not entry:
print(f" в {arch} нет {ext}")
continue
(tmp / outname).write_bytes(z.read(entry))
got[ext] = outname
out = _read_work_dir_files(tmp)
print("=== вывод _read_work_dir_files (обрезано) ===")
for line in out.splitlines():
if line.startswith("###") or "проприетарный" in line or "не удалось" in line:
print(" " + line[:110])
fails = 0 fails = 0
def chk(name, cond, hint=""): def chk(name, cond, hint=""):
global fails global fails
print((" ok: " if cond else " FAIL: ") + name + ("" if cond else f" — {hint}")) print((" ok: " if cond else " FAIL: ") + name + ("" if cond else f" — {hint}"))
if not cond: if not cond:
fails += 1 fails += 1
if ".xls" in got:
chk(".xls читается (xlrd)", "Лист:" in out and "не удалось" not in out.split("sample.xls")[1][:200], "нет данных листа")
if ".doc" in got:
seg = out.split("sample.doc")[1][:400] if "sample.doc" in out else ""
chk(".doc читается (catdoc)", "не удалось" not in seg and len(seg.strip()) > 20, "пустой/ошибка")
if ".docx" in got:
seg = out.split("sample.docx")[1][:600] if "sample.docx" in out else ""
chk(".docx читается", "не удалось" not in seg and len(seg.strip()) > 30, "пусто/ошибка")
# Отдельно — ТАБЛИЦЫ docx (главная фича п.5) на СИНТЕТИЧЕСКОМ docx с таблицей. def test_formats_real():
from claude_bridge_glm import _read_docx global fails
import docx as _docxlib fails = 0
_d = _docxlib.Document() tmp = Path(tempfile.mkdtemp())
_t = _d.add_table(rows=2, cols=2) got = {}
_t.rows[0].cells[0].text = "Работа"; _t.rows[0].cells[1].text = "Объём" for arch, ext, outname in SAMPLES:
_t.rows[1].cells[0].text = "Копание ям"; _t.rows[1].cells[1].text = "411 м3" ap = BASE / arch
_tp = tmp / "tbl.docx"; _d.save(str(_tp)) if not ap.exists():
_txt = _read_docx(_tp, 10000) print(f" ПРОПУСК {arch} (нет)")
chk(".docx таблицы читаются", "Копание ям" in _txt and "411 м3" in _txt and " | " in _txt, "таблица упущена") continue
if ".gsfx" in got: with zipfile.ZipFile(ap) as z:
chk(".gsfx парсится (Смета)", "Смета .gsfx" in out and "Шифр:" in out, "не распознан") entry = next((n for n in z.namelist()
if ".esw" in got: if n.lower().endswith(ext) and not n.endswith("/")), None)
chk(".esw честный отказ", "проприетарный" in out, "нет отказа") if not entry:
print(f" в {arch} нет {ext}")
continue
(tmp / outname).write_bytes(z.read(entry))
got[ext] = outname
shutil.rmtree(tmp, ignore_errors=True) out = _read_work_dir_files(tmp)
print("ALL PASS" if not fails else f"{fails} FAILED") print("=== вывод _read_work_dir_files (обрезано) ===")
sys.exit(fails) for line in out.splitlines():
if line.startswith("###") or "проприетарный" in line or "не удалось" in line:
print(" " + line[:110])
if ".xls" in got:
chk(".xls читается (xlrd)", "Лист:" in out and "не удалось" not in out.split("sample.xls")[1][:200], "нет данных листа")
if ".doc" in got:
seg = out.split("sample.doc")[1][:400] if "sample.doc" in out else ""
chk(".doc читается (catdoc)", "не удалось" not in seg and len(seg.strip()) > 20, "пустой/ошибка")
if ".docx" in got:
seg = out.split("sample.docx")[1][:600] if "sample.docx" in out else ""
chk(".docx читается", "не удалось" not in seg and len(seg.strip()) > 30, "пусто/ошибка")
# Отдельно — ТАБЛИЦЫ docx (главная фича п.5) на СИНТЕТИЧЕСКОМ docx с таблицей.
from claude_bridge_glm import _read_docx
import docx as _docxlib
_d = _docxlib.Document()
_t = _d.add_table(rows=2, cols=2)
_t.rows[0].cells[0].text = "Работа"; _t.rows[0].cells[1].text = "Объём"
_t.rows[1].cells[0].text = "Копание ям"; _t.rows[1].cells[1].text = "411 м3"
_tp = tmp / "tbl.docx"; _d.save(str(_tp))
_txt = _read_docx(_tp, 10000)
chk(".docx таблицы читаются", "Копание ям" in _txt and "411 м3" in _txt and " | " in _txt, "таблица упущена")
if ".gsfx" in got:
chk(".gsfx парсится (Смета)", "Смета .gsfx" in out and "Шифр:" in out, "не распознан")
if ".esw" in got:
chk(".esw честный отказ", "проприетарный" in out, "нет отказа")
shutil.rmtree(tmp, ignore_errors=True)
print("ALL PASS" if not fails else f"{fails} FAILED")
assert fails == 0, f"{fails} проверок форматов упали"
if __name__ == "__main__":
test_formats_real()
+30 -21
View File
@@ -1,32 +1,41 @@
"""Real-тест parse_gsfx_file на настоящем .gsfx (гонять на dev2). """Real-тест parse_gsfx_file на настоящем .gsfx (гонять на dev2; без корпуса — skip).
Извлекает один .gsfx из реального архива и парсит. Извлекает один .gsfx из реального архива и парсит.
Запуск: cd ~/smeta-web-dev2 && python3 test_gsfx_server.py""" Запуск скриптом: cd ~/smeta-web-dev2 && python3 tests/test_gsfx_server.py"""
import shutil import shutil
import sys
import tempfile import tempfile
import zipfile import zipfile
from pathlib import Path from pathlib import Path
import pytest
from gge_tools import parse_gsfx_file from gge_tools import parse_gsfx_file
SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/АРХИВ ОБЩИЙ_Гранд-смета.zip") SRC = Path("/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/АРХИВ ОБЩИЙ_Гранд-смета.zip")
tmp = Path(tempfile.mkdtemp())
with zipfile.ZipFile(SRC) as z:
name = next(n for n in z.namelist() if n.lower().endswith(".gsfx"))
p = tmp / "s.gsfx"
p.write_bytes(z.read(name))
r = parse_gsfx_file(p) def test_gsfx_real():
assert "error" not in r, r if not SRC.exists():
print(f" code={r['code']} | total={r['total']} | positions={r['positions_count']} | region={r['region'][:28]}") pytest.skip("нет реальных данных корпуса (гонять на dev2)")
assert r["code"] == "ЛС-07-01-01", r["code"] tmp = Path(tempfile.mkdtemp())
assert abs(r["total"] - 16113326.39) < 1.0, r["total"] with zipfile.ZipFile(SRC) as z:
assert r["positions_count"] > 0, r name = next(n for n in z.namelist() if n.lower().endswith(".gsfx"))
p0 = r["positions"][0] p = tmp / "s.gsfx"
assert p0["code"] and p0["name"], p0 p.write_bytes(z.read(name))
# quantity>0 у хотя бы одной позиции — ловит баг русской запятой в Result.
assert any(p["quantity"] > 0 for p in r["positions"]), "все quantity == 0 (запятая?)" r = parse_gsfx_file(p)
print(f" пример позиции: {p0}") assert "error" not in r, r
shutil.rmtree(tmp, ignore_errors=True) print(f" code={r['code']} | total={r['total']} | positions={r['positions_count']} | region={r['region'][:28]}")
print("ALL PASS") assert r["code"] == "ЛС-07-01-01", r["code"]
assert abs(r["total"] - 16113326.39) < 1.0, r["total"]
assert r["positions_count"] > 0, r
p0 = r["positions"][0]
assert p0["code"] and p0["name"], p0
# quantity>0 у хотя бы одной позиции — ловит баг русской запятой в Result.
assert any(p["quantity"] > 0 for p in r["positions"]), "все quantity == 0 (запятая?)"
print(f" пример позиции: {p0}")
shutil.rmtree(tmp, ignore_errors=True)
print("ALL PASS")
if __name__ == "__main__":
test_gsfx_real()
+70 -45
View File
@@ -1,11 +1,31 @@
"""Интеграционный тест маскировки в _stream_and_save (гонять на сервере, где есть env). """Интеграционный тест маскировки в _stream_and_save (гонять на сервере, где есть env).
Подменяет stream_claude на подставные потоки и проверяет: сырой 401 не уходит ни в Подменяет stream_claude на подставные потоки и проверяет: сырой 401 не уходит ни в
стрим, ни в БД; нормальный ответ проходит как есть.""" стрим, ни в БД; нормальный ответ проходит как есть.
Гейт: нужна ЖИВАЯ БД приложения (файл + схема) — без неё skip до импорта main,
иначе модуль-левел clear_history падал бы 'no such table' при сборке pytest."""
import asyncio import asyncio
import sys import sqlite3
import main import pytest
from db import get_history, clear_history
import db as _dbmod
def _db_ready() -> bool:
if not _dbmod.DB_PATH.exists():
return False
try:
_dbmod.get_history("probe@local", "probe-gate")
return True
except sqlite3.OperationalError:
return False
if not _db_ready():
pytest.skip("нет живой БД приложения (гонять на сервере с .env)", allow_module_level=True)
import main # noqa: E402
from db import get_history, clear_history # noqa: E402
USER = "masktest@local" USER = "masktest@local"
RAW_401 = ('Failed to authenticate. API Error: 401 {"type":"error","error":' RAW_401 = ('Failed to authenticate. API Error: 401 {"type":"error","error":'
@@ -41,51 +61,56 @@ def check(name, cond):
return 0 if cond else 1 return 0 if cond else 1
fails = 0 def test_mask_integration():
FRIENDLY = main.PROVIDER_ERROR_MESSAGE fails = 0
FRIENDLY = main.PROVIDER_ERROR_MESSAGE
# Case A — ошибка приходит как event: text # Case A — ошибка приходит как event: text
tabA = "mask-A" tabA = "mask-A"
clear_history(USER, tabA) clear_history(USER, tabA)
outA = drive([_sse("text", {"text": RAW_401})], tabA) outA = drive([_sse("text", {"text": RAW_401})], tabA)
fails += check("A: стрим содержит friendly", FRIENDLY in outA) fails += check("A: стрим содержит friendly", FRIENDLY in outA)
fails += check("A: стрим НЕ содержит сырой 401", "authentication_error" not in outA and "API Error" not in outA) fails += check("A: стрим НЕ содержит сырой 401", "authentication_error" not in outA and "API Error" not in outA)
fails += check("A: в БД сохранён friendly", saved_assistant(tabA) == FRIENDLY) fails += check("A: в БД сохранён friendly", saved_assistant(tabA) == FRIENDLY)
fails += check("A: в БД нет сырого 401", "authentication_error" not in (saved_assistant(tabA) or "")) fails += check("A: в БД нет сырого 401", "authentication_error" not in (saved_assistant(tabA) or ""))
# Case B — ошибка приходит как event: done result # Case B — ошибка приходит как event: done result
tabB = "mask-B" tabB = "mask-B"
clear_history(USER, tabB) clear_history(USER, tabB)
outB = drive([_sse("done", {"result": RAW_401})], tabB) outB = drive([_sse("done", {"result": RAW_401})], tabB)
fails += check("B: стрим friendly, без сырого", FRIENDLY in outB and "authentication_error" not in outB) fails += check("B: стрим friendly, без сырого", FRIENDLY in outB and "authentication_error" not in outB)
fails += check("B: в БД friendly", saved_assistant(tabB) == FRIENDLY) fails += check("B: в БД friendly", saved_assistant(tabB) == FRIENDLY)
# Case C — нормальный ответ проходит как есть # Case C — нормальный ответ проходит как есть
tabC = "mask-C" tabC = "mask-C"
clear_history(USER, tabC) clear_history(USER, tabC)
normal = "Расценка ГЭСН 28-01-001, НР 130%. Стоимость 401 руб." normal = "Расценка ГЭСН 28-01-001, НР 130%. Стоимость 401 руб."
outC = drive([_sse("text", {"text": normal}), _sse("done", {"result": ""})], tabC) outC = drive([_sse("text", {"text": normal}), _sse("done", {"result": ""})], tabC)
fails += check("C: нормальный ответ в стриме", normal in outC) fails += check("C: нормальный ответ в стриме", normal in outC)
fails += check("C: нормальный ответ в БД", saved_assistant(tabC) == normal) fails += check("C: нормальный ответ в БД", saved_assistant(tabC) == normal)
# Case D — ошибка GLM-пути («Ошибка GLM API: …») тоже маскируется (регресс P0: # Case D — ошибка GLM-пути («Ошибка GLM API: …») тоже маскируется (регресс P0:
# раньше сырой 401 с URL бэкенда утекал юзеру и в историю на GLM-пути). # раньше сырой 401 с URL бэкенда утекал юзеру и в историю на GLM-пути).
tabD = "mask-D" tabD = "mask-D"
clear_history(USER, tabD) clear_history(USER, tabD)
GLM_ERR = "Ошибка GLM API: Client error '401 Unauthorized' for url 'https://open.bigmodel.cn/'" GLM_ERR = "Ошибка GLM API: Client error '401 Unauthorized' for url 'https://open.bigmodel.cn/'"
outD = drive([_sse("text", {"text": GLM_ERR})], tabD) outD = drive([_sse("text", {"text": GLM_ERR})], tabD)
fails += check("D: GLM-ошибка → friendly в стриме, без сырого", FRIENDLY in outD and "401" not in outD) fails += check("D: GLM-ошибка → friendly в стриме, без сырого", FRIENDLY in outD and "401" not in outD)
fails += check("D: GLM-ошибка → friendly в БД", saved_assistant(tabD) == FRIENDLY) fails += check("D: GLM-ошибка → friendly в БД", saved_assistant(tabD) == FRIENDLY)
# Аудит: замаскированный инцидент виден оператору (log_action agent_error) — # Аудит: замаскированный инцидент виден оператору (log_action agent_error) —
# единственный канал, по которому узнают о проблеме. Удали log_action → упадёт. # единственный канал, по которому узнают о проблеме. Удали log_action → упадёт.
from db import get_audit_log from db import get_audit_log
fails += check("инцидент залогирован (agent_error)", fails += check("инцидент залогирован (agent_error)",
len(get_audit_log(action="agent_error", limit=10)) > 0) len(get_audit_log(action="agent_error", limit=10)) > 0)
# cleanup # cleanup
for t in ("mask-A", "mask-B", "mask-C", "mask-D"): for t in ("mask-A", "mask-B", "mask-C", "mask-D"):
clear_history(USER, t) clear_history(USER, t)
print("ALL PASS" if not fails else f"{fails} FAILED") print("ALL PASS" if not fails else f"{fails} FAILED")
sys.exit(fails) assert fails == 0, f"{fails} проверок маскировки упали"
if __name__ == "__main__":
test_mask_integration()
+35 -25
View File
@@ -1,36 +1,46 @@
"""Серверный real-тест распаковки rar (гонять на dev2, где есть unar + реальный rar). """Серверный real-тест распаковки rar (гонять на dev2, где есть unar + реальный rar;
Запуск: cd ~/smeta-web-dev2 && set -a && . ./.env && set +a && python3 tests/test_rar_server.py""" без корпуса — skip).
Запуск скриптом: cd ~/smeta-web-dev2 && set -a && . ./.env && set +a && python3 tests/test_rar_server.py"""
import shutil import shutil
import sys
import tempfile import tempfile
import time import time
from pathlib import Path from pathlib import Path
import pytest
import archive_host as ah import archive_host as ah
from db import get_history, clear_history from db import get_history, clear_history
RAR = "/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/09.0200.rar" RAR = "/home/mcp-user/smeta-web-data/smeta/b1f47437-2254-4267-a584-4d2ea050e100/09.0200.rar"
# 1) синхронная распаковка реального rar
tmp = Path(tempfile.mkdtemp())
r = ah.extract_rarlike(Path(RAR), tmp)
assert r["ok"] and r["files"] > 0, r
print(f" ok sync: {r['files']} файлов → {Path(r['target']).name}/")
shutil.rmtree(tmp, ignore_errors=True)
# 2) async + system-сообщение в БД def test_rar_real():
USER, TAB = "rartest@local", "rar-int" if not Path(RAR).exists():
clear_history(USER, TAB) pytest.skip("нет реальных данных корпуса (гонять на dev2)")
wd = Path(tempfile.mkdtemp()) # 1) синхронная распаковка реального rar
ah.extract_rarlike_async(RAR, wd, USER, TAB) tmp = Path(tempfile.mkdtemp())
for _ in range(60): r = ah.extract_rarlike(Path(RAR), tmp)
if any(x["role"] == "system" and "распакован" in x["content"] for x in get_history(USER, TAB)): assert r["ok"] and r["files"] > 0, r
break print(f" ok sync: {r['files']} файлов → {Path(r['target']).name}/")
time.sleep(0.5) shutil.rmtree(tmp, ignore_errors=True)
sysmsg = [x["content"] for x in get_history(USER, TAB) if x["role"] == "system"]
assert any("распакован" in m for m in sysmsg), ("нет system-сообщения", sysmsg) # 2) async + system-сообщение в БД
assert (wd / "09.0200_extracted").exists(), "нет папки распаковки" USER, TAB = "rartest@local", "rar-int"
print(f" ok async: {sysmsg[-1]}") clear_history(USER, TAB)
clear_history(USER, TAB) wd = Path(tempfile.mkdtemp())
shutil.rmtree(wd, ignore_errors=True) ah.extract_rarlike_async(RAR, wd, USER, TAB)
print("ALL PASS") for _ in range(60):
if any(x["role"] == "system" and "распакован" in x["content"] for x in get_history(USER, TAB)):
break
time.sleep(0.5)
sysmsg = [x["content"] for x in get_history(USER, TAB) if x["role"] == "system"]
assert any("распакован" in m for m in sysmsg), ("нет system-сообщения", sysmsg)
assert (wd / "09.0200_extracted").exists(), "нет папки распаковки"
print(f" ok async: {sysmsg[-1]}")
clear_history(USER, TAB)
shutil.rmtree(wd, ignore_errors=True)
print("ALL PASS")
if __name__ == "__main__":
test_rar_real()