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>
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
"""Юнит-тест 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)
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Real-тест parse_gsfx_file на настоящем .gsfx (гонять на dev2).
|
||||
Извлекает один .gsfx из реального архива и парсит.
|
||||
Запуск: cd ~/smeta-web-dev2 && python3 test_gsfx_server.py"""
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
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")
|
||||
Reference in New Issue
Block a user