airtest.core.api module¶
这个模块包含了Airtest核心API。
-
init_device
(platform='Android', uuid=None, **kwargs)[源代码]¶ 初始化设备,并设置为当前设备。
参数: - platform – Android, IOS or Windows
- uuid – 目标设备的uuid,例如Android的序列号,Windows的窗口句柄,或iOS的uuid
- kwargs – 可选的平台相关的参数,例如Android下的 ``cap_method=JAVACAP``参数
返回: device对象
示例: >>> init_device(platform="Android",uuid="SJE5T17B17", cap_method="JAVACAP") >>> init_device(platform="Windows",uuid="123456")
-
connect_device
(uri)[源代码]¶ 用URI字符串来初始化设备,并且设置为当前设备。
参数: uri – 一个用于初始化设备的URI字符串,例如
android://adbhost:adbport/serialno?param=value¶m2=value2
返回: device对象
示例: >>> connect_device("Android:///") # local adb device using default params >>> # local device with serial number SJE5T17B17 and custom params >>> connect_device("Android:///SJE5T17B17?cap_method=javacap&touch_method=adb") >>> # remote device using custom params Android://adbhost:adbport/serialno >>> connect_device("Android://127.0.0.1:5037/10.254.60.1:5555") >>> connect_device("Windows:///") # connect to the desktop >>> connect_device("Windows:///123456") # Connect to the window with handle 123456 >>> connect_device("windows:///?title_re='.*explorer.*'") # Connect to the window that name include "explorer" >>> connect_device("Windows:///123456?foreground=False") # Connect to the window without setting it foreground >>> connect_device("iOS:///127.0.0.1:8100") # iOS device >>> connect_device("iOS:///http://localhost:8100/?mjpeg_port=9100") # iOS with mjpeg port >>> connect_device("iOS:///http://localhost:8100/?mjpeg_port=9100&&udid=00008020-001270842E88002E") # iOS with mjpeg port and udid >>> connect_device("iOS:///http://localhost:8100/?mjpeg_port=9100&&uuid=00008020-001270842E88002E") # udid/uuid/serialno are all ok
-
set_current
(idx)[源代码]¶ 设置当前设备。
参数: idx – uuid或已初始化的设备列表中的编号,从0开始
引发: IndexError – 当查找不到设备时
返回: None
支持平台: Android, iOS, Windows
示例: >>> # switch to the first phone currently connected >>> set_current(0) >>> # switch to the phone with serial number serialno1 >>> set_current("serialno1")
-
auto_setup
(basedir=None, devices=None, logdir=None, project_root=None, compress=None)[源代码]¶ 自动配置运行环境,如果当前没有连接设备的话,就默认尝试连接Android设备。
参数: - basedir – 设置当前脚本的所在路径,也可以直接传
__file__
变量进来 - devices – 一个内容为
connect_device uri
字符串的列表 - logdir – 可设置脚本运行时的log保存路径,默认值为None则不保存log,如果设置为True则自动保存在<basedir>/log目录中。
- project_root – 用于设置PROJECT_ROOT变量,方便
using
接口的调用 - compress – 屏幕截图的压缩比率,在[1, 99]范围内的整数,默认是10
示例: >>> auto_setup(__file__) >>> auto_setup(__file__, devices=["Android://127.0.0.1:5037/SJE5T17B17"], ... logdir=True, project_root=r"D:\test\logs", compress=90)
- basedir – 设置当前脚本的所在路径,也可以直接传
-
shell
(cmd)[源代码]¶ 在目标设备上运行远程shell指令
参数: cmd – 需要在设备上运行的指令,例如
ls /data/local/tmp
返回: shell指令的输出内容
支持平台: Android
示例: >>> # Execute commands on the current device adb shell ls >>> print(shell("ls"))
>>> # Execute adb instructions for specific devices >>> dev = connect_device("Android:///device1") >>> dev.shell("ls")
>>> # Switch to a device and execute the adb command >>> set_current(0) >>> shell("ls")
-
start_app
(package, activity=None)[源代码]¶ 在设备上启动目标应用
参数: - package – 想要启动的应用包名package name,例如
com.netease.my
- activity – 需要启动的activity,默认为None,意为main activity
返回: None
支持平台: Android, iOS
示例: >>> start_app("com.netease.cloudmusic") >>> start_app("com.apple.mobilesafari") # on iOS
- package – 想要启动的应用包名package name,例如
-
stop_app
(package)[源代码]¶ 终止目标应用在设备上的运行
参数: package – 需要终止运行的应用包名 package name,另见
start_app
返回: None
支持平台: Android, iOS
示例: >>> stop_app("com.netease.cloudmusic")
-
clear_app
(package)[源代码]¶ 清理设备上的目标应用数据
参数: package – 包名 package name,另见
start_app
返回: None
支持平台: Android
示例: >>> clear_app("com.netease.cloudmusic")
-
install
(filepath, **kwargs)[源代码]¶ 安装应用到设备上
参数: - filepath – 需要被安装的应用路径
- kwargs – 平台相关的参数
kwargs
,请参考对应的平台接口文档
返回: None
支持平台: Android, iOS
示例: >>> install(r"D:\demo\test.apk") # install Android apk >>> # adb install -r -t D:\demo\test.apk >>> install(r"D:\demo\test.apk", install_options=["-r", "-t"])
>>> install(r"D:\demo\test.ipa") # install iOS ipa >>> install("http://www.example.com/test.ipa") # install iOS ipa from url
-
uninstall
(package)[源代码]¶ 卸载设备上的应用
参数: package – 需要被卸载的包名 package name,另见
start_app
返回: None
支持平台: Android, iOS
示例: >>> uninstall("com.netease.cloudmusic")
-
snapshot
(filename=None, msg='', quality=None, max_size=None)[源代码]¶ 对目标设备进行一次截图,并且保存到文件中。
参数: - filename – 保存截图的文件名,默认保存路径为 ``ST.LOG_DIR``中
- msg – 截图文件的简短描述,将会被显示在报告页面中
- quality – 图片的质量,[1,99]的整数,默认是10
- max_size – 图片的最大尺寸,例如 1200
返回: {“screen”: filename, “resolution”: resolution of the screen} or None
支持平台: Android, iOS, Windows
示例: >>> snapshot(msg="index") >>> # save the screenshot to test.jpg >>> snapshot(filename="test.png", msg="test")
可以设置截图的画质和大小
>>> # Set the screenshot quality to 30 >>> ST.SNAPSHOT_QUALITY = 30 >>> # Set the screenshot size not to exceed 600*600 >>> # if not set, the default size is the original image size >>> ST.IMAGE_MAXSIZE = 600 >>> # The quality of the screenshot is 30, and the size does not exceed 600*600 >>> touch((100, 100)) >>> # The quality of the screenshot of this sentence is 90 >>> snapshot(filename="test.png", msg="test", quality=90) >>> # The quality of the screenshot is 90, and the size does not exceed 1200*1200 >>> snapshot(filename="test2.png", msg="test", quality=90, max_size=1200)
-
touch
(v, times=1, **kwargs)[源代码]¶ 在当前设备画面上进行一次点击
参数: - v – 点击位置,可以是一个
Template
图片实例,或是一个绝对坐标(x, y)
- times – 点击次数
- kwargs – 平台相关的参数
kwargs
,请参考对应的平台接口文档
返回: finial position to be clicked, e.g. (100, 100)
支持平台: Android, Windows, iOS
示例: 点击绝对坐标:
>>> touch((100, 100))
点击图片的中心位置:
>>> touch(Template(r"tpl1606730579419.png", target_pos=5))
点击两次:
>>> touch((100, 100), times=2)
在Android和Windows下,可以设置点击持续时间:
>>> touch((100, 100), duration=2)
右键点击(Windows):
>>> touch((100, 100), right_click=True)
- v – 点击位置,可以是一个
-
click
(v, times=1, **kwargs)¶ 在当前设备画面上进行一次点击
参数: - v – 点击位置,可以是一个
Template
图片实例,或是一个绝对坐标(x, y)
- times – 点击次数
- kwargs – 平台相关的参数
kwargs
,请参考对应的平台接口文档
返回: finial position to be clicked, e.g. (100, 100)
支持平台: Android, Windows, iOS
示例: 点击绝对坐标:
>>> touch((100, 100))
点击图片的中心位置:
>>> touch(Template(r"tpl1606730579419.png", target_pos=5))
点击两次:
>>> touch((100, 100), times=2)
在Android和Windows下,可以设置点击持续时间:
>>> touch((100, 100), duration=2)
右键点击(Windows):
>>> touch((100, 100), right_click=True)
- v – 点击位置,可以是一个
-
double_click
(v)[源代码]¶ 双击
参数: v – 点击位置,可以是一个
Template
图片实例,或是一个绝对坐标(x, y)
返回: 实际点击位置坐标
(x, y)
示例: >>> double_click((100, 100)) >>> double_click(Template(r"tpl1606730579419.png"))
-
swipe
(v1, v2=None, vector=None, **kwargs)[源代码]¶ 在当前设备画面上进行一次滑动操作。
- 有两种传入参数的方式
swipe(v1, v2=Template(...))
# 从 v1 滑动到 v2swipe(v1, vector=(x, y))
# 从 v1 开始滑动,沿着vector方向。
参数: - v1 – 滑动的起点,可以是一个Template图片实例,或是绝对坐标
(x, y)
- v2 – 滑动的终点,可以是一个Template图片实例,或是绝对坐标
(x, y)
- vector – 滑动动作的矢量坐标,可以是绝对坐标
(x,y)
或是屏幕百分比,例如(0.5, 0.5)
- **kwargs – 平台相关的参数
kwargs
,请参考对应的平台接口文档
引发: Exception – 当没有足够的参数来执行滑动时引发异常
返回: 原点位置和目标位置
支持平台: Android, Windows, iOS
示例: >>> swipe(Template(r"tpl1606814865574.png"), vector=[-0.0316, -0.3311]) >>> swipe((100, 100), (200, 200))
自定义滑动持续时间和经过几步到达终点:
>>> # swiping lasts for 1 second, divided into 6 steps >>> swipe((100, 100), (200, 200), duration=1, steps=6)
-
pinch
(in_or_out='in', center=None, percent=0.5)[源代码]¶ 在设备屏幕上执行一个双指pinch捏合操作
参数: - in_or_out – 向内捏合或向外扩大,在[“in”, “out”] 中枚举一个值
- center – pinch动作的中心位置,默认值为None则为屏幕中心点
- percent – pinch动作的屏幕百分比,默认值为0.5
返回: None
支持平台: Android
示例: 两指向屏幕中心点捏合:
>>> pinch()
将(100, 100)作为中心点,向外扩张两指:
>>> pinch('out', center=(100, 100))
-
keyevent
(keyname, **kwargs)[源代码]¶ 在设备上执行keyevent按键事件
参数: - keyname – 平台相关的按键名称
- **kwargs – 平台相关的参数
kwargs
,请参考对应的平台接口文档
返回: None
支持平台: Android, Windows, iOS
示例: Android
: 相当于执行了adb shell input keyevent KEYNAME
>>> keyevent("HOME") >>> # The constant corresponding to the home key is 3 >>> keyevent("3") # same as keyevent("HOME") >>> keyevent("BACK") >>> keyevent("KEYCODE_DEL")
参见
- Module
airtest.core.android.adb.ADB.keyevent
相当于调用
android.adb.keyevent()
- Android Keyevent
Android.KeyEvent
的参考文档
Windows
: 使用pywinauto.keyboard
进行按键点击:
>>> keyevent("{DEL}") >>> keyevent("%{F4}") # close an active window with Alt+F4
参见
Module
airtest.core.win.win.Windows.keyevent
- pywinauto.keyboard
Documentation for
pywinauto.keyboard
iOS
: Only supports home/volumeUp/volumeDown:
>>> keyevent("HOME") >>> keyevent("volumeUp")
-
text
(text, enter=True, **kwargs)[源代码]¶ 在目标设备上输入文本,文本框需要处于激活状态。
参数: - text – 要输入的文本
- enter – 是否在输入完毕后,执行一次
Enter
,默认是True
返回: None
支持平台: Android, Windows, iOS
示例: >>> text("test") >>> text("test", enter=False)
在Android上,有时你需要在输入完毕后点击搜索按钮:
>>> text("test", search=True)
参见
Module
airtest.core.android.ime.YosemiteIme.code
如果希望输入其他按键,可以用这个接口:
>>> text("test") >>> device().yosemite_ime.code("3") # 3 = IME_ACTION_SEARCH
Ref: Editor Action Code
-
sleep
(secs=1.0)[源代码]¶ 设置一个等待sleep时间,它将会被显示在报告中
参数: secs – sleep的时长
返回: None
支持平台: Android, Windows, iOS
示例: >>> sleep(1)
-
wait
(v, timeout=None, interval=0.5, intervalfunc=None)[源代码]¶ 等待当前画面上出现某个匹配的Template图片
参数: - v – 要等待出现的目标Template实例
- timeout – 等待匹配的最大超时时长,默认为None即默认取
ST.FIND_TIMEOUT
的值 - interval – 尝试查找匹配项的时间间隔(以秒为单位)
- intervalfunc – 在首次尝试查找匹配失败后的回调函数
引发: TargetNotFoundError – 在超时后仍未找到目标则触发
返回: 匹配目标的坐标
支持平台: Android, Windows, iOS
示例: >>> wait(Template(r"tpl1606821804906.png")) # timeout after ST.FIND_TIMEOUT >>> # find Template every 3 seconds, timeout after 120 seconds >>> wait(Template(r"tpl1606821804906.png"), timeout=120, interval=3)
你可以在每次查找目标失败时,指定一个回调函数:
>>> def notfound(): >>> print("No target found") >>> wait(Template(r"tpl1607510661400.png"), intervalfunc=notfound)
-
exists
(v)[源代码]¶ 检查设备上是否存在给定目标
参数: v – 要检查的目标
返回: 如果未找到目标,则返回False,否则返回目标的坐标
支持平台: Android, Windows, iOS
示例: >>> if exists(Template(r"tpl1606822430589.png")): >>> touch(Template(r"tpl1606822430589.png"))
因为
exists()
会返回坐标,我们可以直接点击坐标来减少一次图像查找>>> pos = exists(Template(r"tpl1606822430589.png")) >>> if pos: >>> touch(pos)
-
find_all
(v)[源代码]¶ 在设备屏幕上查找所有出现的目标并返回其坐标列表
参数: v – 寻找目标
返回: 结果列表, [{‘result’: (x, y), ‘rectangle’: ( (left_top, left_bottom, right_bottom, right_top) ), ‘confidence’: 0.9}, …]
支持平台: Android, Windows, iOS
示例: >>> find_all(Template(r"tpl1607511235111.png")) [{'result': (218, 468), 'rectangle': ((149, 440), (149, 496), (288, 496), (288, 440)), 'confidence': 0.9999996423721313}]
Some useful functions¶
-
using
(path)[源代码]¶ Import a function from another .air script, the
using
interface will find the image path from the imported function.参数: path – relative or absolute. This function transforms a given relative path, searching in the project root, current working directory, or the current script’s directory, into an absolute path and adds it to the sys.path and G.BASEDIR. Returns:
实际案例
Suppose our project structure is as follows:
demo/ foo/ bar.air baz.air main.py
If we want to reference foo/bar.air and baz.air in main.py, we can write:
# main.py from airtest.core.api import * ST.PROJECT_ROOT = r"D:\demo" # This line can be ignored if it is the current working directory using("foo/bar.air") using("baz.air")
If we want to reference baz.air in foo/bar.air, we can write:
# foo/bar.air from airtest.core.api import * using("../baz.air")
-
log
(arg, timestamp=None, desc='', snapshot=False)[源代码]¶ Insert user log, will be displayed in Html report.
参数: - arg – log message or Exception object
- timestamp – the timestamp of the log, default is time.time()
- desc – description of log, default is arg.class.__name__
- snapshot – whether to take a screenshot, default is False
返回: None
实际案例
>>> log("hello world", snapshot=True) >>> log({"key": "value"}, timestamp=time.time(), desc="log dict") >>> try: 1/0 except Exception as e: log(e)
Assertions in airtest¶
All assert statements can be found here: airtest.core.assertions