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:
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user