335 lines
17 KiB
Python
335 lines
17 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""P0 接口测试夹具:把 app 源码拷进临时目录,随机端口起**真实服务子进程**。
|
||
|
||
为什么拷贝整个 app/:api_server / session_job 的库路径一律由 __file__ 推导
|
||
(<目录>/CostReview/data/history.db),把 app/ 原样拷到 tmp/CostReview/app 后,
|
||
同构目录自然指向临时库 —— 生产库(CostReview/data/*.db)零接触,也不用改任何被测代码。
|
||
|
||
门禁:副本没有 license_build_config.py(开发版路径),LICENSE_DATA_DIR 指到临时目录,
|
||
里面放 {"enforce": false} —— 与本地开发豁免同款,业务 API 全部放行。
|
||
"""
|
||
import os
|
||
import shutil
|
||
import socket
|
||
import subprocess
|
||
import sys
|
||
import time
|
||
import zipfile
|
||
from xml.sax.saxutils import quoteattr
|
||
|
||
import httpx
|
||
import pytest
|
||
|
||
_APP_SRC = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) # .../CostReview/app
|
||
# 期次月序号(batches.x_period_start_m 口径:年*12+月)
|
||
PERIOD_202607 = 2026 * 12 + 7
|
||
|
||
|
||
def _free_port():
|
||
s = socket.socket()
|
||
s.bind(("127.0.0.1", 0))
|
||
port = s.getsockname()[1]
|
||
s.close()
|
||
return port
|
||
|
||
|
||
# ------------------------------------------------------------------ 造数
|
||
def make_cos4(path, proj_name, bills, lmes=(), build_unit="测试建设单位",
|
||
proj_lmes=None, uw_lmes=None, zip_ts=None, uw_lme_attrs=None,
|
||
lme_rot=False, norm_extra=""):
|
||
"""构造最小可解析的 .cos4(zip 内 Project.xml + 单位工程 xml)。
|
||
|
||
bills: [(编码, 名称, 特征, 单位, 工程量, 单价)] —— 分部分项清单(自动配 1 条定额 + 定额消耗)
|
||
lmes: [(编码, 名称, 规格, 单位, 不含税价, 含税价)] —— 工料机(会进 lmes 与项目级汇总)
|
||
proj_lmes/uw_lmes: 分别覆盖项目级/单位级汇总的行(默认都用 lmes;
|
||
决策 108 测试用——造「仅项目工料机有」的场景)
|
||
uw_lme_attrs: {编码: ' Class="A" Weight="0"...'} 单位级 LME_SUM 追加的文字/标志属性
|
||
(定额单价专题·决策 259 flags 全采链路测试用;值须自带引号、前导空格)
|
||
另固定带:1 条措施清单(安全文明施工费)、项目特征 1 条、总造价 1234567.89。
|
||
"""
|
||
_uw_attr = (uw_lme_attrs or {}).get
|
||
lme_proj = "".join(
|
||
'<LabourMaterialsEquipmentsMachinesSummary Number=%s Name=%s Specification=%s Unit=%s'
|
||
' Kind="1" Quantity="100" NoTaxPrice=%s TaxPrice=%s/>'
|
||
% (quoteattr(it[0]), quoteattr(it[1]), quoteattr(it[2]), quoteattr(it[3]),
|
||
quoteattr(it[4]), quoteattr(it[5]))
|
||
for it in (lmes if proj_lmes is None else proj_lmes))
|
||
proj = (
|
||
'<ConstructionProject Name=%s FileKind="1" BulidUnit=%s>'
|
||
'<SummaryOfCost Total="1234567.89"/>'
|
||
'<InfoItem Name="工程类别" Value="房屋建筑"/>'
|
||
'<DivisionalAndElementalProject Number="SEC1" Name="主体工程">'
|
||
'<UnitWorks Number="UW1"/></DivisionalAndElementalProject>'
|
||
'%s</ConstructionProject>'
|
||
% (quoteattr(proj_name), quoteattr(build_unit), lme_proj))
|
||
|
||
def _bill_xml(i, b):
|
||
num, name, attr, unit, qty, price = b
|
||
qty, price = float(qty), float(price)
|
||
lme0 = ((lmes[i % len(lmes)][0] if lme_rot else lmes[0][0])
|
||
if lmes else "000001") # lme_rot=多清单轮转引用不同 LME(各配现算量)
|
||
return (
|
||
'<WorkElement Number=%s Name=%s Attr=%s Unit=%s Quantity=%s Price=%s Total=%s>'
|
||
'<Norm Number="N-%d" Name=%s Unit=%s Quantity=%s Price="80" Total=%s>'
|
||
'<LabourMaterialsEquipmentsMachinesElement Number=%s Quantity="1.5"/>%s'
|
||
'</Norm></WorkElement>'
|
||
% (quoteattr(num), quoteattr(name), quoteattr(attr), quoteattr(unit),
|
||
quoteattr(str(qty)), quoteattr(str(price)), quoteattr(str(qty * price)),
|
||
i + 1, quoteattr(name + "安装"), quoteattr(unit),
|
||
quoteattr(str(qty)), quoteattr(str(qty * 80)), quoteattr(lme0),
|
||
norm_extra))
|
||
|
||
uw = (
|
||
'<UnitWorks Number="UW1" Name="1号楼" Total="999999" Specialty="建筑工程">'
|
||
'<SummaryOfCost Construction="800000" DivisionalAndElementalWorks="700000"'
|
||
' Preliminaries="50000" CostForHSE="20000" SundryCosts="10000" Tax="30000"/>'
|
||
'<DivisionalWorks Number="D1" Name="安装工程" Code="03">%s</DivisionalWorks>'
|
||
'<Preliminaries><UnitWorksPreliminaryWorkElement Number="CS1"'
|
||
' Name="安全文明施工费" Attr="" Unit="项" Quantity="1" Price="50000" Total="50000"/>'
|
||
'</Preliminaries>%s</UnitWorks>'
|
||
% ("".join(_bill_xml(i, b) for i, b in enumerate(bills)),
|
||
"".join(
|
||
'<LabourMaterialsEquipmentsMachinesSummary Number=%s Name=%s Specification=%s'
|
||
' Unit=%s Kind="1" Quantity="100" NoTaxPrice=%s TaxPrice=%s%s/>'
|
||
% (quoteattr(it[0]), quoteattr(it[1]), quoteattr(it[2]), quoteattr(it[3]),
|
||
quoteattr(it[4]), quoteattr(it[5]), _uw_attr(it[0]) or "")
|
||
for it in (lmes if uw_lmes is None else uw_lmes))))
|
||
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as z:
|
||
# zip_ts(决策 243 测试用):同内容不同 zip 时间戳 → 不同 sha256(前后台禁同文件后,
|
||
# 「同一份数据」要进两边就得是两个文件;解析结果不变,值断言不受影响)
|
||
if zip_ts is None:
|
||
z.writestr("Project.xml", proj.encode("utf-8"))
|
||
z.writestr("UW1.xml", uw.encode("utf-8"))
|
||
else:
|
||
for nm, data in (("Project.xml", proj.encode("utf-8")), ("UW1.xml", uw.encode("utf-8"))):
|
||
zi = zipfile.ZipInfo(nm, date_time=(2026, 1, 1, 0, 0, zip_ts))
|
||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||
z.writestr(zi, data)
|
||
return path
|
||
|
||
|
||
def make_swt(path, proj_name, units, total=None, tenderee="测试建设单位"):
|
||
"""构造最小可解析的 .SWT(深圳市工程造价数据交换标准 SJG77-2020)。
|
||
|
||
units: [{
|
||
"id","name","total","a","b","c","d","e","b1", # 单位工程与 Summary 五项
|
||
"bills":[{"code","name","feature","unit","qty","rate",
|
||
"norms":[{"code","name","unit","qty","rate","res":[(rid, usage)]}]}],
|
||
"resources":[{"id","code","name","spec","unit","rate","qty","kind",
|
||
"subs":[(rid, usage)]}],
|
||
"measures":[{"code","name","unit","total","children":[...]}] # 可嵌套
|
||
}]
|
||
⚠️ ResourceID 在 SWT 里是单位工程内部编号:不同 unit 可用同一个 id 指不同编码,
|
||
这正是回归要覆盖的重号场景。
|
||
"""
|
||
def attrs(d):
|
||
return " ".join("%s=%s" % (k, quoteattr(str(v))) for k, v in d.items() if v is not None)
|
||
|
||
def measure_xml(m):
|
||
return '<MeasureItem %s>%s</MeasureItem>' % (
|
||
attrs({"MeasureItemID": m.get("id", ""), "Code": m["code"], "Name": m["name"],
|
||
"Unit": m.get("unit", "项"), "Total": m.get("total", 0), "Sequence": 1}),
|
||
"".join(measure_xml(c) for c in m.get("children", [])))
|
||
|
||
ups = []
|
||
for u in units:
|
||
resources = "".join(
|
||
'<ResourceItem %s>%s</ResourceItem>' % (
|
||
attrs({"ResourceID": r["id"], "Code": r["code"], "Name": r["name"],
|
||
"Spec": r.get("spec", ""), "Unit": r.get("unit", ""),
|
||
"Rate": r.get("rate", 0), "Quantity": r.get("qty", 0), "Total": 0,
|
||
"CostKind": r.get("kind", 2), "Provider": 0,
|
||
"StandardCode": r["code"], "NormLibrary": ""}),
|
||
"".join('<ResourceUsage ResourceID=%s Usage=%s/>' % (
|
||
quoteattr(str(rid)), quoteattr(str(usage))) for rid, usage in r.get("subs", [])))
|
||
for r in u.get("resources", []))
|
||
bills = "".join(
|
||
'<BQItem %s><Norms>%s</Norms></BQItem>' % (
|
||
attrs({"BQItemID": b.get("id", ""), "Code": b["code"], "Name": b["name"],
|
||
"Feature": b.get("feature", ""), "Unit": b["unit"], "Quantity": b["qty"],
|
||
"Rate": b["rate"], "Total": round(float(b["qty"]) * float(b["rate"]), 2),
|
||
"Sequence": 1}),
|
||
"".join(
|
||
'<NormItem %s>%s</NormItem>' % (
|
||
attrs({"NormItemID": n.get("id", ""), "Code": n["code"], "Name": n["name"],
|
||
"Unit": n["unit"], "Quantity": n["qty"], "Rate": n["rate"],
|
||
"Total": round(float(n["qty"]) * float(n["rate"]), 2), "Sequence": 1}),
|
||
"".join('<NormResUsageItem ResourceID=%s Usage=%s/>' % (
|
||
quoteattr(str(rid)), quoteattr(str(usage)))
|
||
for rid, usage in n.get("res", [])))
|
||
for n in b.get("norms", [])))
|
||
for b in u.get("bills", []))
|
||
measures = "".join(measure_xml(m) for m in u.get("measures", []))
|
||
summary = "".join(
|
||
'<SummaryItem CostCode=%s CostKind=%s Name=%s Total=%s/>' % (
|
||
quoteattr(code), quoteattr(str(kind)), quoteattr(name),
|
||
quoteattr(str(u.get(key, 0))))
|
||
for code, kind, name, key in (("A", 8, "分部分项工程", "a"), ("B", 15, "措施项目", "b"),
|
||
("B1", 22, "安全文明施工费", "b1"),
|
||
("C", 16, "其他项目", "c"), ("D", 21, "增值税", "d"),
|
||
("E", 24, "工程造价", "e")))
|
||
ups.append(
|
||
'<UnitProject ProjectID=%s Name=%s Total=%s>'
|
||
'<Summary>%s</Summary>'
|
||
'<BQTable><BQTitle BQTitleID="1" Name="整个项目">%s</BQTitle></BQTable>'
|
||
'%s'
|
||
'<Resource>%s</Resource>'
|
||
'</UnitProject>' % (
|
||
quoteattr(str(u["id"])), quoteattr(u["name"]), quoteattr(str(u.get("total", 0))),
|
||
summary, bills,
|
||
('<MeasureTable><MeasureTitle MeasureTitleID="2" Name="措施项目">%s'
|
||
'</MeasureTitle></MeasureTable>' % measures) if measures else "",
|
||
resources))
|
||
if total is None:
|
||
total = sum(float(u.get("total", 0)) for u in units)
|
||
xml = ('<?xml version="1.0" encoding="utf-8"?>\r\n'
|
||
'<ConstructProject Code="001" Name=%s Tenderee=%s Standard="深圳市工程造价数据交换标准" '
|
||
'FileType="2" Version="SJG77-2020" TaxModel="1">'
|
||
'<TenderInfo Total=%s/>'
|
||
'<ProjectAddInfo><ProjectAddInfoItem Name="编制人" Value="测试"/></ProjectAddInfo>'
|
||
'<SingleProject ProjectID="1" Name="单项一" Total=%s>%s</SingleProject>'
|
||
'</ConstructProject>' % (
|
||
quoteattr(proj_name), quoteattr(tenderee), quoteattr(str(total)),
|
||
quoteattr(str(total)), "".join(ups)))
|
||
with open(path, "w", encoding="utf-8", newline="") as f:
|
||
f.write(xml)
|
||
return str(path)
|
||
|
||
|
||
# ------------------------------------------------------------------ 服务夹具
|
||
@pytest.fixture(scope="session")
|
||
def server(tmp_path_factory):
|
||
root = tmp_path_factory.mktemp("apisrv")
|
||
app_dst = root / "CostReview" / "app"
|
||
shutil.copytree(_APP_SRC, app_dst,
|
||
ignore=shutil.ignore_patterns("__pycache__", "_deprecated", "tests"))
|
||
src_dir = root / "后台需要导入的项目" # api_server 的 SRC_DIR(PRJ_DIR 同级)
|
||
src_dir.mkdir()
|
||
lic = root / "lic"
|
||
lic.mkdir()
|
||
(lic / "config.json").write_text('{"enforce": false}', encoding="utf-8")
|
||
port = _free_port()
|
||
env = dict(os.environ, PR_PORT=str(port), LICENSE_DATA_DIR=str(lic))
|
||
log = open(root / "server.log", "wb")
|
||
proc = subprocess.Popen([sys.executable, "run_server_headless.py"],
|
||
cwd=str(app_dst), env=env, stdout=log,
|
||
stderr=subprocess.STDOUT)
|
||
client = httpx.Client(base_url="http://127.0.0.1:%d" % port, timeout=60)
|
||
deadline = time.time() + 30
|
||
while time.time() < deadline:
|
||
try:
|
||
if client.get("/api/license/status").status_code == 200:
|
||
break
|
||
except Exception:
|
||
if proc.poll() is not None:
|
||
raise RuntimeError("测试服务进程退出,日志:\n" +
|
||
open(root / "server.log", encoding="utf-8",
|
||
errors="replace").read())
|
||
time.sleep(0.3)
|
||
else:
|
||
proc.terminate()
|
||
raise RuntimeError("测试服务 30s 未就绪,日志:\n" +
|
||
open(root / "server.log", encoding="utf-8",
|
||
errors="replace").read())
|
||
yield {"client": client, "root": root, "src_dir": src_dir, "port": port,
|
||
"db": str(root / "CostReview" / "data" / "history.db"),
|
||
"sessdb": str(root / "CostReview" / "data" / "session.db"),
|
||
"log": str(root / "server.log")}
|
||
client.close()
|
||
proc.terminate()
|
||
try:
|
||
proc.wait(10)
|
||
except Exception:
|
||
proc.kill()
|
||
log.close()
|
||
|
||
|
||
# ------------------------------------------------------------------ 请求小助手
|
||
def post(server, path, body):
|
||
r = server["client"].post(path, json=body)
|
||
assert r.status_code == 200, "%s -> HTTP %d: %s" % (path, r.status_code, r.text[:300])
|
||
return r.json()
|
||
|
||
|
||
def get(server, path, **params):
|
||
r = server["client"].get(path, params=params)
|
||
assert r.status_code == 200, "%s -> HTTP %d: %s" % (path, r.status_code, r.text[:300])
|
||
return r.json()
|
||
|
||
|
||
def fixture_file(server, name, proj_name, bills, lmes=()):
|
||
"""把 .cos4 造进副本的待导入目录(_allowed_source_path 只放行 SRC_DIR/uploads)。"""
|
||
return make_cos4(str(server["src_dir"] / name), proj_name, bills, lmes)
|
||
|
||
|
||
def twin_file(server, src_path, tag="twin"):
|
||
"""决策 243 测试用:把已有 zip 件重打包成**同内容不同哈希**的双胞胎件
|
||
(zip 时间戳平移),落 source_files 哈希命名——前后台禁同文件后,
|
||
同一份数据要进两边就用这一对(后台用原件、工作台用双胞胎)。"""
|
||
import hashlib
|
||
import io as _io
|
||
raw = open(src_path, "rb").read()
|
||
buf = _io.BytesIO()
|
||
with zipfile.ZipFile(_io.BytesIO(raw)) as zi, zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zo:
|
||
for nm in zi.namelist():
|
||
zinfo = zipfile.ZipInfo(nm, date_time=(2026, 1, 1, 0, 0, 7))
|
||
zinfo.compress_type = zipfile.ZIP_DEFLATED
|
||
zo.writestr(zinfo, zi.read(nm))
|
||
tw = buf.getvalue()
|
||
dst = os.path.join(str(server["root"]), "CostReview", "data", "source_files",
|
||
"%s_%s.cos4" % (hashlib.sha256(tw).hexdigest(), tag))
|
||
with open(dst, "wb") as f:
|
||
f.write(tw)
|
||
return dst
|
||
|
||
|
||
def drop_sessions(server, *names):
|
||
"""按工程名删台账(决策 242:导入入口同文件/同名一律拒绝——测试要重导同名,
|
||
必须先走真实删除接口清掉旧会话,顺带覆盖删除链路)。
|
||
删除是两段式:等后台清理线程把子表/备注清完再返回,避免毫秒级竞态。"""
|
||
import sqlite3
|
||
import time as _t
|
||
con = sqlite3.connect("file:%s?mode=ro" % server["sessdb"], uri=True)
|
||
try:
|
||
ids = [r[0] for n in names
|
||
for r in con.execute("SELECT id FROM sessions WHERE TRIM(name)=?", (n,))]
|
||
finally:
|
||
con.close()
|
||
if not ids:
|
||
return
|
||
assert post(server, "/api/session/delete", {"ids": ids})["ok"] is True
|
||
for _ in range(100): # 最多等 5 秒:子表行清零 = 后台清理完成
|
||
con = sqlite3.connect("file:%s?mode=ro" % server["sessdb"], uri=True)
|
||
try:
|
||
n = con.execute("SELECT COUNT(*) FROM s_bills WHERE session_id IN (%s)"
|
||
% ",".join("?" * len(ids)), ids).fetchone()[0]
|
||
finally:
|
||
con.close()
|
||
if n == 0:
|
||
return
|
||
_t.sleep(0.05)
|
||
raise AssertionError("后台清理超时:s_bills 仍有 %d 行" % n)
|
||
|
||
|
||
def price_xlsx_file(server, fname, rows, sheet="价格明细"):
|
||
"""造**标准模板** xlsx(2026-10-12 新口径,9 列表头严格)进待导入目录。
|
||
|
||
rows: [(目录路径, 编码, 名称, 规格, 单位, 不含税价, 税率, 含税价, 备注), ...]
|
||
目录路径用「/」分隔多级;空串 = 未分类。
|
||
"""
|
||
from openpyxl import Workbook
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = sheet
|
||
ws.append(["目录", "材料编码", "材料名称", "规格型号", "单位",
|
||
"不含税单价", "税率", "含税单价", "备注"])
|
||
for r in rows:
|
||
ws.append(list(r))
|
||
p = server["src_dir"] / fname
|
||
wb.save(p)
|
||
return str(p)
|
||
|
||
|
||
META = {"kind": "project", "province": "广东省", "city": "珠海市",
|
||
"district": "香洲区", "period_from": PERIOD_202607, "period_to": PERIOD_202607}
|