84 lines
3.3 KiB
Python
84 lines
3.3 KiB
Python
# UI 测试具体实现 (使用 Playwright)
|
||
from playwright.async_api import async_playwright, expect
|
||
import os
|
||
import datetime
|
||
|
||
async def execute_ui_test_case(test_case_id: str, url_path: str, browser_type: str, headless: bool, user_data: dict):
|
||
"""
|
||
实际执行UI测试的函数。
|
||
这里使用 Playwright,你也可以替换成 Selenium。
|
||
"""
|
||
base_url = "https://playwright.dev" # 假设 UI 测试的基地址
|
||
full_url = f"{base_url}{url_path}"
|
||
|
||
log_output = []
|
||
success = False
|
||
screenshot_path = None
|
||
html_report_path = None
|
||
|
||
browser = None
|
||
page = None
|
||
|
||
log_output.append(f"Executing UI test: {test_case_id} - {full_url} with {browser_type}")
|
||
|
||
try:
|
||
async with async_playwright() as p:
|
||
if browser_type == "chromium":
|
||
browser = await p.chromium.launch(headless=headless)
|
||
elif browser_type == "firefox":
|
||
browser = await p.firefox.launch(headless=headless)
|
||
elif browser_type == "webkit":
|
||
browser = await p.webkit.launch(headless=headless)
|
||
else:
|
||
raise ValueError(f"Unsupported browser type: {browser_type}")
|
||
|
||
page = await browser.new_page()
|
||
|
||
# 模拟登录(如果需要)
|
||
if user_data:
|
||
log_output.append(f"Attempting to log in with user: {user_data.get('user')}")
|
||
# 假设有一个登录页面
|
||
await page.goto(f"{base_url}/login")
|
||
await page.fill('input[name="username"]', user_data.get('user', ''))
|
||
await page.fill('input[name="password"]', user_data.get('pass', ''))
|
||
await page.click('button[type="submit"]')
|
||
await page.wait_for_url(full_url) # 等待跳转到目标页面
|
||
|
||
await page.goto(full_url)
|
||
log_output.append(f"Navigated to: {full_url}")
|
||
|
||
# 示例UI操作和断言
|
||
# 查找一个元素并验证其文本
|
||
element = page.locator("text=Playwright enables reliable end-to-end testing for modern web apps.")
|
||
await expect(element).to_be_visible()
|
||
log_output.append("Found expected text on page.")
|
||
|
||
# 点击一个链接
|
||
await page.click("text=Docs")
|
||
await page.wait_for_url("**/docs/intro")
|
||
log_output.append("Clicked 'Docs' link and navigated.")
|
||
|
||
success = True
|
||
log_output.append("UI Test PASSED.")
|
||
|
||
except Exception as e:
|
||
log_output.append(f"UI Test FAILED (Exception): {e}")
|
||
success = False
|
||
finally:
|
||
if page:
|
||
try:
|
||
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
|
||
screenshot_filename = f"screenshot_{test_case_id}_{timestamp}.png"
|
||
screenshot_path = os.path.join("/tmp", screenshot_filename)
|
||
await page.screenshot(path=screenshot_path)
|
||
log_output.append(f"Screenshot saved to: {screenshot_path}")
|
||
except Exception as e:
|
||
log_output.append(f"Failed to take screenshot: {e}")
|
||
|
||
if browser:
|
||
try:
|
||
await browser.close()
|
||
except Exception as e:
|
||
log_output.append(f"Failed to close browser: {e}")
|
||
|
||
return success, "\n".join(log_output), screenshot_path, html_report_path |