Files
pricing_review/test/界面体检/导入Excel_e2e.py
lianjianwei2024 8250a265fb fix(manual): 手工导出骨架与导入边界修复,单位按目录自然序排列
- 上传口骨架收集改为空操作,骨架仅经升级入库(决策 231/补记十四)
- s_lme_lib 价格快照垫底,修手工会话组成子行价格落 0
- 导出编辑相交消解:删除块与闭合前插入冲突时重映射,防采纳定额丢失/碎 XML
- _span 识别自闭合标签,防容器配对失败留孤儿闭合
- 手工导入放开空名/同名/深层级校验
- 单位顺序改按左侧目录树序(单项入库序+组内编号自然序)
- 补齐手工导出/导入/MCP 切换相关测试
2026-10-28 16:20:34 +08:00

257 lines
15 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.
# -*- coding: utf-8 -*-
"""决策 233 无头浏览器实测(铁律 8:前端行为改动必须把真实路径走一遍)。
主人定(2026-10-28):打开项目弹框底部常驻 [模板][导入Excel](打开按钮右边);点「导入Excel」
右边展开现目录树;去掉顶栏「导入项目」按钮(修改决策 230);共用左侧 工程名称/基准期次/地区/
建设单位字段,创建落库;有项目打开也可建;单位工程行 [Excel 导出](方案a,231 通道同构)+
[导入单位工程] 不变。
路径:
① 空态:弹框四按钮齐、顶栏无「导入项目」、空态提示指向 打开项目→导入Excel;
② 展开面板:右侧目录树、标书行隐藏、标题变化;再点收起(取消/复位路径);
③ 创建:共用字段+行内改名 → 创建工程 → 跳转新手工工程(地区/建设单位落库);
④ 编辑回填:重开面板,名称/期次/地区/建设单位/树回填,按钮=保存(更新目录树);
⑤ 导入单位工程(filechooser 真路径)→ 行 ✓ 计数 → 保存;
⑥ 行内 Excel 导出:下载 E2E单位甲.xlsx,openpyxl 断言架子与合价列(231 同构);
守卫:无数据单位提示、未保存提示;
⑦ 有项目打开(普通工程)时点导入Excel 也走创建 → 新手工工程;
⑧ 模板按钮下载 单位工程导入模板.xlsx。
用真实骨架件:后台需要导入的项目/合并工料机测试(原).cos4。隔离副本服务,退出整体删除。
"""
import io
import os
import tempfile
import sys
import urllib.parse
from pathlib import Path
_HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, _HERE)
from server_env import Server # noqa: E402
_REAL = Path(_HERE).parents[1] / "后台需要导入的项目" / "合并工料机测试(原).cos4"
PERIOD = 2026 * 12 + 7
ROWS = [
["单位工程", "", "分部", "我方一级分部", "", "", "", ""],
["我方一级分部", "041001001001", "清单", "我方清单甲", "1.特征一", "m²", 126.5, 385],
]
def _seed(server):
"""真实骨架件开普通工程 + 造单位工程 xlsx → (sid_normal, xlsx路径)。"""
from openpyxl import Workbook
assert _REAL.exists(), "真实骨架件不在本机:%s" % _REAL
r = server.client.post("/api/admin/upload", content=_REAL.read_bytes(),
headers={"Content-Type": "application/octet-stream",
"X-File-Name": urllib.parse.quote(_REAL.name)})
assert r.json().get("ok"), r.text[:200]
r = server.client.post("/api/audit", json={
"path": r.json()["path"], "name": "普通工程T", "period_from": PERIOD,
"period_to": PERIOD, "base_period_m": PERIOD})
assert r.json().get("ok"), r.text[:200]
sid_normal = r.json()["session_id"]
wb = Workbook()
ws = wb.active
ws.title = "分部分项"
ws.append(["上一级名称", "编码", "类型", "名称", "项目特征", "单位", "工程量", "单价"])
for row in ROWS:
ws.append(row)
ws2 = wb.create_sheet("措施项目")
ws2.append(["名称", "编码", "项目特征", "单位", "工程量", "单价"])
ws2.append(["安全文明施工费", "", "", "项", 1, 120000])
fp = os.path.join(server.src_dir, "manual_e2e.xlsx")
wb.save(fp)
return sid_normal, fp
def _pick_browser(pw):
for kwargs in ({"headless": True}, {"headless": True, "channel": "chrome"},
{"headless": True, "channel": "msedge"}):
try:
return pw.chromium.launch(**kwargs)
except Exception:
continue
raise RuntimeError("无可用 Chromium 内核浏览器")
def _set_period(page):
page.evaluate("setPeriod(document.getElementById('oper'),'2026-07','2026-07')")
def main():
log = os.path.join(tempfile.gettempdir(), "import_excel_e2e_server.log")
server = Server(log)
server.__enter__()
out = []
try:
sid_normal, xlsx = _seed(server)
from playwright.sync_api import sync_playwright
with sync_playwright() as pw:
browser = _pick_browser(pw)
try:
ctx = browser.new_context(accept_downloads=True)
ctx.add_init_script("try{delete window.showSaveFilePicker;}catch(e){}")
page = ctx.new_page()
page.on("pageerror", lambda e: out.append("!! 页面JS错误:%s" % e))
base = server.base
# ---- ① 空态:四按钮 + 顶栏按钮已除 + 空态提示 ----
page.goto(base + "/workbench.html")
page.wait_for_selector("button:has-text('打开项目')", timeout=30000)
assert page.locator("#impWrap").count() == 0, "顶栏导入项目容器应已移除"
assert "导入Excel" in page.inner_text("#rawtree"), "空态提示没指向 导入Excel"
page.click("button:has-text('打开项目')")
page.wait_for_selector("#omask.on", timeout=10000)
for t in ("取消", "打开", "模板", "导入Excel"):
assert page.is_visible("#omask .mfoot button:has-text('%s')" % t), t
assert not page.is_visible("#opanel"), "面板默认应收起"
out.append("① 空态:底部 [取消][打开][模板][导入Excel] 常驻,顶栏旧按钮已除 ✓")
# ---- ② 展开面板 / 再点收起 ----
page.click("#impBtnX")
page.wait_for_selector("#itree .ied", timeout=10000)
assert page.is_visible("#opanel") and not page.is_visible("#ofileRow")
assert "导入Excel" in page.inner_text("#otitle")
assert page.inner_text("#obtnGo") == "创建工程"
assert page.locator("#itree .iab:has-text('Excel 导出')").count() == 1
assert page.locator("#itree .iab:has-text('导入单位工程')").count() == 1
# 补记三:右目录占 60%(660/1100),左表单等比缩小 388/标签56;拖缘调宽高;名称悬浮
lw = page.eval_on_selector("#oleft", "el=>Math.round(el.getBoundingClientRect().width)")
tw = page.eval_on_selector("#opanel", "el=>Math.round(el.getBoundingClientRect().width)")
assert lw == 388 and abs(tw - 660) <= 2, (lw, tw)
assert page.eval_on_selector(
"#oleft .row > span:not(.combo)",
"el=>Math.round([...document.querySelectorAll('#oleft .row > span:not(.combo)')]"
".find(s=>s.getBoundingClientRect().width>0).getBoundingClientRect().width)") == 56
hb = page.locator("#odlg .rsz-e").bounding_box()
ex, ey = hb["x"] + hb["width"] / 2, hb["y"] + hb["height"] / 2
page.mouse.move(ex, ey); page.mouse.down(); page.mouse.move(ex + 60, ey + 3); page.mouse.up()
hs = page.locator("#odlg .rsz-s").bounding_box()
sx, sy = hs["x"] + hs["width"] / 2, hs["y"] + hs["height"] / 2
page.mouse.move(sx, sy); page.mouse.down(); page.mouse.move(sx + 60, sy + 9); page.mouse.up()
dw = page.eval_on_selector("#odlg", "el=>Math.round(el.getBoundingClientRect().width)")
dh = page.eval_on_selector("#odlg", "el=>Math.round(el.getBoundingClientRect().height)")
assert 1150 <= dw <= 1166 and 674 <= dh <= 688, (dw, dh)
assert page.locator("#itree .inm").last.get_attribute("title") == "单位工程 1"
out.append("② 展开:右目录占六成/左栏388/标签56,拖宽至 %d、拖高至 %d,悬浮title ✓" % (dw, dh))
page.click("#impBtnX")
assert not page.is_visible("#opanel") and page.is_visible("#ofileRow")
assert not page.is_visible("#odlg .rsz-e"), "收起态拖拽把手应收起"
assert page.eval_on_selector(
"#oleft", "el=>Math.round(el.getBoundingClientRect().width)") == 604, "收起态左栏应回 604"
page.click("#impBtnX")
out.append("② 点导入Excel 右侧展开现目录树,再点收起,行内两按钮齐 ✓")
# ---- ③ 创建:共用字段 + 行内改名 → 创建工程 ----
page.fill("#oname", "打开项目E2E")
_set_period(page)
page.evaluate("impSelSet('oprov','广东省');impSelSet('ocity','珠海市');"
"impSelSet('odist','香洲区')")
page.fill("#obuid", "某某建设单位")
urow = page.locator("#itree .ied", has_text="单位工程").last
urow.locator(".inm").click()
urow.locator("input").fill("E2E单位甲")
urow.locator("input").press("Enter")
with page.expect_navigation(timeout=60000):
page.click("#obtnGo")
page.wait_for_selector("#sinfo:not(:has-text('尚未打开工程'))", timeout=30000)
sid_m = int(page.url.split("sid=")[1])
it = next(x for x in server.client.get("/api/sessions").json()["items"]
if x["id"] == sid_m)
assert it["manual"] is True
st = server.client.get("/api/session/manual/state",
params={"session_id": sid_m}).json()
assert st["province"] == "广东省" and st["bulid_unit"] == "某某建设单位", st
assert st["sections"][0]["units"][0]["name"] == "E2E单位甲"
out.append("③ 创建工程 → 跳转新手工工程,地区/建设单位落库、树与改名生效 ✓")
# ---- ④ 编辑回填 ----
page.click("button:has-text('打开项目')")
page.wait_for_selector("#omask.on", timeout=10000)
assert not page.is_visible("#opanel"), "重开弹框面板应复位收起"
page.click("#impBtnX")
page.wait_for_function(
"document.getElementById('obtnGo').textContent.includes('更新目录树')",
timeout=15000)
assert page.input_value("#oname") == "打开项目E2E"
assert page.eval_on_selector("#oprov", "el=>el.value") == "广东省"
assert page.input_value("#obuid") == "某某建设单位"
assert "编辑目录树" in page.inner_text("#otitle")
out.append("④ 编辑回填:名称/期次/地区/建设单位/树齐,标题带编辑目录树 ✓")
# ---- ⑤ 守卫 + 导入单位工程(filechooser 真路径)----
page.click("#itree .iab:has-text('Excel 导出')")
page.wait_for_function(
"document.getElementById('imsg').textContent.includes('还没有清单数据')",
timeout=10000)
out.append("⑤a 无数据单位点 Excel 导出 → 提示不产文件 ✓")
with page.expect_file_chooser(timeout=10000) as fc:
page.click("#itree .iab:has-text('导入单位工程')")
fc.value.set_files(xlsx)
page.wait_for_selector("#itree .iok", timeout=30000)
assert "清单1" in page.inner_text("#itree")
with page.expect_navigation(timeout=60000):
page.click("#obtnGo")
page.wait_for_selector("#sinfo:not(:has-text('尚未打开工程'))", timeout=30000)
out.append("⑤b 导入单位工程(原入口不变)→ 行 ✓ 计数 → 保存 ✓")
# ---- ⑥ 行内 Excel 导出真实下载 ----
page.click("button:has-text('打开项目')")
page.click("#impBtnX")
page.wait_for_function(
"document.getElementById('obtnGo').textContent.includes('更新目录树')",
timeout=15000)
with page.expect_download(timeout=120000) as dl:
page.click("#itree .iab:has-text('Excel 导出')")
name = dl.value.suggested_filename
assert name == "E2E单位甲.xlsx", name
pth = os.path.join(tempfile.gettempdir(), "e2e_import_excel_unit.xlsx")
dl.value.save_as(pth)
from openpyxl import load_workbook
wb = load_workbook(pth)
assert wb.sheetnames == ["填写说明", "分部分项", "措施项目"], wb.sheetnames
head = [c.value for c in wb["分部分项"][1]]
assert head[-2:] == ["合价", "备注"], head
rows = [list(r) for r in wb["分部分项"].iter_rows(min_row=2, values_only=True)]
jia = next(r for r in rows if r[3] == "我方清单甲")
assert abs(jia[8] - round(126.5 * 385, 2)) < 0.01, "合价没现算"
out.append("⑥ 行内 Excel 导出 → %s,231 同构架子+合价现算 ✓" % name)
# ---- ⑦ 有项目打开(普通工程)时也走创建 ----
page.goto("%s/workbench.html?sid=%d" % (base, sid_normal))
page.wait_for_selector("#btnExport:not([disabled])", timeout=30000)
page.click("button:has-text('打开项目')")
page.wait_for_selector("#omask.on", timeout=10000)
page.click("#impBtnX")
page.wait_for_selector("#itree .ied", timeout=10000)
assert not page.is_visible("#ofileRow")
page.fill("#oname", "有项目时新建E2E")
_set_period(page)
with page.expect_navigation(timeout=60000):
page.click("#obtnGo")
new_sid = int(page.url.split("sid=")[1])
assert new_sid != sid_normal
it = next(x for x in server.client.get("/api/sessions").json()["items"]
if x["id"] == new_sid)
assert it["manual"] is True and it["name"] == "有项目时新建E2E"
out.append("⑦ 普通工程打开时点导入Excel → 建成新手工工程并切换 ✓")
# ---- ⑧ 模板按钮 ----
page.click("button:has-text('打开项目')")
page.wait_for_selector("#omask.on", timeout=10000)
with page.expect_download(timeout=60000) as dl:
page.click("#omask .mfoot button:has-text('模板')")
assert dl.value.suggested_filename == "单位工程导入模板.xlsx"
out.append("⑧ 模板按钮 → 单位工程导入模板.xlsx ✓")
finally:
browser.close()
finally:
server.__exit__(None, None, None)
print("\n".join(out))
print("无头浏览器实测:全部通过")
if __name__ == "__main__":
main()