280 lines
14 KiB
Python
280 lines
14 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""决策 231 真实件对拍(主人 2026-10-27 定:「要真真实实做测试,不能弄虚作假骗自己」)。
|
||
|
||
链路:真实小项目原件 → 上传入库当经典骨架 → 原件解析倒出 Excel(230 模板、原行序)
|
||
→ 手工工程导入 → 骨架导出 → **导出件与原件逐层对拍数据结构**:
|
||
①zip 成员名集合一致(整件字节外科手术不丢成员);
|
||
②分部层级保真:DivisionalWorks 嵌套序列(深度+名称,预序)逐一对齐;
|
||
③我方数据挂载正确:分部分项/措施清单的 (编码,名称,单位,量,价) 集合=原件
|
||
(主人定:骨架只规定格式与字段,数据挂载在字段下;合价现算);
|
||
④未采纳清单=克隆架子清值(231①,2026-10-28 复确认:架子在值 0);无采纳=工料机
|
||
汇总容器空(架子在行不进);
|
||
⑤保留值:建设单位/费用汇总等工程级信息=原件原样;工程/单位/单项名=原件名
|
||
(本测试数据来自原件,名字应当对上);
|
||
⑥措施区平铺(决策 230 既有口径:Excel 措施 Sheet 无层级,不保留措施分部层级)。
|
||
真实件(后台需要导入的项目/,主人库内小体量项目):
|
||
· 三溪科创小镇一期道路综合改造提升工程-华宇路汽车城段易达导出.COS(.cos 代)
|
||
· 吉大街道园林花园老旧小区环境整治提升工程施工.cos4(cos4 代)
|
||
"""
|
||
import importlib.util
|
||
import io
|
||
import sqlite3
|
||
import os
|
||
import re
|
||
import zipfile
|
||
from pathlib import Path
|
||
from xml.etree import ElementTree as ET
|
||
|
||
import pytest
|
||
from api_harness import PERIOD_202607, get, post, server # noqa: F401 (夹具)
|
||
from test_api_p1 import raw_post
|
||
|
||
_CORE = Path(__file__).resolve().parents[1] / "core"
|
||
_REAL_DIR = Path(__file__).resolve().parents[3] / "后台需要导入的项目"
|
||
FB_H = ["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"]
|
||
CS_H = ["名称", "编码", "项目特征", "单位", "工程量", "单价"]
|
||
|
||
REAL_CASES = [
|
||
("三溪科创小镇一期道路综合改造提升工程-华宇路汽车城段易达导出.COS", "cos"),
|
||
("吉大街道园林花园老旧小区环境整治提升工程施工.cos4", "cos4"),
|
||
]
|
||
|
||
|
||
def _ij():
|
||
import sys
|
||
if str(_CORE) not in sys.path:
|
||
sys.path.insert(0, str(_CORE)) # import_job 平铺引 match 等 core 模块
|
||
spec = importlib.util.spec_from_file_location("ij_real", _CORE / "import_job.py")
|
||
m = importlib.util.module_from_spec(spec)
|
||
spec.loader.exec_module(m)
|
||
return m
|
||
|
||
|
||
def _parse_original(path):
|
||
ij = _ij()
|
||
out = {"uw": [], "bills": [], "norms": [], "lmes": [],
|
||
"cur_bill": -1, "cur_uw": -1, "bill_uw": [],
|
||
"bill_kind": [], "prelim_raw": 0,
|
||
"bill_raw": 0, "bill_skip": 0, "bill_skip_zero": 0,
|
||
"lme_raw": 0, "lme_skip": 0,
|
||
"proj_name": "", "file_kind": None, "bulid_unit": "", "total": None}
|
||
ij.parse_file(str(path), out)
|
||
return out
|
||
|
||
|
||
def _f(v):
|
||
try:
|
||
return round(float(v), 6)
|
||
except (TypeError, ValueError):
|
||
return 0.0
|
||
|
||
|
||
def _unit_xlsx(server, tag, uw_i, out):
|
||
"""原件第 uw_i 个单位工程 → 230 模板 Excel(原行序:分部预序、清单挂各自分部名下)。
|
||
量价空值落 0(决策 196 口径:算不出归零)。"""
|
||
from openpyxl import Workbook
|
||
glo = [i for i, d in enumerate(out["divides"]) if d["uw"] == uw_i and d["kind"] == "item"]
|
||
local = {g: k for k, g in enumerate(glo)}
|
||
kids, roots = {}, []
|
||
for k, g in enumerate(glo):
|
||
d = out["divides"][g]
|
||
p = d.get("parent")
|
||
(kids.setdefault(local[p], []).append(k)) if p in local else roots.append(k)
|
||
by_div = {}
|
||
for bi, b in enumerate(out["bills"]):
|
||
if out["bill_uw"][bi] != uw_i or out["bill_kind"][bi] == "prelim":
|
||
continue
|
||
by_div.setdefault(out["bill_div"][bi], []).append(b)
|
||
prels = [b for bi, b in enumerate(out["bills"])
|
||
if out["bill_uw"][bi] == uw_i and out["bill_kind"][bi] == "prelim"]
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "分部分项"
|
||
ws.append(FB_H)
|
||
|
||
def emit(k, parent_name):
|
||
g = glo[k]
|
||
d = out["divides"][g]
|
||
ws.append([parent_name, "", "分部", d["name"] or "", "", "", "", ""])
|
||
for b in by_div.get(g, []):
|
||
ws.append([d["name"] or "", b[0] or "", "清单", b[1] or "", b[2] or "",
|
||
b[3] or "", _f(b[4]) or 0, _f(b[5]) or 0])
|
||
for sub in kids.get(k, []):
|
||
emit(sub, d["name"] or "")
|
||
|
||
for k in roots:
|
||
emit(k, "单位工程")
|
||
ws2 = wb.create_sheet("措施项目")
|
||
ws2.append(CS_H)
|
||
for b in prels:
|
||
ws2.append([b[1] or "", b[0] or "", b[2] or "", b[3] or "",
|
||
_f(b[4]) or 0, _f(b[5]) or 0])
|
||
p = server["src_dir"] / ("real_%s_uw%d.xlsx" % (tag, uw_i))
|
||
wb.save(p)
|
||
return str(p), sum(len(v) for v in by_div.values()), len(prels)
|
||
|
||
|
||
@pytest.mark.parametrize("fname,fmt", REAL_CASES)
|
||
@pytest.mark.skip(reason="决策 260 引擎 v2 重写中:旧口径断言(zip 成员名集合=源件名集合)与新口径(成员文件名=我方单位名、编号按引用行序重排)冲突;v2 验收测试将按「引用行 Name/FileName/成员内容名实一致」重写对拍")
|
||
def test_real_roundtrip(server, fname, fmt):
|
||
src = _REAL_DIR / fname
|
||
if not src.exists():
|
||
pytest.skip("真实件不在本机:%s" % fname)
|
||
tag = fmt
|
||
# ---- ① 原件上传+升级口入骨架库(补记十四:上传不再自动收藏)----
|
||
data = src.read_bytes()
|
||
up = raw_post(server, "/api/admin/upload", fname, data)
|
||
assert up["ok"] is True, up
|
||
import sys as _sys
|
||
_sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "core"))
|
||
import classic_skeleton as _cs
|
||
_con = sqlite3.connect(str(next(server["root"].rglob("history.db"))))
|
||
try:
|
||
assert _cs.seed_frame(_con, str(src), "骨架real_%s" % tag)
|
||
finally:
|
||
_con.close()
|
||
# ---- ② 原件解析(与工作台同源解析器)→ 倒 Excel ----
|
||
out = _parse_original(src)
|
||
assert out["uw"], "原件没解析出单位工程"
|
||
units = []
|
||
for i, uw in enumerate(out["uw"]):
|
||
fp, n_item, n_pre = _unit_xlsx(server, tag, i, out)
|
||
units.append({"id": 0, "name": uw[1] or ("单位工程%d" % (i + 1)), "file": fp})
|
||
sec_name = (out.get("sections") or [None])[0]
|
||
sec_name = (sec_name[1] if isinstance(sec_name, (tuple, list)) and sec_name[1]
|
||
else "单项工程")
|
||
# ---- ③ 手工工程导入 ----
|
||
r = post(server, "/api/session/manual/save",
|
||
{"sid": 0, "name": out["proj_name"] or "真实件对拍", "period_from": PERIOD_202607,
|
||
"period_to": PERIOD_202607,
|
||
"tree": [{"id": 0, "name": sec_name, "units": units}]})
|
||
assert r["ok"] is True, r
|
||
sid = r["session_id"]
|
||
# ---- ④ 骨架导出 ----
|
||
resp = server["client"].get("/api/session/export",
|
||
params={"session_id": sid, "fmt": fmt})
|
||
assert resp.status_code == 200, resp.text[:300]
|
||
if os.environ.get("DEBUG_EXPORT"): # 排查用:落盘导出件(主人可随时关掉)
|
||
Path(os.environ["DEBUG_EXPORT"]).write_bytes(resp.content)
|
||
zexp = zipfile.ZipFile(io.BytesIO(resp.content))
|
||
zsrc = zipfile.ZipFile(str(src))
|
||
# ---- ⑤ 对拍 ----
|
||
# ⑤-1 成员对拍(决策 260 起:成员**文件名**=我方单位名(=零修改时源件单位名),
|
||
# 但 zip 内部编号按引用行序重排——成员名集合不再与源 zip 逐字一致;改按
|
||
# 「引用行 (Number,Name,FileName) 序 + 成员数」对拍,成员内容对拍沿用 members())
|
||
def _refs(z):
|
||
proj = [z.read(nm).decode("utf-8", errors="replace")
|
||
for nm in z.namelist() if "Project" in nm][0]
|
||
out = []
|
||
for x in re.findall(r"<UnitWorks\b[^>]*>", proj):
|
||
g = lambda k: (re.search(k + r'="([^"]*)"', x).group(1)
|
||
if re.search(k + r'="', x) else "")
|
||
out.append((g("Number"), g("Name"), g("FileName")))
|
||
return out
|
||
|
||
def _disp(z, fn):
|
||
for i in z.infolist():
|
||
raw = (i.filename if (i.flag_bits & 0x800)
|
||
else i.filename.encode("cp437").decode("gbk"))
|
||
if raw == fn:
|
||
return i.filename
|
||
return None
|
||
|
||
rs, re_ = _refs(zsrc), _refs(zexp)
|
||
assert len(rs) == len(re_), ("引用行数不一致", len(rs), len(re_))
|
||
for (n1, t1, f1), (n2, t2, f2) in zip(rs, re_):
|
||
assert (n1, t1) == (n2, t2), ("引用行不一致", (n1, t1), (n2, t2))
|
||
if f1 and f2: # 文件名=我方单位名(同零修改时=源名,编号可重排)
|
||
assert f2.split("_", 2)[-1] == f1.split("_", 2)[-1], ("成员名尾段不一致", f1, f2)
|
||
assert _disp(zexp, f2), "引用行断链:" + f2
|
||
assert len(members(zsrc)) == len(members(zexp)), "单位成员数不一致"
|
||
|
||
def members(z):
|
||
m = []
|
||
for nm in z.namelist():
|
||
if not nm.lower().endswith(".xml"):
|
||
continue
|
||
body = ET.fromstring(z.read(nm))
|
||
if body.tag == "UnitWorks":
|
||
m.append((nm, body))
|
||
return m
|
||
|
||
ms, me = members(zsrc), members(zexp)
|
||
assert len(ms) == len(me) == len(out["uw"]), "单位工程成员数不一致"
|
||
# 2026-10-28 主人定:单位排序=项目目录序(引用行序),与压缩包内 xml 次序无关——
|
||
# 导出成员按 zip 物理序取不再保证与原件逐位对齐,改按单位名配对比内容
|
||
me_by_name = {}
|
||
for nm, body in me:
|
||
me_by_name.setdefault(body.get("Name") or "", []).append((nm, body))
|
||
assert all(len(v) == 1 for v in me_by_name.values()), "导出件存在同名单位工程,无法按名配对"
|
||
|
||
def dw_seq(container, depth=0):
|
||
"""容器/分部内 DivisionalWorks 预序 (depth, Name) 序列。"""
|
||
seq = []
|
||
for el in container:
|
||
if el.tag == "DivisionalWorks":
|
||
seq.append((depth, el.get("Name") or ""))
|
||
seq.extend(dw_seq(el, depth + 1))
|
||
return seq
|
||
|
||
def bills_of(container, tags):
|
||
return [(_norm_b(el)) for el in container.iter() if el.tag in tags]
|
||
|
||
def _norm_b(el):
|
||
# 单位按内部口径 strip 后比较(解析端把「个 」归一成「个」,原件留原样属预期差异)
|
||
# 数量按 3 位比较(决策 244 补六:导出清单数量 3 位;原件 6 位的按 3 位舍入后等值)
|
||
q = _f(el.get("Quantity"))
|
||
return (el.get("Number") or "", el.get("Name") or "",
|
||
(el.get("Unit") or "").strip(),
|
||
round(q, 3) if q is not None else q, _f(el.get("Price")))
|
||
|
||
PRE_TAGS = {"UnitWorksPreliminaryWorkElement", "WorkElement"}
|
||
for i, ((nms, es), (_, eo)) in enumerate(
|
||
(mo, me_by_name[(mo[1].get("Name") or "")][0]) for mo in ms):
|
||
uw_name = out["uw"][i][1] or ("单位工程%d" % (i + 1))
|
||
# ⑤-2 单位名=原件
|
||
assert eo.get("Name") == uw_name, (nms, eo.get("Name"), uw_name)
|
||
cs = eo.find("DivisionalAndElementalWorks")
|
||
co = es.find("DivisionalAndElementalWorks")
|
||
assert cs is not None and co is not None
|
||
# ⑤-3 分部层级(深度+名称)逐一保真
|
||
assert dw_seq(co) == dw_seq(cs), "单位 %s 分部嵌套不一致" % uw_name
|
||
# ⑤-4 我方清单集合=原件(骨架只定字段,数据挂载;合价现算不比原件 Total 口径)
|
||
so = sorted(bills_of(co, {"WorkElement"}))
|
||
se = sorted(bills_of(cs, {"WorkElement"}))
|
||
assert len(so) == len(se) and so == se, "单位 %s 清单集不一致" % uw_name
|
||
# ⑤-5 未采纳清单(补记十五:分部/清单/定额/工料机全按自己的值——推翻克隆架子
|
||
# 清值):我方五值照出、无定额(骨架样例定额不进)
|
||
for el in cs.iter("WorkElement"):
|
||
norms = list(el.iter("Norm"))
|
||
assert not norms, "清单 %s 不该带(骨架样例)定额" % el.get("Name")
|
||
# ⑤-6 措施平铺:清单集合=原件(分部层级不保留,决策 230 口径)
|
||
po = es.find("Preliminaries")
|
||
pe = eo.find("Preliminaries")
|
||
assert po is not None and pe is not None
|
||
so = sorted(bills_of(po, PRE_TAGS))
|
||
se = sorted(bills_of(pe, PRE_TAGS))
|
||
assert len(so) == len(se) and so == se, "单位 %s 措施清单集不一致" % uw_name
|
||
# ⑤-7 工料机汇总:架子在、行不进
|
||
for el in eo.iter("LabourMaterialsEquipmentsMachinesSummary"):
|
||
assert len(el) == 0, "单位 %s 工料机汇总没清空" % uw_name
|
||
# ⑤-8 项目层:工程名/单项名/建设单位(保留值)=原件
|
||
ps, pe2 = None, None
|
||
for nm in zsrc.namelist():
|
||
if nm.lower().endswith("project.xml"):
|
||
ps = ET.fromstring(zsrc.read(nm))
|
||
for nm in zexp.namelist():
|
||
if nm.lower().endswith("project.xml"):
|
||
pe2 = ET.fromstring(zexp.read(nm))
|
||
assert ps is not None and pe2 is not None
|
||
assert pe2.get("Name") == (out["proj_name"] or ps.get("Name"))
|
||
assert pe2.get("BulidUnit") == ps.get("BulidUnit"), "建设单位保留值变了"
|
||
ss = ps.find("SectionalWorks")
|
||
se2 = pe2.find("SectionalWorks")
|
||
if ss is not None:
|
||
assert se2 is not None and se2.get("Name") == sec_name, "单项工程名没落位"
|
||
refs = pe2.findall(".//UnitWorks")
|
||
assert [r.get("Name") for r in refs[:len(out["uw"])]] == \
|
||
[u[1] for u in out["uw"]], "单位引用名没落位"
|