Skip to content

5.3 Airtest launcher introduction (trial)

In the process of writing test scripts, the simple statements encapsulated by airtest may not meet the needs of more complex code writing. This chapter mainly introduces some advanced features in script writing.

Airtest scripts currently support the following custom functions:

  • Set parameters during script execution
  • Add a custom method, or replace the default method
  • Execute initialization or cleanup code, or even call other scripts

1. Launcher introduction

When Airtest runs the use case script, it implements a class called AirtestCase on the basis of inheriting unittest.TestCase, and adds all relevant functions for executing the basic Airtest script.

Therefore, if you need to add custom functions, you only need to add your own code to setup and teardown based on the AirtestCase class.If the content of these settings and functions is relatively fixed, you can use these as a launcher to initialize the relevant custom environment before running the actual test case.

For details about this section, please refer to: Related content of the Airtest help documentation.

2. Launcher example

Here is a custom sample code of custom_launcher.py:

from airtest.cli.runner import AirtestCase, run_script
from airtest.cli.parser import runner_parser


class CustomAirtestCase(AirtestCase):

    def setUp(self):
        print("custom setup")
        # add var/function/class/.. to globals
        # self.scope["hunter"] = "i am hunter"
        # self.scope["add"] = lambda x: x+1

        # exec setup script
        super(CustomAirtestCase, self).setUp()

    def tearDown(self):
        print("custom tearDown")
        # exec teardown script
        super(CustomAirtestCase, self).setUp()


if __name__ == '__main__':
    ap = runner_parser()
    args = ap.parse_args()
    run_script(args, CustomAirtestCase)

Its main function is: on the basis of AirtestCase, add some custom content, and at the same time you can also use it as a launcher to run the actual test case.

For example:

python custom_launcher.py test.air --device Android:///serial_num --log log_path

This command line uses the custom launcher custom_launcher.py to run a script named test.air.

3. Launcher in Airtest-IDE

In IDE, there are two ways to run the script. The first is to simply write the Airtest code to be run in the edit box, and then you can run the script in the default way without additional code.

The second is to implement a custom launcher based on the launcher just introduced. This will initialize a custom environment for later Airtest code to run.

Configuration method

Find the menu-"Options"-"Settings"-"Airtest", then click "Custom Launcher" to open the file selection window and select the custom file launcher.py.

Click "Edit" to edit the content of the file launcher.py, and click "OK" button to make the new configuration take effect.

Code example

The following is an example of using the launcher code in AirtestIDE (Compared to the 6.1.2 Launcher Example that can be run directly from the command line just now, the IDE can color the code line .And in the future IDE may also support additional features):

from airtest.cli.runner import run_script
from airtest.cli.parser import runner_parser
from airtest.core.settings import Settings as ST
# If the script runs in the IDE, the IDE will automatically load AirtestCase. 
# If you want to run the script independently from the command line, you need to manually import AirtestCase
if not global().get("AirtestCase"):
    from airtest.cli.runner import AirtestCase

class CustomAirtestCase(AirtestCase):
    def __init__(self):
        super(CustomAirtestCase, self).__init__()

    def setUp(self):
        print("custom setup")
        super(CustomAirtestCase, self).setUp()

    def tearDown(self):
        print("custom tearDown")
        super(CustomAirtestCase, self).tearDown()

if __name__ == '__main__':
    ap = runner_parser()
    args = ap.parse_args()
    run_script(args, CustomAirtestCase)

4. Introduction to custom content in launcher

In the custom launcher code, after inheriting AirtestCase, you can set the environment variables when executing the script in the setUp () and tearDown () methods:

class CustomAirtestCase(AirtestCase):
    def setUp(self):
        # add var/function/class/.. to globals
        super(CustomAirtestCase, self).setUp()

Add custom variables and methods

Add custom variables to self.scope, and then use this launcher to run Airtest scripts. These variables can be used directly in the script code without redefining:

def setUp(self):
    self.scope["hunter"] = "i am hunter"
    self.scope["add"] = lambda x: x+1

Add subscripts before or after the official script

When executing test cases, there is a very common type of requirement, which is to execute a fixed initialization script before the formal use case, or to execute a cleanup script after the use case is completed.

In the custom Airtest launcher, you can use very simple code to accomplish this type of requirement:

class CustomAirtestCase(AirtestCase):
    PROJECT_ROOT = "Public path for subscripts"  
    # You can place the subscripts in a public directory

    def setUp(self):
        # exec setup script
        self.exec_other_script("setup.air")  
        # Assume that the setup.air script is stored in the PROJECT_ROOT directory. You do not need to fill in the absolute path when you call it. You can write the relative path directly.
        super(CustomAirtestCase, self).setUp()

    def tearDown(self):
        # exec teardown script
        self.exec_other_script("teardown.air")
        super(CustomAirtestCase, self).setUp()

Note: The exec_other_script interface will be gradually deprecated in the future. It is now recommended that you use theusing interface provided by airtest when calling another script. See the example below.

In the official script, add the subscript

Another common requirement is to execute subscripts in the script. You can also store the subscripts in the public directory PROJECT_ROOT, and then call the code in the script test.air:

from airtest.core.api import using
using("common.air")
from common import common_function
common_function()

Modify Airtest's default parameter values

In the process of running the script and identifying the image of Airtest, because the parameter values of the default configuration may not meet the actual operation needs, the following code shows how to modify the default parameter configuration:

from airtest.core.settings import Settings as ST

class CustomAirtestCase(AirtestCase):
    def setUp(self):
        ST.THRESHOLD = 0.75

The above code changes the default image recognition threshold to 0.75 (the default value is 0.6), which reduces the error rate of image recognition.

In the settings of airtest.core.settings, the following configuration options can be modified:

THRESHOLD Image recognition threshold, between 0 and 1, the greater the higher the recognition accuracy
THRESHOLD_STRICT High demand threshold used for image recognition in assert statements, default value is 0.7
RESIZE_METHOD Redefinition of UI cross-resolution rules during image recognition
LOG_DIR The path where the script run logs are stored. The default is the current path of the script.
LOG_FILE The name of the log file for the running log. The default is log.txt.
OPDELAY How long to wait after each operation for the next operation, default 0.1s
FIND_TIMEOUT Timeout for image search, default is 20s

Register custom devices for more complex operations

In Airtest, three types of devices are supported by default: Android, Windows, and IOS. You can use the parameter --device Android: /// on the command line to execute the script to specify that the script runs on a certain type of device.

If you need to modify some of the operations of these devices, you can implement a new device and register it in Airtest, which can be called when you run the script.

For example, when the Airtest script in the IDE is running in Windows mode, some modifications to the Windows code of Airtest are required due to the size of the screenshot. So the IDE implements a new class called WindowsInIDE:

from airtest.core.win.win import Windows, screenshot
class WindowsInIDE(Windows):
    def snapshot(self, filename="tmp.png"):
        # Implemented special screenshot operations related to the IDE
        pass

Then, register this WindowsInIDE to Airtest in the launcher:

class AirtestIDECase(AirtestCase):
"""Used alone in the IDE, added special Windows related processing"""
def __init__(self):
    if get_platform() == "Windows":
        import WindowsInIDE
        # Register an ide exclusive windows mode device to airtest
        from airtest.core.api import G
        G.register_custom_device(WindowsInIDE)
    super(AirtestIDECase, self).__init__()

After registration, when executing the script, modify the device parameter in the run instruction, and you can run the script with the new device name just registered:

python launcher.py test.air --device WindowsInIDE:///

Add incoming parameters when running the script

When running the script in Airtest, the parameters attached to the command airtest run test.air are fixed. If you want to add custom parameters, you can add them inlauncher.py, so that you can get them at runtime:

class CustomAirtestCase(AirtestCase):
    def setUp(self):
        if self.args.utilfile:
            print(self.args.utilfile)

if __name__ == '__main__':
    ap = runner_parser()
    ap.add_argument(
        "--utilfile", help="utils filepath to implement your own funcs")
    args = ap.parse_args()
    run_script(args, CustomAirtestCase)

In the above example, we added a parameter --utilfile. So in the following run, we can use this parameter:

python launcher.py test.air --utilfile utils.py

5. Summary

Custom launchers can modify configuration items and implement more complex requirements. Similar to unittest, they can run the original Airtest script as a test case.

To implement a custom launcher in the IDE, follow these steps:

  1. Create a new custom_launcher.py file and implement a class that inherits AirtestCase.
  2. In the setUp () and tearDown () methods, add the operation you want to achieve.
  3. In the IDE's Options-Configuration-Airtest configuration, set custom_launcher.py just implemented as the launcher.
  4. Just click to run the script. Or use the command line: python custom_launcher.py test.air airtest + script parameters