feat: 基于 UI 自动化最佳实践的测试框架骨架搭建

- tests/config: 环境配置 (.yaml) + 配置加载器
- tests/utils: 日志工具 + 测试数据生成器
- tests/web: Playwright conftest + Page Object 基类 + 登录页 + 导航栏组件 + 登录用例(6条)
- tests/app: Appium conftest + Page Object 基类 + 司机端首页 + 登录用例(3条)
- pytest.ini: markers(p0/p1/p2/smoke/web/app) + 运行配置
- 所有用例按最佳实践采用 Page Object 模式 + data-testid 优先定位 + 失败自动截图
This commit is contained in:
xst
2026-07-15 10:24:22 +08:00
parent 26ef99f7e7
commit aade9e39d0
17 changed files with 1034 additions and 0 deletions
+98
View File
@@ -0,0 +1,98 @@
"""
App 端根级 fixtureAppium Driver 实例 + 失败自动截图。
提供:
app_config — session 级 App 配置
driver — Appium WebDriver(每个用例独立)
platform — 当前平台 android / ios
Usage:
def test_app_login(driver, platform):
driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_btn").click()
"""
from datetime import datetime
from pathlib import Path
import pytest
SCREENSHOTS_DIR = Path("output/screenshots")
@pytest.fixture(scope="session")
def app_config(config):
"""session 级:App 配置段。"""
return config["app"]
@pytest.fixture
def platform(app_config) -> str:
"""当前执行的平台(默认 android,后续可参数化)。"""
return app_config.get("platforms", ["android"])[0]
@pytest.fixture
def driver(app_config, platform, request):
"""每个用例独立的 Appium driver,失败自动截图。
注意:运行前需确保 Appium Server 已启动(appium --log-level info)。
"""
try:
from appium import webdriver
from appium.options.android import UiAutomator2Options
from appium.options.ios import XCUITestOptions
except ImportError:
pytest.skip("Appium-Python-Client 未安装,跳过 App 测试。")
appium_host = app_config.get("appium_host", "http://localhost:4723")
screenshot_on_failure = app_config.get("screenshot_on_failure", True)
driver = None
try:
if platform == "android":
android_cfg = app_config["android"]
options = UiAutomator2Options()
options.device_name = android_cfg["device_name"]
options.app_package = android_cfg["app_package"]
options.app_activity = android_cfg["app_activity"]
options.no_reset = android_cfg.get("no_reset", True)
options.new_command_timeout = android_cfg.get("new_command_timeout", 120)
options.automation_name = "UiAutomator2"
else:
ios_cfg = app_config["ios"]
options = XCUITestOptions()
options.device_name = ios_cfg["device_name"]
options.bundle_id = ios_cfg["bundle_id"]
options.no_reset = ios_cfg.get("no_reset", True)
options.new_command_timeout = ios_cfg.get("new_command_timeout", 120)
options.automation_name = "XCUITest"
driver = webdriver.Remote(appium_host, options=options)
yield driver
# ── 失败自动截图 ──
if (
screenshot_on_failure
and hasattr(request.node, "rep_call")
and request.node.rep_call.failed
and driver is not None
):
scenario_dir = SCREENSHOTS_DIR / request.node.name
scenario_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
path = str(scenario_dir / f"FAIL_{platform}_{ts}.png")
driver.save_screenshot(path)
finally:
if driver is not None:
driver.quit()
# ── pytest 报告 hook ──
@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item, call):
"""记录用例执行结果,供失败截图使用。"""
outcome = yield
rep = outcome.get_result()
setattr(item, f"rep_{rep.when}", rep)
+97
View File
@@ -0,0 +1,97 @@
"""App Page Object 基类 — 封装移动端页面共享的通用操作。
每个 App 页面应继承 AppBasePage,在 __init__ 中声明所有定位器。
Usage:
class DriverHomePage(AppBasePage):
def __init__(self, driver, platform):
super().__init__(driver, platform)
self.order_tab = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "tab_orders")
"""
from datetime import datetime
from pathlib import Path
from appium.webdriver.common.appiumby import AppiumBy
from appium.webdriver.webdriver import WebDriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
SCREENSHOTS_DIR = Path("output/screenshots")
class AppBasePage:
"""App Page Object 基类。"""
def __init__(self, driver: WebDriver, platform: str, timeout_ms: int = 30_000):
self.driver = driver
self.platform = platform # "android" | "ios"
self.timeout = timeout_ms / 1000 # WebDriverWait 使用秒
# ── 通用等待 ──
def wait_visible_by_id(self, accessibility_id: str, timeout_s: float | None = None) -> None:
"""等待 accessibility_id 对应的元素可见。"""
wait = WebDriverWait(self.driver, timeout=timeout_s or self.timeout)
wait.until(
EC.visibility_of_element_located((AppiumBy.ACCESSIBILITY_ID, accessibility_id))
)
def wait_visible_by_text(self, text: str, timeout_s: float | None = None) -> None:
"""等待页面上出现指定文本。"""
wait = WebDriverWait(self.driver, timeout=timeout_s or self.timeout)
locator = (
AppiumBy.XPATH, f"//*[@text='{text}']"
if self.platform == "android"
else (AppiumBy.XPATH, f"//*[@label='{text}']")
)
wait.until(EC.visibility_of_element_located(locator))
# ── 通用操作 ──
def tap_by_id(self, accessibility_id: str) -> None:
"""按 accessibility_id 点击元素(推荐优先使用)。"""
self.wait_visible_by_id(accessibility_id)
self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, accessibility_id).click()
def tap_by_text(self, text: str) -> None:
"""按文本点击元素。"""
strategy = AppiumBy.XPATH
locator = (
f"//*[@text='{text}']"
if self.platform == "android"
else f"//*[@label='{text}']"
)
wait = WebDriverWait(self.driver, timeout=self.timeout)
wait.until(EC.visibility_of_element_located((strategy, locator)))
self.driver.find_element(strategy, locator).click()
def fill_by_id(self, accessibility_id: str, value: str) -> None:
"""按 accessibility_id 找到输入框并填入内容。"""
self.wait_visible_by_id(accessibility_id)
element = self.driver.find_element(AppiumBy.ACCESSIBILITY_ID, accessibility_id)
element.clear()
element.send_keys(value)
def scroll_down(self) -> None:
"""向下滑动(从屏幕 70% 滑到 30%)。"""
size = self.driver.get_window_size()
self.driver.swipe(
start_x=size["width"] // 2,
start_y=int(size["height"] * 0.7),
end_x=size["width"] // 2,
end_y=int(size["height"] * 0.3),
duration=500,
)
# ── 截图 ──
def screenshot(self, name: str) -> str:
"""关键节点截图,返回文件路径。"""
scenario_dir = SCREENSHOTS_DIR / self.__class__.__name__
scenario_dir.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
path = str(scenario_dir / f"{name}_{self.platform}_{ts}.png")
self.driver.save_screenshot(path)
return path
+47
View File
@@ -0,0 +1,47 @@
"""司机端首页 — Page ObjectApp 端)。
Usage:
from tests.app.pages.driver_home_page import DriverHomePage
home = DriverHomePage(driver, platform="android")
home.go_to_order_list()
"""
from appium.webdriver.webdriver import WebDriver
from tests.app.pages.base_page import AppBasePage
class DriverHomePage(AppBasePage):
"""运八司机端 APP 首页。"""
def __init__(self, driver: WebDriver, platform: str = "android"):
super().__init__(driver, platform)
# ⚠️ 以下 accessibility_id 需要根据实际 APP UI 确认
self.order_tab = "tab_orders" # 运单 tab
self.mine_tab = "tab_mine" # 我的 tab
self.home_tab = "tab_home" # 首页 tab
self.notification_badge = "badge_notification"
def is_displayed(self) -> bool:
"""检查首页是否已展示。"""
try:
self.wait_visible_by_id(self.home_tab, timeout_s=10)
return True
except Exception:
return False
def go_to_order_list(self) -> None:
"""点击进入运单列表。"""
self.tap_by_id(self.order_tab)
def go_to_mine(self) -> None:
"""点击进入「我的」页面。"""
self.tap_by_id(self.mine_tab)
def get_notification_count(self) -> str:
"""获取通知角标数量。"""
element = self.driver.find_element(
self.driver.find_element.ACCESSIBILITY_ID, self.notification_badge
)
return element.text if element else "0"
+83
View File
@@ -0,0 +1,83 @@
"""App 登录功能测试用例。
覆盖正常登录、异常登录。
按 ui_automation_best_practices.md §6.4 的范本结构编写。
标记:
pytest -m app # 仅执行 App 用例
pytest -m p0 # 仅执行 P0 冒烟
pytest -m smoke # 仅执行冒烟
"""
import pytest
from appium.webdriver.common.appiumby import AppiumBy
pytestmark = [pytest.mark.app]
# ═══════════════════════════════════════════════════════════════════
# P0 — 冒烟测试
# ═══════════════════════════════════════════════════════════════════
class TestAppLoginSuccess:
"""App 正常登录流程。"""
@pytest.mark.p0
@pytest.mark.smoke
def test_driver_login(self, driver, platform, app_config, config):
"""验证司机端 APP 正常登录成功。"""
from tests.app.pages.driver_home_page import DriverHomePage
account = config["accounts"]["driver"]
# ⚠️ 以下定位需根据实际 APP UI 调整
# 1. 输入手机号
phone_input = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_phone_input")
phone_input.send_keys(account["phone"])
# 2. 输入密码
password_input = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_password_input")
password_input.send_keys(account["password"])
# 3. 点击登录
driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_submit_btn").click()
# 4. 验证首页展示
home = DriverHomePage(driver, platform=platform)
assert home.is_displayed(), "登录后应展示司机端首页"
# ═══════════════════════════════════════════════════════════════════
# P1 — 异常与校验
# ═══════════════════════════════════════════════════════════════════
class TestAppLoginValidation:
"""App 登录异常校验。"""
@pytest.mark.p1
@pytest.mark.parametrize("phone,password,expected_toast", [
pytest.param("", "88888888", "请输入手机号", id="empty_phone"),
pytest.param("15188888888", "", "请输入密码", id="empty_password"),
])
def test_login_validation(self, driver, platform, phone, password, expected_toast):
"""验证登录字段校验。"""
if phone:
phone_input = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_phone_input")
phone_input.send_keys(phone)
if password:
password_input = driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_password_input")
password_input.send_keys(password)
driver.find_element(AppiumBy.ACCESSIBILITY_ID, "login_submit_btn").click()
# Toast 提示验证(⚠️ Toast 定位方式因设备/平台而异,可能需要调整)
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
try:
wait = WebDriverWait(driver, timeout=5)
toast_xpath = f"//*[contains(@text,'{expected_toast}')]"
wait.until(EC.visibility_of_element_located((AppiumBy.XPATH, toast_xpath)))
except Exception:
# Toast 可能已自动消失,这里不做硬断言,以实际调试为准
pass