Files
anorandClaude Opus 4.8 59aeb54aa1 feat: парсер .gsfx (ГРАНД-Смета новый формат) + MCP-tool parse_gsfx_file
Пункт 1 мастер-плана по анализу корпуса: .gsfx (555 файлов) не читался. .gsfx = zip с
Properties.txt (шапка/итог cp1251) + Data.xml (позиции windows-1251). gge_tools.parse_gsfx_file
достаёт code/name/region/total + позиции (Code/Caption/Units/Quantity.Result), XXE-safe
(defusedxml→fallback). MCP-tool parse_gsfx_file + .gsfx в ALLOWED_EXTENSIONS обоих bridge.
Real-тест поймал баг: русская запятая в Result (0,24) → _ru_float. Юнит mutation-safe +
серверный real-тест на настоящем .gsfx (ЛС-07-01-01, 87 позиций, итог 16.1М). APP_VERSION→2026-07-15c.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-15 20:39:27 +10:00

85 lines
3.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Юнит-тест parse_gsfx_file на СИНТЕТИЧЕСКОМ .gsfx (сам собираю zip с
Properties.txt + Data.xml в cp1251). Реальный .gsfx проверяется отдельно на сервере.
Mutation-safe: сломай извлечение @Code/Total → соответствующий assert упадёт."""
import os
import sys
import tempfile
import zipfile
from pathlib import Path
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from gge_tools import parse_gsfx_file
PROPS = (
"DocType=sdtSmeta\r\n"
"Attribs.LocNum=ЛС-07-01-01\r\n"
"Attribs.ConName=Электрификация путей\r\n"
"Attribs.Description=Наружное освещение\r\n"
"Total=16113326.39\r\n"
"RegionInfo.RegionName=ФСНБ-2022 (с Изм. 1-12)\r\n"
)
DATA = (
'<?xml version="1.0" encoding="windows-1251"?>\r\n'
'<Document ProgramVersion="14.3" Generator="GrandSmeta">\r\n'
' <Chapter>\r\n'
' <Position Number="1" Code="ГЭСНм08-03-596-08" Caption="Прожектор на мачте" Units="100 шт">\r\n'
' <Quantity Fx="24/100" Result="0,24"/>\r\n'
' </Position>\r\n'
' <Position Number="2" Code="ФССЦ-01.2.03" Caption="Кабель силовой" Units="1000 м">\r\n'
' <Quantity Result="1,5"/>\r\n'
' </Position>\r\n'
' </Chapter>\r\n'
'</Document>\r\n'
)
def _make_gsfx(dirpath: Path) -> Path:
p = dirpath / "смета.gsfx"
with zipfile.ZipFile(p, "w") as z:
z.writestr("Properties.txt", PROPS.encode("cp1251"))
z.writestr("Data.xml", DATA.encode("cp1251"))
z.writestr("Data.sign", b"\x00\x01")
return p
def test_header_from_properties():
d = Path(tempfile.mkdtemp())
r = parse_gsfx_file(_make_gsfx(d))
assert "error" not in r, r
assert r["code"] == "ЛС-07-01-01", r
assert r["name"] == "Электрификация путей", r
assert abs(r["total"] - 16113326.39) < 0.01, r
assert "ФСНБ-2022" in r["region"], r
def test_positions_from_dataxml():
d = Path(tempfile.mkdtemp())
r = parse_gsfx_file(_make_gsfx(d))
assert r["positions_count"] == 2, r
p0 = r["positions"][0]
assert p0["code"] == "ГЭСНм08-03-596-08", p0
assert p0["name"] == "Прожектор на мачте", p0
assert p0["unit"] == "100 шт", p0
assert abs(p0["quantity"] - 0.24) < 1e-6, p0
def test_bad_zip_returns_error():
d = Path(tempfile.mkdtemp())
bad = d / "broken.gsfx"
bad.write_bytes(b"not a zip at all")
r = parse_gsfx_file(bad)
assert "error" in r, r
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:
fn(); print(f" ok: {fn.__name__}")
except Exception:
failed += 1; print(f" FAIL: {fn.__name__}"); traceback.print_exc()
print("ALL PASS" if not failed else f"{failed} FAILED")
sys.exit(failed)