name: u2-test description: uiautomator2 Android UI 自动化参考。理解 u2 设备连接、元素定位策略(xpath/text/resource-id)、隐式等待与显式等待差异。使用场景:(1) 排查设备连接问题,(2) 了解元素定位方法,(3) 理解等待机制差异。注意:操作必须通过 Action 层,不直接调用 u2 API。
uiautomator2 Android UI 测试技能
⚠️ 重要:本项目中禁止直接 import uiautomator2 或 AndroidDriver。 所有 UI 操作必须通过
Action类(action/action.py)调用。 本技能提供 uiautomator2 底层知识作为参考。
项目中的正确用法
# ✅ 通过 Action 层操作
from framework.action import Action
action = Action(platform="android")
result = action.click("xpath, //*[@resource-id='com.example.app:id/btnMain']")
# ✅ 通过 ElementRegistry 获取元素定位(推荐)
from framework.core.element_registry import get_registry
locator = get_registry().resolve("my_button")
result = action.click(locator)
# ❌ 禁止直接使用
import uiautomator2 as u2
d = u2.connect(...)
d.click(...)
设备连接(参考)
# 初始化
adb connect 10.162.95.154:45843
python -m uiautomator2 init
# 验证
adb devices
设备配置集中在 config/test_config.yaml。
元素定位策略(参考)
uiautomator2 支持的定位方式(了解即可,实际从 config 取):
| 策略 | 稳定性 | 示例 |
|---|---|---|
| resource-id | ⭐⭐⭐ | com.example.app:id/btnSwitch |
| text | ⭐⭐ | 确定 |
| XPath | ⭐ | //*[@text='OK'] |
项目中元素统一在 config/elements/ YAML 中定义,格式:
btn_switch: "xpath, //*[@resource-id='com.example.app:id/btnSwitch']"
等待机制
# ✅ 通过 Action 的超时参数
action.wait_for_element("xpath, ...", timeout=30.0)
# ❌ 避免硬 sleep
import time; time.sleep(3)
分层约束
tests ──→ page ──→ action ──→ driver (uiautomator2)
- tests 层禁止 import action 或 uiautomator2
- page 层禁止直接操作 driver
- 只有 action 层直接与 uiautomator2 交互
详见根目录 AGENTS.md。
关键文件
| 文件 | 说明 |
|---|---|
action/action.py |
Action 统一入口(461 行) |
action/ui_drivers/android_driver.py |
Android 平台 driver |
config/test_config.yaml |
设备连接配置 |
config/elements/ |
元素定位 YAML |
触发条件
- Android 设备连接配置
- 了解 uiautomator2 底层机制
- 元素定位策略参考