409 lines
15 KiB
Python
409 lines
15 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
jnpf 平台 - 通用操作封装
|
|
可复用的功能脚本
|
|
|
|
配置通过环境变量:
|
|
- JNPF_BASE_URL: 基础URL (默认从 JNPF_HOST 和 JNPF_APP_CODE 构建)
|
|
- JNPF_APP_CODE: 应用代码 (如 dr, workSystem)
|
|
- JNPF_USERNAME: 用户名
|
|
- JNPF_PASSWORD: 密码
|
|
- JNPF_TEMP_DIR: 临时目录
|
|
"""
|
|
from playwright.sync_api import sync_playwright
|
|
import os
|
|
import json
|
|
import time
|
|
from typing import List, Dict, Optional
|
|
|
|
from config import get_config, get_login_url, BASE_URL, TEMP_DIR, USERNAME, PASSWORD
|
|
|
|
|
|
class JnpfClient:
|
|
"""jnpf 平台通用操作封装"""
|
|
|
|
def __init__(self, app_code: str = None, base_url: str = None, headless: bool = True):
|
|
"""
|
|
初始化客户端
|
|
|
|
Args:
|
|
app_code: 应用代码,如 dr, workSystem。如果提供将构建设置URL。
|
|
base_url: 直接指定基础URL,优先级高于 app_code。
|
|
headless: 是否无头模式运行。
|
|
"""
|
|
self.config = get_config()
|
|
self.headless = headless
|
|
self.browser = None
|
|
self.page = None
|
|
|
|
# Determine URL
|
|
if base_url:
|
|
self.base_url = base_url
|
|
elif app_code:
|
|
host = os.environ.get("JNPF_HOST", "192.168.1.18:13880")
|
|
self.base_url = f"http://{host}/jnpf_app_{app_code}"
|
|
else:
|
|
self.base_url = BASE_URL
|
|
|
|
self.login_url = f"{self.base_url}/login"
|
|
|
|
def __enter__(self):
|
|
self.p = sync_playwright().start()
|
|
self.browser = self.p.chromium.launch(headless=self.headless)
|
|
self.page = self.browser.new_page()
|
|
return self
|
|
|
|
def __exit__(self, *args):
|
|
if self.browser:
|
|
self.browser.close()
|
|
if self.p:
|
|
self.p.stop()
|
|
|
|
def login(self, username: str = None, password: str = None) -> bool:
|
|
"""
|
|
登录(浏览器自动化方式)
|
|
|
|
注意:由于JNPF前端密码加密机制,直接使用浏览器自动化可能失败。
|
|
如失败,请使用 login_via_api() 方法。
|
|
"""
|
|
try:
|
|
self.page.goto(self.login_url)
|
|
self.page.wait_for_load_state('domcontentloaded')
|
|
|
|
username = username or self.config["username"]
|
|
password = password or self.config["password"]
|
|
|
|
self.page.fill('#form_item_account', username)
|
|
self.page.fill('#form_item_password', password)
|
|
self.page.click('button:has-text("登 录")')
|
|
self.page.wait_for_url("**/home**", timeout=15000)
|
|
self.page.wait_for_load_state('networkidle')
|
|
return True
|
|
except Exception as e:
|
|
print(f"登录失败: {e}")
|
|
return False
|
|
|
|
def login_via_api(self, encrypted_password: str = None) -> bool:
|
|
"""
|
|
通过API登录并注入token到浏览器
|
|
|
|
JNPF前端对密码做了加密,浏览器自动化登录失败时使用此方法。
|
|
|
|
Args:
|
|
encrypted_password: 预加密的密码(96字符)。如不提供,使用配置中的密码。
|
|
|
|
Returns:
|
|
bool: 登录是否成功
|
|
"""
|
|
import requests
|
|
|
|
try:
|
|
# Determine base URL for API - extract from base_url like http://nginx:80/jnpf_app_tds
|
|
import re
|
|
match = re.search(r'(https?://[^/]+)', self.base_url)
|
|
api_base = match.group(1) if match else self.base_url
|
|
api_url = f"{api_base}/api/oauth/Login"
|
|
|
|
username = self.config["username"]
|
|
password = encrypted_password or self.config.get("password", "")
|
|
|
|
# If password is not 96 chars, it's not encrypted - this will fail
|
|
origin = "hash" if len(password) == 96 else "password"
|
|
|
|
# API login
|
|
resp = requests.post(api_url, data={
|
|
"account": username,
|
|
"password": password,
|
|
"origin": origin,
|
|
"grant_type": "password",
|
|
"timestamp": "0"
|
|
}, timeout=10)
|
|
|
|
if resp.status_code == 200:
|
|
data = resp.json()
|
|
if data.get("code") == 200:
|
|
token = data["data"]["token"]
|
|
# Inject token via localStorage
|
|
self.page.goto(self.login_url)
|
|
self.page.wait_for_load_state('domcontentloaded')
|
|
self.page.evaluate(f"""
|
|
() => {{
|
|
localStorage.setItem("token", "{token}");
|
|
localStorage.setItem("userInfo", JSON.stringify({{
|
|
userName: "{username}",
|
|
userId: "{data['data'].get('user_id', '')}"
|
|
}}));
|
|
}}
|
|
""")
|
|
self.page.reload()
|
|
self.page.wait_for_load_state('networkidle')
|
|
time.sleep(2)
|
|
return True
|
|
|
|
print(f"API login failed: {resp.status_code}")
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f"API login failed: {e}")
|
|
return False
|
|
|
|
def get_menu(self) -> List[Dict]:
|
|
"""获取左侧菜单结构"""
|
|
menu_data = self.page.evaluate('''
|
|
() => {
|
|
const menus = [];
|
|
document.querySelectorAll('.jnpf-sub-menu, .jnpf-sub-menu-content').forEach(subMenu => {
|
|
const titleEl = subMenu.querySelector('.jnpf-sub-menu-content__title');
|
|
const title = titleEl?.innerText?.trim() || '';
|
|
const items = [];
|
|
subMenu.querySelectorAll('.jnpf-menu-item').forEach(item => {
|
|
const text = item.innerText?.trim()?.split('\\n')[0];
|
|
if (text) items.push({ text });
|
|
});
|
|
if (title) menus.push({ category: title, items });
|
|
});
|
|
return menus;
|
|
}
|
|
''')
|
|
return menu_data
|
|
|
|
def click_menu(self, item_name: str, category: str = None):
|
|
"""
|
|
点击菜单项
|
|
|
|
Args:
|
|
item_name: 菜单项名称(支持部分匹配)
|
|
category: 分类名称(可选,扁平菜单结构下通常不需要)
|
|
"""
|
|
# jnpf menus are flat - directly click the item
|
|
# Use JS click for hidden elements
|
|
menu_item = self.page.locator(f'.jnpf-menu-item:has-text("{item_name}")').first
|
|
if menu_item.count() > 0:
|
|
self.page.evaluate('el => el.click()', menu_item.element_handle())
|
|
self.page.wait_for_load_state('networkidle')
|
|
self.page.wait_for_timeout(1000)
|
|
elif category:
|
|
# Fallback: expand category then click
|
|
self.page.locator(f'.jnpf-sub-menu-content:has-text("{category}")').first.click()
|
|
self.page.wait_for_timeout(800)
|
|
menu_item = self.page.locator(f'.jnpf-menu-item:has-text("{item_name}")').first
|
|
if menu_item.count() > 0:
|
|
self.page.evaluate('el => el.click()', menu_item.element_handle())
|
|
self.page.wait_for_load_state('networkidle')
|
|
self.page.wait_for_timeout(1000)
|
|
|
|
def screenshot(self, name: str, temp_dir: str = None):
|
|
"""截图"""
|
|
temp = temp_dir or self.config["temp_dir"]
|
|
self.page.screenshot(path=f"{temp}/{name}", full_page=True)
|
|
|
|
def wait_modal(self, timeout: int = 5000):
|
|
"""等待弹窗"""
|
|
self.page.wait_for_selector('.ant-modal', timeout=timeout)
|
|
|
|
def close_modal(self):
|
|
"""关闭弹窗"""
|
|
# Try multiple close methods
|
|
close_btn = self.page.locator('.ant-modal button:has-text("关 闭")')
|
|
if close_btn.count() > 0:
|
|
self.page.evaluate('el => el.click()', close_btn.first.element_handle())
|
|
self.page.wait_for_timeout(300)
|
|
return
|
|
|
|
cancel_btn = self.page.locator('.ant-modal button:has-text("取 消")')
|
|
if cancel_btn.count() > 0:
|
|
self.page.evaluate('el => el.click()', cancel_btn.first.element_handle())
|
|
self.page.wait_for_timeout(300)
|
|
return
|
|
|
|
self.page.keyboard.press('Escape')
|
|
self.page.wait_for_timeout(300)
|
|
|
|
@property
|
|
def crud(self):
|
|
"""CRUD 操作助手"""
|
|
return CrudHelper(self.page, self.config["temp_dir"])
|
|
|
|
|
|
class CrudHelper:
|
|
"""CRUD 操作辅助类"""
|
|
|
|
def __init__(self, page, temp_dir: str = None):
|
|
self.page = page
|
|
self.temp_dir = temp_dir or TEMP_DIR
|
|
|
|
def add(self, field_name: str, value: str, modal_selector: str = '.ant-modal'):
|
|
"""新增操作"""
|
|
add_btn = self.page.locator('button:has-text("新增")').first
|
|
self.page.evaluate('el => el.click()', add_btn.element_handle())
|
|
self.page.wait_for_selector(modal_selector, timeout=5000)
|
|
self.page.wait_for_timeout(500)
|
|
|
|
modal = self.page.locator(modal_selector)
|
|
|
|
# By ID first, then by placeholder
|
|
input_field = modal.locator(f'input#{field_name}')
|
|
if input_field.count() == 0:
|
|
input_field = modal.locator(f'input[placeholder*="{field_name}"]').first
|
|
if input_field.count() == 0:
|
|
input_field = modal.locator('input[placeholder="请输入"]').first
|
|
|
|
if input_field.count() > 0:
|
|
input_field.fill(value)
|
|
|
|
save_btn = modal.locator('button:has-text("确 定")').first
|
|
self.page.evaluate('el => el.click()', save_btn.element_handle())
|
|
self.page.wait_for_timeout(2000) # Wait instead of waiting for hidden
|
|
|
|
# Check for validation errors
|
|
errors = self.page.locator('.ant-form-item-explain-error').all()
|
|
if errors:
|
|
return False, [e.inner_text() for e in errors]
|
|
|
|
return True, []
|
|
|
|
def select_dropdown(self, label_text: str, option_index: int = 0):
|
|
"""
|
|
选择下拉框选项
|
|
|
|
Args:
|
|
label_text: 表单字段的label文字 (e.g., "授权类型")
|
|
option_index: 选项索引 (默认0=第一个)
|
|
|
|
Note: Uses mouse.click with bounding_box to trigger dropdown (page.evaluate click doesn't work)
|
|
"""
|
|
modal = self.page.locator('.ant-modal')
|
|
form_items = modal.locator('.ant-form-item').all()
|
|
|
|
for item in form_items:
|
|
try:
|
|
label = item.locator('.ant-form-item-label label')
|
|
if label.count() > 0 and label_text in label.inner_text():
|
|
select = item.locator('.ant-select')
|
|
if select.count() > 0:
|
|
box = select.bounding_box()
|
|
if box:
|
|
# Use mouse.click to trigger dropdown
|
|
self.page.mouse.click(box['x'] + box['width']/2, box['y'] + box['height']/2)
|
|
self.page.wait_for_timeout(800)
|
|
|
|
dropdown = self.page.locator('.ant-select-dropdown:visible')
|
|
if dropdown.count() > 0:
|
|
options = dropdown.first.locator('.ant-select-item').all()
|
|
if len(options) > option_index:
|
|
self.page.evaluate('el => el.click()', options[option_index].element_handle())
|
|
self.page.wait_for_timeout(300)
|
|
return True
|
|
except Exception as e:
|
|
print(f"Select dropdown failed: {e}")
|
|
return False
|
|
|
|
def edit(self, target_text: str, new_value: str):
|
|
"""编辑操作"""
|
|
rows = self.page.locator('.vxe-body--row').all()
|
|
for row in rows:
|
|
if target_text in row.inner_text():
|
|
edit_btn = row.locator('button:has-text("编辑")').first
|
|
self.page.evaluate('el => el.click()', edit_btn.element_handle())
|
|
self.page.wait_for_selector('.ant-modal', timeout=5000)
|
|
|
|
modal = self.page.locator('.ant-modal')
|
|
inputs = modal.locator('input[placeholder="请输入"]').all()
|
|
if inputs:
|
|
inputs[0].fill(new_value)
|
|
|
|
save_btn = modal.locator('button:has-text("确 定")').first
|
|
self.page.evaluate('el => el.click()', save_btn.element_handle())
|
|
self.page.wait_for_timeout(2000)
|
|
break
|
|
|
|
def delete(self, target_text: str):
|
|
"""删除操作"""
|
|
rows = self.page.locator('.vxe-body--row').all()
|
|
for row in rows:
|
|
if target_text in row.inner_text():
|
|
delete_btn = row.locator('button:has-text("删除")').first
|
|
self.page.evaluate('el => el.click()', delete_btn.element_handle())
|
|
self.page.wait_for_timeout(500)
|
|
|
|
confirm = self.page.locator('.ant-modal-confirm')
|
|
if confirm.count() > 0:
|
|
confirm_btn = confirm.locator('button:has-text("确 定")').first
|
|
self.page.evaluate('el => el.click()', confirm_btn.element_handle())
|
|
else:
|
|
self.page.locator('.ant-modal button:has-text("确 定")').first.click()
|
|
self.page.wait_for_timeout(1000)
|
|
break
|
|
|
|
|
|
def login_and_get_menu(app_code: str = None):
|
|
"""登录并获取菜单"""
|
|
with JnpfClient(app_code=app_code) as client:
|
|
if not client.login():
|
|
print("登录失败")
|
|
return None
|
|
|
|
menus = client.get_menu()
|
|
|
|
print("\n=== jnpf 菜单结构 ===")
|
|
for cat in menus:
|
|
print(f"\n【{cat['category']}】")
|
|
for item in cat['items']:
|
|
print(f" - {item['text']}")
|
|
|
|
return menus
|
|
|
|
|
|
def test_basic_crud(app_code: str = None, menu_item: str = "列表标签面板"):
|
|
"""测试基本CRUD流程"""
|
|
with JnpfClient(app_code=app_code) as client:
|
|
if not client.login():
|
|
return
|
|
|
|
client.click_menu(menu_item)
|
|
client.screenshot("crud_list.png")
|
|
|
|
print("\n=== 测试新增 ===")
|
|
if client.page.locator('button:has-text("新增")').count() > 0:
|
|
add_btn = client.page.locator('button:has-text("新增")').first
|
|
client.page.evaluate('el => el.click()', add_btn.element_handle())
|
|
client.wait_modal()
|
|
client.screenshot("crud_add_modal.png")
|
|
|
|
modal = client.page.locator('.ant-modal')
|
|
inputs = modal.locator('input').all()
|
|
for inp in inputs[:3]:
|
|
ph = inp.get_attribute('placeholder') or '请输入'
|
|
try:
|
|
inp.fill(f'测试_{ph}')
|
|
except:
|
|
pass
|
|
|
|
client.screenshot("crud_add_filled.png")
|
|
client.close_modal()
|
|
|
|
print("CRUD 测试完成")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import argparse
|
|
|
|
parser = argparse.ArgumentParser(description='jnpf E2E 测试')
|
|
parser.add_argument('--app-code', help='应用代码 (如 dr, workSystem)')
|
|
parser.add_argument('--username', help='用户名')
|
|
parser.add_argument('--password', help='密码')
|
|
args = parser.parse_args()
|
|
|
|
if args.app_code:
|
|
os.environ["JNPF_APP_CODE"] = args.app_code
|
|
if args.username:
|
|
os.environ["JNPF_USERNAME"] = args.username
|
|
if args.password:
|
|
os.environ["JNPF_PASSWORD"] = args.password
|
|
|
|
config = get_config()
|
|
os.makedirs(config["temp_dir"], exist_ok=True)
|
|
|
|
print("运行测试...")
|
|
login_and_get_menu(app_code=args.app_code)
|