Skip to content

About

Android UI 自动化测试框架 - 基于 Appium 2 + UIAutomator2 + Pytest

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Android UI 自动化测试框架

基于 Python、Pytest、Appium 2 和 UIAutomator2,适用于 Android 真机与模拟器。框架包含 Page Object、显式等待、失败证据采集和 Allure 报告。

目录结构

config/android.yaml             默认配置
src/android_ui/config.py        配置加载与校验
src/android_ui/driver.py        Appium Driver 工厂
src/android_ui/artifacts.py     截图、Page Source、logcat
src/android_ui/pages/           Page Object 基类
tests/conftest.py               Pytest fixtures 与失败钩子
tests/e2e/test_app_launch.py    通用启动冒烟用例
tests/unit/                     不依赖设备的框架单元测试
scripts/check_environment.py    本机环境检查

1. 安装依赖

环境要求:Python 3.9+、JDK 17、Android SDK Platform Tools、Node.js 和 Appium 2。

python3 -m venv .venv
source .venv/bin/activate
python -m pip install -U pip
pip install -e '.[dev]'

npm install -g appium
appium driver install uiautomator2

2. 连接设备

打开 Android 设备的开发者选项和 USB 调试,然后确认设备已授权:

adb devices
python scripts/check_environment.py

设备应显示为 device。若显示 unauthorized,请在手机上确认 USB 调试授权。

3. 配置应用

cp .env.example .env

二选一配置:

  • 测试本地 APK:设置 ANDROID_APP=/absolute/path/app.apk
  • 测试已安装应用:设置 ANDROID_APP_PACKAGE 和 ANDROID_APP_ACTIVITY

多台设备时必须设置 ANDROID_UDID。.env 已被 Git 忽略,不要提交账号、密码或令牌。

4. 启动和执行

终端一:

appium --base-path /

终端二:

# 不依赖设备
pytest tests/unit -q

# Android 启动冒烟测试
pytest tests/e2e -m smoke --alluredir=allure-results

# 查看报告
allure serve allure-results

也可以指定其他配置文件:

pytest tests/e2e --config config/android.yaml

5. 添加业务页面

页面对象继承 BasePage,优先使用 AppiumBy.ID 或 AppiumBy.ACCESSIBILITY_ID。不要使用固定休眠;统一使用 BasePage 提供的显式等待。

from appium.webdriver.common.appiumby import AppiumBy

from android_ui.pages.base_page import BasePage


class LoginPage(BasePage):
    USERNAME = (AppiumBy.ID, "com.example.app:id/username")
    PASSWORD = (AppiumBy.ID, "com.example.app:id/password")
    SUBMIT = (AppiumBy.ACCESSIBILITY_ID, "登录")

    def login(self, username: str, password: str) -> None:
        self.type_text(self.USERNAME, username)
        self.type_text(self.PASSWORD, password)
        self.tap(self.SUBMIT)

测试必须包含明确断言:

def test_login(driver):
    page = LoginPage(driver)
    page.login("test-user", "password-from-environment")
    assert page.is_visible((AppiumBy.ID, "com.example.app:id/home"))

失败产物

用例失败时自动写入 artifacts/<用例名>/:

  • screenshot.png
  • page_source.xml
  • logcat.txt

若安装了 allure-pytest,这些文件同时附加到 Allure 报告。

稳定性约定

  • 优先级:resource-id > accessibility id > Android UIAutomator > XPath。
  • 禁止 time.sleep(),等待页面信号或元素状态。
  • 测试数据和凭据通过环境变量或外部服务注入。
  • 多设备并行时,每台设备需要独立的 udid、systemPort 和 Appium 会话配置。

About

Android UI 自动化测试框架 - 基于 Appium 2 + UIAutomator2 + Pytest

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages