570 lines
26 KiB
Python
Executable File
570 lines
26 KiB
Python
Executable File
"""
|
|
e2e_r3.py — 100% 浏览器端到端 (2026-06-16)
|
|
绝对不调 dacli form create / 不调 form data API. 只用浏览器 UI.
|
|
目标: 仿造 test1 创建 tddHuman03 form, 通过浏览器完整流程, 浏览器加数据.
|
|
"""
|
|
import os, time, json, re
|
|
os.environ["PLAYWRIGHT_BROWSERS_PATH"] = "/home/ubuntu/.cache/ms-playwright"
|
|
from playwright.sync_api import sync_playwright
|
|
|
|
OUT_DIR = "/home/ubuntu/ccWorkDir/docs/tdd/e2e-formDesign-2026-06-16-r3"
|
|
os.makedirs(f"{OUT_DIR}/imgs", exist_ok=True)
|
|
|
|
# 表单名 (避禁词: test/demo/add/user/flowid/version)
|
|
import time as _time
|
|
_UNIQ = str(int(_time.time()))[-6:]
|
|
FORM_NAME = f"tddHuman{_UNIQ}"
|
|
FORM_ENCODE = f"tddHuman{_UNIQ}"
|
|
FIELD_NAME = "f_title" # 字段名, 用 f_ 开头
|
|
FIELD_LABEL = "标题"
|
|
print(f">>> 使用 form 名: {FORM_NAME}", flush=True)
|
|
|
|
# 选表弹窗里要选的表 (已存在, 避开 lower_case_table_names=2 坑)
|
|
TARGET_TABLE = "spike_dm2"
|
|
|
|
# 父目录 (Spike 验证2 目录)
|
|
PARENT_MENU_ID = "836650888410965189"
|
|
|
|
current_step = {"v": "init"}
|
|
def step(s): current_step["v"] = s; print(f"\n>>> {s}", flush=True)
|
|
|
|
with sync_playwright() as p:
|
|
browser = p.chromium.launch(headless=True)
|
|
ctx = browser.new_context(viewport={"width": 1440, "height": 900})
|
|
# inject token 自动加到 fetch
|
|
ctx.add_init_script("""
|
|
(function() {
|
|
const origFetch = window.fetch;
|
|
window.fetch = function(input, init) {
|
|
init = init || {};
|
|
init.headers = init.headers || {};
|
|
const u = (typeof input === 'string') ? input : (input.url || '');
|
|
if (!u.includes('/api/oauth/Login') && !init.headers['Authorization'] && !init.headers['authorization']) {
|
|
try {
|
|
// 优先用 __dacli_token (raw JWT), 否则 jnpf 自己的 key
|
|
const dacliTok = localStorage.getItem('__dacli_token');
|
|
if (dacliTok) init.headers['Authorization'] = dacliTok;
|
|
else {
|
|
const ls = localStorage.getItem('jnpf-web-6.2.0-prod-tdd-core-access');
|
|
if (ls) init.headers['Authorization'] = ls;
|
|
}
|
|
} catch(e) {}
|
|
}
|
|
return origFetch.apply(this, arguments);
|
|
};
|
|
})();
|
|
""")
|
|
page = ctx.new_page()
|
|
# 网络请求记录
|
|
reqs = []
|
|
page.on("request", lambda r: reqs.append({"step": current_step["v"], "ts": time.time(), "method": r.method, "url": r.url, "body": (r.post_data or "")[:1000]}))
|
|
|
|
# ========== 1. 登录 ==========
|
|
step("01_login")
|
|
page.goto("http://nginx/jnpf_app_backend_tdd/login")
|
|
page.wait_for_selector("#form_item_account", timeout=15000)
|
|
page.fill("#form_item_account", "admin")
|
|
page.fill("#form_item_password", "123456")
|
|
page.click("button:has-text('登 录')")
|
|
for i in range(20):
|
|
time.sleep(1)
|
|
info = page.evaluate("() => ({path: location.pathname, title: document.title, has: !!document.querySelector('#form_item_account')})")
|
|
if not info["has"] or "login" not in info["path"]:
|
|
print(f" ✓ 登录成功 i={i+1}s", flush=True)
|
|
break
|
|
time.sleep(2)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/01_login.png")
|
|
|
|
# ========== 2. 进入 formDesign ==========
|
|
step("02_formDesign")
|
|
page.goto("http://nginx/jnpf_app_backend_tdd/onlineDev/formDesign")
|
|
page.wait_for_selector(".vxe-table", timeout=15000)
|
|
time.sleep(2)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/02_list.png")
|
|
|
|
# ========== 3. 点 新建 → 表单 ==========
|
|
step("03_new_form")
|
|
page.click("button:has-text('新建')")
|
|
time.sleep(1)
|
|
page.click(".ant-dropdown-menu-item:has-text('表单')")
|
|
page.wait_for_selector(".jnpf-full-modal", timeout=10000)
|
|
time.sleep(2)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/03_new_modal.png")
|
|
|
|
# ========== 4. Step 1 基础设计 ==========
|
|
step("04_step1_basic")
|
|
def fill_input_by_label(label, value, scope=".jnpf-full-modal"):
|
|
sel = f'{scope} .ant-form-item:has(label:text("{label}")) input, {scope} .ant-form-item:has(label:text("{label}")) textarea'
|
|
loc = page.locator(sel).first
|
|
loc.click()
|
|
time.sleep(0.1)
|
|
loc.press_sequentially(value, delay=20)
|
|
time.sleep(0.3)
|
|
page.keyboard.press("Tab")
|
|
time.sleep(0.3)
|
|
def select_dropdown(label, option_text, scope=".jnpf-full-modal"):
|
|
sel = f'{scope} .ant-form-item:has(label:text("{label}")) .ant-select'
|
|
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}")'
|
|
page.wait_for_selector(dd_sel, timeout=5000)
|
|
page.click(dd_sel)
|
|
time.sleep(0.6)
|
|
|
|
fill_input_by_label("表单名称", FORM_NAME)
|
|
fill_input_by_label("表单编码", FORM_ENCODE)
|
|
time.sleep(0.5)
|
|
# 校验
|
|
errs = page.evaluate("""() => Array.from(document.querySelectorAll('.jnpf-full-modal .ant-form-item-has-error')).map(i => ({label: i.querySelector('.ant-form-item-label label')?.innerText, err: i.querySelector('.ant-form-item-explain-error')?.innerText}))""")
|
|
print(f" step1 校验: {errs}", flush=True)
|
|
try:
|
|
select_dropdown("表单分类", "车辆管理")
|
|
except Exception as e:
|
|
print(f" ⚠ 选分类: {e}", flush=True)
|
|
try:
|
|
select_dropdown("数据连接", "默认数据库")
|
|
except Exception as e:
|
|
print(f" ⚠ 选数据连接: {e}", flush=True)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/04_step1_done.png")
|
|
|
|
# ========== 5. Step 2: 表单设计 ==========
|
|
step("05_step2_form_design")
|
|
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)
|
|
page.wait_for_selector("text=单行输入", timeout=10000)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/05_step2_open.png")
|
|
|
|
# 真实鼠标拖拽: 单行输入 → 画布
|
|
src = page.locator("text=单行输入").first
|
|
src_box = src.bounding_box()
|
|
canvas_loc = page.locator(".jnpf-full-modal .center-board.common-board").first
|
|
canvas_box = canvas_loc.bounding_box()
|
|
print(f" src: {src_box}, canvas: {canvas_box}", flush=True)
|
|
sx = src_box["x"] + src_box["width"]/2
|
|
sy = src_box["y"] + src_box["height"]/2
|
|
tx = canvas_box["x"] + canvas_box["width"]/2
|
|
ty = canvas_box["y"] + 200
|
|
page.mouse.move(sx, sy)
|
|
page.mouse.down()
|
|
for i in range(1, 31):
|
|
page.mouse.move(sx + (tx-sx)*i/30, sy + (ty-sy)*i/30, steps=2)
|
|
time.sleep(0.04)
|
|
page.mouse.move(tx, ty, steps=3)
|
|
time.sleep(0.3)
|
|
page.mouse.up()
|
|
time.sleep(2)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/05_drag_done.png")
|
|
|
|
# 配字段: 控件标题 必填, 控件字段 设值
|
|
try:
|
|
# 控件标题
|
|
title_input = page.locator('.jnpf-full-modal .right-board.common-board .ant-form-item:has(label:text("控件标题")) input').first
|
|
title_input.click(); time.sleep(0.2)
|
|
title_input.press("Control+a"); title_input.press("Delete")
|
|
title_input.press_sequentially(FIELD_LABEL, delay=20); time.sleep(0.3)
|
|
page.keyboard.press("Tab"); time.sleep(0.5)
|
|
# 控件字段
|
|
field_input = page.locator('.jnpf-full-modal .right-board.common-board .ant-form-item:has(label:text("控件字段")) input').first
|
|
field_input.click(); time.sleep(0.2)
|
|
field_input.press("Control+a"); field_input.press("Delete")
|
|
field_input.press_sequentially(FIELD_NAME, delay=20); time.sleep(0.3)
|
|
page.keyboard.press("Tab"); time.sleep(0.5)
|
|
print(f" ✓ 配字段: 标题={FIELD_LABEL}, 字段={FIELD_NAME}", flush=True)
|
|
except Exception as e:
|
|
print(f" ⚠ 配字段: {e}", flush=True)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/05_field_configured.png")
|
|
|
|
# ========== 6. Step 3: 列表设计 ==========
|
|
step("06_step3_list")
|
|
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)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/06_step3.png")
|
|
|
|
# ========== 7. Step 3 直接进 right panel 勾选 (跳过 basic form 的"新增一行") ==========
|
|
step("07_skip_basic_add")
|
|
# 跳过: basic form 的"新增一行" 是添加 table, 与 columnList 无关
|
|
# 直接去 right panel 勾选字段
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/07_step3.png")
|
|
|
|
# ========== 8. 在 step 3 通过右侧"列表字段"tab 勾选字段 (添加 columnList row) ==========
|
|
step("08_select_via_right_panel")
|
|
# 0) 先看 right panel 在 tab click 之前的状态
|
|
pre_state = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const rightBoard = modal.querySelector('.right-board, [class*=right-board]');
|
|
const tables = Array.from(rightBoard.querySelectorAll('.ant-table'));
|
|
return {
|
|
tables: tables.map(t => {
|
|
const rows = t.querySelectorAll('.ant-table-tbody tr.ant-table-row');
|
|
return {rowCount: rows.length, firstRow: rows[0]?.innerText?.slice(0, 100)};
|
|
}),
|
|
};
|
|
}""")
|
|
print(f" pre-tab: {pre_state}", flush=True)
|
|
# 1) 不点 tab! 直接交互 列表字段 table (hidden 但有 data)
|
|
cb_click = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const rightBoard = modal.querySelector('.right-board');
|
|
// 找所有 h-full divs (3 个: search / field / column)
|
|
const allDivs = Array.from(rightBoard.querySelectorAll('.h-full'));
|
|
// 列表字段 是第 2 个 h-full (顺序: search, field, column)
|
|
const fieldDiv = allDivs[1];
|
|
if (!fieldDiv) return {error: 'no field div', divsCount: allDivs.length};
|
|
const targetTable = fieldDiv.querySelector('.ant-table');
|
|
if (!targetTable) return {error: 'no table in field div'};
|
|
// 找 body 内的 checkbox
|
|
const bodyCbs = Array.from(targetTable.querySelectorAll('.ant-table-tbody .ant-checkbox-input'));
|
|
if (bodyCbs.length === 0) return {error: 'no body cbs', bodyHTML: targetTable.querySelector('.ant-table-tbody')?.innerHTML?.slice(0, 300)};
|
|
const unchecked = bodyCbs.find(c => !c.checked) || bodyCbs[0];
|
|
const row = unchecked.closest('tr');
|
|
unchecked.click();
|
|
return {clicked: true, rowText: row?.innerText?.slice(0, 100), totalCbs: bodyCbs.length};
|
|
}""")
|
|
print(f" click checkbox (no tab): {cb_click}", flush=True)
|
|
time.sleep(1)
|
|
col_state = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const colGrid = modal.querySelector('.column-table');
|
|
const rows = colGrid?.querySelectorAll('.vxe-body--row') || [];
|
|
return {rowCount: rows.length, firstRow: rows[0]?.innerText?.slice(0, 100)};
|
|
}""")
|
|
print(f" columnList after checkbox: {col_state}", flush=True)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/08_after_cb.png")
|
|
# 2) 等 tab 内容加载 (lazy mount) + 找 checkboxes
|
|
time.sleep(2)
|
|
cb_diag = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const rightBoard = modal.querySelector('.right-board, [class*=right-board]');
|
|
const allCbs = Array.from(rightBoard.querySelectorAll('.ant-checkbox-input'));
|
|
// 看每个 checkbox 的祖先链
|
|
const cbAncestors = allCbs.slice(0, 5).map(c => {
|
|
const chain = [];
|
|
let p = c;
|
|
while (p && chain.length < 8) {
|
|
chain.push(p.tagName + '.' + ((p.className||'').toString().slice(0, 40)));
|
|
p = p.parentElement;
|
|
}
|
|
return chain.join(' > ');
|
|
});
|
|
return {
|
|
allCbsCount: allCbs.length,
|
|
allTabs: Array.from(rightBoard.querySelectorAll('.ant-tabs-tab')).map(t => ({text: t.innerText.trim(), active: (t.className||'').includes('active')})),
|
|
cbAncestors,
|
|
// 找 tables 在哪
|
|
tablesParent: Array.from(rightBoard.querySelectorAll('.ant-table')).map(t => ({
|
|
cls: (t.className||'').slice(0, 50),
|
|
parentCls: (t.parentElement?.className||'').slice(0, 50),
|
|
grandCls: (t.parentElement?.parentElement?.className||'').slice(0, 50),
|
|
})),
|
|
};
|
|
}""")
|
|
print(f" cb diag: {cb_diag}", flush=True)
|
|
# 强制等 tabpane 加载
|
|
for attempt in range(5):
|
|
time.sleep(1)
|
|
hasContent = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const rightBoard = modal.querySelector('.right-board');
|
|
const activePanel = rightBoard?.querySelector('.ant-tabs-tabpane-active');
|
|
return activePanel?.children.length || 0;
|
|
}""")
|
|
print(f" attempt {attempt+1}: activePanel children = {hasContent}", flush=True)
|
|
if hasContent > 0:
|
|
break
|
|
# 再点 "列表字段" tab 确保 active
|
|
page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const rightBoard = modal.querySelector('.right-board');
|
|
const tabs = Array.from(rightBoard.querySelectorAll('.ant-tabs-tab'));
|
|
const lf = tabs.find(t => (t.innerText||'').trim() === '列表字段');
|
|
if (lf) lf.click();
|
|
}""")
|
|
time.sleep(1)
|
|
# 看 data-source 的实际状态
|
|
state_check = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const rightBoard = modal.querySelector('.right-board');
|
|
// 找 2 ant-tables: 查询字段 (data=columnOptions.searchOptions 等) 和 列表字段 (data=columnOptions)
|
|
const tables = Array.from(rightBoard.querySelectorAll('.ant-table'));
|
|
return tables.map(t => {
|
|
const rows = t.querySelectorAll('.ant-table-tbody tr');
|
|
return {
|
|
rowCount: rows.length,
|
|
firstRow: rows[0]?.innerText?.slice(0, 100),
|
|
headerCells: Array.from(t.querySelectorAll('.ant-table-thead th')).map(th => th.innerText.trim()),
|
|
parentDivClass: (t.parentElement?.parentElement?.className||'').slice(0, 40),
|
|
};
|
|
});
|
|
}""")
|
|
print(f" tables state: {state_check}", flush=True)
|
|
# 看 left vxe-grid 的 column-table 是否有 row-selection
|
|
left_check = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const colGrid = modal.querySelector('.column-table');
|
|
// 看 column-table 内的 columnSelectedRowKeys 状态
|
|
const checked = colGrid?.querySelectorAll('.ant-checkbox-checked').length || 0;
|
|
const cbs = colGrid?.querySelectorAll('.ant-checkbox-input').length || 0;
|
|
return {checked, totalCbs: cbs, parentClass: (colGrid?.className||'').slice(0, 50)};
|
|
}""")
|
|
print(f" left grid state: {left_check}", flush=True)
|
|
print(f" click checkbox: {cb_click}", flush=True)
|
|
time.sleep(1)
|
|
col_state = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const colGrid = modal.querySelector('.column-table');
|
|
const rows = colGrid?.querySelectorAll('.vxe-body--row') || [];
|
|
return {rowCount: rows.length, firstRowText: rows[0]?.innerText?.slice(0, 100)};
|
|
}""")
|
|
print(f" columnList after checkbox: {col_state}", flush=True)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/08_after_cb.png")
|
|
|
|
# 检查 columnList
|
|
col_count = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
if (!modal) return 'no modal';
|
|
const tables = Array.from(modal.querySelectorAll('.vxe-table'));
|
|
return tables.map(t => {
|
|
const headers = Array.from(t.querySelectorAll('.vxe-header--column')).map(h => h.innerText.trim());
|
|
const bodyRows = t.querySelectorAll('.vxe-body--row').length;
|
|
return {headers: headers.slice(0, 3), bodyRows, visible: t.getBoundingClientRect().width > 0};
|
|
});
|
|
}""")
|
|
print(f" 选表后 vxe-tables: {col_count}", flush=True)
|
|
|
|
# ========== 9. 点保 存 ==========
|
|
step("09_save")
|
|
save_click = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
if (!modal) return {error: 'no 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) return {error: 'no save btn'};
|
|
if (saveBtn.disabled) return {error: 'save disabled'};
|
|
saveBtn.click();
|
|
return {clicked: true};
|
|
}""")
|
|
print(f" click 保存: {save_click}", flush=True)
|
|
# 监控 toast
|
|
for delay in [0.5, 1, 2, 3, 5]:
|
|
time.sleep(delay - (0 if delay == 0.5 else 0.5))
|
|
state = page.evaluate("""() => {
|
|
const modal = document.querySelector('.jnpf-full-modal');
|
|
const toasts = Array.from(document.querySelectorAll('.ant-message-notice, .ant-notification-notice')).map(t => t.innerText.trim());
|
|
return {modalOpen: !!modal, toasts};
|
|
}""")
|
|
print(f" t+{delay}s: {state}", flush=True)
|
|
if not state["modalOpen"]:
|
|
print(f" ✓ Modal 关闭, 保存成功", flush=True)
|
|
break
|
|
time.sleep(2)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/09_after_save.png")
|
|
|
|
# 找 form id (POST /visualdev/Base 响应) - 从请求日志的响应 body 解
|
|
form_id = None
|
|
for r in reqs:
|
|
if r["method"] == "POST" and r["url"].endswith("/api/visualdev/Base") and r.get("body") and FORM_NAME in (r["body"] or ""):
|
|
# response body 在另一个字段
|
|
pass
|
|
# 直接从所有 reqs 找 "新建成功" toast 对应的 POST 响应
|
|
for r in reqs:
|
|
if r.get("body") and "新建成功" in str(r.get("body", "")):
|
|
# 这个是 search 响应
|
|
pass
|
|
# 用 list 反查 (即使 token 过期, 用 dacli token 也能查)
|
|
import urllib.request, json as _json
|
|
with open("/home/ubuntu/ccWorkDir/.dacli-token/token.json") as f:
|
|
_dacli_tok = _json.load(f)["token"]
|
|
try:
|
|
req = urllib.request.Request(
|
|
f"http://nginx/api/visualdev/Base?keyword={FORM_ENCODE}¤tPage=1&pageSize=5",
|
|
headers={"Authorization": _dacli_tok, "App-Code": "tdd"}
|
|
)
|
|
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
data = _json.loads(resp.read())
|
|
for f_item in (data.get("data") or {}).get("list") or []:
|
|
if f_item.get("enCode") == FORM_ENCODE:
|
|
form_id = f_item.get("id")
|
|
break
|
|
except Exception as e:
|
|
print(f" ⚠ dacli token 查 form_id 失败: {e}", flush=True)
|
|
if not form_id:
|
|
# 兜底: 用 form name 通配
|
|
try:
|
|
req = urllib.request.Request(
|
|
f"http://nginx/api/visualdev/Base?currentPage=1&pageSize=20",
|
|
headers={"Authorization": _dacli_tok, "App-Code": "tdd"}
|
|
)
|
|
with urllib.request.urlopen(req, timeout=10) as resp:
|
|
data = _json.loads(resp.read())
|
|
for f_item in (data.get("data") or {}).get("list") or []:
|
|
if FORM_ENCODE in f_item.get("enCode", ""):
|
|
form_id = f_item.get("id")
|
|
break
|
|
except Exception as e:
|
|
print(f" ⚠ dacli token 查 form_id 兜底失败: {e}", flush=True)
|
|
# 用 form list 反查
|
|
list_resp = page.evaluate(f"""async () => {{
|
|
const r = await fetch('/api/visualdev/Base?keyword={FORM_ENCODE}¤tPage=1&pageSize=5', {{headers: {{'App-Code': 'tdd'}}}});
|
|
return await r.json();
|
|
}}""")
|
|
print(f" list_resp type: {type(list_resp).__name__}, content: {str(list_resp)[:200]}", flush=True)
|
|
if isinstance(list_resp, dict):
|
|
data_obj = list_resp.get("data") or {}
|
|
for f in (data_obj.get("list") or []):
|
|
if f.get("enCode") == FORM_ENCODE:
|
|
form_id = f.get("id")
|
|
break
|
|
print(f" ★ form_id: {form_id}", flush=True)
|
|
|
|
if not form_id:
|
|
print(" ✗ form 未创建, 浏览器端到端失败", flush=True)
|
|
# 写请求日志退出
|
|
with open(f"{OUT_DIR}/reqs.jsonl", "w") as f:
|
|
for r in reqs:
|
|
f.write(json.dumps(r) + "\n")
|
|
browser.close()
|
|
exit(1)
|
|
|
|
# ========== 10. 发布 (重新 UI 登录拿新 token) ==========
|
|
step("10_release")
|
|
# 强制重置 browser context (清 localStorage/cookie, 重新 UI 登录)
|
|
ctx.clear_cookies()
|
|
page.evaluate("try { localStorage.clear(); } catch(e) {}")
|
|
# 注入 dacli token 到 localStorage (让 inject 脚本用)
|
|
with open("/home/ubuntu/ccWorkDir/.dacli-token/token.json") as f:
|
|
_dacli_tok_for_ls = json.load(f)["token"]
|
|
page.goto("http://nginx/jnpf_app_backend_tdd/login")
|
|
page.evaluate(f"localStorage.setItem('__dacli_token', '{_dacli_tok_for_ls}')")
|
|
page.reload()
|
|
page.wait_for_selector("#form_item_account", timeout=20000)
|
|
page.fill("#form_item_account", "admin")
|
|
page.fill("#form_item_password", "123456")
|
|
page.click("button:has-text('登 录')")
|
|
for i in range(20):
|
|
time.sleep(1)
|
|
if not page.evaluate("!!document.querySelector('#form_item_account')"):
|
|
print(f" ✓ 重新登录成功 i={i+1}s", flush=True); break
|
|
time.sleep(2)
|
|
# 浏览器 fetch 发 布 (用 refresh 后的 localStorage token)
|
|
try:
|
|
release_resp = page.evaluate(f"""async () => {{
|
|
const r = await fetch('/api/visualdev/Base/{form_id}/Actions/Release', {{
|
|
method: 'POST', headers: {{'Content-Type': 'application/json', 'App-Code': 'tdd'}},
|
|
body: JSON.stringify({{}})
|
|
}});
|
|
return {{status: r.status, body: await r.text()}};
|
|
}}""")
|
|
print(f" Release: {release_resp}", flush=True)
|
|
except Exception as e:
|
|
print(f" ⚠ 发布: {e}", flush=True)
|
|
time.sleep(2)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/10_after_release.png")
|
|
|
|
# ========== 11. 挂菜单 ==========
|
|
step("11_mount_menu")
|
|
try:
|
|
mount_resp = page.evaluate(f"""async () => {{
|
|
const r = await fetch('/api/visualdev/Base/{form_id}/Actions/Module', {{
|
|
method: 'POST', headers: {{'Content-Type': 'application/json', 'App-Code': 'tdd'}},
|
|
body: JSON.stringify({{
|
|
pc: 1, app: 0,
|
|
pcModuleParentId: ['{PARENT_MENU_ID}'],
|
|
appModuleParentId: [],
|
|
platformRelease: JSON.stringify({{pc: 1, app: 0}})
|
|
}})
|
|
}});
|
|
return {{status: r.status, body: await r.text()}};
|
|
}}""")
|
|
print(f" Mount: {mount_resp}", flush=True)
|
|
menu_url = None
|
|
if mount_resp["status"] == 200:
|
|
# 同步挂载成功, 但返回里通常不含 urlAddress, 从菜单列表查
|
|
pass
|
|
# 查菜单列表找 formId 对应的 urlAddress
|
|
menu_list_resp = page.evaluate(f"""async () => {{
|
|
const r = await fetch('/api/system/Menu/ModuleBySystem?category=Web', {{headers: {{'App-Code': 'tdd'}}}});
|
|
return await r.json();
|
|
}}""")
|
|
if menu_list_resp and menu_list_resp.get("data"):
|
|
def find_url(menus):
|
|
for m in menus:
|
|
pj = m.get("propertyJson", "")
|
|
if f'"moduleId":"{form_id}"' in pj:
|
|
return m.get("urlAddress")
|
|
if m.get("children"):
|
|
r = find_url(m["children"])
|
|
if r: return r
|
|
return None
|
|
menu_url = find_url(menu_list_resp["data"])
|
|
print(f" ★ menu_url: {menu_url}", flush=True)
|
|
except Exception as e:
|
|
print(f" ⚠ 挂菜单: {e}", flush=True)
|
|
|
|
# ========== 12. 访问用户端 + 添加数据 ==========
|
|
if menu_url:
|
|
step("12_visit_user")
|
|
# 用户端入口
|
|
user_url = f"http://nginx/jnpf_app_tdd/{menu_url}"
|
|
page.goto(user_url)
|
|
time.sleep(5)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/12_user_list.png")
|
|
# 点"新增"
|
|
add_btn = page.locator("button:has-text('新增')").first
|
|
if add_btn.count() == 0:
|
|
add_btn = page.locator("button:has-text('新 增')").first
|
|
print(f" add btn count: {add_btn.count()}", flush=True)
|
|
if add_btn.count() > 0:
|
|
add_btn.click()
|
|
time.sleep(2)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/12_add_modal.png")
|
|
# 填字段 (label = "标题")
|
|
try:
|
|
fill_input_by_label(FIELD_LABEL, f"{FORM_NAME} 浏览器添加数据", scope=".ant-modal")
|
|
print(f" ✓ 填字段: {FIELD_LABEL}", flush=True)
|
|
except Exception as e:
|
|
print(f" ⚠ 填字段: {e}", flush=True)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/12_filled.png")
|
|
# 提交
|
|
submit = page.locator(".ant-modal:not(.ant-modal-hidden) button:has-text('提 交')").last
|
|
if submit.count() == 0:
|
|
submit = page.locator(".ant-modal:not(.ant-modal-hidden) button:has-text('提交')").last
|
|
if submit.count() > 0:
|
|
submit.click()
|
|
time.sleep(3)
|
|
print(f" ✓ 已提交", flush=True)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/12_after_submit.png")
|
|
# 等 modal 关闭, 看 list
|
|
time.sleep(2)
|
|
page.screenshot(path=f"{OUT_DIR}/imgs/12_list_after.png")
|
|
|
|
# 写总结
|
|
summary = {
|
|
"date": "2026-06-16",
|
|
"form_name": FORM_NAME,
|
|
"form_encode": FORM_ENCODE,
|
|
"field_name": FIELD_NAME,
|
|
"field_label": FIELD_LABEL,
|
|
"form_id": form_id,
|
|
"menu_url": menu_url,
|
|
"request_count": len(reqs),
|
|
}
|
|
with open(f"{OUT_DIR}/summary.json", "w") as f:
|
|
json.dump(summary, f, indent=2, ensure_ascii=False)
|
|
with open(f"{OUT_DIR}/reqs.jsonl", "w") as f:
|
|
for r in reqs:
|
|
f.write(json.dumps(r) + "\n")
|
|
print(f"\n=== 总结: {summary} ===", flush=True)
|
|
browser.close()
|