airtest.core.api module¶
This module contains the Airtest Core APIs.
-
init_device
(platform='Android', uuid=None, **kwargs)[source]¶ Initialize device if not yet, and set as current device.
Parameters: - platform – Android, IOS or Windows
- uuid – uuid for target device, e.g. serialno for Android, handle for Windows, uuid for iOS
- kwargs – Optional platform specific keyword args, e.g. cap_method=JAVACAP for Android
Returns: device instance
Example: >>> init_device(platform="Android",uuid="SJE5T17B17", cap_method="JAVACAP") >>> init_device(platform="Windows",uuid="123456")
-
connect_device
(uri)[source]¶ Initialize device with uri, and set as current device.
Parameters: uri – an URI where to connect to device, e.g. android://adbhost:adbport/serialno?param=value¶m2=value2
Returns: device instance
Example: >>> 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:///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
-
device
()[source]¶ Return the current active device.
Returns: current device instance
Example: >>> dev = device() >>> dev.touch((100, 100))
-
set_current
(idx)[source]¶ Set current active device.
Parameters: idx – uuid or index of initialized device instance
Raises: IndexError – raised when device idx is not found
Returns: None
Platforms: Android, iOS, Windows
Example: >>> # 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)[source]¶ Auto setup running env and try connect android device if not device connected.
Parameters: - basedir – basedir of script, __file__ is also acceptable.
- devices – connect_device uri in list.
- logdir – log dir for script report, default is None for no log, set to
True
for<basedir>/log
. - project_root – project root dir for using api.
- compress – The compression rate of the screenshot image, integer in range [1, 99], default is 10
Example: >>> auto_setup(__file__) >>> auto_setup(__file__, devices=["Android://127.0.0.1:5037/SJE5T17B17"], ... logdir=True, project_root=r"D:\test\logs", compress=90)
-
shell
(cmd)[source]¶ Start remote shell in the target device and execute the command
Parameters: cmd – command to be run on device, e.g. “ls /data/local/tmp”
Returns: the output of the shell cmd
Platforms: Android
Example: >>> # 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)[source]¶ Start the target application on device
Parameters: - package – name of the package to be started, e.g. “com.netease.my”
- activity – the activity to start, default is None which means the main activity
Returns: None
Platforms: Android, iOS
Example: >>> start_app("com.netease.cloudmusic") >>> start_app("com.apple.mobilesafari") # on iOS
-
stop_app
(package)[source]¶ Stop the target application on device
Parameters: package – name of the package to stop, see also start_app
Returns: None
Platforms: Android, iOS
Example: >>> stop_app("com.netease.cloudmusic")
-
clear_app
(package)[source]¶ Clear data of the target application on device
Parameters: package – name of the package, see also start_app
Returns: None
Platforms: Android
Example: >>> clear_app("com.netease.cloudmusic")
-
install
(filepath, **kwargs)[source]¶ Install application on device
Parameters: - filepath – the path to file to be installed on target device
- kwargs – platform specific kwargs, please refer to corresponding docs
Returns: None
Platforms: Android
Example: >>> install(r"D:\demo\test.apk") >>> # adb install -r -t D:\demo\test.apk >>> install(r"D:\demo\test.apk", install_options=["-r", "-t"])
-
uninstall
(package)[source]¶ Uninstall application on device
Parameters: package – name of the package, see also start_app
Returns: None
Platforms: Android
Example: >>> uninstall("com.netease.cloudmusic")
-
snapshot
(filename=None, msg='', quality=None, max_size=None)[source]¶ Take the screenshot of the target device and save it to the file.
Parameters: - filename – name of the file where to save the screenshot. If the relative path is provided, the default
location is
ST.LOG_DIR
- msg – short description for screenshot, it will be recorded in the report
- quality – The image quality, integer in range [1, 99], default is 10
- max_size – the maximum size of the picture, e.g 1200
Returns: {“screen”: filename, “resolution”: resolution of the screen} or None
Platforms: Android, iOS, Windows
Example: >>> snapshot(msg="index") >>> # save the screenshot to test.jpg >>> snapshot(filename="test.png", msg="test")
The quality and size of the screenshot can be set:
>>> # 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)
- filename – name of the file where to save the screenshot. If the relative path is provided, the default
location is
-
wake
()[source]¶ Wake up and unlock the target device
Returns: None
Platforms: Android
Example: >>> wake()
Note
Might not work on some models
-
home
()[source]¶ Return to the home screen of the target device.
Returns: None
Platforms: Android, iOS
Example: >>> home()
-
touch
(v, times=1, **kwargs)[source]¶ Perform the touch action on the device screen
Parameters: - v – target to touch, either a
Template
instance or absolute coordinates (x, y) - times – how many touches to be performed
- kwargs – platform specific kwargs, please refer to corresponding docs
Returns: finial position to be clicked, e.g. (100, 100)
Platforms: Android, Windows, iOS
Example: Click absolute coordinates:
>>> touch((100, 100))
Click the center of the picture(Template object):
>>> touch(Template(r"tpl1606730579419.png", target_pos=5))
Click 2 times:
>>> touch((100, 100), times=2)
Under Android and Windows platforms, you can set the click duration:
>>> touch((100, 100), duration=2)
Right click(Windows):
>>> touch((100, 100), right_click=True)
- v – target to touch, either a
-
click
(v, times=1, **kwargs)¶ Perform the touch action on the device screen
Parameters: - v – target to touch, either a
Template
instance or absolute coordinates (x, y) - times – how many touches to be performed
- kwargs – platform specific kwargs, please refer to corresponding docs
Returns: finial position to be clicked, e.g. (100, 100)
Platforms: Android, Windows, iOS
Example: Click absolute coordinates:
>>> touch((100, 100))
Click the center of the picture(Template object):
>>> touch(Template(r"tpl1606730579419.png", target_pos=5))
Click 2 times:
>>> touch((100, 100), times=2)
Under Android and Windows platforms, you can set the click duration:
>>> touch((100, 100), duration=2)
Right click(Windows):
>>> touch((100, 100), right_click=True)
- v – target to touch, either a
-
double_click
(v)[source]¶ Perform double click
Parameters: v – target to touch, either a
Template
instance or absolute coordinates (x, y)Returns: finial position to be clicked
Example: >>> double_click((100, 100)) >>> double_click(Template(r"tpl1606730579419.png"))
-
swipe
(v1, v2=None, vector=None, **kwargs)[source]¶ Perform the swipe action on the device screen.
- There are two ways of assigning the parameters
swipe(v1, v2=Template(...))
# swipe from v1 to v2swipe(v1, vector=(x, y))
# swipe starts at v1 and moves along the vector.
Parameters: - v1 – the start point of swipe, either a Template instance or absolute coordinates (x, y)
- v2 – the end point of swipe, either a Template instance or absolute coordinates (x, y)
- vector – a vector coordinates of swipe action, either absolute coordinates (x, y) or percentage of screen e.g.(0.5, 0.5)
- **kwargs –
platform specific kwargs, please refer to corresponding docs
Raises: Exception – general exception when not enough parameters to perform swap action have been provided
Returns: Origin position and target position
Platforms: Android, Windows, iOS
Example: >>> swipe(Template(r"tpl1606814865574.png"), vector=[-0.0316, -0.3311]) >>> swipe((100, 100), (200, 200))
Custom swiping duration and number of steps(Android and iOS):
>>> # 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)[source]¶ Perform the pinch action on the device screen
Parameters: - in_or_out – pinch in or pinch out, enum in [“in”, “out”]
- center – center of pinch action, default as None which is the center of the screen
- percent – percentage of the screen of pinch action, default is 0.5
Returns: None
Platforms: Android
Example: Pinch in the center of the screen with two fingers:
>>> pinch()
Take (100,100) as the center and slide out with two fingers:
>>> pinch('out', center=(100, 100))
-
keyevent
(keyname, **kwargs)[source]¶ Perform key event on the device
Parameters: - keyname – platform specific key name
- **kwargs –
platform specific kwargs, please refer to corresponding docs
Returns: None
Platforms: Android, Windows, iOS
Example: Android
: it is equivalent to executingadb 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")
See also
- Module
airtest.core.android.adb.ADB.keyevent
Equivalent to calling the
android.adb.keyevent()
- Android Keyevent
Documentation for more
Android.KeyEvent
Windows
: Usepywinauto.keyboard
module for key input:
>>> keyevent("{DEL}") >>> keyevent("%{F4}") # close an active window with Alt+F4
See also
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)[source]¶ Input text on the target device. Text input widget must be active first.
Parameters: - text – text to input, unicode is supported
- enter – input Enter keyevent after text input, default is True
Returns: None
Platforms: Android, Windows, iOS
Example: >>> text("test") >>> text("test", enter=False)
On Android, sometimes you need to click the search button after typing:
>>> text("test", search=True)
See also
Module
airtest.core.android.ime.YosemiteIme.code
If you want to enter other keys on the keyboard, you can use the interface:
>>> text("test") >>> device().yosemite_ime.code("3") # 3 = IME_ACTION_SEARCH
Ref: Editor Action Code
-
sleep
(secs=1.0)[source]¶ Set the sleep interval. It will be recorded in the report
Parameters: secs – seconds to sleep
Returns: None
Platforms: Android, Windows, iOS
Example: >>> sleep(1)
-
wait
(v, timeout=None, interval=0.5, intervalfunc=None)[source]¶ Wait to match the Template on the device screen
Parameters: - v – target object to wait for, Template instance
- timeout – time interval to wait for the match, default is None which is
ST.FIND_TIMEOUT
- interval – time interval in seconds to attempt to find a match
- intervalfunc – called after each unsuccessful attempt to find the corresponding match
Raises: TargetNotFoundError – raised if target is not found after the time limit expired
Returns: coordinates of the matched target
Platforms: Android, Windows, iOS
Example: >>> 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)
You can specify a callback function every time the search target fails:
>>> def notfound(): >>> print("No target found") >>> wait(Template(r"tpl1607510661400.png"), intervalfunc=notfound)
-
exists
(v)[source]¶ Check whether given target exists on device screen
Parameters: v – target to be checked
Returns: False if target is not found, otherwise returns the coordinates of the target
Platforms: Android, Windows, iOS
Example: >>> if exists(Template(r"tpl1606822430589.png")): >>> touch(Template(r"tpl1606822430589.png"))
Since
exists()
will return the coordinates, we can directly click on this return value to reduce one image search:>>> pos = exists(Template(r"tpl1606822430589.png")) >>> if pos: >>> touch(pos)
-
find_all
(v)[source]¶ Find all occurrences of the target on the device screen and return their coordinates
Parameters: v – target to find
Returns: list of results, [{‘result’: (x, y), ‘rectangle’: ( (left_top, left_bottom, right_bottom, right_top) ), ‘confidence’: 0.9}, …]
Platforms: Android, Windows, iOS
Example: >>> find_all(Template(r"tpl1607511235111.png")) [{'result': (218, 468), 'rectangle': ((149, 440), (149, 496), (288, 496), (288, 440)), 'confidence': 0.9999996423721313}]
Assertions in airtest¶
All assert statements can be found here: airtest.core.assertions