# -*- coding: utf-8 -*- """导出后缀口径(2026-11-03 决策 264 补记:骨架回灌单一通路后重写)。 旧引擎 export_cos.export_zip 已拆除;后缀不再由旧引擎从源文件名猜—— ①骨架挑选按内容/后缀(classic_skeleton.suffix_of 支持任意后缀); ②导出文件名后缀跟导出格式走(export_v2.out_name)。 """ import hashlib import io import os import sqlite3 import sys import uuid import zipfile from xml.etree import ElementTree as ET sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "core"))) import api_harness as H # noqa: E402 import classic_skeleton as cs # noqa: E402 import export_v2 as ev # noqa: E402 from api_harness import get, post, server # noqa: F401,E402 (夹具须经导入注册) def test_suffix_of_any_ext(): cases = { "工程-招标控制价.cos4": "cos4", "工程-招标控制价.COS4": "cos4", "工程-招标控制价.cos": "cos", "工程-招标控制价.COS": "cos", "工程-招标控制价.swt": "swt", "工程-招标控制价.abc": "abc", # 未来新格式:能导入就按原格式出 "8d6675537cc1f5f55d4812d3695afac3604c75cbcc884574d48138a3f2e863fa": None, } for name, want in cases.items(): assert cs.suffix_of(name) == want, "%s → %s (期望 %s)" % (name, cs.suffix_of(name), want) def test_out_name_follows_suffix(): assert ev.out_name("后缀工程", "cos4") == "后缀工程-审核版.cos4" assert ev.out_name("后缀工程", "cos") == "后缀工程-审核版.cos" assert ev.out_name("", "abc") == "工程-审核版.abc" def test_blank_package_annotated(tmp_path): """骨架库导出「完全空骨架(原格式)+自增/固定标注」(2026-11-03 新增功能): 包内两个成员、值全空、每个结构位带规则注释、XML 可解析。""" src = H.make_cos4(str(tmp_path / "blank_src.cos4"), "骨架标注工程", [("B001", "清单甲", "1、x", "m3", 1, 100)], [("000001", "人工", "", "工日", "1", "1")]) # 给夹具补一条单价计算行(x_side 类固定子块的标注样本) buf = io.BytesIO() with zipfile.ZipFile(src) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo: for n in z.namelist(): d = z.read(n) if n.lower() != "project.xml": d = d.replace(b"", b'', 1) zo.writestr(n, d) src2 = tmp_path / "blank_src2.cos4" src2.write_bytes(buf.getvalue()) con = sqlite3.connect(str(tmp_path / "h.db")) con.row_factory = sqlite3.Row sig = cs.seed_frame(con, str(src2), "标注骨架") assert sig data, fn, err = ev.build_blank_package(con, sig) con.close() assert err is None and fn.endswith(".cos4") and data[:2] == b"PK" z = zipfile.ZipFile(io.BytesIO(data)) names = [i.filename for i in z.infolist()] assert "Project.xml" in names and len(names) == 2, names proj = z.read("Project.xml").decode("utf-8") unit = z.read([n for n in names if n != "Project.xml"][0]).decode("utf-8") ET.fromstring(proj) ET.fromstring(unit) assert "导出规则:自增区域" in unit assert "自增区域:至少 1 个" in unit assert "自增块:按数据块循环" in unit or "自增行:按数据行循环" in unit assert "固定" not in unit assert 'Number="B001"' not in unit and 'Number="B001"' not in proj # 完全空(不带数据) def test_rule_registry(): """结构位规则:区域下限 1(至少一个空壳)、行/块下限 0;全部自增,不再有「固定」。""" region = ET.fromstring('') assert ev.min_count("SummaryOfCost") == 1 assert "自增区域" in ev.rule_note(region) and "固定" not in ev.rule_note(region) leaf = ET.fromstring('') assert ev.min_count("AddiCost") == 0 assert "自增行" in ev.rule_note(leaf) block = ET.fromstring("") assert "自增块" in ev.rule_note(block) at = ET.fromstring('') assert "自增区域" in ev.rule_note(at) # 导出条数 = max(下限, 数据条数) assert ev.row_count("SummaryOfCost", 0) == 1 assert ev.row_count("AttrInfo", 0) == 1 assert ev.row_count("AddiCost", 0) == 0 assert ev.row_count("AddiCost", 3) == 3 def test_lme_summary_two_shapes(): """工料机汇总行两种形态(普通行 / 带台班组成的块行)各按自己的样板输出—— 不能只用一个样板:否则另一形态的列被丢掉(2026-11-03 主人实测)。""" import json as _json host = ET.fromstring( "" '' '' '' "" "") rows = [ ["A1", "普通行", "", "个", 1, 2, 10, 0, 10, None, None, None, None, _json.dumps({"ExtraA": "va"})], ["B1", "组合行", "", "台班", 7, 1, 20, 0, 20, None, None, None, None, _json.dumps({"ExtraB": "vb"})], ] ev._emit_sums(host, rows, {"B1": [("C1", 1.5)]}) sums = [c for c in host if c.tag == "LabourMaterialsEquipmentsMachinesSummary"] assert len(sums) == 2 by = {s.get("Number"): s for s in sums} assert by["A1"].get("ExtraA") == "va" and len(by["A1"]) == 0 assert by["B1"].get("ExtraB") == "vb" kids = [c for c in by["B1"] if c.tag == "LabourMaterialsEquipmentsMachinesElement"] assert len(kids) == 1 and kids[0].get("Number") == "C1" assert kids[0].get("Quantity") == "1.500000" # 两种形态在序列化上必须分开:普通行自闭合、组合行带闭合标签 import skeleton_engine as _se txt = _se.serialize(host, 0, " ", keep_values=True) line_a = next(ln for ln in txt.splitlines() if 'Number="A1"' in ln) line_b = next(ln for ln in txt.splitlines() if 'Number="B1"' in ln) assert line_a.rstrip().endswith("/>"), line_a assert line_b.rstrip().endswith(">"), line_b assert "" in txt def test_blankpkg_endpoint(server): """后台接口:/api/admin/frames/blankpkg/ 直接下载原格式空骨架(带标注)。""" p = H.make_cos4(str(server["src_dir"] / "blank_ep_raw.cos4"), "标注端点工程", [("B001", "清单甲", "1、x", "m3", 1, 100)], [("000001", "人工", "", "工日", "1", "1")]) con = sqlite3.connect(server["db"]) con.row_factory = sqlite3.Row try: sig = cs.seed_frame(con, p, "端点骨架") finally: con.close() assert sig r = server["client"].get("/api/admin/frames/blankpkg/%s" % sig) assert r.status_code == 200, r.text[:200] assert r.content[:2] == b"PK" z = zipfile.ZipFile(io.BytesIO(r.content)) assert "Project.xml" in z.namelist() for i in z.infolist(): # 成员名必须是 GBK 原始字节(不带 UTF-8 旗标) assert not (i.flag_bits & 0x800), i.filename if i.filename != "Project.xml": assert i.filename.encode("cp437").decode("gbk") == "@_1_单位工程.xml" unit = z.read([n for n in z.namelist() if n != "Project.xml"][0]).decode("utf-8") ET.fromstring(unit) assert "自增" in unit and "固定" not in unit assert "导出规则:自增区域" in unit def test_export_member_names_gbk(server): """导出件成员名=GBK 原始字节、与 Project.xml 的 FileName 对得上(2026-11-03 主人实测乱码回归): 易达/广联达原件都是 GBK 条目名且不带 UTF-8 旗标;写成 UTF-8+旗标会被对方按 GBK 解读成乱码。""" proj = "成员名工程-" + uuid.uuid4().hex[:6] p = H.make_cos4(str(server["src_dir"] / ("nm_%s_raw.cos4" % proj[-6:])), proj, [("B001", "清单甲", "1、x", "m3", 10, 100)], [("000001", "人工", "", "工日", "1", "1")]) raw = open(p, "rb").read() hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files", "%s_nm.cos4" % hashlib.sha256(raw).hexdigest()) with open(hp, "wb") as f: f.write(raw) assert post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))["ok"] audit = {"name": proj, "province": H.META["province"], "city": H.META["city"], "district": H.META["district"], "period_from": H.PERIOD_202607, "period_to": H.PERIOD_202607, "file_kind": 1} sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"] r = server["client"].get("/api/session/export", params={"session_id": sid}) assert r.headers["content-type"].startswith("application/zip"), r.text[:300] z = zipfile.ZipFile(io.BytesIO(r.content)) proj_xml = z.read("Project.xml").decode("utf-8") n = 0 for i in z.infolist(): if i.filename == "Project.xml": continue n += 1 assert not (i.flag_bits & 0x800), "成员名不能带 UTF-8 旗标:%r" % i.filename gbk = i.filename.encode("cp437").decode("gbk") assert gbk.endswith(".xml"), gbk assert 'FileName="%s"' % gbk in proj_xml, (gbk, proj_xml[:200]) assert n >= 1 def test_unit_side_rows_exported(server): """单位工程非数据层(SummaryOfCost/AddiCost、AttrInfo…)也是数据:导入采集、导出按数据行重建。 2026-11-03 主人定「AddiCost 也是自增行,代码务必匹配」回归。""" proj = "非数据层工程-" + uuid.uuid4().hex[:6] p = H.make_cos4(str(server["src_dir"] / ("side_%s_raw.cos4" % proj[-6:])), proj, [("B001", "清单甲", "1、x", "m3", 10, 100)], [("000001", "人工", "", "工日", "1", "1")]) # 给夹具补:SummaryOfCost 带 2 条 AddiCost;AttrInfo 一组两行;(项目级同款 2 条) buf = io.BytesIO() with zipfile.ZipFile(p) as z, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo: for n in z.namelist(): d = z.read(n) if n.lower() == "project.xml": t = d.decode("utf-8") t = t.replace( '', '' '' '') d = t.encode("utf-8") else: t = d.decode("utf-8") t = t.replace( '', '' '' '') t = t.replace( "", '' '' '') d = t.encode("utf-8") zo.writestr(n, d) src = server["src_dir"] / ("side_%s.cos4" % proj[-6:]) src.write_bytes(buf.getvalue()) raw = open(str(src), "rb").read() hp = os.path.join(str(server["root"]), "CostReview", "data", "source_files", "%s_side.cos4" % hashlib.sha256(raw).hexdigest()) with open(hp, "wb") as f: f.write(raw) assert post(server, "/api/admin/import", dict(H.META, path=hp, name=proj))["ok"] audit = {"name": proj, "province": H.META["province"], "city": H.META["city"], "district": H.META["district"], "period_from": H.PERIOD_202607, "period_to": H.PERIOD_202607, "file_kind": 1} sid = post(server, "/api/audit", dict(audit, path=H.twin_file(server, hp)))["session_id"] # 用独立骨架库(只放本件骨架)直接走 export_v2,避免并行用例的骨架库干扰 hpath = str(server["root"] / ("side_hist_%s.db" % proj[-6:])) hic = sqlite3.connect(hpath) hic.row_factory = sqlite3.Row try: assert cs.seed_frame(hic, hp, "非数据层骨架-" + proj[-6:]) sc = sqlite3.connect(server["sessdb"]) sc.row_factory = sqlite3.Row try: data, _fn, err = ev.export_v2(hic, sc, sid, "cos4", src_path=hp) finally: sc.close() finally: hic.close() assert err is None, err z = zipfile.ZipFile(io.BytesIO(data)) unit = z.read([n for n in z.namelist() if n != "Project.xml"][0]).decode("utf-8") assert unit.count("