小程序Airtest自动化测试脚本
启动微信 & 进入小程序登录流程自动化商品浏览交互断言与截图异常处理与日志控件选择器(text / resourceId)图像模板文件即可快速搭建属于你的小程序自动化测试框架!
·
微信小程序自动化测试 设计的 Airtest 脚本模板(Python),包含常用操作:启动微信 → 搜索小程序 → 进入指定页面 → 点击/输入/断言 → 截图报告。
🧩 一、环境准备(前置条件)
-
安装 AirtestIDE 或 Airtest 库:
pip install airtest pocoui
-
手机开启 USB 调试 + 微信调试模式(设置 → 通用 → 开发者工具 → 开启“USB调试”)
-
使用数据线连接手机,确保
adb devices
能识别设备 -
微信版本建议 ≥ 8.0,部分老版本不支持 Poco 控件识别
📜 二、Airtest 小程序自动化脚本模板(完整可运行)
✅ 支持 Android 微信小程序(iOS 需额外配置 WebDriverAgent,较复杂,本文以 Android 为主)
# -*- encoding=utf8 -*-
__author__ = "YourName"
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
import time
# 初始化设备和Poco
auto_setup(__file__)
poco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)
# ====================【全局配置】====================
MINI_PROGRAM_NAME = "你的小程序名称" # 替换为实际小程序名,如“京东购物”
SEARCH_KEYWORD = "你的小程序" # 搜索框中输入的关键词
WAIT_TIMEOUT = 10 # 全局等待超时时间
# ====================【封装常用函数】====================
def start_wechat():
"""启动微信"""
stop_app("com.tencent.mm")
start_app("com.tencent.mm")
sleep(3)
assert_exists(Template(r"tpl1700000000000.png", record_pos=(0.0, 0.0), resolution=(1080, 2340)), "微信启动成功")
def enter_mini_program():
"""进入小程序"""
# 点击搜索框
touch(Template(r"tpl_search_box.png", record_pos=(0.0, -0.8), resolution=(1080, 2340)))
sleep(1)
# 输入小程序名称
text(SEARCH_KEYWORD)
sleep(1)
# 点击搜索
touch(Template(r"tpl_search_btn.png", record_pos=(0.45, -0.8), resolution=(1080, 2340)))
sleep(2)
# 点击搜索结果中的小程序
mini_program_icon = poco(text=MINI_PROGRAM_NAME)
if mini_program_icon.exists():
mini_program_icon.click()
sleep(5) # 等待小程序加载
else:
raise Exception(f"未找到小程序: {MINI_PROGRAM_NAME}")
def wait_element_exists(poco_selector, timeout=WAIT_TIMEOUT):
"""等待元素出现"""
for i in range(timeout):
if poco_selector.exists():
return True
sleep(1)
raise Exception(f"元素 {poco_selector} 在 {timeout} 秒内未出现")
def take_screenshot_and_log(msg):
"""截图并记录日志"""
snapshot(msg=msg)
# ====================【测试用例:登录流程示例】====================
def test_login_flow():
"""测试:小程序登录流程"""
# 点击“我的”Tab
my_tab = poco(text="我的")
wait_element_exists(my_tab)
my_tab.click()
take_screenshot_and_log("点击【我的】Tab")
# 点击“立即登录”
login_btn = poco(text="立即登录")
if login_btn.exists():
login_btn.click()
take_screenshot_and_log("点击【立即登录】")
# 选择微信一键登录
wechat_login = poco(text="微信用户一键登录")
wait_element_exists(wechat_login)
wechat_login.click()
take_screenshot_and_log("选择微信一键登录")
# 授权确认(如果弹出)
allow_btn = poco(text="允许")
if allow_btn.exists():
allow_btn.click()
take_screenshot_and_log("点击授权【允许】")
# 验证登录成功(如:出现用户名)
username = poco("userNickname") # 替换为实际控件ID或text
wait_element_exists(username, 15)
assert username.get_text(), "登录后用户名为空"
take_screenshot_and_log("登录成功,显示用户名")
else:
print("用户已登录,跳过登录步骤")
# ====================【测试用例:首页商品浏览】====================
def test_browse_product():
"""测试:首页浏览商品"""
# 返回首页
back_home = poco(text="首页")
if back_home.exists():
back_home.click()
take_screenshot_and_log("返回首页")
# 点击第一个商品
first_product = poco("productItem").offspring("productName")[0] # 根据实际结构调整
wait_element_exists(first_product)
first_product.click()
take_screenshot_and_log("点击第一个商品")
# 验证商品详情页标题
product_title = poco("productTitle")
wait_element_exists(product_title)
title_text = product_title.get_text()
assert title_text, "商品标题为空"
print(f"进入商品详情页:{title_text}")
take_screenshot_and_log(f"商品详情页:{title_text}")
# ====================【主执行流程】====================
def run_tests():
"""主函数:执行所有测试用例"""
try:
start_wechat()
enter_mini_program()
# 执行测试用例
test_login_flow()
test_browse_product()
print("✅ 所有测试用例执行成功!")
except Exception as e:
print(f"❌ 测试失败:{str(e)}")
raise e
finally:
# 可选:测试结束后关闭小程序或微信
# keyevent("BACK")
# sleep(1)
# keyevent("BACK")
pass
# ====================【运行】====================
if __name__ == '__main__':
run_tests()
🖼️ 三、图像模板文件说明(.png)
脚本中使用了 Template(r"xxx.png")
,这是 Airtest 的图像识别方式。你需要:
- 使用 AirtestIDE 录制功能 截取对应控件图片(如搜索框、搜索按钮)
- 保存到脚本同目录下
- 替换脚本中的
tpl_xxx.png
为你自己的文件名
💡 建议:优先使用 Poco 控件识别(文本/ID),图像识别作为 fallback(比如无法获取控件时)
📊 四、生成 Allure / HTML 报告(可选)
在脚本开头加入:
from airtest.report.report import simple_report
脚本末尾加入:
simple_report(__file__, logpath=True, output='report.html')
运行后会自动生成 report.html
,包含操作步骤、截图、日志。
⚙️ 五、进阶技巧 & 注意事项
技巧 | 说明 |
---|---|
✅ 使用 Poco 代替图像识别 | 更稳定,不受分辨率/主题色影响 |
✅ 设置全局等待超时 | 避免因加载慢导致脚本失败 |
✅ 失败自动重试机制 | 对网络请求类操作可加 retry 装饰器 |
✅ 多设备并发 | 使用 airtest run xxx.air --device Android://... 并行跑 |
✅ 日志分级 | 使用 log() , snapshot() 记录关键步骤 |
❗ 避免硬编码坐标 | 不同机型坐标不同,用 Poco 或相对位置 |
🧪 六、常见问题解决
Q1: 找不到控件?
→ 使用 AirtestIDE 的 “UI 查看器” 查看真实控件属性(text/content-desc/resourceId)
Q2: 小程序内元素无法识别?
→ 确保开启了“USB调试(微信开发者选项)”,部分小程序需官方白名单支持
Q3: 图像识别不准?
→ 提高截图清晰度,在 IDE 中调整 threshold(默认 0.7~0.9)
Q4: 如何断言文本/数值?
price_text = poco("productPrice").get_text()
assert "¥99" in price_text, f"价格不符,实际:{price_text}"
📥 七、项目结构建议(团队协作)
wechat_miniapp_test/
├── main.py # 主脚本
├── utils/ # 封装函数
│ └── wechat_utils.py
├── cases/ # 测试用例模块
│ ├── test_login.py
│ └── test_order.py
├── templates/ # 图像模板
│ ├── tpl_search_box.png
│ └── tpl_search_btn.png
├── report/ # 生成报告
└── requirements.txt # 依赖列表
✅ 总结
这份模板覆盖了:
- 启动微信 & 进入小程序
- 登录流程自动化
- 商品浏览交互
- 断言与截图
- 异常处理与日志
你只需替换:
MINI_PROGRAM_NAME
- 控件选择器(text / resourceId)
- 图像模板文件
即可快速搭建属于你的小程序自动化测试框架!
更多推荐
所有评论(0)