首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >Appium 的工程化——Page Object、并行执行与 CI 稳定性治理

Appium 的工程化——Page Object、并行执行与 CI 稳定性治理

原创
作者头像
资源大佬 jzit-top
发布于 2026-12-03 18:17:53
发布于 2026-12-03 18:17:53
00
举报

引言

第一篇解决"单条用例怎么写对",这一篇解决"一千条用例怎么跑得稳、跑得快、跑得起"。移动自动化的工程化难点,与 Web 有三处结构性差异:设备是有限资源(不能像浏览器一样随便开)、应用启动成本高(每次 cold start 数十秒)、状态残留更顽固(缓存、登录态、权限弹窗)。

这三处差异决定了 Appium 的工程化必须围绕三个机制建设:Page Object 降低维护成本、设备池与并行调度提升吞吐、重置策略与失败诊断保证可重复。本文给出可落地的实现。

一、Page Object:把"定位"与"业务动作"分离

Page Object 的核心不是"把元素放进一个类",而是让业务用例只描述意图,不接触定位细节。当 UI 改版时,只改 Page 类,不改用例:

代码语言:javascript
复制
# pages/base_page.py
from appium.webdriver.common.appiumby import AppiumBy
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class BasePage:
    def __init__(self, driver):
        self.driver = driver
        self.wait = WebDriverWait(driver, timeout=15, poll_frequency=0.5)

    def tap(self, locator):
        self.wait.until(EC.element_to_be_clickable(locator)).click()

    def type_text(self, locator, text: str):
        el = self.wait.until(EC.visibility_of_element_located(locator))
        el.clear()
        el.send_keys(text)
        if self.driver.is_keyboard_shown():
            self.driver.hide_keyboard()

    def text_of(self, locator) -> str:
        return self.wait.until(EC.visibility_of_element_located(locator)).text

代码语言:javascript
复制
# pages/login_page.py
from .base_page import BasePage
from appium.webdriver.common.appiumby import AppiumBy

class LoginPage(BasePage):
    EMAIL = (AppiumBy.ACCESSIBILITY_ID, "login_email")
    PASSWORD = (AppiumBy.ACCESSIBILITY_ID, "login_password")
    SUBMIT = (AppiumBy.ACCESSIBILITY_ID, "login_submit")
    ERROR = (AppiumBy.ACCESSIBILITY_ID, "login_error")

    def login(self, email: str, password: str) -> "HomePage":
        self.type_text(self.EMAIL, email)
        self.type_text(self.PASSWORD, password)
        self.tap(self.SUBMIT)
        return HomePage(self.driver)

    def error_message(self) -> str:
        return self.text_of(self.ERROR)

代码语言:javascript
复制
# tests/test_login.py —— 用例只描述业务意图
def test_login_with_wrong_password(driver):
    page = LoginPage(driver)
    page.login("qa@example.com", "wrong-password")
    assert "密码错误" in page.error_message()

login() 返回 HomePage 的设计叫链式导航:它让"登录成功后进入首页"这个业务事实变成类型签名的一部分,用例读起来就是一段业务描述。

二、重置策略:按用例粒度选择成本最低的方案

Appium 的 no_reset / full_reset 是粗粒度开关,真实项目需要更细的控制。三种策略按成本从低到高:

  1. 不重置,靠 API 清理:最快。通过后端接口删除测试数据,或用深链直接跳到目标页。
  2. clearSystemFiles=False + 结束进程:中等。保留安装,仅杀进程,适合登录态可复用的场景。
  3. full_reset=True:最慢。重装应用,仅在测试首次安装或权限相关场景使用。
代码语言:javascript
复制
import subprocess

def restart_app_keep_login(driver, package: str, activity: str):
    """策略 2:不重装,仅冷启动,保留登录态"""
    driver.terminate_app(package)
    driver.activate_app(package)
    # 等待首页关键元素,确认已恢复
    from selenium.webdriver.support import expected_conditions as EC
    WebDriverWait(driver, 20).until(
        EC.visibility_of_element_located((AppiumBy.ACCESSIBILITY_ID, "home_feed"))
    )

纪律:测试数据的清理优先走 API,而不是通过 UI 操作。UI 清理既慢又脆弱,且会把"清理失败"和"业务失败"混在一起。

三、并行执行:设备池 + xdist,按设备隔离

Appium 并行的关键是每个 worker 绑定一台设备,而不是多个 worker 抢同一台。标准做法是用 pytest-xdist 加设备列表,按 worker_id 分配:

代码语言:javascript
复制
# conftest.py
import pytest, os
from appium import webdriver
from appium.options.android import UiAutomator2Options

DEVICES = [
    {"udid": "emulator-5554", "port": 4723},
    {"udid": "emulator-5556", "port": 4725},
]

@pytest.fixture(scope="function")
def driver(request, worker_id):
    if worker_id == "master":
        dev = DEVICES[0]
    else:
        idx = int(worker_id.replace("gw", "")) % len(DEVICES)
        dev = DEVICES[idx]

    opts = UiAutomator2Options()
    opts.platform_name = "Android"
    opts.device_name = dev["udid"]
    opts.set_capability("appium:udid", dev["udid"])
    opts.app_package = "com.example.app"
    opts.app_activity = ".MainActivity"
    opts.no_reset = False

    d = webdriver.Remote(f"http://127.0.0.1:{dev['port']}", options=opts)
    d._worker_id = worker_id
    yield d
    d.quit()
代码语言:javascript
复制
# 启动两个 Appium Server,各绑一台设备
appium -p 4723 -U emulator-5554 --allow-cors &
appium -p 4725 -U emulator-5556 --allow-cors &

# 按设备数并行
pytest -n 2 --dist loadscope

--dist loadscope 比默认的 load 更适合移动测试:同一个测试类/模块会被分到同一个 worker,减少跨设备的上下文切换,同时避免同一业务模块的用例分散导致数据竞争。

四、稳定性治理:截图、日志、重试三件套

移动测试的失败诊断成本极高——失败时设备已经退出到某个未知状态。失败瞬间的现场必须自动留存:

代码语言:javascript
复制
# conftest.py(续)
import datetime, pathlib
from slugify import slugify

@pytest.hookimpl(hookwrapper=True)
def pytest_runtest_makereport(item, call):
    outcome = yield
    rep = outcome.get_result()
    if rep.when == "call" and rep.failed:
        driver = item.funcargs.get("driver")
        if driver is None:
            return
        ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        out = pathlib.Path("artifacts") / slugify(item.name) / ts
        out.mkdir(parents=True, exist_ok=True)

        driver.save_screenshot(str(out / "screen.png"))
        (out / "page_source.xml").write_text(driver.page_source, encoding="utf-8")
        (out / "logcat.txt").write_text(
            subprocess.run(["adb", "-s", driver.capabilities["udid"],
                            "logcat", "-d", "-t", "500"],
                           capture_output=True, text=True).stdout,
            encoding="utf-8",
        )

page_source.xml 是最有价值的产物——它记录了失败时刻的完整 UI 树,可以直接回答"元素到底存不存在、id 是什么"。很多人只截了图,却仍然无法定位问题,就是因为缺了这份 XML。

重试的纪律:只在 CI 上重试、最多重试一次、且重试的用例必须单独标记。一个每次都需要重试才能过的用例,说明它本身不稳定,重试只是在掩盖问题:

代码语言:javascript
复制
# pytest.ini 或 pyproject.toml
# [tool.pytest.ini_options]
# reruns = 1
# reruns_delay = 2
# 仅 CI 启用:pytest --reruns 1

五、CI 集成:分层触发与设备预热

CI 编排的原则是把快的放在前面,把贵的放在后面:

代码语言:javascript
复制
# .github/workflows/mobile-test.yml
name: mobile-e2e
on: [pull_request]
jobs:
  smoke:
    runs-on: [self-hosted, android]
    steps:
      - uses: actions/checkout@v4
      - name: 预热模拟器
        run: |
          adb devices | grep emulator || emulator -avd test_avd -no-window -no-audio &
          adb wait-for-device
      - name: 运行冒烟用例
        run: pytest -m smoke -n 2 --dist loadscope
      - uses: actions/upload-artifact@v4
        if: failure()
        with: { name: artifacts, path: artifacts/ }

设备预热是移动 CI 最容易被忽略的一步。模拟器 cold boot 需要 30–60 秒,如果放在用例里等,每次都会拖慢反馈。预热脚本把它提前到 job 启动阶段,用例开始时设备已就绪。

小结

Appium 工程化的专业性,体现在四个机制上:Page Object 隔离定位细节、重置策略按成本分级、并行按设备隔离、失败现场自动留存。再叠加"快反馈在前"的 CI 编排,移动自动化才从"开发者的本地脚本"变成"团队的持续质量门禁"。它真正的价值不在于覆盖多少用例,而在于失败时你能不能在三分钟内知道为什么失败。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

目录
  • 引言
    • 一、Page Object:把"定位"与"业务动作"分离
    • 二、重置策略:按用例粒度选择成本最低的方案
    • 三、并行执行:设备池 + xdist,按设备隔离
    • 四、稳定性治理:截图、日志、重试三件套
    • 五、CI 集成:分层触发与设备预热
    • 小结
问题归档专栏文章快讯文章归档关键词归档