Files
smeta-web/tests/test_build_xlsx.py
T
anorandClaude Opus 4.8 9b153518ae feat: разборщик реальных Excel-смет в staging-корпус (#6)
build_xlsx_staging.py: код-якорь + эвристика по строке (раскладки 10/19/27 колонок),
обезличивание через corpus_anon (техполя + scrub + канарейка→карантин), ценовой гейт
5x медианы, dedup по sha1+составу. Цена null где нет в строке (не выдумываем).
build_ext_index.py: staging_xlsx подключён в ext-индекс (живой не трогаем).
tests/test_build_xlsx.py: 3 раскладки + утечка→карантин, red-green.
Прогон на 18 реальных: 7 смет, 206 расценок, 0 утечек, 0 ценовых выбросов.

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

164 lines
7.3 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.
"""Тест build_xlsx_staging на синтетических xlsx трёх реальных раскладок.
RED-GREEN: ассерты выведены из семантики строк (код/ед./объём/цена), а не из
фактического выхода парсера — сломай CODE_RE/эвристику qty, и тесты упадут
(проверено мутацией: CODE_RE -> ^$ валит test_layouts, отключение leak-гейта
валит test_leak_quarantined).
Раскладки повторяют реальные образцы:
10-кол. (самодельная): №@0, код@1, наим@2, ед@3, объём@4, ПЗ@5, НР@6, СП@7,
цена@8, сумма@9; цена×объём = сумма.
19-кол.: код@1, наим@2, ед@3, объём@4, цены@5..13 (ПЗ/ед × объём = ПЗ), прим@14.
27-кол. (ГРАНД): шапка ~20 строк метаданных (НЕ извлекать — там утечки),
код@2 «ГЭСН …», наим@7, ед@13, объём@19, сумма@26.
"""
import os
import sys
from pathlib import Path
import openpyxl
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from scripts.build_xlsx_staging import Builder, _struct_leaks # noqa: E402
def _save(path, rows, ncols):
wb = openpyxl.Workbook()
ws = wb.active
for r, row in enumerate(rows, start=1):
for c, v in enumerate(row, start=1):
if v is not None:
ws.cell(row=r, column=c, value=v)
for c in range(len(row) + 1, ncols + 1):
ws.cell(row=r, column=c)
wb.save(path)
def _write_10col(path):
_save(path, [
["№", "Шифр", "Наименование", "Ед.", "Кол-во", "ПЗ", "НР", "СП", "Цена", "Сумма"],
[1, "04-01-006-03", "Роторное бурение скважины в грунтах группы 3",
"100 м", 0.2, 324807, 66628, 28285, 419720, 83944],
[2, "ФСБЦ-01.7.03.01-0001", "Вода (промывочная жидкость)",
"м³", 12.848, 22.85, None, None, 22.85, 293.58],
["ИТОГО", None, None, None, None, None, None, None, None, 84237.58],
], 10)
def _write_19col(path):
_save(path, [
["Поз.", "Шифр расценки", "Наименование работ и затрат", "Ед.", "Кол-во"],
["1а", "01-01-022-08",
"Разработка грунта с погрузкой на автосамосвалы в траншеях (экскаватор 0,65 м³)",
"1000 м³", 0.1546, 59713.49, 11220.97, 9231.71, 1734.76, 92,
1595.98, 46, 797.99, 11625.68, "Включает котлованы под колодцы"],
], 19)
def _write_27col(path):
head = [["Наименование субъекта Российской Федерации", None, "Еврейская АО"],
["ЛОКАЛЬНЫЙ СМЕТНЫЙ РАСЧЕТ (СМЕТА) № ЛСР-06-01-К2.2"],
["№ п/п", "Обоснование", None, None, None, None, None,
"Наименование работ и затрат"]]
pos = [None] * 27
pos[0], pos[2] = "1", "ГЭСН 01-01-010-27"
pos[7] = "Разработка грунта (III группа) одноковшовым экскаватором"
pos[13], pos[19], pos[26] = "тыс.м³", 0.069713, 7886.46
_save(path, head + [pos], 27)
def _write_leak(path):
_save(path, [
["№", "Шифр", "Наименование", "Ед.", "Кол-во", "ПЗ", "НР", "СП", "Цена", "Сумма"],
[1, "08-01-003-07", "Гидроизоляция колодцев на объекте ст. Николаевка обмазочная",
"100 м²", 0.48, None, None, None, 10600.88, 5088.42],
[2, "23-01-001-01", "Устройство основания под трубопроводы: песчаного",
"10 м³", 4.678, None, None, None, 4170.16, 19508.01],
], 10)
@pytest.fixture()
def staged(tmp_path):
b = Builder()
for name, writer in (("f10.xlsx", _write_10col), ("f19.xlsx", _write_19col),
("f27.xlsx", _write_27col), ("leak.xlsx", _write_leak)):
writer(tmp_path / name)
b.feed(tmp_path / name)
return b, b.finalize()
def _by_code(result):
return {it["code"]: it for it in result["items"]}
def test_layouts_extracted(staged):
_, result = staged
items = _by_code(result)
it10 = items["04-01-006-03"]
assert it10["unit"] == "100 м"
assert it10["qty"]["median"] == 0.2
assert it10["unit_cost_cur"] == 419720 # цена/ед: 419720 × 0,2 = 83944 (сумма)
assert it10["examples"][0]["total"] == 83944
mat = items["01.7.03.01-0001"]
assert mat["norm_base"] == "ФСБЦ"
assert mat["unit"] == "м³"
assert mat["qty"]["median"] == 12.848
assert mat["unit_cost_cur"] == 22.85
it19 = items["01-01-022-08"]
assert it19["unit"] == "1000 м³"
assert it19["qty"]["median"] == 0.1546
assert it19["unit_cost_cur"] == 59713.49 # ПЗ/ед: 59713,49 × 0,1546 = ПЗ 9231,71
assert "Разработка грунта" in it19["name"]
it27 = items["01-01-010-27"]
assert it27["norm_base"] == "ГЭСН"
assert it27["unit"] == "тыс.м³"
# qty в агрегате округлён до 4 знаков (как в arp-эталоне), сырой — в examples
assert it27["qty"]["median"] == pytest.approx(0.069713, abs=5e-5)
assert it27["examples"][0]["qty"] == 0.069713
# в строке только сумма → цена/ед = сумма/объём
assert it27["unit_cost_cur"] == pytest.approx(7886.46 / 0.069713, rel=1e-3)
# шапка с «Еврейская АО» не извлечена ни в один item
assert not any("Еврейская" in it["name"] for it in result["items"])
def test_leak_quarantined(staged):
b, result = staged
items = _by_code(result)
# позиция с топонимом («ст. Николаевка») — в карантине, не в staging
assert "08-01-003-07" not in items
assert b.quarantine_counts["leak"] == 1
assert any(e["reason"] == "leak" and "Николаевка" in e["detail"]
for e in b.quarantine_log)
# чистая позиция из ТОГО ЖЕ файла осталась в staging (карантин попозиционный)
assert "23-01-001-01" in items
assert b.meta["positions_quarantined"] == 1
def test_no_leaks_in_items(staged):
_, result = staged
assert result["items"]
for it in result["items"]:
assert not _struct_leaks(it), f"утечка в item {it['code']}"
def test_duplicate_file_skipped(staged, tmp_path):
b, _ = staged
_write_10col(tmp_path / "f10_copy.xlsx") # тот же состав → дубль по fingerprint
before = b.meta["positions_total"]
b.feed(tmp_path / "f10_copy.xlsx")
assert b.meta["duplicates"] == 1
assert b.meta["positions_total"] == before
def test_empty_file_quarantined(tmp_path):
b = Builder()
_save(tmp_path / "empty.xlsx", [["Сопоставление карьеров", "без кодов расценок"]], 5)
b.feed(tmp_path / "empty.xlsx")
assert b.quarantine_counts["parse_error_or_empty"] == 1
assert not b.occ