Files
smeta-web/tests/test_formats_server.py

94 lines
4.2 KiB
Python

"""Real-тест чтения форматов в GLM-пути (_read_work_dir_files) на НАСТОЯЩИХ файлах
из загруженных архивов (гонять на dev2, где стоят xlrd/catdoc/tesseract/docx).
Вытаскивает по одному образцу .xls/.doc/.docx/.gsfx/.esw и проверяет вывод.
Без корпуса — skip всего модуля (гейт стоит ДО импорта claude_bridge_glm:
его цепочка тянет pymorphy3, которого нет вне сервера)."""
import shutil
import tempfile
import zipfile
from pathlib import Path
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"),
("!_ТЗ ДЛЯ.zip", ".doc", "sample.doc"),
("!_ТЗ ДЛЯ.zip", ".docx", "sample.docx"),
("АРХИВ ОБЩИЙ_Гранд-смета.zip", ".gsfx", "sample.gsfx"),
("очистные тумнин.zip", ".esw", "sample.esw"),
]
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
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
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()