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&param2=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("Android://127.0.0.1:5037/10.234.60.1:5555?name=serialnumber")  # add serialno to params
>>> 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
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, iOS

Example:
>>> install(r"D:\demo   est.apk")  # install Android apk
>>> # adb install -r -t D:\demo\test.apk
>>> install(r"D:\demo   est.apk", install_options=["-r", "-t"])
>>> install(r"D:\demo   est.ipa") # install iOS ipa
>>> install("http://www.example.com/test.ipa") # install iOS ipa from url
uninstall(package)[source]

Uninstall application on device

Parameters:

package – name of the package, see also start_app

Returns:

None

Platforms:

Android, iOS

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)
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 on relative coordinates, for example, click on the center of the screen:

>>> touch((0.5, 0.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)
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 on relative coordinates, for example, click on the center of the screen:

>>> touch((0.5, 0.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)
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 v2

  • swipe(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)

Use relative coordinates to swipe, such as swiping from the center right to the left of the screen:

>>> swipe((0.7, 0.5), (0.2, 0.5))
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 executing 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")

See also

Module airtest.core.android.adb.ADB.keyevent

Equivalent to calling the android.adb.keyevent()

Android Keyevent

Documentation for more Android.KeyEvent

  • Windows: Use pywinauto.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}]
get_clipboard(*args, **kwargs)[source]

Get the content from the clipboard.

Returns:

str

Platforms:

Android, iOS, Windows

Example:
>>> text = get_clipboard()  # Android or local iOS
>>> print(text)
>>> # When the iOS device is a remote device, or more than one wda is installed on the device, you need to specify the wda_bundle_id
>>> text = get_clipboard(wda_bundle_id="com.WebDriverAgentRunner.xctrunner")
>>> print(text)
set_clipboard(content, *args, **kwargs)[source]

Set the content from the clipboard.

Parameters:

content – str

Returns:

None

Platforms:

Android, iOS, Windows

Example:
>>> set_clipboard("content")  # Android or local iOS
>>> print(get_clipboard())
>>> # When the iOS device is a remote device, or more than one wda is installed on the device, you need to specify the wda_bundle_id
>>> set_clipboard("content", wda_bundle_id="com.WebDriverAgentRunner.xctrunner")
paste(*args, **kwargs)[source]

Paste the content from the clipboard.

Platforms:

Android, iOS, Windows

Returns:

None

Example:
>>> set_clipboard("content")
>>> paste()  # will paste "content" to the device

Some useful functions

using(path)[source]

Import a function from another .air script, the using interface will find the image path from the imported function.

Parameters:

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:

Examples

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 set the project root path to ST.PROJECT_ROOT, or make sure the project root path is the current working directory. 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)[source]

Insert user log, will be displayed in Html report.

Parameters:
  • 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

Returns:

None

Examples

>>> log("hello world", snapshot=True)
>>> log({"key": "value"}, timestamp=time.time(), desc="log dict")
>>> try:
        1/0
    except Exception as e:
        log(e)
logwrap(f)[source]

A decorator used to add the current function to the airtest log, which can be seen on the report html page

Parameters:

f – The function being decorated

Returns:

The decorated function

Examples

Add foo() to the airtest report html page:

@logwrap
def foo():
    pass

Assertions in airtest

All assert statements can be found here: airtest.core.assertions