Files
anorandClaude Opus 4.8 13cb936c5c feat: расширение корпуса — .gge(ДВ)/.gsfx/.arp(ОСНБЖ) в ext-индекс (#2-#5)
Три глубоких парсера (Fable): merge_gge (РИМ .gge регион ДВ/цены 2025), gsfx_deep (ресурсы+
состав работ+НР/СП+источник цены из 555 .gsfx), arp_deep (ОСНБЖ ж/д: Кнр/Ксп/Кизв+ресурсы,
объём f26 численно верифицирован, сверка с парной .xls). Анти-отравление: каждая запись несёт
norm_base+price_level, БИМ-сметы 2001 и ценовые выбросы 5× → карантин, обезличено corpus_anon
(0 утечек). Сведено в ОТДЕЛЬНЫЙ estimates_ext_index.json (1891 расценка+1703 мат+1114 КА) —
живой ВСЖМ-индекс не тронут; _load_estimates/_load_ka грузят оба; find_in_real_estimates отдаёт
norm_base/price_level; _search_corpus предупреждает «не смешивай базы/уровни цен».
Попутно: gge_deep KA-регион fallback, corpus_anon +паттерн ИНН в underscore. Все тесты (юнит
mutation-safe + real-data) зелёные, регресс ВСЖМ цел. APP_VERSION→2026-07-16a.

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

200 lines
10 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.
"""Юнит-тесты парсеров 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>
<Coefficients>
<Coefficient><Name>Стесненные условия</Name><Reason>421/пр_2022_прил.10</Reason>
<Values><Value><CoefValue>1.15</CoefValue><Target>ОТ</Target></Value></Values></Coefficient>
</Coefficients>
<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>
<Coefficients>
<Coefficient><Reason>571/пр_2022_п.83_т.2</Reason>
<Values><Value><CoefValue>0.7</CoefValue><Target>Расход</Target></Value></Values></Coefficient>
<Final><Values><Value><CoefValue>0.7</CoefValue><Target>Расход</Target></Value></Values></Final>
</Coefficients>
<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"
# позиционный коэффициент с Target
assert p["coefficients"][0] == {"name": "Стесненные условия",
"reason": "421/пр_2022_прил.10",
"value": "1.15", "target": "ОТ"}
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"]["grade"] == "6"
# коэф НА РЕСУРС: норма 5.5 базовая, эффективная = 5.5 × 0.7 (демонтаж 571/пр)
assert m["coef"] == {"factors": {"Расход": 0.7}, "reason": "571/пр_2022_п.83_т.2"}
assert round(m["consumption"] * m["coef"]["factors"]["Расход"], 3) == 3.85
# прямой материал + 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_parse_ka_regionname_fallback():
# КА ДВ-корпуса 2025: регион оффера лежит в Region/RegionName, не Region/Name
xml = KA_XML.replace("<Region><Name>г. Москва</Name></Region>",
"<Region><RegionCode>77</RegionCode>"
"<RegionName>г. Москва</RegionName></Region>")
items = parse_ka(xml.encode("utf-8"))
assert items[0]["offers"][0]["region"] == "г. Москва"
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__}")
for fn in (test_parse_ka_regionname_fallback, test_scrub):
fn()
passed += 1
print(f"OK {fn.__name__}")
print(f"\n{passed}/5 тестов прошли")