Skip to content

9.3 Common script logic and code examples

1. Code example

Sample code for the Airtest script can be found here.The test_blackjack.air is a normal .air script. You can download it and open it in AirtestIDE for viewing.Similarly, the pure_python_example is a common .py script (the content is the same as the .py file with the same name as the .air script). In order to illustrate that an airtest script is actually a common .py file, it just introduces a third-party library airtest in python.

As for Poco's sample demo and code, please download it here. Then you can try to view the UI tree after installing it on your phone and familiar with API usage.

We also have a Example repository on Github, which contains some code examples that have appeared in this tutorial, and you can also refer to it.

2. How to connect a phone / windows window

According to the diffrent Run Script method, the method of connecting to the mobile phone is also slightly different. For example, when running the script using airtest run test.air, you only need to follow the content of the document and add --device device connection string to the command line.For how to fill in the device string, please refer to Documentation, and here is a simple example:

>airtest run untitled.air --device Android:///Mobile device number --log log/
>python -m airtest run untitled.air --device Android:///Mobile device number --log log/
If you import airtest/poco in a .py script file and want to run it as a normal python script, you can use the interface connect_device in the script code:
from airtest.core.api import *
connect_device("Android:///")  # device string
These two connection methods only need to choose one. If both are used, it is likely to cause other problems such as repeated connections.

If the device string Android: /// is not well written, you can directly connect the device with AirtestIDE first, and copy the printed string --device Android: /// when running the script in the IDE. So you can connect to the device simply and conveniently.

3. keyevent

Sometimes you need to enter some designated keys in the script, such as clicking the HOME key, BACK key, etc. If the device is an Android device, you can refer to Google's Android Key Code. (If domestic users can't open this link, they can search directly with keywords: Android keyevent).

Example: keyevent (" KEYCODE_DEL ") Or enter the key code directly, note that the parameter is a string: keyevent (" 67 ")

In Windows, please refer to the Windows Key Code provided by the pywinauto library .

Example: keyevent("{BACKSPACE}")

IOS devices only support keyevent for HOME button currently.

4. How to enter text

Text input interface in Airtest -text

If you want to implement text input in a script, you generally need this process:

  1. Click where you want to enter and activate the input cursor
  2. Call airtest's text () interface to enter content

image

As shown in the figure, the program first clicks the input location , and then calls the text interface for input. At runtime, the phone will be automatically installed with an application named yosemite.apk, and then enabled yosemite input method for input.

And it should be noted that after using the text interface, the input method of the mobile phone will be switched to the yosemite input method, so you can't see the normal keyboard (no need to panic).If you need to input manually, you can restore it by switching the input method back to the system input method in the system's input method settings. At the same time, we also provide Android phone assistant function. And in the phone assistant, you can simply click the mouse to switch the input method.

Handling of input failures

If the input of the text () interface fails, please check if your phone prevents the installation and operation of the apk, or if it is caused by compatibility issues with some phones. Please refer to Android Connection FAQ. And some models of mobile phones are not allowed to call the third-party input method when entering the password, please refer to the FAQ document to modify the phone settings.

At the same time, you can try to set the yosemite input method as the phone's default input method, and then call thetext()interface.

Some models of mobile phones fail to use the text() interface when entering the password. This is because Language and Input Method-Safe Input in the phone settings is not turned on. After turning on this option, you can use a non-native input method to enter the password.

Some special models of mobile phones may be prone to failure when using the Yosemite input method and cannot enter text (OPPO and Vivo brands are more likely to appear). If there is no need to enter Chinese, you can try to use the adb shell input command for text input :

shell("input text 'hello world'")
At the same time, the above adb shell input can be directly set as the default input method, replacing the original Yosemite input. For example, you can initialize the phone in python code like this:
from airtest.core.api import *
# Equivalent to using the --device Android:///?Ime_method=ADBIME in the command line to connect to the phone
init_device("Android", ime_method="ADBIME")
text("hello")
Some simulators (such as the Night God Simulator) may not be successful during input. You can try to confirm whether the hardware-physical keyboard is turned on in the settings, and try to close this option. Then set the default input method to yosemite input method and try again. For specific settings, please refer to Simulator related issues.

Enter and search key after input

The text interface has a default parameter enter = True, which will automatically press the Enter key (equivalent to keyevent (" ENTER ")) after inputting. If you don't need it, please enterenter = False.For some input boxes, you need to click the Search button on the input keyboard to activate the search operation after entering the content. You can pass in the parameter search = True:

text("test", search=True)
The keyevent ("ENTER") of the Enter key is different from the search and line feed operations in the input method. The extra key displayed in the input method is EDITOR CODE, and thesearch = True in this code just now is passed in the editor code 3. The search key is the most commonly used key, so we encapsulate it into the text interface. If there is a need to click other buttons besidessearch, you need to consult the document Editor Action Code to get the code (if you can't visit the webpage, you can search for the keyword IME_ACTION_SEARCH), and then manually enter the code to click:
dev = device()
# Click the Go button of the input method, IME_ACTION_GO,The corresponding key value is 2, similarly, the search key of input method actually corresponds to 3   
dev.yosemite_ime.code("2")
# The above code is equivalent to the following shell call  
# shell("am broadcast -a ADB_EDITOR_CODE --ei code 2")
For more code, you can query Editor Action Code to get it. If the webpage is not accessible, you can search for the keyword IME_ACTION_SEARCH by yourself.

set_text in Poco

In addition to the text interface of airtest, we also provide a set_text interface in poco. This interface can directly set text without calling the input method.But the specified control must be an input control. For example, in Android, it is a widget with EditText type:

poco("com.android.mms:id/recipients_editor").set_text("test")
We recommend that if the project has been connected to poco, you can try to use poco's set_text to set the text content. If you cannot input (some models and some input boxes may not support the set_text interface), then try using the text interface of airtest.

5. How to delete the contents of the input box

At present, deleting the contents of the input box can be done through the keyevent interface. Refer to the first section of this chapter 3. keyevent, it is easy to write the delete operation of the corresponding platform. For example, under the Android platform, there are two ways of writing:

keyevent("KEYCODE_DEL")
keyevent("67")  
#67 is the delete key, please note that the thing you need to pass in is a string
Airtest simulates the operation of the user. When deleting the content of an input box, the user will click the delete button N times in a row. Therefore, in the airtest script, you need to write a loop to continuously run N keyevent operations:
for i in range(10):
    keyevent("67")
However, if Poco is already connected, you can consider directly using Poco's set_text interface and setting the input box content to an empty string: poco("xxx").set_text("")

6. Properly add sleep interface to add wait in airtest script

During the script writing process, if there is a continuous click operation, the screen content may change continuously. Sometimes it may cause the script to run to the click operation, but it is found to have no effect.This is because the screen content switching speed is too fast, while the interface is not yet stable, airtest has performed element recognition and operation, which has resulted in no successful click on the corresponding element.

Therefore, we generally recommend that after some operation steps are completed, wait for a suitable time before proceeding to the next step, such as:

from airtest.core.api import *
start_app("test_package")
sleep(5)
touch([500, 500])
sleep(1)
touch([600, 0])
If you want to increase a fixed uniform waiting time after each step, we provide a global variable named OPDELAY. Setting it can modify the interval between airtest operations. You can refer to the OPDELAY related introduction in the Airtest script related configuration chapter.

7. How to reference other encapsulated methods in .air scripts

If you want to call a public function encapsulated in another .air script, you can do this:

from airtest.core.api import using
# Relative or absolute path, make sure the code can find it  
using("common.air")

from common import common_function
common_function()
If the subscripts that need to be referenced are all placed in a certain directory, you can set a default project root directory PROJECT_ROOT so that when using theusing interface, you can find other subscripts in the current root directory without filling in the complete path. In this way, it is more convenient for the scripts to call each other.

For example, we create a script named test1.air, the actual path is /User/test/project/test1.air :

from airtest.core.api import *

def test():
    touch("tmp.png")
Another script main.air in the same directory can reference the test inside test1.air:
from airtest.core.api import *

ST.PROJECT_ROOT = "/User/test/project"
using("test1.air")
from test1 import test

8. Continuous swipe and custom swipe actions

Sometimes on the Android mobile phone, we need to realize the operation of continuously sliding multiple points (such as the screen's sliding pattern unlock function).So we provide a swipe_along operation, the sample code is as follows:

from airtest.core.api import *
dev = device()  # Get the current mobile device
# Slide through 3 coordinates in order  
dev.minitouch.swipe_along([(100, 100), (200, 200), (300, 300)])
Regarding the acquisition of the screen coordinates of the mobile phone, you can refer to the content of IDE Settings-Device. Turn on the Show Real-time Cursor Coordinate option, And you can see the coordinate information on the screen of the mobile phone. You can also copy the coordinates to the clipboard by right-clicking the mouse. This can easily implement some requirements for sliding between coordinates, as shown in the figure:

image

Please note that this interface is currently only available when the default minitouch mode is used. At the same time, we also provide a custom click or slide operation scheme, which can be used for everyone to achieve more demanding operations:

from airtest.core.api import *
from airtest.core.android.minitouch import *

connect_device("Android:///")

# Realize the operation of two fingers clicking at the same time 
multitouch_event = [
    DownEvent((100, 100), 0),  # Finger 1 press (100, 100)
    DownEvent((200, 200), 1),  # Finger 2 press (200, 200)
    SleepEvent(1),
    UpEvent(0), UpEvent(1)]  # Lift two fingers separately  

device().minitouch.perform(multitouch_event)
The interface used in the above code is a low-level operation. So the coordinate system used is the original coordinates of the device, and it has not undergone coordinate conversion of the horizontal or vertical screen (the default is vertical screen).If you need to operate the horizontal screen, you can perform coordinate conversion by yourself. The specific code example address is here.

9.Import win32api on Windows reports errors

If some versions of the local Python environment are used on the Windows platform, the following error message will appear:

<Module>
    import win32api
ImportError: DLL load failed: The specified program cannot be found.
If you directly copy the dll file to the System32 directory, there may be cases where win32api can be used in airtest, but local Python cannot be used. So we recommend that you run the following instructions to update to version 223 of pywin32.
pip uninstall pywin32
pip install pywin32==223