From d3ff72d10d847362db9345f2882848c3f6858d60 Mon Sep 17 00:00:00 2001 From: ssw Date: Wed, 17 Jun 2026 17:24:33 +0800 Subject: [PATCH] auto(a17f98b34161): session end @ 2026-06-17T17:24:32 (+1f) --- .../scripts/e2e_r3_v2_engine.py | 210 ++++++++++++++---- 1 file changed, 162 insertions(+), 48 deletions(-) diff --git a/skills/jnpf-browser-automation/scripts/e2e_r3_v2_engine.py b/skills/jnpf-browser-automation/scripts/e2e_r3_v2_engine.py index b23f113..4cd9985 100644 --- a/skills/jnpf-browser-automation/scripts/e2e_r3_v2_engine.py +++ b/skills/jnpf-browser-automation/scripts/e2e_r3_v2_engine.py @@ -4,7 +4,7 @@ e2e_r3_v2_engine.py — 通用引擎 (10 控件端到端) 参考: e2e_r3.py 单控件基线 (drag → config → save → release → mount → fill → assert) 架构: 读 controls_config.json, 循环跑 10 控件, 失败收集不 abort """ -import json, os, time, urllib.request +import json, os, time, urllib.request, urllib.parse from typing import Any, Dict, List from playwright.sync_api import Page @@ -208,6 +208,7 @@ class ControlEngine: self._save_form() # Task 5 实现 form_id = self._get_form_id(form_name) # Task 5 实现 + print(f" form_id={form_id} form_name={form_name}", flush=True) # 2026-06-17 续: save 后用 REST API patch options (修 #53-#55 续) # Vue reactive 在 prod build 不可用, 改走 GET → 改 JSON → PUT @@ -243,7 +244,8 @@ class ControlEngine: time.sleep(2) self.page.goto("http://nginx/jnpf_app_backend_tdd/onlineDev/formDesign") - self.page.wait_for_selector(".vxe-table", timeout=15000) + # 修 r10 冷启动: 页面 SPA 加载需时, 15s 偶尔不够 + self.page.wait_for_selector(".vxe-table", timeout=60000) time.sleep(2) self.page.click("button:has-text('新建')") time.sleep(1) @@ -526,27 +528,34 @@ class ControlEngine: opts = opts_raw else: opts = [] + # 修 r10 run5 残留: 若已有 fullName/id 形式 (来自 inject_options_from_config) 则跳过, + # 避免被当作 {label, value} 解析后写回空字符串. + already_jnpf = bool(opts) and all(isinstance(o, dict) and ("fullName" in o or "id" in o) for o in opts) new_opts = [] - for o in opts: - if not isinstance(o, dict): continue - no = {"fullName": o.get("label", ""), "id": str(o.get("value", ""))} - if isinstance(o.get("children"), list): - no["children"] = [] - for cc in o["children"]: - if not isinstance(cc, dict): continue - no["children"].append({ - "fullName": cc.get("label", ""), - "id": str(cc.get("value", "")), - "children": [ - {"fullName": ccc.get("label", ""), "id": str(ccc.get("value", ""))} - for ccc in cc.get("children", []) if isinstance(ccc, dict) - ] if isinstance(cc.get("children"), list) else None, - }) - if no["children"][-1]["children"] is None: - del no["children"][-1]["children"] - new_opts.append(no) - # 关键: 后端 String 类型, 必须 JSON 序列化 - field["options"] = json.dumps(new_opts, ensure_ascii=False) + if not already_jnpf: + for o in opts: + if not isinstance(o, dict): continue + no = {"fullName": o.get("label", ""), "id": str(o.get("value", ""))} + if isinstance(o.get("children"), list): + no["children"] = [] + for cc in o["children"]: + if not isinstance(cc, dict): continue + no["children"].append({ + "fullName": cc.get("label", ""), + "id": str(cc.get("value", "")), + "children": [ + {"fullName": ccc.get("label", ""), "id": str(ccc.get("value", ""))} + for ccc in cc.get("children", []) if isinstance(ccc, dict) + ] if isinstance(cc.get("children"), list) else None, + }) + if no["children"][-1]["children"] is None: + del no["children"][-1]["children"] + new_opts.append(no) + else: + new_opts = opts + # 修 r10 run11: 写为 JSON 数组 (workSystem 格式, 前端期望) + # 后端 String 字段会被 Jackson 直接序列化为 JSON 数组, 不需双编码 + field["options"] = new_opts # props 映射: 让 JnpfSelect/JnpfRadio/JnpfCascader/JnpfCheckbox 知道读什么字段 field["props"] = field.get("props") or {} field["props"]["label"] = "fullName" @@ -590,12 +599,15 @@ class ControlEngine: vmodel_to_ctrl = {c["fieldName"]: c for c in self.config["controls"]} def inject_options_from_config(field): - """如果 field 是 select/radio/checkbox/cascader 且无 options, 从 controls_config 注入""" + """如果 field 是 select/radio/checkbox/cascader, 从 controls_config 强制注入 options + 修 r10 run6: 之前 'if field.get(options)' 跳过, 但 designer-side Vue reactive 失败时 + 写入了 [{'fullName':'', 'id':''}] 这种空对象, 必须强制覆盖 + 修 r10 run7: 即使 designer 写入了有效的 default options (如 '选项一/选项二'), + 也要用 config 的 schemaOpts 覆盖, 保证 user_end_fill 测试值能匹配表单实际选项 + """ if not isinstance(field, dict): return jk = (field.get("__config__") or {}).get("jnpfKey") if jk not in OPTION_CONTROLS: return - # 已有 options 不覆盖 (避免破坏 designer-side 数据) - if field.get("options"): return vmodel = field.get("__vModel__") ctrl = vmodel_to_ctrl.get(vmodel) if not ctrl: return @@ -607,7 +619,10 @@ class ControlEngine: if isinstance(o.get("children"), list): no["children"] = [to_jnpf(c) for c in o["children"]] return no - field["options"] = json.dumps([to_jnpf(o) for o in schema_opts], ensure_ascii=False) + # 修 r10 run11: 写为 JSON 数组而非字符串. workSystem formData 的 options 是 JSON 数组 + # (前端期望的格式), TDD 之前存成字符串导致前端无法解析显示. + # 既然 backend FieLdsModel.java:231 是 String, 数组会被 jnpf 的 JSON 序列化器直接序列化为 JSON 数组字符串, 不需要双编码. + field["options"] = [to_jnpf(o) for o in schema_opts] field["props"] = field.get("props") or {} field["props"]["label"] = "fullName" field["props"]["value"] = "id" @@ -625,15 +640,44 @@ class ControlEngine: if had_opts_before or jk in OPTION_CONTROLS: patched_count += 1 - if patched_count == 0: + # 修 r10 run9: 用户端表格读 columnData, 同样需要从 config 覆盖 options + column_data_str = data.get("columnData") + column_data = None + column_patched_count = 0 + if column_data_str: + try: + column_data = json.loads(column_data_str) + if isinstance(column_data, dict): + col_fields = column_data.get("columnOptions", []) or [] + for cf in col_fields: + if not isinstance(cf, dict): continue + jk = (cf.get("__config__") or {}).get("jnpfKey") + if jk in OPTION_CONTROLS: + inject_options_from_config(cf) + column_patched_count += 1 + # 修 r10 run10: 用户端表头 (columnList) 同样读 formData.options + # 之前只 patch columnOptions, 漏了 columnList → 表头 select/radio 显示旧 default options + col_list = column_data.get("columnList", []) or [] + for cl in col_list: + if not isinstance(cl, dict): continue + jk = cl.get("jnpfKey") or (cl.get("__config__") or {}).get("jnpfKey") + if jk in OPTION_CONTROLS: + inject_options_from_config(cl) + column_patched_count += 1 + except Exception as e: + print(f" ⚠ columnData parse 失败: {e}", flush=True) + + if patched_count == 0 and column_patched_count == 0: print(f" ⚠ patch 无效 (没有 field 被改), 不 PUT", flush=True) return - print(f" patched {patched_count}/{len(fields)} fields", flush=True) + print(f" patched {patched_count}/{len(fields)} formData fields, {column_patched_count} columnData fields", flush=True) form_data["fields"] = fields # 3. PUT 回写 data["formData"] = json.dumps(form_data, ensure_ascii=False) + if column_data is not None: + data["columnData"] = json.dumps(column_data, ensure_ascii=False) try: req = urllib.request.Request( f"http://nginx/api/visualdev/Base/{form_id}", @@ -696,7 +740,16 @@ class ControlEngine: self._add_result("_all", "mount", "fail", str(e)) def _user_end_fill_all_and_assert(self): - """用户端填 10 字段 + 提交 + 列表断言 (修复 #51: 不要硬 assert, 标记 list_assert status)""" + """用户端填 10 字段 + 提交 + 列表断言 (修复 #51: 不要硬 assert, 标记 list_assert status) + 修 r10 run16: 整段 try/except 包裹, 防止列表断言 reload 超时让整个 e2e 崩溃 + """ + try: + self._user_end_fill_inner() + except Exception as e: + print(f" ⚠ user_end_fill_all 异常: {e}", flush=True) + self._add_result("_all", "list_assert", "fail", str(e)[:200]) + + def _user_end_fill_inner(self): # 找用户端 URL (从 dacli menu list 反查) menu_url = self._get_user_url() if not menu_url: @@ -731,14 +784,44 @@ class ControlEngine: if submit.count() > 0: submit.click() time.sleep(3) + # 修 r10 run17: 等待 modal 关闭, 避免 reload 时还在 form 状态 + try: + self.page.wait_for_selector(".ant-modal:not(.ant-modal-hidden)", state="hidden", timeout=10000) + print(" modal 已关闭", flush=True) + except Exception as e: + print(f" ⚠ modal 未关, 重试点确定: {e}", flush=True) + # 重试点确定 + try: + self.page.locator(".ant-modal:not(.ant-modal-hidden) button:has-text('确 定')").last.click() + time.sleep(2) + except: pass else: print(" ⚠ 找不到提交按钮", flush=True) # 列表断言 (修复 #51: 不再硬 assert, 记为结果) self.page.wait_for_timeout(2000) - # 刷新一次让列表显示新行 - self.page.reload() - time.sleep(3) + # 刷新一次让列表显示新行 (修 r10 run15: 偶发 reload 超时, 加 try/except 兜底; + # 修 r10 run19: JNPF 用户端列表不自动刷新, 需要等 API 写完 + 点查询/搜索) + try: + self.page.reload(wait_until="domcontentloaded", timeout=20000) + time.sleep(3) + except Exception as e: + print(f" ⚠ reload 超时, 用 page.goto 重试: {e}", flush=True) + try: + self.page.goto(f"http://nginx/jnpf_app_{self.config['appCode']}/{menu_url}", wait_until="domcontentloaded", timeout=20000) + time.sleep(3) + except Exception as e2: + print(f" ⚠ goto 也失败: {e2}", flush=True) + # 修 r10 run19: 点查询按钮让列表重新拉数据 (JNPF 在线表单不会自动刷新) + try: + for btn_text in ["查询", "搜 索", "搜索"]: + btn = self.page.locator(f"button:has-text('{btn_text}')").first + if btn.count() > 0: + btn.click() + time.sleep(2) + break + except Exception as e: + print(f" ⚠ 点查询按钮失败: {e}", flush=True) row_count = self.page.locator(".ant-table-tbody tr.ant-table-row").count() print(f" 列表行数: {row_count}", flush=True) if row_count >= 1: @@ -747,29 +830,51 @@ class ControlEngine: self._add_result("_all", "list_assert", "fail", "rowCount=0") def _get_user_url(self) -> str: - """从菜单列表反查 urlAddress (用 dacli menu list)""" + """从菜单列表反查 urlAddress (修 r10 run13: 用 /api/system/Menu/ModuleBySystem 跨 app 查询) + """ import subprocess env = {**os.environ, "DACLI_TOKEN_DIR": "/home/ubuntu/ccWorkDir/.dacli-token"} + # 1. 优先用 HTTP API 跨 app 查询 (不依赖 dacli 当前 app context) + try: + with open("/home/ubuntu/ccWorkDir/.dacli-token/token.json") as f: + token = json.load(f)["token"] + req = urllib.request.Request( + f"http://nginx/api/system/Menu/ModuleBySystem?keyword={urllib.parse.quote(self.config['formPrefix'])}", + headers={"Authorization": token, "App-Code": self.config["appCode"], "Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=10) as resp: + data = json.loads(resp.read()) + items = data.get("data") or [] + if isinstance(items, dict): items = items.get("list", []) + # 修 r10 run14: 递归遍历 children (菜单是树形, keyword 只匹配父级) + def walk(node): + if not isinstance(node, dict): return None + fn = node.get("fullName", "") + ua = node.get("urlAddress") + if ua and self.config["formPrefix"] in fn: + return ua + for c in node.get("children", []) or []: + r = walk(c) + if r: return r + return None + for it in items: + ua = walk(it) + if ua: return ua + except Exception as e: + print(f" ⚠ HTTP API 反查 urlAddress 失败: {e}", flush=True) + # 2. 兜底: 仍用 dacli menu list (当前 app) try: r = subprocess.run( ["npx", "tsx", "/home/ubuntu/ccWorkDir/dacli/src/cli.ts", "menu", "list", "--keyword", self.config["formPrefix"], "--json"], - capture_output=True, text=True, timeout=30, + capture_output=True, text=True, timeout=120, cwd="/home/ubuntu/ccWorkDir", env=env, ) import re - # 直接 json 找 urlAddress m = re.search(r'"urlAddress"\s*:\s*"([^"]+)"', r.stdout) if m: return m.group(1) - # 兜底: 文本表格解析 - for line in r.stdout.split("\n"): - if "urlAddress" in line or "urladdress" in line.lower(): - parts = line.split() - for p in parts: - if "/" in p and len(p) > 5: - return p.strip() except Exception as e: - print(f" ⚠ 反查 urlAddress 失败: {e}", flush=True) + print(f" ⚠ dacli menu list 兜底失败: {e}", flush=True) return None def _fill_one_field_user_end(self, ctrl: dict): @@ -901,16 +1006,25 @@ class ControlEngine: self.page.keyboard.press("Enter"); time.sleep(0.3) def _fill_cascader(self, ue: dict): - """cascader: click → 逐级 panel → click 各 level option (按 fieldLabel 限定)""" + """cascader: click → 逐级 panel → click 各 level option (按 fieldLabel 限定) + 修 r10 run14: JNPF JnpfCascader 在 user-end 实际渲染为 .ant-cascader (含 .ant-select), + 旧 .ant-cascader-picker selector 在 prod build 失败 → 多 selector 兜底 + """ label = ue.get("fieldLabel", "") if label: - sel = f'{self._field_item(label)} .ant-cascader-picker' + base = self._field_item(label) + # 多 selector 兜底: .ant-cascader-picker | .ant-cascader | .ant-select.cascader + for sel in [f"{base} .ant-cascader-picker", f"{base} .ant-cascader", f"{base} .ant-select.cascader"]: + if self.page.locator(sel).count() > 0: + self.page.locator(sel).first.click(); time.sleep(0.6) + break + else: + raise RuntimeError(f"cascader picker not found in {label}") else: - sel = ue["fillSelector"] - self.page.locator(sel).first.click(); time.sleep(0.6) + self.page.locator(ue["fillSelector"]).first.click(); time.sleep(0.6) for level, txt in enumerate(ue["fillValue"]): panel_sel = f".ant-cascader-menu:nth-of-type({level+1}) .ant-cascader-menu-item:has-text('{txt}')" - self.page.wait_for_selector(panel_sel, timeout=3000) + self.page.wait_for_selector(panel_sel, timeout=5000) self.page.click(panel_sel); time.sleep(0.4) def _summary(self) -> dict: