Python Airtest自动化测试工具的使用攻略
什么是Airtest
Airtest是一个开源Python库,针对Android/iOS的游戏和应用开发的UI自动化测试工具。使用Airtest可以方便快捷地进行自动测试,提高测试效率。Airtest可以支持多种测试方式,包括GUI,截图比对,OCR识别,用户操作录制回放等。
安装Airtest
使用pip命令可以安装最新的Airtest版本:
pip install -U airtest
也可以安装指定版本:
pip install -U airtest==<version>
基础操作
连接设备
首先,需要连接Android手机或iOS设备。Airtest提供了两种方式进行连接:USB连接和WiFi连接。对于USB连接,Airtest需要ADB工具;对于WiFi连接,Airtest需要mumu模拟器或Real vivo手机进行虚拟AP部署。
from airtest.core.api import connect_device
# USB连接
connect_device("Android://127.0.0.1:5037/0")
# WiFi连接(mumu模拟器)
connect_device("Android://127.0.0.1:7555/0")
# WiFi连接(Real vivo手机)
connect_device("Android://<ipaddress>:7912/0")
运行脚本
在Airtest安装完成并连接设备后,可以通过以下命令运行脚本:
airtest run <script_file>
获取截图
在Airtest中,可以使用snapshot()
函数获取当前设备截图:
from airtest.core.api import snapshot
snapshot("test.png")
坐标点击
使用touch()
函数进行坐标点击:
from airtest.core.api import touch
# 点击屏幕坐标(100, 200)
touch((100, 200))
执行操作
Airtest支持录制操作并进行回放。在录制操作时,可以选择录制鼠标点击、按键输入、滚轮滑动等操作。回放过程即重现已录制的操作。
from airtest.core.api import *
# 进行录制并保存到文件
start_recording()
touch((100, 200))
stop_recording('playback.air')
# 执行已保存的操作
exec_file('playback.air')
验证UI
在Airtest中,可以通过比较图片和像素值来验证UI。使用assert_exists()
函数来验证元素是否存在:
from airtest.core.api import *
# 截图并进行比对操作
snapshot('test.png')
# 验证UI
assert_exists(Template('test.png'), 'test image')
示例说明
示例1:使用Airtest进行简单的点击操作测试
这个示例是为了介绍怎样使用Airtest进行最简单的点击操作测试。首先需要准备一个可以点击的应用。
from airtest.core.api import *
# 连接设备
connect_device('Android://127.0.0.1:5037/0')
# 打开应用
start_app('com.android.browser')
# 点击屏幕中央的坐标
touch(Template('central_point.png'))
示例2:使用Airtest进行UI验证测试
这个示例是为了介绍怎样使用Airtest进行UI验证测试。首先需要准备一个有明显特征的图像。
from airtest.core.api import *
# 连接设备
connect_device('Android://127.0.0.1:5037/0')
# 打开应用
start_app('com.android.browser')
# 进行截屏
snapshot('screenshot.png')
# 验证UI
assert_exists(Template('logo.png'), 'logo')
在这个示例中,我们使用了assert_exists()
函数进行UI验证。Template()
函数的参数是需要对比的图像。如果UI元素存在,则返回True;否则返回False。assert_exists()
函数还使用了第二个参数,来说明验证的UI元素。如果元素不存在,则会输出这个参数作为消息提示。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:python Airtest自动化测试工具的的使用 - Python技术站