Files
dacli/docs/archive/jnpf-browser-automation/scripts/e2e_r3_v2_engine.py
T

1884 lines
93 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.
"""
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, urllib.parse
from typing import Any, Dict, List
from playwright.sync_api import Page
OUT_DIR = f"/home/ubuntu/ccWorkDir/docs/tdd/e2e-controls-{time.strftime('%Y-%m-%d')}-r20"
# GenItem 最小模板 (从 web 源码 componentMap.ts 调研, 2026-06-17 v1)
# 完整 10 控件模板, 每个只保留渲染所需最小字段
GENITEM_TEMPLATES = {
"input": {
"__config__": {
"jnpfKey": "input", "label": "单行输入", "tag": "JnpfInput",
"tagIcon": "icon-ym icon-ym-generator-input", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "blur",
},
"style": {"width": "100%"},
"placeholder": "请输入",
"clearable": True, "maxlength": None, "showCount": False,
"readonly": False, "disabled": False,
},
"textarea": {
"__config__": {
"jnpfKey": "textarea", "label": "多行输入", "tag": "JnpfTextarea",
"tagIcon": "icon-ym icon-ym-generator-textarea", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "blur",
},
"style": {"width": "100%"},
"placeholder": "请输入",
"autoSize": {"minRows": 4, "maxRows": 4},
"clearable": True, "maxlength": None, "showCount": False,
"readonly": False, "disabled": False,
},
"inputNumber": {
"__config__": {
"jnpfKey": "inputNumber", "label": "数字输入", "tag": "JnpfInputNumber",
"tagIcon": "icon-ym icon-ym-generator-number", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False,
},
"style": {"width": "100%"},
"placeholder": "请输入",
"min": None, "max": None, "precision": None,
"readonly": False, "disabled": False,
},
"switch": {
"__config__": {
"jnpfKey": "switch", "label": "开关", "tag": "JnpfSwitch",
"tagIcon": "icon-ym icon-ym-generator-switch", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False,
},
"disabled": False,
},
"select": {
"__config__": {
"jnpfKey": "select", "label": "下拉选择", "tag": "JnpfSelect",
"tagIcon": "icon-ym icon-ym-generator-select", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False,
},
# 修复 #53: props.fieldNames 让 jnpf-select 知道读 option.label/value
# 来源 RSelect.vue:15 :field-names="activeData.props"
"props": {"label": "label", "value": "value"},
"placeholder": "请选择",
"options": [],
"multiple": False,
"disabled": False,
"clearable": True,
"filterable": False,
},
"radio": {
"__config__": {
"jnpfKey": "radio", "label": "单选框组", "tag": "JnpfRadio",
"tagIcon": "icon-ym icon-ym-generator-radio", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False,
},
# 修复 #54: radio 也用 activeData.props 读 option 字段
"props": {"label": "label", "value": "value"},
"options": [],
"disabled": False,
},
"checkbox": {
"__config__": {
"jnpfKey": "checkbox", "label": "多选框组", "tag": "JnpfCheckbox",
"tagIcon": "icon-ym icon-ym-generator-checkbox", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False,
},
# 修复 checkbox: 同 select/radio
"props": {"label": "label", "value": "value"},
"options": [],
"disabled": False,
},
"datePicker": {
"__config__": {
"jnpfKey": "datePicker", "label": "日期选择", "tag": "JnpfDatePicker",
"tagIcon": "icon-ym icon-ym-generator-date", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False,
},
"placeholder": "请选择",
"format": "yyyy-MM-dd",
"valueFormat": "yyyy-MM-dd",
"disabled": False,
},
"timePicker": {
"__config__": {
"jnpfKey": "timePicker", "label": "时间选择", "tag": "JnpfTimePicker",
"tagIcon": "icon-ym icon-ym-generator-time", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False,
},
"placeholder": "请选择",
"format": "HH:mm",
"valueFormat": "HH:mm",
"disabled": False,
},
"cascader": {
"__config__": {
"jnpfKey": "cascader", "label": "级联选择", "tag": "JnpfCascader",
"tagIcon": "icon-ym icon-ym-generator-cascader", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False,
},
# 修复 #55: cascader 多级用 children 字段
# 来源 RCascader.vue:22 :field-names="activeData.props"
"props": {"label": "label", "value": "value", "children": "children"},
"placeholder": "请选择",
"options": [],
"disabled": False,
"clearable": True,
},
# ===== v2 新增 10 控件模板 (2026-06-17) =====
# 1. colorPicker — 颜色选择 (jnpf-key: colorPicker)
# 来源: web/.../FormGenerator/src/helper/componentMap.ts colorPicker entry
"colorPicker": {
"__config__": {
"jnpfKey": "colorPicker", "label": "颜色选择", "tag": "JnpfColorPicker",
"tagIcon": "icon-ym icon-ym-generator-color", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "change",
},
"showAlpha": False,
"colorFormat": "hex",
"disabled": False,
},
# 2. rate — 评分 (a-rate, click stars)
"rate": {
"__config__": {
"jnpfKey": "rate", "label": "评分", "tag": "JnpfRate",
"tagIcon": "icon-ym icon-ym-generator-rate", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": 0,
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "change",
},
"count": 5,
"allowHalf": False,
"disabled": False,
},
# 3. slider — 滑块 (a-slider, click rail or drag)
"slider": {
"__config__": {
"jnpfKey": "slider", "label": "滑块", "tag": "JnpfSlider",
"tagIcon": "icon-ym icon-ym-generator-slider", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": 0,
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "change",
},
"style": {"width": "100%"},
"min": 0, "max": 100, "step": 1,
"disabled": False,
},
# 4. treeSelect — 下拉树形 (jnpf-tree-select)
"treeSelect": {
"__config__": {
"jnpfKey": "treeSelect", "label": "下拉树形", "tag": "JnpfTreeSelect",
"tagIcon": "icon-ym icon-ym-generator-tree", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "change",
"dataType": "static", "dictionaryType": "", "propsUrl": "", "propsName": "",
"useCache": True, "templateJson": [],
},
"props": {"label": "label", "value": "value", "children": "children"},
"placeholder": "请选择",
"options": [],
"multiple": False,
"clearable": True,
"filterable": True,
"disabled": False,
},
# 5. uploadImg — 图片上传 (a-upload, accept=image)
"uploadImg": {
"__config__": {
"jnpfKey": "uploadImg", "label": "图片上传", "tag": "JnpfUploadImg",
"tagIcon": "icon-ym icon-ym-generator-upload", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": [],
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "change",
},
"disabled": False,
"fileSize": 5, "sizeUnit": "MB", "limit": 3,
"accept": "image/*", "buttonText": "上传图片",
"showType": "button", # button / dragger
},
# 6. uploadFile — 文件上传 (a-upload, accept=*)
"uploadFile": {
"__config__": {
"jnpfKey": "uploadFile", "label": "文件上传", "tag": "JnpfUploadFile",
"tagIcon": "icon-ym icon-ym-generator-upload", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": [],
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "change",
},
"disabled": False,
"fileSize": 10, "sizeUnit": "MB", "limit": 5,
"accept": "*/*", "buttonText": "上传文件",
"showType": "button",
},
# 7. relationForm — 关联表单 (jnpf-relation-form, popup + table)
"relationForm": {
"__config__": {
"jnpfKey": "relationForm", "label": "关联表单", "tag": "JnpfRelationForm",
"tagIcon": "icon-ym icon-ym-generator-menu", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": "",
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "change",
"transferList": [],
},
"style": {"width": "100%"},
"placeholder": "请选择",
"modelId": "",
"relationField": "f_name",
"hasPage": False, "pageSize": 20,
"columnOptions": [
{"label": "名称", "value": "f_name", "width": 200}
],
},
# 8. userSelect — 用户选择 (jnpf-user-select, popup + user list)
"userSelect": {
"__config__": {
"jnpfKey": "userSelect", "label": "用户选择", "tag": "JnpfUserSelect",
"tagIcon": "icon-ym icon-ym-generator-user", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": [],
"defaultCurrent": False,
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "change",
},
"style": {"width": "100%"},
"placeholder": "请选择用户",
"ableRelation": False,
"multiple": True,
"selectType": "all", # all / custom / department / role / position / group
},
# 9. organizeSelect — 组织选择 (jnpf-organize-select, popup + tree)
"organizeSelect": {
"__config__": {
"jnpfKey": "organizeSelect", "label": "组织选择", "tag": "JnpfOrganizeSelect",
"tagIcon": "icon-ym icon-ym-generator-company", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": "",
"defaultCurrent": False,
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "change",
},
"style": {"width": "100%"},
"placeholder": "请选择组织",
"ableRelation": False,
"multiple": False,
"selectType": "department", # department / company / all
},
# 10. editor — 富文本 (jnpf-editor, contenteditable)
"editor": {
"__config__": {
"jnpfKey": "editor", "label": "富文本", "tag": "JnpfEditor",
"tagIcon": "icon-ym icon-ym-generator-rich-text", "showLabel": True,
"span": 24, "visibility": ["pc", "app"], "layout": "colFormItem",
"regList": [], "required": False, "labelWidth": None, "tableAlign": "left",
"tableFixed": "none", "className": [], "defaultValue": None,
"dragDisabled": False, "tableName": "", "noShow": False, "trigger": "blur",
},
"style": {"width": "100%"},
"placeholder": "请输入内容",
"disabled": False,
},
}
class ControlEngine:
def __init__(self, page: Page, config_path: str):
self.page = page
self.config = self._load_config(config_path)
self.results: List[Dict[str, Any]] = []
os.makedirs(f"{OUT_DIR}/imgs", exist_ok=True)
def _load_config(self, path: str) -> dict:
with open(path, encoding="utf-8") as f:
c = json.load(f)
# 2026-06-17 v2: 支持 20 控件 (v1=10 控件, v2=20 控件)
assert c.get("version") in ("v1", "v2"), f"unsupported version: {c.get('version')}"
assert len(c["controls"]) >= 10, f"expected >= 10 controls, got {len(c['controls'])}"
return c
def _step(self, s: str):
print(f"\n>>> {s}", flush=True)
def _add_result(self, jnpfKey: str, step: str, status: str, error: str = None):
r = {"jnpfKey": jnpfKey, "step": step, "status": status}
if error: r["error"] = error[:200]
self.results.append(r)
print(f" [{jnpfKey}] {step}: {status}" + (f" - {error[:80]}" if error else ""), flush=True)
def run_all(self) -> Dict[str, Any]:
"""主入口: 8 步"""
self._step("01_login_and_open_designer")
self._login_and_open_designer() # Task 3 实现
self._step("02_create_form_with_name")
form_name = self._create_form_with_name() # Task 3 实现
self._step("03_inject_widgets") # 替代原 drag (Task 4 实现)
try:
self._inject_widgets()
for ctrl in self.config["controls"]:
self._add_result(ctrl["jnpfKey"], "inject", "ok")
except Exception as e:
for ctrl in self.config["controls"]:
self._add_result(ctrl["jnpfKey"], "inject", "fail", str(e))
self._step("04_add_to_column_list")
self._add_all_to_column_list() # Task 5 实现
self._step("05_save_form")
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
# 修 #X6 (2026-06-17): drag inject 会丢控件 (实测 tddCtrl699499: 拖 20 控件, 入库仅 18),
# 改走 _replace_form_data_via_api 完整用 GenItem 模板重建 formData,
# 不依赖 drag 顺序, 100% 控件类型 + label + 字段名对齐
self._step("05.5_patch_options")
try:
self._replace_form_data_via_api(form_id)
except Exception as e:
print(f" ⚠ replace_form_data 失败, fallback patch_options: {e}", flush=True)
try:
self._patch_options_via_api(form_id)
except Exception as e2:
print(f" ⚠ patch_options fallback 失败: {e2}", flush=True)
self._step("06_release_and_mount")
self._release_and_mount(form_id) # Task 6 实现
self._step("07_user_end_fill")
self._user_end_fill_all_and_assert(form_name) # Task 7 实现 (修 #57: 传 form_name 给 API verify)
self._step("08_summary")
return self._summary()
# Task 3 实现: 复用 e2e_r3.py 单控件基线 1-4 步逻辑
def _login_and_open_designer(self):
"""登录 + 进 formDesigner + 点新建/表单 → 弹出 jnpf-full-modal"""
# 2026-06-17 v2 fix: 用 domcontentloaded 替代默认 load, 避免 JNPF SPA 资源加载超时
self.page.goto("http://nginx/jnpf_app_backend_tdd/login",
wait_until="domcontentloaded", timeout=60000)
self.page.wait_for_selector("#form_item_account", timeout=15000)
self.page.fill("#form_item_account", "admin")
self.page.fill("#form_item_password", "123456")
self.page.click("button:has-text('登 录')")
for i in range(20):
time.sleep(1)
has = self.page.evaluate("!!document.querySelector('#form_item_account')")
if not has:
print(f" ✓ 登录成功 i={i+1}s", flush=True)
break
time.sleep(2)
self.page.goto("http://nginx/jnpf_app_backend_tdd/onlineDev/formDesign",
wait_until="domcontentloaded", timeout=60000)
# 修 r10 冷启动: 页面 SPA 加载需时, 15s 偶尔不够
self.page.wait_for_selector(".vxe-table", timeout=60000)
time.sleep(2)
self.page.click("button:has-text('新建')")
time.sleep(1)
self.page.click(".ant-dropdown-menu-item:has-text('表单')")
self.page.wait_for_selector(".jnpf-full-modal", timeout=10000)
time.sleep(2)
def _create_form_with_name(self) -> str:
"""Step 1 基础设计: 填表名+编码+分类+数据连接 → 返回 form_name"""
form_name = f"{self.config['formPrefix']}{int(time.time())%1000000}"
self._fill_input_by_label("表单名称", form_name)
self._fill_input_by_label("表单编码", form_name)
try: self._select_dropdown("表单分类", "车辆管理")
except Exception as e: print(f" ⚠ 选分类: {e}", flush=True)
try: self._select_dropdown("数据连接", "默认数据库")
except Exception as e: print(f" ⚠ 选数据连接: {e}", flush=True)
return form_name
def _fill_input_by_label(self, label: str, value: str, scope: str = ".jnpf-full-modal"):
sel = f'{scope} .ant-form-item:has(label:text("{label}")) input, {scope} .ant-form-item:has(label:text("{label}")) textarea'
loc = self.page.locator(sel).first
loc.click(); time.sleep(0.1)
loc.press_sequentially(value, delay=20); time.sleep(0.3)
self.page.keyboard.press("Tab"); time.sleep(0.3)
def _select_dropdown(self, label: str, option_text: str, scope: str = ".jnpf-full-modal"):
sel = f'{scope} .ant-form-item:has(label:text("{label}")) .ant-select'
self.page.locator(sel).first.click(); time.sleep(0.6)
dd_sel = f'.ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item:has-text("{option_text}")'
self.page.wait_for_selector(dd_sel, timeout=5000)
self.page.click(dd_sel); time.sleep(0.6)
# 6 个 placeholder 方法 (后续 Task 实现)
def _inject_widgets(self):
"""1 次注入 10 控件到 formDesigner 内部 state (替代 30×10 次 drag)
修复 #44: 必须先点"下一步"到 step 2 (form design), FormGenerator 才会挂载
修复 #45: 生产 build 移除了 __vueParentComponent/__vnode.__vueComponent 标记,
改用真实 mouse drag (复用 e2e_r3.py 9 步基线)
"""
# 0. 先点"下一步" 从 step 1 → step 2 (form design, .jnpf-basic-generator 所在)
self.page.evaluate("""() => {
const modal = document.querySelector('.jnpf-full-modal');
if (!modal) return;
const btns = Array.from(modal.querySelectorAll('.jnpf-full-modal-header button'));
const next = btns.find(b => (b.innerText||'').trim().includes('下一步') && !b.disabled);
if (next) next.click();
}""")
time.sleep(3)
# 等 FormGenerator 真正挂载
self.page.wait_for_selector(".jnpf-basic-generator", timeout=10000)
# 1. 真实 mouse drag 每个控件 (生产 build 没有 __vnode/__vueParentComponent)
canvas = self.page.locator(".jnpf-full-modal .center-board.common-board").first
canvas_box = canvas.bounding_box()
ty = canvas_box["y"] + 200 # 落点 Y, 每次 +60 防止重叠
for idx, ctrl in enumerate(self.config["controls"]):
widget_label = ctrl["label"] # 如 "单行输入"
# 找左侧 widget 标签 (jnpf-left-board 内的 text 元素)
try:
src = self.page.get_by_text(widget_label, exact=True).first
src_box = src.bounding_box(timeout=3000)
except Exception:
# 兜底: locator has-text
src = self.page.locator(f'.jnpf-full-modal >> text="{widget_label}"').first
src_box = src.bounding_box(timeout=3000)
sx = src_box["x"] + src_box["width"]/2
sy = src_box["y"] + src_box["height"]/2
# 落点: 每次下移 60px, 避免重叠
tx = canvas_box["x"] + canvas_box["width"]/2 + (idx % 2) * 200
ty_i = canvas_box["y"] + 100 + (idx // 2) * 80
# 真实鼠标拖拽
self.page.mouse.move(sx, sy)
self.page.mouse.down()
for i in range(1, 16):
self.page.mouse.move(sx + (tx-sx)*i/15, sy + (ty_i-sy)*i/15, steps=2)
time.sleep(0.03)
self.page.mouse.move(tx, ty_i, steps=3)
time.sleep(0.2)
self.page.mouse.up()
time.sleep(0.8)
# 配控件标题 + 控件字段
try:
title_input = self.page.locator('.jnpf-full-modal .right-board.common-board .ant-form-item:has(label:text("控件标题")) input').first
title_input.click(); time.sleep(0.15)
title_input.press("Control+a"); title_input.press("Delete")
title_input.press_sequentially(ctrl["fieldLabel"], delay=15); time.sleep(0.2)
self.page.keyboard.press("Tab"); time.sleep(0.3)
field_input = self.page.locator('.jnpf-full-modal .right-board.common-board .ant-form-item:has(label:text("控件字段")) input').first
field_input.click(); time.sleep(0.15)
field_input.press("Control+a"); field_input.press("Delete")
field_input.press_sequentially(ctrl["fieldName"], delay=15); time.sleep(0.2)
self.page.keyboard.press("Tab"); time.sleep(0.3)
except Exception as e:
print(f" ⚠ [{ctrl['jnpfKey']}] 配字段失败: {e}", flush=True)
time.sleep(2)
# 修复 #53-#55 (2026-06-17 续): drag 后所有 options 转 {fullName, id} 格式
# 源码依据:
# - useDynamic.ts:148 addSelectItem() → {fullName, id}
# - useDynamic.ts:90-91 props.value='id', props.label='fullName'
# - DataProperties.vue:137-138 右面板读 element.fullName/id
# - RSelect.vue:15 :field-names="activeData.props"
self._transform_options_to_jnpf_shape()
def _transform_options_to_jnpf_shape(self):
"""把 drag-injected widgets 的 options 转成 JNPF canonical {fullName, id}
适用控件: select / radio / checkbox / cascader (4 个用 activeData.options 的)
cascader 多级递归处理 children
"""
OPTION_CONTROLS = {"select", "radio", "checkbox", "cascader", "treeSelect"}
def to_jnpf(opt):
"""单个 option: {label, value} → {fullName, id}; cascader children 递归"""
jnpf = {"fullName": opt.get("label", ""), "id": str(opt.get("value", ""))}
if "children" in opt and isinstance(opt["children"], list):
jnpf["children"] = [to_jnpf(c) for c in opt["children"]]
return jnpf
result = self.page.evaluate("""(args) => {
const OPTION_CONTROLS = args.controls;
const toJnpf = (opt) => {
const jnpf = {fullName: opt.label || '', id: String(opt.value ?? '')};
if (Array.isArray(opt.children)) jnpf.children = opt.children.map(toJnpf);
return jnpf;
};
// 找 drawingList: 先试 .jnpf-basic-generator setupState, 失败则遍历 .ant-form-item
const genEl = document.querySelector('.jnpf-basic-generator');
let widgets = null;
if (genEl && genEl.__vueParentComponent) {
const st = genEl.__vueParentComponent.setupState?.state;
widgets = st?.drawingList;
}
if (!widgets) {
// 兜底: 从画布读 .ant-form-item 的 __vModel__ (data-v key)
const items = document.querySelectorAll('.jnpf-basic-generator .ant-form-item');
// 这里不强求拿 drawingList, transform 由 Python 端处理
return {error: 'no reactive access, falling back', itemCount: items.length};
}
const transformed = [];
for (const w of widgets) {
if (!OPTION_CONTROLS.includes(w.__config__?.jnpfKey)) continue;
if (!Array.isArray(w.options)) continue;
w.options = w.options.map(toJnpf);
// 修正 props: 我们已转成 {fullName, id}, 让 JnpfSelect 知道怎么读
if (!w.props) w.props = {};
w.props.label = 'fullName';
w.props.value = 'id';
if (w.__config__.jnpfKey === 'cascader') {
w.props.children = 'children';
}
transformed.push({jnpfKey: w.__config__.jnpfKey, count: w.options.length});
}
return {transformed, total: widgets.length};
}""", {"controls": list(OPTION_CONTROLS)})
print(f" options transform: {result}", flush=True)
if "error" in result:
# 兜底: reactive 不可用, 跳过 (后续会暴露为 #53-#55)
print(f" ⚠ reactive access 失败: {result.get('error')}, options 未转换", flush=True)
def _add_all_to_column_list(self):
"""进 step 3 + 循环点隐藏 div 复选框 (复用 key-discoveries #3)"""
# 进 step 3
self.page.evaluate("""() => {
const modal = document.querySelector('.jnpf-full-modal');
const btns = Array.from(modal.querySelectorAll('.jnpf-full-modal-header button'));
const next = btns.find(b => (b.innerText||'').trim().includes('下一步') && !b.disabled);
if (next) next.click();
}""")
time.sleep(3)
# 循环点 10 个 checkbox (基于 label 文本匹配, 不是基于序号)
for ctrl in self.config["controls"]:
try:
self.page.evaluate(f"""() => {{
const modal = document.querySelector('.jnpf-full-modal');
const rightBoard = modal.querySelector('.right-board');
const allDivs = Array.from(rightBoard.querySelectorAll('.h-full'));
const fieldDiv = allDivs[1];
if (!fieldDiv) return;
const targetTable = fieldDiv.querySelector('.ant-table');
if (!targetTable) return;
const bodyCbs = Array.from(targetTable.querySelectorAll('.ant-table-tbody .ant-checkbox-input'));
const target = bodyCbs.find(c => c.closest('tr').innerText.includes('{ctrl["fieldLabel"]}'));
if (target && !target.checked) target.click();
}}""")
time.sleep(0.3)
self._add_result(ctrl["jnpfKey"], "columnList", "ok")
except Exception as e:
self._add_result(ctrl["jnpfKey"], "columnList", "fail", str(e))
def _save_form(self):
"""点保存 + 等 modal 关 (复用 e2e_r3.py 9 步)
修复 #48: 当前是 step 3, 走 columnDesignRef.getData → handleRequest (后端 POST)
修复 #48b: 即使后端保存成功, modal 也不自动关 (设计器模式) — 需手动点"关 闭"
"""
save_click = self.page.evaluate("""() => {
const modal = document.querySelector('.jnpf-full-modal');
const btns = Array.from(modal.querySelectorAll('.jnpf-full-modal-header button'));
const saveBtn = btns.find(b => (b.innerText||'').trim().includes('保 存') || (b.innerText||'').trim().includes('保存'));
if (!saveBtn || saveBtn.disabled) return {error: 'no save btn / disabled', disabled: saveBtn?.disabled};
saveBtn.click();
return {clicked: true};
}""")
print(f" click 保存: {save_click}", flush=True)
# 等后端保存完成 (toast 出现)
for delay in [1, 2, 3, 5, 8, 12]:
time.sleep(delay - (1 if delay == 1 else 1))
state = self.page.evaluate("""() => {
const messages = Array.from(document.querySelectorAll('.ant-message-notice-content, .ant-notification-notice')).map(e => e.innerText?.slice(0, 100));
const errs = Array.from(document.querySelectorAll('.ant-form-item-has-error, .jnpf-validate-popover, .ant-form-explain')).map(e => e.innerText?.slice(0, 100));
return {messages, errs};
}""")
if any('成功' in m or 'success' in m.lower() for m in state["messages"]):
print(f" ✓ 后端保存成功 (toast): {state['messages']}", flush=True)
# 现在手动点 "关 闭" 按钮
self.page.evaluate("""() => {
const modal = document.querySelector('.jnpf-full-modal');
const btns = Array.from(modal.querySelectorAll('.jnpf-full-modal-header button'));
const close = btns.find(b => (b.innerText||'').trim().includes('关 闭') || (b.innerText||'').trim().includes('关闭'));
if (close) close.click();
}""")
time.sleep(1)
return
if state["errs"]:
print(f" ⚠ validation errors: {state['errs']}", flush=True)
self.page.screenshot(path=f"{OUT_DIR}/imgs/05_save_blocked.png")
print(f" ⚠ Modal 未关, 状态: {state}", flush=True)
def _get_form_id(self, form_name: str) -> str:
"""用 dacli token 反查 form_id (form_name 通常等于 enCode)"""
with open("/home/ubuntu/ccWorkDir/.dacli-token/token.json") as f:
token = json.load(f)["token"]
try:
req = urllib.request.Request(
f"http://nginx/api/visualdev/Base?keyword={form_name}&currentPage=1&pageSize=5",
headers={"Authorization": token, "App-Code": self.config["appCode"]},
)
with urllib.request.urlopen(req, timeout=10) as r:
data = json.loads(r.read())
for f_item in (data.get("data") or {}).get("list") or []:
if f_item.get("enCode") == form_name:
return f_item.get("id")
except Exception as e:
print(f" ⚠ dacli token 查 form_id 失败: {e}", flush=True)
raise RuntimeError(f"form_id 未找到 (form_name={form_name})")
def _replace_form_data_via_api(self, form_id: str):
"""REST API 完整重建 formData + columnData (修 #X6, 2026-06-17)
背景: drag inject 会丢控件 (实测拖 20 控件, 入库仅 18),
而且 widget 类型与 label/field 不匹配 (slider 用了 treeSelect 的 "部门" label).
解决: 用 GENITEM_TEMPLATES + controls_config 100% 重建 fields + columnList,
PUT 回 form. 不依赖 drag 顺序.
字段顺序: 按 controls_config 顺序 (与 configSchema 一致)
字段类型: 从 GENITEM_TEMPLATES 取 (jnpfKey, tag, 所有属性)
字段 label: 用 ctrl["fieldLabel"] (中文化)
字段 vModel: 用 ctrl["fieldName"] (snake_case + f_ 前缀)
options: 复用 patch_options 的转换 (label/value → fullName/id)
"""
with open("/home/ubuntu/ccWorkDir/.dacli-token/token.json") as f:
token = json.load(f)["token"]
headers = {"Authorization": token, "App-Code": self.config["appCode"], "Content-Type": "application/json"}
# 1. GET 当前 form
try:
req = urllib.request.Request(
f"http://nginx/api/visualdev/Base/{form_id}",
headers=headers,
)
with urllib.request.urlopen(req, timeout=10) as r:
resp = json.loads(r.read())
data = resp.get("data") or {}
except Exception as e:
print(f" ⚠ GET form {form_id} 失败: {e}", flush=True)
return
# 2. 构建新 formData.fields (用 GENITEM_TEMPLATES 重建)
# 保留 formData 顶层结构 (popupType / classNames / labelWidth 等)
form_data_str = data.get("formData")
if not form_data_str:
print(f" ⚠ form {form_id} 无 formData 字段", flush=True)
return
try:
form_data = json.loads(form_data_str)
except Exception as e:
print(f" ⚠ formData JSON parse 失败: {e}", flush=True)
return
# 3. 重建 fields 列表 (按 controls_config 顺序)
new_fields = []
OPTION_CONTROLS = {"select", "radio", "checkbox", "cascader", "treeSelect"}
def to_jnpf_opt(o):
"""{label, value} → {fullName, id}, cascader children 递归"""
jnpf = {"fullName": o.get("label", ""), "id": str(o.get("value", ""))}
if isinstance(o.get("children"), list):
jnpf["children"] = [to_jnpf_opt(c) for c in o["children"]]
return jnpf
for ctrl in self.config["controls"]:
jk = ctrl["jnpfKey"]
if jk not in GENITEM_TEMPLATES:
print(f" ⚠ GenItem template 缺: {jk}, 跳过", flush=True)
continue
# 复制模板 (深拷贝避免污染)
field = json.loads(json.dumps(GENITEM_TEMPLATES[jk]))
# 覆盖 label / vModel / span
field["__config__"]["label"] = ctrl["fieldLabel"]
field["__vModel__"] = ctrl["fieldName"]
# 注入 options (select/radio/checkbox/cascader/treeSelect)
if jk in OPTION_CONTROLS:
schema_opts = (ctrl.get("configSchema") or {}).get("options")
if schema_opts:
field["options"] = [to_jnpf_opt(o) for o in schema_opts]
if not field.get("props"):
field["props"] = {}
field["props"]["label"] = "fullName"
field["props"]["value"] = "id"
if jk == "cascader" or jk == "treeSelect":
field["props"]["children"] = "children"
# 注入其他 schema 字段 (colorFormat, count, min/max, placeholder, etc.)
schema = ctrl.get("configSchema") or {}
for k, v in schema.items():
if k == "options":
continue # 已处理
if k in field:
field[k] = v
new_fields.append(field)
form_data["fields"] = new_fields
print(f" ✓ 重建 formData.fields: {len(new_fields)} 个 (来自 controls_config)", flush=True)
# 4. 重建 columnData.columnList (用同样的 fields, 简化字段)
new_column_list = []
for ctrl in self.config["controls"]:
jk = ctrl["jnpfKey"]
jnpf_key = jk # 与 v2 命名一致
# columnList 简版: 只保留渲染所需字段
col = {
"jnpfKey": jnpf_key,
"__config__": {
"jnpfKey": jnpf_key,
"label": ctrl["fieldLabel"],
"showLabel": True,
},
"__vModel__": ctrl["fieldName"],
"label": ctrl["fieldLabel"],
}
new_column_list.append(col)
column_data_str = data.get("columnData")
if column_data_str:
try:
column_data = json.loads(column_data_str)
except Exception:
column_data = {"columnList": [], "columnOptions": []}
else:
column_data = {"columnList": [], "columnOptions": []}
column_data["columnList"] = new_column_list
# columnOptions 也要更新 (用于 add 弹窗下拉)
column_data["columnOptions"] = new_column_list
print(f" ✓ 重建 columnData.columnList: {len(new_column_list)} 个", flush=True)
# 5. PUT 回写
data["formData"] = json.dumps(form_data, ensure_ascii=False)
data["columnData"] = json.dumps(column_data, ensure_ascii=False)
try:
req = urllib.request.Request(
f"http://nginx/api/visualdev/Base/{form_id}",
method="PUT",
headers=headers,
data=json.dumps(data, ensure_ascii=False).encode("utf-8"),
)
with urllib.request.urlopen(req, timeout=15) as r:
put_resp = json.loads(r.read())
print(f" PUT form: rc={put_resp.get('code')} msg={put_resp.get('msg', '')[:100]}", flush=True)
except Exception as e:
print(f" ⚠ PUT form 失败: {e}", flush=True)
def _patch_options_via_api(self, form_id: str):
"""REST API patch: GET formData → transform options to JNPF {fullName, id} → PUT
修 #53-#55 续 (Task 17): Vue reactive 在 prod build 不可用, 改用 REST API 修补.
触发时机: _save_form 之后, _release_and_mount 之前.
"""
OPTION_CONTROLS = {"select", "radio", "checkbox", "cascader", "treeSelect"}
def transform_options(field):
"""递归转换 field.options: {label, value} → {fullName, id}
同时设 props.label='fullName', props.value='id', cascader 加 props.children
注意: 后端 FieLdsModel.java:231 private String options;
options 存的是 JSON 字符串, 不是数组!
"""
if not isinstance(field, dict):
return
jnpf_key = (field.get("__config__") or {}).get("jnpfKey")
if jnpf_key not in OPTION_CONTROLS:
# 子表递归
children = (field.get("__config__") or {}).get("children")
if isinstance(children, list):
for c in children: transform_options(c)
return
# options 可能是 string (后端存的) 或 list (前端存的)
opts_raw = field.get("options")
if isinstance(opts_raw, str):
try: opts = json.loads(opts_raw)
except: opts = []
elif isinstance(opts_raw, list):
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 = []
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"
field["props"]["value"] = "id"
if jnpf_key == "cascader":
field["props"]["children"] = "children"
with open("/home/ubuntu/ccWorkDir/.dacli-token/token.json") as f:
token = json.load(f)["token"]
headers = {"Authorization": token, "App-Code": self.config["appCode"], "Content-Type": "application/json"}
# 1. GET 当前 form (含 formData JSON)
try:
req = urllib.request.Request(
f"http://nginx/api/visualdev/Base/{form_id}",
headers=headers,
)
with urllib.request.urlopen(req, timeout=10) as r:
resp = json.loads(r.read())
data = resp.get("data") or {}
except Exception as e:
print(f" ⚠ GET form {form_id} 失败: {e}", flush=True)
return
# 2. 解析 formData JSON, 遍历 fields
form_data_str = data.get("formData")
if not form_data_str:
print(f" ⚠ form {form_id} 无 formData 字段", flush=True)
return
try:
form_data = json.loads(form_data_str)
except Exception as e:
print(f" ⚠ formData JSON parse 失败: {e}", flush=True)
return
fields = form_data.get("fields", []) if isinstance(form_data, dict) else []
patched_count = 0
# 构建 vModel → config 控件 的查找表 (Task 17 review fix: designer-side inject 丢了 options,
# 需要从 controls_config.json 重新注入)
vmodel_to_ctrl = {c["fieldName"]: c for c in self.config["controls"]}
def inject_options_from_config(field):
"""如果 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
vmodel = field.get("__vModel__")
ctrl = vmodel_to_ctrl.get(vmodel)
if not ctrl: return
schema_opts = (ctrl.get("configSchema") or {}).get("options")
if not schema_opts: return
# 转换: {label, value} → {fullName, id}
def to_jnpf(o):
no = {"fullName": o.get("label", ""), "id": str(o.get("value", ""))}
if isinstance(o.get("children"), list):
no["children"] = [to_jnpf(c) for c in o["children"]]
return no
# 修 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"
if jk == "cascader":
field["props"]["children"] = "children"
print(f" [inject from config] {vmodel} ({jk}): +{len(schema_opts)} options", flush=True)
for f in fields:
# 1) 先从 config 注入缺失的 options
inject_options_from_config(f)
# 2) 然后 transform 已有 options
jk = (f.get("__config__") or {}).get("jnpfKey") if isinstance(f, dict) else None
had_opts_before = bool(jk in OPTION_CONTROLS and f.get("options"))
transform_options(f)
if had_opts_before or jk in OPTION_CONTROLS:
patched_count += 1
# 修 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)} 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}",
method="PUT",
headers=headers,
data=json.dumps(data, ensure_ascii=False).encode("utf-8"),
)
with urllib.request.urlopen(req, timeout=15) as r:
put_resp = json.loads(r.read())
print(f" PUT form: rc={put_resp.get('code')} msg={put_resp.get('msg', '')[:100]}", flush=True)
except Exception as e:
print(f" ⚠ PUT form 失败: {e}", flush=True)
def _release_and_mount(self, form_id: str):
"""发布 + 挂菜单 (走 dacli subprocess 加速, 浏览器兜底)
dacli v0.9 实测 flag 名:
- form release: 位置参数 <id>
- menu create: --formId, --pcParents (逗号分隔), --fullName
修复 #49: subprocess 设 cwd + DACLI_TOKEN_DIR env, 否则 dacli 找不到 token.json 触发 login → Account error
"""
import subprocess
dacli_cmd = ["npx", "tsx", "/home/ubuntu/ccWorkDir/dacli/src/cli.ts"]
parent = self.config["parentMenuId"]
prefix = self.config["formPrefix"]
env = {**os.environ, "DACLI_TOKEN_DIR": "/home/ubuntu/ccWorkDir/.dacli-token"}
# 1. 发布
try:
r = subprocess.run(
dacli_cmd + ["form", "release", form_id],
capture_output=True, text=True, timeout=60,
cwd="/home/ubuntu/ccWorkDir", env=env,
)
print(f" dacli form release: rc={r.returncode}", flush=True)
if r.returncode != 0:
print(f" stderr: {r.stderr[:300]}", flush=True)
self._add_result("_all", "release", "ok" if r.returncode == 0 else "fail",
None if r.returncode == 0 else (r.stderr or r.stdout)[:200])
except Exception as e:
print(f" ⚠ dacli release 失败: {e}", flush=True)
self._add_result("_all", "release", "fail", str(e))
# 2. 挂菜单 (修复 #47: --no-pc 是 bare boolean flag, 不传 = false=允许PC)
try:
r = subprocess.run(
dacli_cmd + ["menu", "create",
"--formId", form_id,
"--pcParents", str(parent),
"--fullName", f"{prefix}-列表"],
capture_output=True, text=True, timeout=60,
cwd="/home/ubuntu/ccWorkDir", env=env,
)
print(f" dacli menu create: rc={r.returncode}", flush=True)
if r.returncode != 0:
print(f" stderr: {r.stderr[:300]}", flush=True)
self._add_result("_all", "mount", "ok" if r.returncode == 0 else "fail",
None if r.returncode == 0 else (r.stderr or r.stdout)[:200])
except Exception as e:
print(f" ⚠ dacli menu create 失败: {e}", flush=True)
self._add_result("_all", "mount", "fail", str(e))
def _user_end_fill_all_and_assert(self, form_name: str = None):
"""用户端填 10 字段 + 提交 + 列表断言 (修复 #51: 不要硬 assert, 标记 list_assert status)
修 r10 run16: 整段 try/except 包裹, 防止列表断言 reload 超时让整个 e2e 崩溃
"""
try:
self._user_end_fill_inner(form_name)
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, form_name: str = None):
# 找用户端 URL (从 dacli menu list 反查)
menu_url = self._get_user_url()
if not menu_url:
print(" ⚠ 找不到用户端 URL, 跳过 user_end", flush=True)
return
self.page.goto(f"http://nginx/jnpf_app_{self.config['appCode']}/{menu_url}",
wait_until="domcontentloaded", timeout=60000)
time.sleep(5)
# 修 #X7 (2026-06-17): 等表格渲染 (空表也算) 再继续, 避免新增按钮没就绪
try:
self.page.wait_for_selector(".ant-table-tbody, .vxe-table--body", timeout=30000)
print(f" ✓ user-end 表格已渲染", flush=True)
except Exception as e:
print(f" ⚠ user-end 表格超时 (继续): {e}", flush=True)
# 修 #X8 (2026-06-17): 截图诊断 + 打印 body 摘要
try:
self.page.screenshot(path=f"{OUT_DIR}/imgs/07_userend_failed.png")
debug_info = self.page.evaluate("""() => ({
url: location.href,
title: document.title,
bodyClasses: document.body.className,
bodyText: (document.body.innerText || '').slice(0, 500),
tableCount: document.querySelectorAll('table').length,
btnCount: document.querySelectorAll('button').length,
hasLayout: !!document.querySelector('.jnpf-content-wrapper, .jnpf-main-layout, .layout-content, #app > div'),
})""")
print(f" 📷 截图: {OUT_DIR}/imgs/07_userend_failed.png", flush=True)
print(f" 🔍 诊断: {debug_info}", flush=True)
except Exception as de:
print(f" ⚠ 诊断失败: {de}", flush=True)
time.sleep(2)
# 点新增
add_btn = self.page.locator("button:has-text('新增')").first
if add_btn.count() == 0:
add_btn = self.page.locator("button:has-text('新 增')").first
if add_btn.count() == 0:
print(" ⚠ 找不到新增按钮, 跳过 user_end", flush=True)
return
add_btn.click()
time.sleep(2)
# 循环填 10 字段 (Task 8 提供 _fill_one_field_user_end)
for ctrl in self.config["controls"]:
try:
self._fill_one_field_user_end(ctrl)
self._add_result(ctrl["jnpfKey"], "user_end_fill", "ok")
except Exception as e:
self._add_result(ctrl["jnpfKey"], "user_end_fill", "fail", str(e))
# 提交 (修 #X5: 2026-06-17 先关残留 popover/dropdown, 避免干扰提交按钮)
# 1. 关闭所有残留 popover (colorPicker/cascader/treeSelect 等)
self.page.keyboard.press("Escape"); time.sleep(0.3)
self.page.keyboard.press("Escape"); time.sleep(0.3)
# 点 modal 标题位置 (cancel blur from 残留控件)
try:
self.page.locator(".ant-modal:not(.ant-modal-hidden) .ant-modal-header").first.click()
time.sleep(0.2)
except: pass
# 2. 找提交按钮 (优先 primary, 多 selector 兜底)
submit = None
for sel in [
".ant-modal:not(.ant-modal-hidden) .ant-modal-footer .ant-btn-primary:has-text('确 定')",
".ant-modal:not(.ant-modal-hidden) .ant-modal-footer .ant-btn-primary",
".ant-modal:not(.ant-modal-hidden) button:has-text('确 定')",
".ant-modal:not(.ant-modal-hidden) button:has-text('提交')",
]:
loc = self.page.locator(sel).last
if loc.count() > 0:
submit = loc
break
if submit is not None:
submit.click()
time.sleep(3)
# 修 r10 run17: 等待 modal 关闭
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) .ant-modal-footer .ant-btn-primary").last.click()
time.sleep(2)
except: pass
else:
print(" ⚠ 找不到提交按钮", flush=True)
# 列表断言 (修复 #51: 不再硬 assert, 记为结果; 修复 r10 run20 #57: 改用 API 验证, 不靠 DOM)
# 用户验证 tddCtrl688176 数据已成功添加, 列表 DOM 渲染有延迟, 直接查 API 更可靠
self.page.wait_for_timeout(2000)
# 用 API 查询刚提交的 form 数据 (POST /visualdev/Base/{id}/actions/List 拿 list)
api_ok, api_count = self._verify_data_via_api(form_name)
if api_ok and api_count >= 1:
self._add_result("_all", "list_assert", "ok", f"api count={api_count}")
# 顺便刷新页面让截图好看
try: self.page.reload(wait_until="domcontentloaded", timeout=10000)
except: pass
else:
# 兜底: DOM 查一次 (兼容性, 旧版 jnpf 可能 list 不会延迟)
try:
self.page.reload(wait_until="domcontentloaded", timeout=15000)
time.sleep(3)
except Exception as e:
print(f" ⚠ reload 超时: {e}", flush=True)
row_count = self.page.locator(".ant-table-tbody tr.ant-table-row").count()
print(f" DOM 列表行数: {row_count} (API: {api_count})", flush=True)
if row_count >= 1 or api_count >= 1:
self._add_result("_all", "list_assert", "ok", f"dom={row_count} api={api_count}")
else:
self._add_result("_all", "list_assert", "fail", f"dom=0 api={api_count}")
def _verify_data_via_api(self, form_name: str):
"""通过 API 验证刚提交的数据是否入库 (#57 修复)
先 GET /api/visualdev/Base 找 formId,
再 POST /api/visualdev/OnlineDev/{modelId}/List 查 list 行数 (修 #58: 正确路径是 OnlineDev/{modelId}/List 不是 Base/{id}/actions/List)
"""
try:
with open("/home/ubuntu/ccWorkDir/.dacli-token/token.json") as f:
token = json.load(f)["token"]
headers = {"Authorization": token, "App-Code": self.config["appCode"], "Content-Type": "application/json"}
# 1. GET formId (按 enCode = form_name 查)
req = urllib.request.Request(
f"http://nginx/api/visualdev/Base?keyword={urllib.parse.quote(form_name)}&currentPage=1&pageSize=5",
headers=headers,
)
with urllib.request.urlopen(req, timeout=10) as r:
resp = json.loads(r.read())
form_id = None
for f_item in (resp.get("data") or {}).get("list") or []:
if f_item.get("enCode") == form_name:
form_id = f_item.get("id")
break
if not form_id:
print(f" ⚠ API verify: 找不到 form_id for {form_name}", flush=True)
return False, 0
# 2. POST list 查数据 (修 #58: 正确路径是 /api/visualdev/OnlineDev/{modelId}/List, 不是 /api/visualdev/Base/{id}/actions/List)
req2 = urllib.request.Request(
f"http://nginx/api/visualdev/OnlineDev/{form_id}/List",
method="POST",
headers=headers,
data=json.dumps({"currentPage": 1, "pageSize": 10}).encode(),
)
with urllib.request.urlopen(req2, timeout=10) as r2:
list_resp = json.loads(r2.read())
list_data = list_resp.get("data") or {}
count = len(list_data.get("list") or [])
print(f" API list verify: form_id={form_id} count={count}", flush=True)
return True, count
except Exception as e:
print(f" ⚠ API verify 失败: {e}", flush=True)
return False, 0
def _get_user_url(self) -> str:
"""从菜单列表反查 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=120,
cwd="/home/ubuntu/ccWorkDir", env=env,
)
import re
m = re.search(r'"urlAddress"\s*:\s*"([^"]+)"', r.stdout)
if m: return m.group(1)
except Exception as e:
print(f" ⚠ dacli menu list 兜底失败: {e}", flush=True)
return None
def _fill_one_field_user_end(self, ctrl: dict):
"""按 fillMethod 分发填值 (修复 #50: 支持 fillOptionText / fillValue 两种键名;
修复 #52: 把 fieldLabel 注入 ue 让 fill 方法用 ant-form-item 限定)"""
ue = {**ctrl["userEnd"], "fieldLabel": ctrl.get("fieldLabel", "")}
method = ue["fillMethod"]
if method == "press_sequentially":
self._fill_press_sequentially(ue)
elif method == "select_option":
ue.setdefault("fillOptionText", ue.get("fillValue"))
self._fill_select_option(ue)
elif method == "click_radio":
ue.setdefault("fillOptionText", ue.get("fillValue"))
self._fill_click_radio(ue)
elif method == "click_checkbox":
self._fill_click_checkbox(ue)
elif method == "click_switch":
self._fill_click_switch(ue)
elif method == "date_picker":
self._fill_date_picker(ue)
elif method == "time_picker":
self._fill_time_picker(ue)
elif method == "cascader":
self._fill_cascader(ue)
# v2 新增 (2026-06-17)
elif method == "click_color_picker":
self._fill_color_picker(ue)
elif method == "click_rate_star":
self._fill_rate_star(ue)
elif method == "click_slider_rail":
self._fill_slider_rail(ue)
elif method == "click_tree_select":
self._fill_tree_select(ue)
elif method == "set_file_input_img":
self._fill_file_input(ue, kind="img")
elif method == "set_file_input_file":
self._fill_file_input(ue, kind="file")
elif method == "click_relation_form_popup":
self._fill_relation_form_popup(ue)
elif method == "click_user_select_popup":
self._fill_user_select_popup(ue)
elif method == "click_organize_select_popup":
self._fill_organize_select_popup(ue)
elif method == "editor_input":
self._fill_editor_input(ue)
else:
raise ValueError(f"unknown fillMethod: {method}")
# 8 种 fillMethod 实现 (修复 #52: 用 fieldLabel 限定 ant-form-item, 避免选错)
def _field_item(self, label: str) -> str:
"""返回 ant-form-item 的 CSS selector, 其 label 含指定文本"""
return f'.ant-modal .ant-form-item:has(.ant-form-item-label:has-text("{label}"))'
def _fill_press_sequentially(self, ue: dict):
"""input/textarea/inputNumber: 逐字符输入 (触发 antd onChange)"""
label = ue.get("fieldLabel", "")
sel = ue["fillSelector"]
# 优先按 fieldLabel 限定, 没有就直接用 selector
if label and "ant-modal" not in sel:
loc = self.page.locator(f'{self._field_item(label)} {sel}').first
else:
loc = self.page.locator(sel).first
loc.click(); time.sleep(0.2)
loc.press_sequentially(ue["fillValue"], delay=20); time.sleep(0.3)
self.page.keyboard.press("Tab"); time.sleep(0.3)
def _fill_select_option(self, ue: dict):
"""select: click → dropdown → click option text (按 fieldLabel 限定 ant-form-item)"""
label = ue.get("fieldLabel", "")
if label:
sel = f'{self._field_item(label)} .ant-select'
else:
sel = ue["fillSelector"]
self.page.locator(sel).first.click(); time.sleep(0.6)
opt_sel = f'.ant-select-dropdown:not(.ant-select-dropdown-hidden) .ant-select-item:has-text("{ue["fillOptionText"]}")'
self.page.wait_for_selector(opt_sel, timeout=5000)
self.page.click(opt_sel); time.sleep(0.6)
def _fill_click_radio(self, ue: dict):
"""radio: click radio wrapper 含指定文本 (按 fieldLabel 限定)"""
label = ue.get("fieldLabel", "")
if label:
sel = f'{self._field_item(label)} .ant-radio-wrapper:has-text("{ue["fillOptionText"]}")'
else:
sel = f'{ue["fillSelector"]}:has-text("{ue["fillOptionText"]}")'
loc = self.page.locator(sel).first
loc.click(); time.sleep(0.3)
def _fill_click_checkbox(self, ue: dict):
"""checkbox: 循环 click 多个 checkbox (按 fieldLabel 限定)
接受 fillOptionTexts (推荐) 或 fillValue (向后兼容, #53 review fix)
"""
label = ue.get("fieldLabel", "")
# Review #3 fix: 接受 fillOptionTexts (新) 或 fillValue (旧/兼容)
options = ue.get("fillOptionTexts") or ue.get("fillValue") or []
if isinstance(options, str):
options = [options]
for txt in options:
if label:
sel = f'{self._field_item(label)} .ant-checkbox-wrapper:has-text("{txt}")'
else:
sel = f'{ue["fillSelector"]}:has-text("{txt}")'
loc = self.page.locator(sel).first
loc.click(); time.sleep(0.3)
def _fill_click_switch(self, ue: dict):
"""switch: 检查 ant-switch-checked class, 点击切到目标状态 (按 fieldLabel 限定)"""
label = ue.get("fieldLabel", "")
if label:
sel = f'{self._field_item(label)} .ant-switch'
else:
sel = ue["fillSelector"]
sw = self.page.locator(sel).first
is_checked = sw.evaluate("el => el.classList.contains('ant-switch-checked')")
target = ue.get("fillValue", True)
if is_checked != target:
sw.click()
time.sleep(0.3)
def _fill_date_picker(self, ue: dict):
"""date picker: 直接 press_sequentially 输入日期 (JNPF 支持键盘输入, 按 fieldLabel 限定)"""
from datetime import datetime, timedelta
label = ue.get("fieldLabel", "")
if label:
sel = f'{self._field_item(label)} input'
else:
sel = ue["fillSelector"]
loc = self.page.locator(sel).first
loc.click(); time.sleep(0.3)
if ue["fillValue"] == "today+1":
val = (datetime.now() + timedelta(days=1)).strftime("%Y-%m-%d")
else:
val = ue["fillValue"]
loc.press_sequentially(val, delay=20); time.sleep(0.3)
self.page.keyboard.press("Enter"); time.sleep(0.3)
def _fill_time_picker(self, ue: dict):
"""time picker: press_sequentially 输入时间 (按 fieldLabel 限定)"""
label = ue.get("fieldLabel", "")
if label:
sel = f'{self._field_item(label)} input'
else:
sel = ue["fillSelector"]
loc = self.page.locator(sel).first
loc.click(); time.sleep(0.3)
loc.press_sequentially(ue["fillValue"], delay=20); time.sleep(0.3)
self.page.keyboard.press("Enter"); time.sleep(0.3)
def _fill_cascader(self, ue: dict):
"""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:
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:
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=5000)
self.page.click(panel_sel); time.sleep(0.4)
# ===== v2 新增 10 种 fill 方法实现 (2026-06-17) =====
def _fill_color_picker(self, ue: dict):
"""colorPicker: click trigger → popover panel → click confirm
来源 (jnpf/前端/jnpf-web-monorepo-framework/.../colorPicker/src/ColorPicker.vue):
- trigger: `<div class="ant-color-picker__trigger">` 在 `<a-popover class="jnpf-color-picker">` 内
- panel: `.ant-color-dropdown__main-wrapper` (SvPanel + HueSlider)
- 确认按钮: `.ant-color-dropdown__btns button:not(.ant-cancel-button)` (text=确 定)
"""
label = ue.get("fieldLabel", "")
if label:
sel = f'{self._field_item(label)} .jnpf-color-picker .ant-color-picker__trigger'
else:
sel = ue["fillSelector"]
# 1. 打开 color picker
loc = self.page.locator(sel).first
if loc.count() == 0:
raise RuntimeError(f"colorPicker trigger not found in {label}")
loc.click(); time.sleep(0.6)
# 2. 等 popover 出现
try:
self.page.wait_for_selector('.ant-color-dropdown__main-wrapper, .ant-color-picker-panel', timeout=5000)
except Exception:
# popover 用了 a-popover, 可能没立即可见, 再等 0.5s
time.sleep(0.5)
# 3. 输入 hex 值 (.ant-color-dropdown__value input)
hex_sel = '.ant-color-dropdown__value input'
if self.page.locator(hex_sel).count() > 0:
hex_loc = self.page.locator(hex_sel).first
hex_loc.click(); time.sleep(0.2)
hex_loc.press_sequentially(ue.get("fillValue", "#1890ff"), delay=20)
time.sleep(0.2)
self.page.keyboard.press("Enter"); time.sleep(0.3)
# 4. 点 .ant-color-dropdown__btns 内 text=确 定 按钮
confirm_sel = '.ant-color-dropdown__btns button:not(.ant-cancel-button)'
if self.page.locator(confirm_sel).count() > 0:
self.page.locator(confirm_sel).first.click(); time.sleep(0.4)
else:
# 兜底: text=确 定
try:
self.page.locator('.ant-color-dropdown__btns >> text=确 定').first.click(); time.sleep(0.4)
except: pass
def _fill_rate_star(self, ue: dict):
"""rate: click Nth star (a-rate → .ant-rate-star, 索引 0-based)
fillValue 是整数 (如 4 = 点第 4 颗星)
"""
label = ue.get("fieldLabel", "")
if label:
base = self._field_item(label)
else:
base = ".ant-modal"
# 找到该 field item 下的 .ant-rate
rate_sel = f'{base} .ant-rate'
if self.page.locator(rate_sel).count() == 0:
raise RuntimeError(f"rate not found in {label}")
stars = self.page.locator(f'{base} .ant-rate-star')
n = int(ue.get("fillValue", 1))
if stars.count() >= n:
stars.nth(n - 1).click() # 1-based → nth(0) = 第 1 颗
else:
stars.last.click()
time.sleep(0.3)
def _fill_slider_rail(self, ue: dict):
"""slider: click handle 拖到目标值
来源 (jnpf/前端/.../ui/src/components/slider/src/Slider.vue):
- wrapper: `<div class="jnpf-slider">` 包 `<Slider>` (a-slider)
- 渲染出 .ant-slider-rail / .ant-slider-handle
"""
label = ue.get("fieldLabel", "")
if label:
base = self._field_item(label)
else:
base = ".ant-modal"
# 1. 在 .jnpf-slider 内找 a-slider handle
handle_sel = f'{base} .jnpf-slider .ant-slider-handle'
if self.page.locator(handle_sel).count() == 0:
# 兜底: 旧路径
handle_sel = f'{base} .ant-slider-handle'
if self.page.locator(handle_sel).count() == 0:
raise RuntimeError(f"slider handle not found in {label}")
target = float(ue.get("fillValue", 50))
cfg = ue.get("configSchema") or {}
mn = float(cfg.get("min", 0))
mx = float(cfg.get("max", 100))
# 2. click handle focus
self.page.locator(handle_sel).first.click(); time.sleep(0.2)
# 3. End 跳 max → ArrowLeft (mx-target)/step 次
self.page.keyboard.press("End"); time.sleep(0.1)
step = float(cfg.get("step", 1))
diff_steps = int(round((mx - target) / step)) if step > 0 else 0
for _ in range(max(0, diff_steps)):
self.page.keyboard.press("ArrowLeft"); time.sleep(0.02)
time.sleep(0.3)
def _fill_tree_select(self, ue: dict):
"""treeSelect: click trigger (a-select) → tree dropdown → click tree node
来源 (jnpf/前端/.../ui/src/components/treeSelect/src/TreeSelect.vue):
- root: `<TreeSelect class="jnpf-tree-select">` (继承 ant-design-vue TreeSelect)
- trigger: `.ant-select-selector` (与 select 一致)
- dropdown: `.ant-tree-select-dropdown .ant-tree-treenode`
"""
label = ue.get("fieldLabel", "")
if label:
base = self._field_item(label)
else:
base = ".ant-modal"
# 1. click trigger
sel = f'{base} .jnpf-tree-select .ant-select-selector'
if self.page.locator(sel).count() == 0:
# 兜底: 没 jnpf 包装, 走 ant-tree-select
sel = f'{base} .ant-tree-select .ant-select-selector'
if self.page.locator(sel).count() == 0:
raise RuntimeError(f"treeSelect trigger not found in {label}")
self.page.locator(sel).first.click(); time.sleep(0.6)
# 2. 等 tree dropdown
dropdown_sel = '.ant-tree-select-dropdown:not(.ant-select-dropdown-hidden)'
try:
self.page.wait_for_selector(dropdown_sel, timeout=5000)
except Exception:
pass
# 3. 点节点
values = ue["fillValue"]
if isinstance(values, str):
values = [values]
for v in values:
node_sel = f'{dropdown_sel} .ant-tree-node-content-wrapper:has-text("{v}")'
if self.page.locator(node_sel).count() > 0:
self.page.locator(node_sel).first.click(); time.sleep(0.4)
else:
raise RuntimeError(f"tree node '{v}' not found")
def _fill_file_input(self, ue: dict, kind: str = "file"):
"""uploadImg / uploadFile: set_input_files 注入测试文件
来源:
- uploadImg: AUpload (ant-design-vue), 含标准 `input[type=file]`
- uploadFile: vue-simple-uploader, 用 UploaderButton, 没有标准 input
(web/apps/jnpf-web-apps-main/src/components/Jnpf/upload/src/UploadFile.vue)
修 #X1 (2026-06-17): uploadFile 改用 file_chooser 监听 + 点 button 触发
"""
import os
# 1. 准备测试文件
files_dir = f"{OUT_DIR}/files"
os.makedirs(files_dir, exist_ok=True)
if kind == "img":
test_file = f"{files_dir}/test_upload.png"
if not os.path.exists(test_file):
import base64
png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg=="
with open(test_file, "wb") as f:
f.write(base64.b64decode(png_b64))
else:
test_file = f"{files_dir}/test_upload.txt"
if not os.path.exists(test_file):
with open(test_file, "w", encoding="utf-8") as f:
f.write("test upload content\n")
label = ue.get("fieldLabel", "")
if label:
base = self._field_item(label)
else:
base = ".ant-modal"
if kind == "img":
# uploadImg: 标准 input[type=file] (AUpload)
input_sel = f'{base} input[type=file]'
file_input = self.page.locator(input_sel).first
if file_input.count() == 0:
raise RuntimeError(f"uploadImg file input not found in {label}")
file_input.set_input_files(test_file)
time.sleep(1.0)
else:
# uploadFile: vue-simple-uploader, 用 UploaderButton 触发 file chooser
# selector: 按钮 + UploaderBtn 内部 input
# 来源: UploaderBtn 渲染 `<input type="file" style="display:none">` 内部
# 多 selector 兜底
btn_sels = [
f'{base} .upload-file-container button', # a-button "上传文件"
f'{base} .uploader-btn', # UploaderBtn 包装
f'{base} .upload-file-container input[type=file]', # 内部 input
]
# 1) 优先直接找 input[type=file] (UploaderBtn 内部有隐藏 input)
input_in_container = f'{base} .upload-file-container input[type=file]'
if self.page.locator(input_in_container).count() > 0:
self.page.locator(input_in_container).first.set_input_files(test_file)
time.sleep(1.0)
return
# 2) 否则监听 filechooser, 点 button 触发
try:
with self.page.expect_file_chooser(timeout=5000) as fc_info:
for sel in btn_sels:
if self.page.locator(sel).count() > 0:
self.page.locator(sel).first.click(); time.sleep(0.3)
break
else:
raise RuntimeError(f"uploadFile button not found in {label}")
file_chooser = fc_info.value
file_chooser.set_files(test_file)
time.sleep(1.0)
except Exception as e:
raise RuntimeError(f"uploadFile file chooser failed: {e}")
def _fill_relation_form_popup(self, ue: dict):
"""relationForm: click a-select trigger → modal with table → select first row → 确 定
来源 (web/apps/jnpf-web-apps-main/src/components/Jnpf/relationForm/src/RelationForm.vue):
- trigger: `<a-select>` (默认 mode), 用 .ant-select-selector
- modal: `<AModal>` (popupType='dialog') 或 `<ADrawer>` (popupType='drawer')
- table: `<a-table>` with list data
注意: modelId 必填才有数据, 否则空弹窗 (能验证 click→modal 流程, 关闭兜底)
"""
label = ue.get("fieldLabel", "")
if label:
base = self._field_item(label)
# relationForm 用 .common-container 包 a-select
trigger_sels = [
f'{base} .common-container .ant-select-selector',
f'{base} .common-container-modal', # 已是 modal 不应再 click
]
else:
trigger_sels = [ue["fillSelector"]]
# 1. 找 trigger 并 click
clicked = False
for sel in trigger_sels:
if self.page.locator(sel).count() > 0:
self.page.locator(sel).first.click(); time.sleep(1.0)
clicked = True
break
if not clicked:
raise RuntimeError(f"relationForm trigger not found in {label}")
# 2. 等 modal/popup
modal_sel = '.ant-modal:not(.ant-modal-hidden) .ant-table, .ant-drawer:not(.ant-drawer-hidden) .ant-table'
try:
self.page.wait_for_selector(modal_sel, timeout=8000)
except Exception:
try:
self.page.wait_for_selector('.ant-modal:not(.ant-modal-hidden), .ant-drawer:not(.ant-drawer-hidden)', timeout=3000)
print(f" ⚠ relationForm modal opened but no table (modelId 未配?)", flush=True)
close_sel = '.ant-modal:not(.ant-modal-hidden) .ant-modal-close, .ant-drawer:not(.ant-drawer-hidden) .ant-drawer-close'
if self.page.locator(close_sel).count() > 0:
self.page.locator(close_sel).first.click(); time.sleep(0.3)
return
except Exception as e:
raise RuntimeError(f"relationForm modal not opened: {e}")
# 3. 点第一行 + 确定
row_sel = '.ant-modal:not(.ant-modal-hidden) .ant-table-tbody tr.ant-table-row, .ant-drawer:not(.ant-drawer-hidden) .ant-table-tbody tr.ant-table-row'
if self.page.locator(row_sel).count() > 0:
self.page.locator(row_sel).first.click(); time.sleep(0.4)
confirm_sel = '.ant-modal:not(.ant-modal-hidden) .ant-btn-primary:has-text("确 定"), .ant-drawer:not(.ant-drawer-hidden) .ant-btn-primary:has-text("确 定")'
if self.page.locator(confirm_sel).count() > 0:
self.page.locator(confirm_sel).first.click(); time.sleep(0.5)
else:
# 兜底: 任何 .ant-btn-primary
primary = '.ant-modal:not(.ant-modal-hidden) .ant-modal-footer .ant-btn-primary, .ant-drawer:not(.ant-drawer-hidden) .ant-drawer-footer .ant-btn-primary'
if self.page.locator(primary).count() > 0:
self.page.locator(primary).first.click(); time.sleep(0.5)
else:
close_sel = '.ant-modal:not(.ant-modal-hidden) .ant-modal-close, .ant-drawer:not(.ant-drawer-hidden) .ant-drawer-close'
if self.page.locator(close_sel).count() > 0:
self.page.locator(close_sel).first.click(); time.sleep(0.3)
def _fill_user_select_popup(self, ue: dict):
"""userSelect: click trigger (a-select OR a-button) → user modal → select first user → 确 定
来源 (web/.../Jnpf/organize/src/UserSelect.vue):
- trigger 模式1 (buttonType='button'): `<AButton>` 在 `.select-tag-list` 内
- trigger 模式2 (默认): `<Select>` (a-select) 用 .ant-select-selector
- modal: `<AModal class="common-select-modal">` title="选择用户"
- 内容: Tabs (用户/组织/岗位/角色) + 用户列表
修 #X2 (2026-06-17): 同时支持两种 trigger 模式
"""
label = ue.get("fieldLabel", "")
if label:
base = self._field_item(label)
trigger_sels = [
f'{base} .select-tag-list .ant-btn', # button mode
f'{base} .ant-select-selector', # a-select mode
f'{base} .user-select-trigger', # 兜底
]
else:
trigger_sels = [ue["fillSelector"]]
clicked = False
for sel in trigger_sels:
if self.page.locator(sel).count() > 0:
self.page.locator(sel).first.click(); time.sleep(1.0)
clicked = True
break
if not clicked:
raise RuntimeError(f"userSelect trigger not found in {label}")
# 2. 等弹窗 (选择用户 title)
popup_sel = '.ant-modal.common-select-modal:not(.ant-modal-hidden), .ant-drawer:not(.ant-drawer-hidden)'
try:
self.page.wait_for_selector(popup_sel, timeout=8000)
except Exception as e:
raise RuntimeError(f"userSelect popup not opened: {e}")
# 3. 点用户列表项 (select-pane-list__item 优先, 兜底 user-list-item)
item_sels = [
'.ant-modal.common-select-modal:not(.ant-modal-hidden) .select-pane-list__item',
'.ant-modal.common-select-modal:not(.ant-modal-hidden) .jnpf-user-list-item',
'.ant-modal.common-select-modal:not(.ant-modal-hidden) .ant-list-item',
'.ant-modal.common-select-modal:not(.ant-modal-hidden) .ant-tree-treenode',
]
clicked_item = False
for sel in item_sels:
if self.page.locator(sel).count() > 0:
self.page.locator(sel).first.click(); time.sleep(0.3)
clicked_item = True
break
if clicked_item:
confirm_sel = '.ant-modal.common-select-modal:not(.ant-modal-hidden) .ant-btn-primary:has-text("确 定")'
if self.page.locator(confirm_sel).count() > 0:
self.page.locator(confirm_sel).first.click(); time.sleep(0.5)
else:
# 没列表项可能需要切到用户 tab, 这里直接关闭
close_sel = '.ant-modal.common-select-modal:not(.ant-modal-hidden) .ant-modal-close'
if self.page.locator(close_sel).count() > 0:
self.page.locator(close_sel).first.click(); time.sleep(0.3)
def _fill_organize_select_popup(self, ue: dict):
"""organizeSelect: click trigger (a-select OR a-button) → org modal with tree → select node → 确 定
来源 (web/.../Jnpf/organize/src/OrganizeSelect.vue):
- trigger 模式1 (buttonType='button'): `<AButton>` 在 `.select-tag-list` 内
- trigger 模式2 (默认): `<Select>` (a-select) 用 .ant-select-selector
- modal: `<AModal class="common-select-modal">` title="选择组织"
- 内容: Tabs + BasicTree (组织树) 或 list (select-pane-list__item)
修 #X3 (2026-06-17): 同时支持两种 trigger 模式
"""
label = ue.get("fieldLabel", "")
if label:
base = self._field_item(label)
trigger_sels = [
f'{base} .select-tag-list .ant-btn',
f'{base} .ant-select-selector',
f'{base} .organize-select-trigger',
]
else:
trigger_sels = [ue["fillSelector"]]
clicked = False
for sel in trigger_sels:
if self.page.locator(sel).count() > 0:
self.page.locator(sel).first.click(); time.sleep(1.0)
clicked = True
break
if not clicked:
raise RuntimeError(f"organizeSelect trigger not found in {label}")
# 2. 等弹窗 (选择组织)
popup_sel = '.ant-modal.common-select-modal:not(.ant-modal-hidden), .ant-drawer:not(.ant-drawer-hidden)'
try:
self.page.wait_for_selector(popup_sel, timeout=8000)
except Exception as e:
raise RuntimeError(f"organizeSelect popup not opened: {e}")
# 3. 点 tree node 或 list item
node_sels = [
'.ant-modal.common-select-modal:not(.ant-modal-hidden) .select-pane-list__item', # list 模式
'.ant-modal.common-select-modal:not(.ant-modal-hidden) .ant-tree-treenode', # tree 模式
]
target = ue.get("fillValue")
clicked_item = False
for sel in node_sels:
if self.page.locator(sel).count() > 0:
if isinstance(target, str) and target:
matched = f'{sel}:has-text("{target}")'
if self.page.locator(matched).count() > 0:
self.page.locator(matched).first.click(); time.sleep(0.4)
clicked_item = True
break
self.page.locator(sel).first.click(); time.sleep(0.3)
clicked_item = True
break
if clicked_item:
confirm_sel = '.ant-modal.common-select-modal:not(.ant-modal-hidden) .ant-btn-primary:has-text("确 定")'
if self.page.locator(confirm_sel).count() > 0:
self.page.locator(confirm_sel).first.click(); time.sleep(0.5)
else:
close_sel = '.ant-modal.common-select-modal:not(.ant-modal-hidden) .ant-modal-close'
if self.page.locator(close_sel).count() > 0:
self.page.locator(close_sel).first.click(); time.sleep(0.3)
def _fill_editor_input(self, ue: dict):
"""editor: tinymce 富文本编辑器
来源 (jnpf/前端/.../ui/src/components/editor/src/Editor.vue):
- root: `<div class="jnpf-tinymce-container">`
- 内部: `<textarea :id="tinymceId">` (hidden, visibility:hidden) + tinymce iframe
- tinymce 渲染出 iframe.contentDocument.body (contenteditable)
修 #X4 (2026-06-17): 走 tinymce API 直接 setContent, 避免 iframe 跨域限制
兜底: 找 .tox-edit-area iframe
"""
label = ue.get("fieldLabel", "")
# 1. 找 tinymce 容器
if label:
base = self._field_item(label)
else:
base = ".ant-modal"
container_sels = [
f'{base} .jnpf-tinymce-container',
f'{base} .tox.tox-tinymce', # tinymce root
]
container = None
for sel in container_sels:
if self.page.locator(sel).count() > 0:
container = self.page.locator(sel).first
break
if container is None:
raise RuntimeError(f"editor container not found in {label}")
# 2. 解析 fillValue (HTML → text)
import re
raw = ue.get("fillValue", "test editor content")
# 把 <br/> 转 \n, 剥剩余 tag
text = raw.replace("<br/>", "\n").replace("<br>", "\n")
text = re.sub(r"<[^>]+>", "", text)
# 3. 优先用 tinymce API (在 main world 执行, 编辑器实例挂 window)
# tinymce 把实例存到 textarea 的 id, 通过 tinymce.get(id) 拿
try:
tid = container.locator("textarea").first.get_attribute("id")
except Exception:
tid = None
if tid:
ok = self.page.evaluate(f"""(args) => {{
const tinymce = window.tinymce;
if (!tinymce) return false;
const ed = tinymce.get(args.tid);
if (!ed) return false;
ed.setContent(args.text);
ed.fire('change');
ed.fire('blur');
return true;
}}""", {"tid": tid, "text": text})
if ok:
time.sleep(0.5)
return
# 4. 兜底: click 容器 + keyboard.type
# tinymce 内嵌 iframe, 先点容器, 然后 type 到当前 focus (tinymce 会接管)
try:
container.click(); time.sleep(0.5)
self.page.keyboard.press("Control+a"); time.sleep(0.2)
self.page.keyboard.press("Delete"); time.sleep(0.2)
self.page.keyboard.type(text, delay=20)
time.sleep(0.5)
except Exception as e:
raise RuntimeError(f"editor fallback type failed: {e}")
def _summary(self) -> dict:
ok = sum(1 for r in self.results if r["status"] == "ok")
fail = sum(1 for r in self.results if r["status"] == "fail")
return {"total": len(self.results), "ok": ok, "fail": fail, "results": self.results}