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 по НАСТОЯЩИМ наименованиям позиций из
.arp/.gsfx и ячейкам реестра замечаний. Метрика: утечки ДО vs остаточные ПОСЛЕ scrub
(остаточные → карантин, в корпус НЕ идут). Гонять на dev2."""
(остаточные → карантин, в корпус НЕ идут). Гонять на dev2; без корпуса — skip."""
import tempfile
import zipfile
from pathlib import Path
import pytest
import corpus_anon as ca
from gge_tools import parse_arp_file, parse_gsfx_file
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 — наименования позиций + шапка + регион
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", [])]
def test_anon_realdata():
if not BASE.exists():
pytest.skip("нет реальных данных корпуса (гонять на dev2)")
tmp = Path(tempfile.mkdtemp())
names: list[str] = []
# реестр замечаний — свободный текст ячеек
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:
# .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 — наименования позиций + шапка + регион
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
for v in row:
if isinstance(v, str) and len(v.strip()) > 8:
names.append(v.strip())
except Exception as e:
print("реестр пропущен:", e)
if residual:
print("--- ОСТАТОЧНЫЕ (пойдут в карантин) ---")
for orig, sc in residual[:8]:
print(" ", repr(sc[:80]))
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])]
import shutil
shutil.rmtree(tmp, ignore_errors=True)
# Гейт: остаточные утечки допустимы (→ карантин), но их доля не должна быть большой,
# иначе скраб слишком дырявый. Порог: < 5% остаточных.
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
shutil.rmtree(tmp, ignore_errors=True)
# Гейт: остаточные утечки допустимы (→ карантин), но их доля не должна быть большой,
# иначе скраб слишком дырявый. Порог: < 5% остаточных.
rate = len(residual) / max(1, len(names))
print(f"доля остаточных: {rate:.1%}")
assert rate < 0.05, f"слишком много остаточных утечек ({rate:.1%}) — скраб дырявый"
print("REALDATA OK")
if __name__ == "__main__":
test_anon_realdata()
+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), значения сверены
глазами по сырому АРПС-тексту и парной .xls-распечатке (Итого по смете).
@@ -9,6 +9,8 @@ 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"))
@@ -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")
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")
# --- шапка + гейт формулы итога ---
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']}")
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")
# --- пункт #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']}")
# --- шапка + гейт формулы итога ---
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']}")
# --- реально применённые коэффициенты позиции 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"]
# --- пункт #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']}")
# --- ресурсы позиции 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)}")
# --- реально применённые коэффициенты позиции 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"]
# --- обезличивание: топоним из шапки вырезан, ФИО не извлечены ---
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"]
# --- ресурсы позиции 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)}")
# --- 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} — сошлось")
# --- обезличивание: топоним из шапки вырезан, ФИО не извлечены ---
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"]
# --- 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")
# --- 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()
+28 -19
View File
@@ -1,29 +1,38 @@
"""Real-тест parse_arp_file на настоящем .arp (гонять на dev2)."""
"""Real-тест parse_arp_file на настоящем .arp (гонять на dev2; без корпуса — skip)."""
import shutil
import sys
import tempfile
import zipfile
from pathlib import Path
import pytest
from gge_tools import parse_arp_file
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)
assert "error" not in r, r
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")
def test_arp_real():
if not SRC.exists():
pytest.skip("нет реальных данных корпуса (гонять на dev2)")
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)
assert "error" not in r, r
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) на НАСТОЯЩИХ файлах
из загруженных архивов (гонять на dev2, где стоят xlrd/catdoc/tesseract/docx).
Вытаскивает по одному образцу .xls/.doc/.docx/.gsfx/.esw и проверяет вывод."""
Вытаскивает по одному образцу .xls/.doc/.docx/.gsfx/.esw и проверяет вывод.
Без корпуса — skip всего модуля (гейт стоит ДО импорта claude_bridge_glm:
его цепочка тянет pymorphy2, которого нет вне сервера)."""
import shutil
import sys
import tempfile
import zipfile
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")
if not BASE.exists():
pytest.skip("нет реальных данных корпуса (гонять на dev2)", allow_module_level=True)
from claude_bridge_glm import _read_work_dir_files # noqa: E402
# (архив, расширение, имя-образца)
SAMPLES = [
("40_Калинина.zip", ".xls", "sample.xls"),
@@ -19,59 +25,69 @@ SAMPLES = [
("очистные тумнин.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
def chk(name, cond, hint=""):
global fails
print((" ok: " if cond else " FAIL: ") + name + ("" if cond else f" — {hint}"))
if not cond:
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 с таблицей.
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, "нет отказа")
def test_formats_real():
global fails
fails = 0
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
shutil.rmtree(tmp, ignore_errors=True)
print("ALL PASS" if not fails else f"{fails} FAILED")
sys.exit(fails)
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])
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 из реального архива и парсит.
Запуск: cd ~/smeta-web-dev2 && python3 test_gsfx_server.py"""
Запуск скриптом: cd ~/smeta-web-dev2 && python3 tests/test_gsfx_server.py"""
import shutil
import sys
import tempfile
import zipfile
from pathlib import Path
import pytest
from gge_tools import parse_gsfx_file
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)
assert "error" not in r, r
print(f" code={r['code']} | total={r['total']} | positions={r['positions_count']} | region={r['region'][:28]}")
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")
def test_gsfx_real():
if not SRC.exists():
pytest.skip("нет реальных данных корпуса (гонять на dev2)")
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)
assert "error" not in r, r
print(f" code={r['code']} | total={r['total']} | positions={r['positions_count']} | region={r['region'][:28]}")
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_claude на подставные потоки и проверяет: сырой 401 не уходит ни в
стрим, ни в БД; нормальный ответ проходит как есть."""
стрим, ни в БД; нормальный ответ проходит как есть.
Гейт: нужна ЖИВАЯ БД приложения (файл + схема) — без неё skip до импорта main,
иначе модуль-левел clear_history падал бы 'no such table' при сборке pytest."""
import asyncio
import sys
import sqlite3
import main
from db import get_history, clear_history
import pytest
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"
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
fails = 0
FRIENDLY = main.PROVIDER_ERROR_MESSAGE
def test_mask_integration():
fails = 0
FRIENDLY = main.PROVIDER_ERROR_MESSAGE
# Case A — ошибка приходит как event: text
tabA = "mask-A"
clear_history(USER, tabA)
outA = drive([_sse("text", {"text": RAW_401})], tabA)
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: в БД сохранён friendly", saved_assistant(tabA) == FRIENDLY)
fails += check("A: в БД нет сырого 401", "authentication_error" not in (saved_assistant(tabA) or ""))
# Case A — ошибка приходит как event: text
tabA = "mask-A"
clear_history(USER, tabA)
outA = drive([_sse("text", {"text": RAW_401})], tabA)
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: в БД сохранён friendly", saved_assistant(tabA) == FRIENDLY)
fails += check("A: в БД нет сырого 401", "authentication_error" not in (saved_assistant(tabA) or ""))
# Case B — ошибка приходит как event: done result
tabB = "mask-B"
clear_history(USER, 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", saved_assistant(tabB) == FRIENDLY)
# Case B — ошибка приходит как event: done result
tabB = "mask-B"
clear_history(USER, 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", saved_assistant(tabB) == FRIENDLY)
# Case C — нормальный ответ проходит как есть
tabC = "mask-C"
clear_history(USER, tabC)
normal = "Расценка ГЭСН 28-01-001, НР 130%. Стоимость 401 руб."
outC = drive([_sse("text", {"text": normal}), _sse("done", {"result": ""})], tabC)
fails += check("C: нормальный ответ в стриме", normal in outC)
fails += check("C: нормальный ответ в БД", saved_assistant(tabC) == normal)
# Case C — нормальный ответ проходит как есть
tabC = "mask-C"
clear_history(USER, tabC)
normal = "Расценка ГЭСН 28-01-001, НР 130%. Стоимость 401 руб."
outC = drive([_sse("text", {"text": normal}), _sse("done", {"result": ""})], tabC)
fails += check("C: нормальный ответ в стриме", normal in outC)
fails += check("C: нормальный ответ в БД", saved_assistant(tabC) == normal)
# Case D — ошибка GLM-пути («Ошибка GLM API: …») тоже маскируется (регресс P0:
# раньше сырой 401 с URL бэкенда утекал юзеру и в историю на GLM-пути).
tabD = "mask-D"
clear_history(USER, tabD)
GLM_ERR = "Ошибка GLM API: Client error '401 Unauthorized' for url 'https://open.bigmodel.cn/'"
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 в БД", saved_assistant(tabD) == FRIENDLY)
# Case D — ошибка GLM-пути («Ошибка GLM API: …») тоже маскируется (регресс P0:
# раньше сырой 401 с URL бэкенда утекал юзеру и в историю на GLM-пути).
tabD = "mask-D"
clear_history(USER, tabD)
GLM_ERR = "Ошибка GLM API: Client error '401 Unauthorized' for url 'https://open.bigmodel.cn/'"
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 в БД", saved_assistant(tabD) == FRIENDLY)
# Аудит: замаскированный инцидент виден оператору (log_action agent_error) —
# единственный канал, по которому узнают о проблеме. Удали log_action → упадёт.
from db import get_audit_log
fails += check("инцидент залогирован (agent_error)",
len(get_audit_log(action="agent_error", limit=10)) > 0)
# Аудит: замаскированный инцидент виден оператору (log_action agent_error) —
# единственный канал, по которому узнают о проблеме. Удали log_action → упадёт.
from db import get_audit_log
fails += check("инцидент залогирован (agent_error)",
len(get_audit_log(action="agent_error", limit=10)) > 0)
# cleanup
for t in ("mask-A", "mask-B", "mask-C", "mask-D"):
clear_history(USER, t)
# cleanup
for t in ("mask-A", "mask-B", "mask-C", "mask-D"):
clear_history(USER, t)
print("ALL PASS" if not fails else f"{fails} FAILED")
sys.exit(fails)
print("ALL PASS" if not fails else f"{fails} FAILED")
assert fails == 0, f"{fails} проверок маскировки упали"
if __name__ == "__main__":
test_mask_integration()
+35 -25
View File
@@ -1,36 +1,46 @@
"""Серверный real-тест распаковки rar (гонять на dev2, где есть unar + реальный rar).
Запуск: cd ~/smeta-web-dev2 && set -a && . ./.env && set +a && python3 tests/test_rar_server.py"""
"""Серверный real-тест распаковки rar (гонять на dev2, где есть unar + реальный rar;
без корпуса — skip).
Запуск скриптом: cd ~/smeta-web-dev2 && set -a && . ./.env && set +a && python3 tests/test_rar_server.py"""
import shutil
import sys
import tempfile
import time
from pathlib import Path
import pytest
import archive_host as ah
from db import get_history, clear_history
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-сообщение в БД
USER, TAB = "rartest@local", "rar-int"
clear_history(USER, TAB)
wd = Path(tempfile.mkdtemp())
ah.extract_rarlike_async(RAR, wd, USER, TAB)
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")
def test_rar_real():
if not Path(RAR).exists():
pytest.skip("нет реальных данных корпуса (гонять на dev2)")
# 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-сообщение в БД
USER, TAB = "rartest@local", "rar-int"
clear_history(USER, TAB)
wd = Path(tempfile.mkdtemp())
ah.extract_rarlike_async(RAR, wd, USER, TAB)
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()