Files
smeta-web/tests/test_gge_deep.py
T
anorandClaude Opus 4.8 6f78d9a32c feat: полнота извлечения — ресурсные индексы/машинисты, структура стоимости, сметная цена КА
Ре-аудит покрытия .gge: добавлено что выбрасывалось — индекс пересчёта ресурсов
с обоснованием, детали машинистов, структура стоимости расценки (машины/материалы/
зарплата), comment позиции, накладные/прибыль в рублях, возвратные материалы.
Фикс Transport (цена из PricePerUnitCur, была 0). КА: сметная цена EstimateWithoutVAT
(идёт в смету, ≠ рыночная) + склад + перевозка. Все парсеры сведены в gge_deep
(parse_ka перенесён из build-скрипта), убраны дубли хелперов. Добавлены юнит-тесты
парсеров (tests/test_gge_deep.py, 4/4). verify_corpus exit 0, обезличивание чисто
(email/телефон/ИНН = 0).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 01:20:59 +10:00

174 lines
8.6 KiB
Python
Raw 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.
"""Юнит-тесты парсеров gge_deep на синтетических фикстурах (без SSD/сети).
Запуск: python3 tests/test_gge_deep.py (или pytest tests/test_gge_deep.py)
Каждая фикстура — минимальный, но представительный XML каждой схемы .gge
с заранее известными значениями; проверяем, что парсер извлекает их точно.
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from gge_deep import parse_estimate_full, parse_vor, parse_ka, scrub # noqa: E402
LSR_XML = """<?xml version="1.0" encoding="UTF-8"?>
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="LocalEstimateResourceIndexMethod-3_01.xsd">
<Object><Estimate>
<Num>ЛСР-06-07-0-06-01</Num>
<Region><RegionName>Тверская область</RegionName></Region>
<PriceLevelBase><Year>2022</Year><Quarter>1</Quarter></PriceLevelBase>
<PriceLevelCur><Year>2025</Year><Quarter>2</Quarter></PriceLevelCur>
<Sections><Section><Items>
<Item>
<Cost>
<Code>01-01-030-05</Code><Prefix>ГЭСН</Prefix>
<Name>Разработка грунта бульдозерами</Name>
<Unit>1000 м3</Unit><QuantityTotal>6.751</QuantityTotal>
<Comment>(тестовый комментарий)</Comment>
<PerUnit><LaborCosts>0</LaborCosts><MachinistLaborCosts>5.5</MachinistLaborCosts></PerUnit>
<ResourcesInternal>
<Machine>
<Code>91.01.01-035</Code><Name>Бульдозеры 79 кВт</Name>
<Consumption>5.5</Consumption><Unit>маш.-ч</Unit>
<PricePerUnitBase>900</PricePerUnitBase><PricePerUnitCur>1224.81</PricePerUnitCur>
<Index><Reason>1030</Reason><Value><IndexValue>1.38</IndexValue></Value></Index>
<Machinist><Grade>6</Grade><Consumption>5.5</Consumption><PricePerUnitCur>541.85</PricePerUnitCur></Machinist>
</Machine>
</ResourcesInternal>
<Totals><Current><Direct>65596.97</Direct><Machines>45477.81</Machines>
<Materials>0</Materials><Salary>20119.16</Salary>
<MachinistSalary>20119.16</MachinistSalary><WorkersSalary>0</WorkersSalary></Current></Totals>
</Cost>
<Overheads><Value>92</Value><Target>ФОТ</Target><Reason>Пр/812-001.1-1</Reason><PriceCur>18509</PriceCur></Overheads>
<Profits><Value>46</Value><Target>ФОТ</Target><Reason>Пр/774-001.1</Reason></Profits>
</Item>
<Item><Material>
<Code>ФСБЦ-02</Code><Name>Песок природный</Name><Unit>м3</Unit>
<ConsumptionTotal>10</ConsumptionTotal><PricePerUnitCur>808.24</PricePerUnitCur>
<IsReturnMat>false</IsReturnMat>
</Material></Item>
<Item><Transport>
<Code>04-1</Code><Name>Погрузка в автотранспорт</Name><Unit>т</Unit>
<QuantityTotal>5.63</QuantityTotal><PricePerUnitCur>267.49</PricePerUnitCur>
</Transport></Item>
</Items></Section></Sections>
</Estimate></Object>
</Construction>"""
VOR_XML = """<?xml version="1.0" encoding="UTF-8"?>
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="QuantityTakeoff-3_01.xsd">
<Num>960-06-1356-ПОС9.2.ВОР17</Num><Reason>Раздел 5</Reason>
<Sections><Section><Name>Открытая прокладка (Московская область)</Name>
<Works><Work>
<Name>Снятие почвенно-растительного слоя</Name><Unit>м3</Unit>
<Quantity>147.3</Quantity><QuantityFormula>147.3*1</QuantityFormula>
<Links><Link><PageDescription>960-06-1356-ПОС9.2-ГЧ.3</PageDescription><PageNumber>173</PageNumber></Link></Links>
</Work></Works>
</Section></Sections>
</Construction>"""
KA_XML = """<?xml version="1.0" encoding="UTF-8"?>
<Construction xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="MarketAnalysis-3_01.xsd">
<ObjectName>Создание высокоскоростной магистрали</ObjectName>
<Items><Item>
<Name>Распашные ворота 4000x2500</Name><Unit>шт</Unit><Type>оборудование</Type>
<Offer>
<OfferCompany><CompanyName>ООО Ромашка</CompanyName><INN>9722010798</INN></OfferCompany>
<OfferPrice><OfferUnitWithoutVAT>90000</OfferUnitWithoutVAT>
<EstimateWithoutVAT>94554</EstimateWithoutVAT><OfferWithVAT>108000</OfferWithVAT>
<DeliveryTerms>без учета перевозки</DeliveryTerms></OfferPrice>
<Storage><Price>1854</Price></Storage><Transportation><Price>2700</Price></Transportation>
<Region><Name>г. Москва</Name></Region>
<OfferDate><Year>2024</Year><Quarter>4</Quarter></OfferDate>
<OriginCountry>РФ</OriginCountry><Winner>true</Winner>
</Offer>
</Item></Items>
</Construction>"""
def _write(tmp, name, xml):
p = tmp / name
p.write_text(xml, encoding="utf-8")
return p
def test_parse_estimate_full(tmp_path):
d = parse_estimate_full(_write(tmp_path, "lsr.gge", LSR_XML))
assert d["code"] == "ЛСР-06-07-0-06-01"
assert d["region"] == "Тверская область"
assert d["price_base"] == "2022 Q1" and d["price_cur"] == "2025 Q2"
pos = [p for p in d["positions"] if p["kind"] == "cost"]
assert len(pos) == 1
p = pos[0]
assert p["code"] == "01-01-030-05" and p["prefix"] == "ГЭСН"
assert p["comment"] == "(тестовый комментарий)"
assert p["machinist_ch"] == 5.5
assert round(p["unit_cost_cur"], 2) == round(65596.97 / 6.751, 2)
assert p["cost_structure"]["machines"] == 45477.81
assert p["cost_structure"]["salary"] == 20119.16
assert p["overhead"] == {"value": "92", "target": "ФОТ",
"reason": "Пр/812-001.1-1", "price_cur": 18509.0}
assert p["profit"]["value"] == "46"
m = p["resources"]["machines"][0]
assert m["code"] == "91.01.01-035" and m["price_cur"] == 1224.81
assert m["index"] == {"value": 1.38, "reason": "1030"}
assert m["machinist"] == {"consumption": 5.5, "price_cur": 541.85, "grade": "6"}
# прямой материал + Transport
assert d["direct_materials"][0]["name"] == "Песок природный"
assert d["direct_materials"][0]["is_return"] is False
tr = [p for p in d["positions"] if p["kind"] == "transport"][0]
assert tr["unit_cost_cur"] == 267.49 # фикс: цена из PricePerUnitCur, не 0
def test_parse_vor(tmp_path):
d = parse_vor(_write(tmp_path, "vor.gge", VOR_XML))
assert d["num"] == "960-06-1356-ПОС9.2.ВОР17" # raw, обезличивание в индексаторе
assert len(d["works"]) == 1
w = d["works"][0]
assert w["name"] == "Снятие почвенно-растительного слоя"
assert w["unit"] == "м3" and w["quantity"] == 147.3
assert w["formula"] == "147.3*1"
assert "ПОС9.2-ГЧ.3" in w["source"] and "л.173" in w["source"]
def test_parse_ka(tmp_path):
items = parse_ka(KA_XML.encode("utf-8"))
assert len(items) == 1
it = items[0]
assert it["name"] == "Распашные ворота 4000x2500" and it["type"] == "оборудование"
o = it["offers"][0]
assert o["vendor"] == "Поставщик 1" # обезличено уже в парсере
assert o["market_price"] == 90000.0
assert o["estimate_price"] == 94554.0 # сметная цена — ключевое
assert o["storage"] == 1854.0 and o["transport"] == 2700.0
assert o["winner"] is True
# реквизиты поставщика НЕ протекают в оффер
blob = str(o)
assert "Ромашка" not in blob and "9722010798" not in blob
def test_scrub():
assert scrub("960-06-1356-СМ3.8.1") == "[…]"
assert scrub("Кабель 960-06-ТКР34") == "Кабель […]"
assert scrub("Опора на ПК5555+94 моста") == "Опора на […] моста"
assert scrub("ст. Новая Тверь ВСМ") == "ст. […] […]"
# бренды товаров и регион поставщика НЕ трогаем
assert scrub("Лоток ЭНЕРГОТЭК ПК-3 100x100") == "Лоток ЭНЕРГОТЭК ПК-3 100x100"
assert scrub("Поставщик из Санкт-Петербурга") == "Поставщик из Санкт-Петербурга"
if __name__ == "__main__":
import tempfile
passed = 0
for fn in (test_parse_estimate_full, test_parse_vor, test_parse_ka):
with tempfile.TemporaryDirectory() as td:
fn(Path(td))
passed += 1
print(f"OK {fn.__name__}")
test_scrub()
passed += 1
print(f"OK test_scrub")
print(f"\n{passed}/4 тестов прошли")