# -*- coding: utf-8 -*- """各页面的检测单实现:界面(截图比底片)+ 功能(按路径点一遍)同时进行。 ⚠️ 规矩(主人定的):页面要一个一个点名。只有 页面清单.json 里 enabled=true 的页面 才会跑下面的检测单;主人没点名的页面一律不检测。 每个函数 = 一张"检测单":照着做、每步判结果、到点拍照。检测单对应的白话说明 见包内 检测单_*.md 文件。 """ import os import shutil import imaging from config import (VIEWPORT, TIME_MASK_JS, ALLOW_4XX, FAIL_TEXTS, CONSOLE_ERR_IGNORE, SETTLE_MS, BASELINE_DIR, OUT_DIR) _PKG = os.path.dirname(os.path.abspath(__file__)) # ================================================================ 通用脚手架 class PageCtx: """一个页面 = 一个全新浏览器上下文(干净的 localStorage,互不干扰)。""" def __init__(self, browser, server, report, pid, update_mode): import config self.server = server self.report = report self.pid = pid self.update = update_mode self.out_dir = os.path.join(_PKG, OUT_DIR) self.js_errors = [] self.console_errors = [] self.bad_api = [] self._ctx = browser.new_context(viewport=VIEWPORT, device_scale_factor=1, locale="zh-CN") self.page = self._ctx.new_page() self.page.set_default_timeout(15000) self.page.on("pageerror", self._on_pageerror) self.page.on("console", self._on_console) self.page.on("response", self._on_response) self.page.on("dialog", lambda d: d.accept()) # 弹框(确认/提示)一律按"确定"过 def close(self): self._ctx.close() # ---------------------------------------------------------------- 监听 def _on_pageerror(self, err): self.js_errors.append(str(err)) def _on_console(self, msg): if msg.type == "error" and not any(k in msg.text for k in CONSOLE_ERR_IGNORE): self.console_errors.append(msg.text[:200]) def _on_response(self, resp): if resp.status >= 400 and not any(k in resp.url for k in ALLOW_4XX): self.bad_api.append("HTTP %d %s" % (resp.status, resp.url)) # ---------------------------------------------------------------- 步骤 def settle(self, ms=SETTLE_MS): try: self.page.wait_for_load_state("networkidle", timeout=5000) except Exception: pass self.page.wait_for_timeout(ms) def goto(self, desc, url): self.page.goto(self.server.base + url, wait_until="load") self.settle() self.report.step("ok", desc, url) def check(self, desc, js, must=True): ok = bool(self.page.evaluate("() => " + js)) self.report.step("ok" if ok else ("fail" if must else "warn"), desc + ("" if ok else " —— 没找到/不成立")) return ok def has_text(self, desc, text, must=True): return self.check(desc, "document.body.innerText.includes(%s)" % _js(text), must) def click(self, desc, sel): self.page.click(sel) self.settle() self.report.step("ok", desc, sel) def fill(self, desc, sel, text): self.page.fill(sel, text) self.settle(300) self.report.step("ok", desc, "填入「%s」" % text) def shot(self, sid, name): """截图 + 与底片对比(或更新底片)。界面检查就在这一步发生。""" shots_dir = os.path.join(self.out_dir, "shots") os.makedirs(shots_dir, exist_ok=True) cur = os.path.join(shots_dir, "%s__%s.png" % (self.pid, sid)) self.page.evaluate(TIME_MASK_JS) # 抹平时间戳,免得底片假差异 self.page.screenshot(path=cur, full_page=True, animations="disabled", caret="hide") base = os.path.join(_PKG, BASELINE_DIR, "%s__%s.png" % (self.pid, sid)) diff_rel = "" if self.update: if os.path.exists(base): d = os.path.join(self.out_dir, "diffs", "%s__%s.png" % (self.pid, sid)) try: v, ratio, note = imaging.compare(base, cur, d) except Exception as e: v, ratio, note, d = "size", 1.0, "旧底片对比失败:%s" % e, "" note = "底片已按本次更新。与旧底片相比:%s" % note v = "updated" # 更新模式:变化只作提示,不算失败 else: v, note = "new", "第一次留底:本次的样子已固定为底片" os.makedirs(os.path.dirname(base), exist_ok=True) shutil.copyfile(cur, base) if v != "new" and os.path.exists(d): diff_rel = "diffs/%s__%s.png" % (self.pid, sid) elif not os.path.exists(base): v, note = "new", "还没有底片:请主人看本次截图,确认后用「确认无误-更新底片」固定" else: d = os.path.join(self.out_dir, "diffs", "%s__%s.png" % (self.pid, sid)) v, ratio, note = imaging.compare(base, cur, d) if v in ("changed", "size"): diff_rel = "diffs/%s__%s.png" % (self.pid, sid) else: d = "" self.report.shot(sid, name, _rel(cur, self.out_dir), "baselines" if os.path.exists(base) else "", diff_rel, v, note) def finish(self, page_name): """收尾三查:页面报错字样 / JS 崩溃 / 接口报错。""" self.settle() body = "" try: body = self.page.evaluate("() => document.body.innerText") except Exception: pass for t in FAIL_TEXTS: if t in body: self.report.step("fail", "页面上出现了「%s」字样" % t) for e in self.js_errors[:5]: self.report.step("fail", "页面 JS 崩溃(脚本错误)", e[:160]) if not self.js_errors: self.report.step("ok", "页面脚本全程无崩溃") for b in self.bad_api[:5]: self.report.step("fail", "后台接口报错", b) if not self.bad_api: self.report.step("ok", "后台接口全程无报错") for c in self.console_errors[:3]: self.report.step("warn", "浏览器控制台有 error 日志", c) v, n = self.report.page_verdict(self.report.pages[-1]) self.report.step("info", "本页小结:%s" % ("✅ 通过" if v == "ok" else ("⚠️ 轻微差异" if v == "warn" else "❌ 有 %d 处问题" % n))) def _js(s): import json return json.dumps(s, ensure_ascii=False) def _rel(path, base): return os.path.relpath(path, base).replace("\\", "/") # ================================================================ 检测单(草稿) # 以下都是"草稿路径":主人点名哪个页面,就按哪张检测单实际跑一遍给主人看, # 主人看过、改过、确认后,该页 enabled=true + 留底,以后每次体检固定照此执行。 def check_sessions(browser, server, report, update): """最近审核页(打开软件第一页)——检测单(2026-10-19 按主人功能清单改版后口径)。""" c = PageCtx(browser, server, report, "sessions", update) report.begin_page("sessions", "最近审核(打开软件第一页)", "样例数据:预置 2 个审核会话(审核工程甲/乙)+ 1 个后台批次;" "口径=主人《功能清单》页面一(2026-10-19 改版后)") try: c.goto("打开页面", "/sessions.html") c.check("标题是「最近审核」", "document.querySelector('h1').innerText.includes('最近审核')") c.check("右上角「工作台」按钮无▶、28px 同款", "(function(){const b=[...document.querySelectorAll('button')]" ".find(x=>x.innerText.trim()==='工作台');" "return !!b && !b.innerText.includes('▶') && b.offsetHeight===28;})()") c.check("刷新按钮已去掉", "![...document.querySelectorAll('button')]" ".some(x=>x.innerText.trim()==='刷新')") c.check("计数文字已取消", "!document.getElementById('cnt')") c.has_text("列表出现「审核工程甲」", "审核工程甲") c.has_text("列表出现「审核工程乙」", "审核工程乙") c.check("共 2 行", "document.querySelectorAll('#tbody tr').length===2") # 功能清单页面一:12 列顺序 / 默认最新在前 / 序号倒序 / 点表头排序(2026-10-20 补) c.check("共 12 列且顺序正确", "(function(){const t=[...document.querySelectorAll('#th th')].map(x=>x.innerText.trim());" "return t.length===12 && t[1]==='序号' && t[2]==='项目名称' && t[3]==='项目总造价' && " "t[4]==='源文件' && t[5]==='单位工程' && t[6]==='清单' && t[7]==='定额' && " "t[8]==='工料机' && t[9]==='备注' && t[10]==='打开时间' && t[11]==='操作';})()") c.check("默认最新在前(第一行=乙)", "document.querySelector('#tbody tr:first-child').innerText.includes('审核工程乙')") c.check("序号倒序编号(2、1)", "(function(){const r=[...document.querySelectorAll('#tbody tr')];" "return r.length===2 && r[0].children[1].innerText.trim()==='2' && " "r[1].children[1].innerText.trim()==='1';})()") c.check("点「项目总造价」表头:先▲再▼", "(function(){const q=()=>document.querySelector('#th th:nth-child(4)');" "q().click();const a=q().innerText.includes('▲');" "q().click();const b=q().innerText.includes('▼');" "return a&&b;})()") c.page.reload(wait_until="load") # 复位排序到默认序,后面的删除测试仍按「第一行=乙」 c.settle() c.shot("01", "首屏(两个会话)") # 筛选:项目名称 + 文件名 c.fill("筛选框输入「甲」", "#fq", "甲") c.check("按名称筛剩 1 行(乙被滤掉)", "document.querySelectorAll('#tbody tr').length===1") c.check("列表里不再有「乙」", "!document.getElementById('tbody').innerText.includes('审核工程乙')") c.shot("02", "按关键字筛选") c.fill("清空筛选框", "#fq", "") # 勾选 → 删除所选亮起(同款尺寸红按钮) c.page.click("#tbody tr:first-child input.f-sel") c.check("勾选后「删除所选 (1)」亮起", "!document.getElementById('bdel').disabled && " "document.getElementById('bdel').innerText.includes('(1)')") c.shot("03", "勾选一条待删") c.page.click("#tbody tr:first-child input.f-sel") # 拖列只动本列(主人功能清单 2026-10-19;与决策 49「拉动的时候按拉动」同口径) w0 = c.page.evaluate("() => [...document.querySelectorAll('#cg col')]" ".map(x => parseFloat(x.style.width) || 0)") box = c.page.locator("#th th").nth(4).locator(".rs").bounding_box() c.page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2) c.page.mouse.down() c.page.mouse.move(box["x"] + box["width"] / 2 + 60, box["y"] + box["height"] / 2, steps=5) c.page.mouse.up() c.settle(300) w1 = c.page.evaluate("() => [...document.querySelectorAll('#cg col')]" ".map(x => parseFloat(x.style.width) || 0)") d = w1[4] - w0[4] same = all(abs(w1[i] - w0[i]) < 1 for i in range(len(w0)) if i != 4) c.report.step("ok" if 55 <= d <= 65 and same else "fail", "拖「源文件」列只动本列(该列 %+.0fpx,其余列未变=%s)" % (d, same)) # 功能清单页面一:拖过的列宽要记住(2026-10-20 补) c.page.reload(wait_until="load") c.settle() w2 = c.page.evaluate("() => [...document.querySelectorAll('#cg col')]" ".map(x => parseFloat(x.style.width) || 0)") c.report.step("ok" if abs(w2[4] - w1[4]) < 2 else "fail", "刷新后列宽仍记住(该列 %.0fpx)" % w2[4]) c.page.evaluate("() => localStorage.clear()") # 复原列宽,别把拖宽带进后续底片 c.page.reload(wait_until="load") c.settle() # 行删除:统一弹框(2026-10-19 主人定:只用一句提示语) c.click("点第一行「删除」打开确认弹框", "#tbody tr:first-child a:has-text('删除')") c.check("确认弹框出现、提示语=「删除后不可恢复,是否删除?」", "document.getElementById('dlgmask').classList.contains('on') && " "document.getElementById('dlgtext').textContent==='删除后不可恢复,是否删除?'") c.check("弹框有「取消 / 删除」两个按钮", "document.getElementById('dlgcancel').offsetParent!==null && " "document.getElementById('dlgok').offsetParent!==null") c.shot("04", "删除确认弹框") c.click("点「取消」不删除", "#dlgcancel") c.check("取消后弹框关闭、行数不变", "!document.getElementById('dlgmask').classList.contains('on') && " "document.querySelectorAll('#tbody tr').length===2") c.click("再点第一行「删除」", "#tbody tr:first-child a:has-text('删除')") c.click("点弹框「删除」", "#dlgok") c.page.wait_for_timeout(500) c.check("删除成功提示=右下角消息(不再弹框)", "!document.getElementById('dlgmask').classList.contains('on') && " "!!document.querySelector('#toastBox .toast') && " "document.querySelector('#toastBox .toast').innerText.includes('已删除')") c.page.wait_for_timeout(3200) # 等右下角消息自动消失,截图与底片一致 c.check("删除后只剩 1 行", "document.querySelectorAll('#tbody tr').length===1") c.has_text("留下的还是「甲」", "审核工程甲") c.shot("05", "删除一条之后") # 全选 → 删除所选 = 删光本页(主人功能清单 2026-10-19) c.page.click("#ckall") c.page.wait_for_timeout(300) c.check("全选后「删除所选 (1)」亮起", "document.getElementById('bdel').innerText.includes('(1)') && " "!document.getElementById('bdel').disabled") c.click("点「删除所选」", "#bdel") c.check("批量删除也走同一弹框", "document.getElementById('dlgtext').textContent==='删除后不可恢复,是否删除?'") c.click("确认批量删除", "#dlgok") c.page.wait_for_timeout(500) c.check("批量删除成功也是右下角消息", "!document.getElementById('dlgmask').classList.contains('on') && " "!!document.querySelector('#toastBox .toast')") c.page.wait_for_timeout(3200) c.has_text("本页已删空(空态提示)", "没有匹配的会话") c.shot("06", "全选删除后空态") finally: c.finish("sessions") c.close() def check_workbench(browser, server, report, update, sid_a): """工作台(审核主页面)——检测单草稿。""" c = PageCtx(browser, server, report, "workbench", update) report.begin_page("workbench", "工作台(审核主页面)", "样例数据:预置审核会话「审核工程甲」+ 后台历史工程供比对") try: c.goto("打开页面(未选会话)", "/workbench.html") c.has_text("出现「打开」工程入口", "打开", must=False) c.check("弹框字段标签:工程名称 / 全国电子标书", "document.querySelector('#oname').closest('.row').textContent.includes('工程名称') && " "document.querySelector('#ofile').closest('.row').textContent.includes('全国电子标书')") c.check("弹框按钮:创建工程与模板均已取消", "!document.querySelector('button[onclick=\"saveTemplate()\"]') && " "!document.querySelector('button[onclick=\"createProject()\"]')") c.shot("00", "初始状态") c.goto("打开会话「审核工程甲」", "/workbench.html?sid=%d" % sid_a) # 会话是异步恢复(recLoad→recOpen→loadLme→loadRaw):等 #sinfo 出名再往下判, # 否则 settle 的 networkidle 可能赶在加载完成前(2026-10-20 实测偶发竞态) try: c.page.wait_for_selector("#sinfo b:text(\"审核工程甲\")", timeout=8000) except Exception: pass c.has_text("顶部显示工程名「审核工程甲」", "审核工程甲") c.check("四个标签齐全(原数据/类似清单/组价不一致清单/项目工料机)", "['原数据','类似清单','组价不一致清单','项目工料机'].every(t => document.body.innerText.includes(t))") c.check("四个页签无计数徽标(2026-10-20 主人定)", "document.querySelectorAll('#tabbar .tab .n').length === 0") c.check("四页签高 24px、不高于顶栏按钮,保留块状圆角", "(() => { const ts=[...document.querySelectorAll('#tabbar .tab')];" " const b=document.querySelector('.tabright .btn'); if(!b) return false;" " const bh=b.getBoundingClientRect().height;" " return ts.length===4 && ts.every(t => { const h=t.getBoundingClientRect().height;" " return Math.abs(h-24)<0.1 && h<=bh && getComputedStyle(t).borderTopLeftRadius==='8px'; }); })()") c.check("四页签底部贴住顶栏横线,高度 24px", "(() => { const bar=document.querySelector('.tabs'); if(!bar) return false;" " const r=bar.getBoundingClientRect(), s=getComputedStyle(bar);" " const bottom=r.bottom-parseFloat(s.borderBottomWidth);" " const ts=[...document.querySelectorAll('#tabbar .tab')];" " return ts.length===4 && ts.every(t => { const q=t.getBoundingClientRect();" " return Math.abs(q.bottom-bottom)<0.1 && Math.abs(q.height-24)<0.1; }); })()") c.check("顶栏恢复原布局:高至少 34px、按钮垂直居中且上下留白", "(() => { const bar=document.querySelector('.tabs');" " const box=document.querySelector('.tabright'); if(!bar || !box) return false;" " const r=bar.getBoundingClientRect(), s=getComputedStyle(bar);" " const bottom=r.bottom-parseFloat(s.borderBottomWidth);" " return r.height>=34 && s.alignItems==='center' && getComputedStyle(box).gap==='8px' && " "[...box.querySelectorAll('.btn, .langseg button')].filter(b => b.getClientRects().length>0).every(b => {" " const q=b.getBoundingClientRect(), topGap=q.top-r.top, bottomGap=bottom-q.bottom;" " return topGap>=3 && bottomGap>=3 && Math.abs(topGap-bottomGap)<=1; }); })()") c.shot("01", "原数据(默认页)") c.click("切到「类似清单」", "#tabbar .tab:has-text('类似清单')") c.shot("02", "类似清单") c.click("切到「组价不一致清单」", "#tabbar .tab:has-text('组价不一致清单')") c.shot("03", "组价不一致清单") c.click("切到「项目工料机」", "#tabbar .tab:has-text('项目工料机')") c.shot("04", "项目工料机") finally: c.finish("workbench") c.close() def check_admin(browser, server, report, update): """后台(价格批次管理)——检测单草稿。""" c = PageCtx(browser, server, report, "admin", update) report.begin_page("admin", "后台(价格批次管理)", "样例数据:预置 1 个入库项目「历史工程B」") try: c.goto("打开页面", "/admin.html") c.check("三个类别页签齐全(入库项目/市场价/信息价)", "['入库项目','市场价','信息价'].every(t => !!document.querySelector('.tab[data-kind]')) " "&& !!document.querySelector('.tab[data-kind=\\'project\\']')") c.has_text("入库项目列表出现「历史工程B」", "历史工程B") c.shot("01", "入库项目") c.click("切到「市场价」", ".tab[data-kind='market']") c.shot("02", "市场价") c.click("切到「信息价」", ".tab[data-kind='info']") c.shot("03", "信息价") c.click("切回「入库项目」", ".tab[data-kind='project']") c.check("后台三个类别页签 24px(2026-10-21 决策 151:与工作台数据页签同高,原 32px 口径取消)", "[...document.querySelectorAll('.tab[data-kind]')].length===3 && " "[...document.querySelectorAll('.tab[data-kind]')].every(t => Math.abs(t.getBoundingClientRect().height-24)<0.1)") c.click("点「明细」进入批次数据页", "a:has-text('明细')") c.check("后台明细四页签高 24px、无计数徽标", "document.querySelectorAll('#dtabs .tab .n').length === 0 && " "document.querySelectorAll('#dtabs .tab').length === 4 && " "[...document.querySelectorAll('#dtabs .tab')].every(t => t.getBoundingClientRect().height===24)") c.check("后台明细四页签底部贴住横线", "(() => { const bar=document.querySelector('#dtabs'); if(!bar) return false;" " const bottom=bar.getBoundingClientRect().bottom-parseFloat(getComputedStyle(bar).borderBottomWidth);" " return [...bar.querySelectorAll('.tab')].every(t => Math.abs(t.getBoundingClientRect().bottom-bottom)<0.1); })()") c.click("数据页签切到「项目工料机」", "#dtabs .tab:has-text('项目工料机')") c.shot("04", "入库项目-项目工料机") c.click("数据页签切回「原数据」", "#dtabs .tab:has-text('原数据')") # ---- 决策 150(2026-10-21 主人定):明细改浏览器式动态标签,弹框取消 ---- c.check("明细在动态标签打开:明细页可见、列表隐藏", "document.querySelectorAll('#xtabs .xtab').length===1 " "&& getComputedStyle(document.getElementById('dpage')).display==='flex' " "&& getComputedStyle(document.getElementById('lpanel')).display==='none'") c.check("标签文字带类型前缀(项目 · 名称),能认出点开的是哪份数据", "document.querySelector('#xtabs .xtab .xl').textContent.startsWith('项目 · ')") c.check("固定三标签没有关闭钮(不可关)", "document.querySelectorAll('.tab[data-kind] .xx').length===0") c.check("重复点同一条明细=聚焦已开标签,不会重复开", "det(DID,'历史工程B','project').then(()=>XTABS.length===1)") c.click("点动态标签 × 关闭", "#xtabs .xtab .xx") c.check("关闭后回列表区:动态标签清空、明细页隐藏、列表可见", "document.querySelectorAll('#xtabs .xtab').length===0 " "&& getComputedStyle(document.getElementById('dpage')).display==='none' " "&& getComputedStyle(document.getElementById('lpanel')).display!=='none'") c.click("再点「明细」重开动态标签", "a:has-text('明细')") c.check("重开后动态标签与明细页恢复", "document.querySelectorAll('#xtabs .xtab').length===1 " "&& getComputedStyle(document.getElementById('dpage')).display==='flex'") finally: c.finish("admin") c.close() CHECKS = {"sessions": check_sessions, "workbench": check_workbench, "admin": check_admin}