### Application Management: start_app(), stop_app(), clear_app(), install(), uninstall() Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md APIs for managing applications on the device, including starting, stopping, clearing data, installing, and uninstalling. ```APIDOC ## Application Management ### start_app(package_name) Starts the specified application on the device. ### Method `start_app(package_name)` ### Parameters - **package_name** (str) - The package name of the application (e.g., 'com.netease.cloudmusic'). Supported on Android and iOS. ### Request Example ```python start_app("com.netease.cloudmusic") ``` ### stop_app(package_name) Stops the specified application on the device. ### Method `stop_app(package_name)` ### Parameters - **package_name** (str) - The package name of the application. Supported on Android and iOS. ### Request Example ```python stop_app("com.netease.cloudmusic") ``` ### clear_app(package_name) Clears the data of the specified application on the device. ### Method `clear_app(package_name)` ### Parameters - **package_name** (str) - The package name of the application. **Android only**. ### Request Example ```python clear_app("com.netease.cloudmusic") ``` ### install(filepath) Installs an application from a file onto the device. ### Method `install(filepath)` ### Parameters - **filepath** (str) - The full path to the application installation file (e.g., .apk). **Android only**. ### Request Example ```python install(r"D:\demo\tutorial-blackjack-release-signed.apk") ``` ### uninstall(package_name) Uninstalls the specified application from the device. ### Method `uninstall(package_name)` ### Parameters - **package_name** (str) - The package name of the application to uninstall. **Android only**. ### Request Example ```python uninstall("com.netease.cloudmusic") ``` ``` -------------------------------- ### Install and Control Android Application Source: https://github.com/airtestproject/airtest/blob/master/playground/test_blackjack.air/test_blackjack.html Use these commands to install an APK, stop a running application, and then start it again. A short sleep is included to ensure the application is ready before proceeding. ```python PKG = "org.cocos2d.blackjack" APK = "blackjack-release-signed.apk" install(APK) amstop(PKG) amstart(PKG) sleep(1) ``` -------------------------------- ### Start Screen Recording with Maximum Time Limit Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/device/android.md This example shows how to start screen recording with a specified maximum duration using `max_time`. The recording will automatically stop after the set time. Ensure `device()` is available. ```python dev = device() dev.start_recording(max_time=30, bit_rate_level=5) dev.stop_recording(output="test_30s.mp4") ``` -------------------------------- ### Install and Prepare Application Source: https://context7.com/airtestproject/airtest/llms.txt Installs the application if not present, then stops and clears it to ensure a clean state before testing. ```python dev = device() if PKG not in dev.list_app(): log("Installing application...") install(APK) # Ensure clean state stop_app(PKG) clear_app(PKG) ``` -------------------------------- ### Install Application: install() Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code.md Installs an application package onto the connected device. Provide the path to the .apk or .ipa file. ```python from airtest.core.api import * install("/path/to/your/app.apk") ``` -------------------------------- ### Minitouch Class Methods Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.touch_methods.minitouch.md This section covers the core methods of the Minitouch class for installation, uninstallation, server setup, client setup, coordinate transformation, and teardown. ```APIDOC ## Minitouch Class ### Description Provides methods for interacting with the Minitouch server on Android devices for touch input simulation. ### Methods #### install() ##### Description Install minitouch. ##### Returns None #### uninstall() ##### Description Uninstall minitouch. ##### Returns None #### setup_server() ##### Description Setup minitouch server and adb forward. ##### Returns server process #### setup_client() ##### Description Setup client in following steps: 1. connect to server 2. receive the header v ^ $ 3. prepare to send ##### Returns None #### transform_xy(x, y) ##### Description Transform coordinates (x, y) according to the device display. ##### Parameters - **x** (coordinate x) - **y** (coordinate y) ##### Returns transformed coordinates (x, y) #### teardown() ##### Description Stop the server and client. ##### Returns None ``` -------------------------------- ### Install App (Recommended) Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.adb.md A recommended method for installing APK files that combines push and install operations. Supports replacing existing installations and various installation options. ```python >>> adb.pm_install("/path/to/your/app.apk") >>> adb.pm_install("/path/to/your/app.apk", replace=True, install_options=["-t"]) ``` -------------------------------- ### Initialize TouchProxy with Auto Setup Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.touch_methods.touch_proxy.md Use this method to automatically set up a TouchProxy instance. It requires an ADB object and can optionally take an orientation transformer and display information. This is the recommended way to get a TouchProxy object for performing touch actions. ```python >>> dev = Android() >>> touch_proxy = TouchProxy.auto_setup(dev.adb, ori_transformer=dev._touch_point_by_orientation) >>> touch_proxy.touch((100, 100)) ``` -------------------------------- ### Start Application: start_app() Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code.md Launches a specified application on the connected device. Provide the package name of the app to start. ```python from airtest.core.api import * start_app("com.example.app") ``` -------------------------------- ### Environment Setup and Shell Commands Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.api.md APIs for automatic environment setup and executing shell commands on devices. ```APIDOC ## POST /airtest/auto_setup ### Description Auto setup running env and try connect android device if not device connected. ### Method POST ### Endpoint /airtest/auto_setup ### Parameters #### Request Body - **basedir** (string) - Optional - basedir of script, __file__ is also acceptable. - **devices** (array of strings) - Optional - connect_device uri in list. - **logdir** (string or boolean) - Optional - log dir for script report, default is None for no log, set to `True` for `/log`. - **project_root** (string) - Optional - project root dir for using api. - **compress** (integer) - Optional - The compression rate of the screenshot image, integer in range [1, 99], default is 10 ### Request Example ```json { "basedir": "/path/to/script", "devices": ["Android:///SJE5T17B17"], "logdir": true, "project_root": "/path/to/project", "compress": 90 } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful setup. #### Response Example ```json { "message": "Environment setup complete." } ``` ## POST /airtest/shell ### Description Start remote shell in the target device and execute the command. ### Method POST ### Endpoint /airtest/shell ### Parameters #### Request Body - **cmd** (string) - Required - Command to be run on device, e.g. “ls /data/local/tmp” - **device_uri** (string) - Optional - URI of the target device if not the current one. ### Request Example ```json { "cmd": "ls", "device_uri": "Android:///device1" } ``` ### Response #### Success Response (200) - **output** (string) - The output of the shell command. #### Response Example ```json { "output": "file1\nfile2\n" } ``` ``` -------------------------------- ### Complete Airtest Test Example Source: https://context7.com/airtestproject/airtest/llms.txt A comprehensive example demonstrating common Airtest patterns for mobile game testing, including setup, configuration, and basic interactions. ```python # -*- encoding=utf8 -*- """ Complete Airtest Test Example Tests a mobile game installation, launch, and basic interactions """ from airtest.core.api import * from airtest.core.cv import Template import os # Setup test environment auto_setup(__file__, logdir=True) # Configuration PWD = os.path.dirname(__file__) PKG = "com.example.game" APK = os.path.join(PWD, "game.apk") ``` -------------------------------- ### Install Application Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.api.md Installs an application on the target device from a local file path or a URL. Supports platform-specific installation options. ```python >>> install(r"D:\demo est.apk") # install Android apk ``` ```python >>> install(r"D:\demo est.apk", install_options=["-r", "-t"]) ``` ```python >>> install(r"D:\demo est.ipa") # install iOS ipa ``` ```python >>> install("http://www.example.com/test.ipa") # install iOS ipa from url ``` -------------------------------- ### Automatic Environment Setup with Airtest Source: https://context7.com/airtestproject/airtest/llms.txt Automate environment setup, device connection, and logging directory creation. Configure devices, log directory location, project root, and screenshot compression quality. ```python from airtest.core.api import auto_setup # Basic setup with current script file auto_setup(__file__) # Full setup with devices, logging, and project root auto_setup( __file__, devices=["Android://127.0.0.1:5037/SJE5T17B17"], logdir=True, # Creates log directory in script folder project_root=r"D:\\test\\project", compress=90 # Screenshot compression quality (1-99) ) ``` -------------------------------- ### Maxtouch Class Methods Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.touch_methods.maxtouch.md This section covers the core methods of the Maxtouch class, including installation, uninstallation, server setup, client setup, coordinate transformation, and teardown. ```APIDOC ## Maxtouch Class ### Description Provides touch methods using Maxtouch for Android devices. ### Methods #### install() ##### Description Install maxtouch. ##### Returns None #### uninstall() ##### Description Uninstall maxtouch. ##### Returns None #### setup_server() ##### Description Setup maxtouch server and adb forward. ##### Returns server process #### setup_client() ##### Description Setup client. ##### Returns None #### transform_xy(x, y) ##### Description Normalized coordinates (x, y). ##### Parameters - **x** (coordinate x) - Required - **y** (coordinate y) - Required ##### Returns transformed coordinates (x, y) #### teardown() ##### Description Stop the server and client. ##### Returns None ``` -------------------------------- ### Start Application and Measure Launch Time Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.android.md Start an application package and its activity, and measure the time it takes for the application to launch. ```python >>> dev.start_app_timing('com.example.app', 'com.example.app.MainActivity') ``` -------------------------------- ### Start and Wait for Application Source: https://context7.com/airtestproject/airtest/llms.txt Starts the application, waits for a specified duration, and then waits for the main menu to load using image recognition. ```python # Start test wake() start_app(PKG) sleep(3) # Wait for main menu try: wait(Template(r"main_menu.png"), timeout=30) log("Main menu loaded", snapshot=True) except TargetNotFoundError: log("Failed to load main menu", snapshot=True) raise ``` -------------------------------- ### Install App Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.adb.md Installs an application package onto the device. Supports replacing existing installations and various installation options. ```python >>> adb.install_app("/path/to/your/app.apk") >>> adb.install_app("/path/to/your/app.apk", replace=True, install_options=["-t", "-g"]) ``` -------------------------------- ### App Installation API Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.android.md APIs for installing and uninstalling applications on a device. ```APIDOC ## POST /airtestproject/airtest/install_multiple_app ### Description Install multiple applications on the device from a given filepath. ### Method POST ### Endpoint /airtestproject/airtest/install_multiple_app ### Parameters #### Query Parameters - **filepath** (string) - Required - Full path to the apk file to be installed on the device. - **replace** (boolean) - Optional - True to replace the existing application, False otherwise. Defaults to False. - **install_options** (list) - Optional - List of installation options. Defaults to []. ### Response #### Success Response (200) - **output** (string) - Output from the installation process. ## POST /airtestproject/airtest/uninstall_app ### Description Uninstall the application from the device. ### Method POST ### Endpoint /airtestproject/airtest/uninstall_app ### Parameters #### Query Parameters - **package** (string) - Required - Package name of the application to uninstall. ### Response #### Success Response (200) - **output** (string) - Output from the uninstallation process. ``` -------------------------------- ### Auto Setup with Custom Devices and Logging Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.api.md Configures the Airtest environment with a specified list of devices, enables logging to a specified directory, sets a project root, and defines screenshot compression level. This provides a comprehensive setup for complex test scenarios. ```python >>> auto_setup(__file__, devices=["Android://127.0.0.1:5037/SJE5T17B17"], ... logdir=True, project_root=r"D:\\test\\logs", compress=90) ``` -------------------------------- ### Install Multiple Apps with Airtest Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.android.md Installs multiple applications onto the device from a specified file path. Supports replacing existing applications and custom installation options. ```python install_multiple_app(filepath, replace=False, install_options=None) ``` -------------------------------- ### Start Android Application Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.api.md Starts a specified Android application package. Use this to launch applications for testing. ```python >>> start_app("com.netease.cloudmusic") ``` -------------------------------- ### Install Application Source: https://context7.com/airtestproject/airtest/llms.txt Install an application on the connected device. Supports Android APKs and iOS IPAs, including installation from URLs for iOS. ```python from airtest.core.api import install # Install Android APK install(r"D:\\apps\\myapp.apk") ``` ```python # Install with options (Android) install(r"D:\\apps\\myapp.apk", install_options=["-r", "-t"]) ``` ```python # Install iOS IPA install(r"D:\\apps\\myapp.ipa") ``` ```python # Install from URL (iOS) install("https://example.com/app.ipa") ``` -------------------------------- ### Start Screen Recording Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.win.win.md Starts recording the device display for a specified duration and saves it to a file. The recording region is limited by the initial app window size. Smaller max_size values reduce CPU load. ```python >>> from airtest.core.api import connect_device, sleep >>> dev = connect_device("Windows:///") >>> save_path = dev.start_recording(output="test.mp4") >>> sleep(30) >>> dev.stop_recording() >>> print(save_path) ``` ```python >>> dev.start_recording(output="test.mp4", max_size=800) ``` -------------------------------- ### Install Multiple Apps Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.adb.md Installs multiple application packages simultaneously. Supports replacing existing installations and various installation options, including partial installs. ```python >>> adb.install_multiple_app(["/path/to/app1.apk", "/path/to/app2.apk"]) >>> adb.install_multiple_app(["/path/to/app.apk"], install_options=["-p"]) ``` -------------------------------- ### Basic Airtest API Usage Source: https://github.com/airtestproject/airtest/blob/master/README.md Connect to an Android device, install an APK, start an app, perform touch and swipe gestures, assert element existence, use key events, and uninstall the app. Ensure you have image templates like 'image_of_a_button.png' available. ```Python from airtest.core.api import * # connect an android phone with adb init_device("Android") # or use connect_device api # connect_device("Android:///") install("path/to/your/apk") start_app("package_name_of_your_apk") touch(Template("image_of_a_button.png")) swipe(Template("slide_start.png"), Template("slide_end.png")) assert_exists(Template("success.png")) keyevent("BACK") home() uninstall("package_name_of_your_apk") ``` -------------------------------- ### Application Installation and Uninstallation Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example.md APIs for installing and uninstalling applications on Android devices. ```APIDOC ## Install Application: install() ### Description Installs an application on the device using its complete APK path. This function only supports the Android platform. ### Method N/A (Function call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python install(r"D:\demo\tutorial-blackjack-release-signed.apk") ``` ## Uninstall Application: uninstall() ### Description Uninstalls an application from the device using its package name. This function only supports the Android platform. ### Method N/A (Function call) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```python uninstall("com.netease.cloudmusic") ``` ``` -------------------------------- ### Start iOS Application Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.api.md Starts a specified iOS application. This is used to launch applications on iOS devices for automation. ```python >>> start_app("com.apple.mobilesafari") # on iOS ``` -------------------------------- ### Install Airtest from Git Repository Source: https://github.com/airtestproject/airtest/blob/master/docs/README_MORE.md Clones the Airtest repository from GitHub and installs it in develop mode using pip. This allows for easier updates via git pull. ```shell git clone https://github.com/AirtestProject/Airtest.git pip install -e airtest ``` -------------------------------- ### Minitouch Protocol Example Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.touch_methods.base_touch.md Example of the minitouch protocol for performing a touch event. This sequence involves pressing down, clicking, waiting, and then releasing. ```default d 0 10 10 50 c u 0 c ``` -------------------------------- ### Install Airtest Python Library Source: https://github.com/airtestproject/airtest/blob/master/README.md Install the Airtest Python library using pip. On macOS/Linux, you may need to grant execute permissions to the adb binary. ```Shell pip install -U airtest ``` ```Shell # for mac cd {your_python_path}/site-packages/airtest/core/android/static/adb/mac # for linux # cd {your_python_path}/site-packages/airtest/core/android/static/adb/linux chmod +x adb ``` -------------------------------- ### Pinch Action Minitouch Protocol Example Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.touch_methods.base_touch.md Example of the minitouch protocol for performing a pinch action. This sequence shows how to control two fingers to pinch in or out on the screen. ```default d 0 0 100 50 d 1 100 0 50 c m 0 10 90 50 m 1 90 10 50 c m 0 20 80 50 m 1 80 20 50 c m 0 20 80 50 m 1 80 20 50 c m 0 30 70 50 m 1 70 30 50 c m 0 40 60 50 m 1 60 40 50 c m 0 50 50 50 m 1 50 50 50 c u 0 u 1 c ``` -------------------------------- ### Launch Application Source: https://context7.com/airtestproject/airtest/llms.txt Start an application on the device. Can specify package name, activity for Android, or just the bundle ID for iOS. ```python from airtest.core.api import start_app # Start app by package name (Android) start_app("com.netease.cloudmusic") ``` ```python # Start app with specific activity (Android) start_app("com.example.app", activity=".MainActivity") ``` ```python # Start app (iOS) start_app("com.apple.mobilesafari") ``` -------------------------------- ### Initialize Airtest Script: auto_setup() Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code.md Use auto_setup() to initialize your Airtest script. This function typically handles necessary setup before script execution. ```python from airtest.core.api import * auto_setup(__file__) ``` -------------------------------- ### Install Airtest Python Package Source: https://github.com/airtestproject/airtest/blob/master/docs/README_MORE.md Installs the Airtest Python package and its dependencies using pip. Use -U for upgrading. ```shell pip install -U airtest ``` -------------------------------- ### Device Management: device(), get_current_device(), set_current() Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md APIs for getting the current device instance and switching between multiple connected devices. ```APIDOC ## Device Management ### device() Returns the instance of the currently active device. ### Method `device()` ### Request Example ```python dev = device() dev.swipe_along([[959, 418],[1157, 564],[1044, 824],[751, 638],[945, 415]]) ``` ### set_current(device_identifier) Sets the currently active device, allowing switching between multiple devices. ### Method `set_current(device_identifier)` ### Parameters - **device_identifier** (int or str) - Can be an index (0, 1, 2...) or a device serial number/UUID. ### Request Example ```python # Switch to the first connected device (index 0) set_current(0) # Switch to the device with serial number 'serialno1' set_current("serialno1") ``` ``` -------------------------------- ### Setup Port Forward Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.adb.md Sets up a local port forward to a device port. Generates a pseudo-random local port if not specified. Supports the 'no-rebind' option. ```python >>> local_port, device_port = adb.setup_forward("tcp:5001") >>> print(f"Forwarding local port {local_port} to device port {device_port}") >>> local_port, device_port = adb.setup_forward(5002, no_rebind=False) >>> print(f"Forwarding local port {local_port} to device port {device_port}") ``` -------------------------------- ### Two Finger Swipe Minitouch Protocol Example Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.touch_methods.base_touch.md Example of the minitouch protocol for performing a two-finger swipe. This demonstrates the sequence of commands for moving two fingers simultaneously across the screen. ```default d 0 0 0 50 d 1 1 0 50 c m 0 20 0 50 m 1 21 0 50 c m 0 40 0 50 m 1 41 0 50 c m 0 60 0 50 m 1 61 0 50 c m 0 80 0 50 m 1 81 0 50 c m 0 100 0 50 m 1 101 0 50 c u 0 u 1 c ``` -------------------------------- ### Start Application on Android Device Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.android.md Launch an application package on the Android device. An optional activity name can also be provided. ```python >>> dev.start_app('com.example.app') ``` -------------------------------- ### Application Management Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.api.md APIs for starting and managing applications on connected devices. ```APIDOC ## POST /airtest/start_app ### Description Start the target application on device. ### Method POST ### Endpoint /airtest/start_app ### Parameters #### Request Body - **package** (string) - Required - Name of the package to be started, e.g. “com.netease.my” - **activity** (string) - Optional - The activity to start, default is None which means the main activity ### Request Example ```json { "package": "com.apple.mobilesafari", "activity": "com.apple.mobilesafari.Safari" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates success. #### Response Example ```json { "message": "Application started successfully." } ``` ``` -------------------------------- ### Set and Get Clipboard Content Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.android.md Demonstrates how to set text content to the device's clipboard and then retrieve it. Also shows how to paste the clipboard content. ```python >>> dev = Android() >>> dev.set_clipboard("hello world") >>> dev.get_clipboard() 'hello world' >>> dev.paste() # paste the clipboard content ``` -------------------------------- ### Initialize and Use ScreenProxy Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.cap_methods.screen_proxy.md Demonstrates how to initialize ScreenProxy using auto_setup with an Android device and then capture and teardown the screen stream. Ensure an Android device is connected and ADB is set up. ```python dev = Android() screen_proxy = ScreenProxy.auto_setup(dev.adb, rotation_watcher=dev.rotation_watcher) screen_proxy.get_frame_from_stream() screen_proxy.teardown_stream() ``` -------------------------------- ### Airtest Screen Recording Source: https://github.com/airtestproject/airtest/blob/master/playground/test_blackjack.air/test_blackjack.html Demonstrates how to start and stop screen recording using Airtest. This is useful for capturing video evidence of test execution. ```python from airtest.core.api import * # Start screen recording # The recording will be saved in the current directory or a specified path # start_recording("my_test_recording.mp4") # Perform test actions here # touch((100, 100)) # sleep(1) # Stop screen recording # stop_recording() # Example with specific parameters (e.g., resolution, bitrate) # start_recording(filename="high_quality_recording.mp4", resolution=(1920, 1080), bitrate=4000000) # ... actions ... # stop_recording() print("Screen recording examples.") ``` -------------------------------- ### Get Android Device Information Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/device/android.md Retrieve the current Android device object and access its built-in methods to get display information and list installed applications. ```python dev = device() # gets the Android object to the current device print(dev.get_display_info()) # to view the display information for the current device print(dev.list_app()) # prints out the list of currently installed apps ``` -------------------------------- ### Airtest Script Execution Source: https://github.com/airtestproject/airtest/blob/master/playground/test_blackjack.air/test_blackjack.html This snippet demonstrates how to execute an Airtest script. Ensure the Airtest framework is properly installed and configured before running. ```python from airtest.core.api import * from airtest.cli.parser import script_helper if __name__ == "__main__": script_helper("__file__") ``` -------------------------------- ### 初始化Airtest脚本环境 Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md 使用auto_setup()自动配置运行环境,可设置脚本路径、设备、日志路径、项目根目录和截图压缩精度。 ```default auto_setup(basedir=None, devices=None, logdir=None, project_root=None, compress=None) ``` ```default auto_setup(__file__) ``` ```default auto_setup(__file__, devices=["android://127.0.0.1:5037/emulator-5554?cap_method=JAVACAP&&ori_method=MINICAPORI&&touch_method=MINITOUCH"], logdir=True, project_root=r"D\test", compress=90) ``` -------------------------------- ### Airtest Log and Reporting Source: https://github.com/airtestproject/airtest/blob/master/playground/test_blackjack.air/test_blackjack.html This example shows how to generate logs and reports for Airtest scripts. Proper logging is crucial for debugging and tracking test execution. ```python from airtest.core.api import * # Log a message log("Starting the test sequence...") # Log an image log(msg="Screenshot", image=snapshot()) # The reporting is usually handled by the Airtest IDE or CLI runner. ``` -------------------------------- ### Get Application Path on Android Device Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.android.md Find the full path of an installed application package on the Android device. ```python >>> dev.path_app('com.example.app') ``` -------------------------------- ### App Management Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.android.md Functions for managing applications on an Android device, including listing, checking, starting, stopping, clearing, and installing apps. ```APIDOC ## App Management ### Description Manage applications installed on the Android device. ### Methods #### `list_app(third_only=False)` Lists installed applications. - **Parameters**: - **third_only** (bool) - Optional - If True, only lists third-party applications. - **Returns**: - array of application package names. #### `path_app(package)` Gets the full path of an installed application package. - **Parameters**: - **package** (str) - Required - The package name of the application. - **Returns**: - The full path to the application package. #### `check_app(package)` Checks if a specific application package is installed on the device. - **Parameters**: - **package** (str) - Required - The package name to check. - **Returns**: - True if the package exists, False otherwise. - **Raises**: - `AirtestError` - If the package is not found. #### `start_app(package, activity=None)` Starts an application and optionally a specific activity. - **Parameters**: - **package** (str) - Required - The package name of the application. - **activity** (str) - Optional - The activity name to start. - **Returns**: - None. #### `start_app_timing(package, activity)` Starts an application and measures the launch time. - **Parameters**: - **package** (str) - Required - The package name of the application. - **activity** (str) - Required - The activity name to start. - **Returns**: - The application launch time in seconds. #### `stop_app(package)` Stops a running application. - **Parameters**: - **package** (str) - Required - The package name of the application. - **Returns**: - None. #### `clear_app(package)` Clears all data associated with an application. - **Parameters**: - **package** (str) - Required - The package name of the application. - **Returns**: - None. #### `install_app(filepath, replace=False, install_options=None)` Installs an application (APK file) onto the device. - **Parameters**: - **filepath** (str) - Required - The full path to the APK file. - **replace** (bool) - Optional - If True, replaces the existing application. Defaults to False. - **install_options** (list) - Optional - A list of additional installation options. - **Returns**: - The output from the installation process. ### Examples ```python >>> from airtest.core.android import Android >>> dev = Android() >>> apps = dev.list_app() >>> dev.start_app('com.example.app') >>> dev.stop_app('com.example.app') >>> dev.install_app('/path/to/your/app.apk') ``` ``` -------------------------------- ### 启动Android/iOS应用 Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md 使用start_app()启动目标应用,需传入应用的包名,支持Android和iOS平台。 ```default start_app("com.netease.cloudmusic") ``` -------------------------------- ### Basic Airtest Script Source: https://github.com/airtestproject/airtest/blob/master/playground/test_blackjack.air/test_blackjack.html A fundamental Airtest script demonstrating basic operations. This snippet is useful for getting started with Airtest for automated testing. ```python from airtest.core.api import * # Initialize device auto_setup(__file__, log=True) # Example: Touch a specific coordinate touch((100, 200)) # Example: Swipe from one point to another swipe((300, 400), (500, 600)) # Example: Find and touch an image # Make sure 'image.png' is in the same directory or a specified search path touch(Template(r"image.png")) # Example: Type text into an input field text( "Hello, Airtest!" ) # Example: Wait for a specific image to appear wait(Template(r"target_image.png"), timeout=10) # Example: Assert if an image exists assert_exists(Template(r"expected_image.png"), "Image not found") # Example: Sleep for a duration sleep(2) print("Script finished.") ``` -------------------------------- ### Get Clipboard Content Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.api.md Retrieves the content from the device's clipboard. For remote iOS devices or multiple WDA installations, specify 'wda_bundle_id'. ```python >>> text = get_clipboard() # Android or local iOS >>> print(text) ``` ```python >>> # 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) ``` -------------------------------- ### Get Case Info with Airtest CLI Source: https://github.com/airtestproject/airtest/blob/master/docs/README_MORE.md Retrieve case information, including author, title, and description, in JSON format using the `airtest info` command. This requires Python to be installed and accessible. ```shell # print case info in json if defined, including: author, title, desc > python -m airtest info "path to your .air dir" {"author": ..., "title": ..., "desc": ...} ``` -------------------------------- ### Script Initialization Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example.md Automatically configure the interface of the running environment, including device, logging, project root, and screenshot compression. ```APIDOC ## auto_setup() ### Description Automatically configure the interface of the running environment, you can configure the path where the current script is located, the device used, the storage path of the log content, the project root directory, and the screenshot compression accuracy. ### Method `auto_setup(basedir=None, devices=None, logdir=None, project_root=None, compress=None)` ### Parameters - **basedir** (string) - Optional - The path where the current script is located. - **devices** (list) - Optional - Configuration for the device to be used. - **logdir** (string or bool) - Optional - The storage path of the log content. - **project_root** (string) - Optional - The project root directory. - **compress** (int) - Optional - Screenshot compression accuracy (0-100). ### Request Example ```python auto_setup(__file__) auto_setup(__file__, devices=["android://127.0.0.1:5037/emulator-5554?cap_method=JAVACAP&&ori_method=MINICAPORI&&touch_method=MINITOUCH"], logdir=True, project_root=r"D:\\test", compress=90) ``` ``` -------------------------------- ### Install Application on Android Device Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.android.md Install an APK file onto the Android device. Supports replacing an existing installation and specifying installation options. ```python >>> dev.install_app('/path/to/your/app.apk', replace=True, install_options=['-r', '-t']) ``` -------------------------------- ### 初始化Windows窗口 Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md 使用init_device()接口初始化Windows窗口,需指定平台和窗口句柄。 ```default # 连接Windows窗口 init_device(platform="Windows",uuid="123456") ``` -------------------------------- ### Script Initialization: auto_setup() Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md Automatically configures the runtime environment for Airtest scripts. It can set the script directory, target device, log saving path, project root, and screenshot compression. ```APIDOC ## auto_setup() ### Description Automatically configures the runtime environment for Airtest scripts. It can set the script directory, target device, log saving path, project root, and screenshot compression. ### Method `auto_setup(basedir=None, devices=None, logdir=None, project_root=None, compress=None)` ### Parameters - **basedir** (str) - Optional - The base directory for the script. - **devices** (list) - Optional - A list of device URIs to connect to. - **logdir** (str or bool) - Optional - Path to save logs, or True to use default. - **project_root** (str) - Optional - The root directory of the project. - **compress** (int) - Optional - Screenshot compression quality (0-100). ### Request Example ```python auto_setup(__file__) auto_setup(__file__, devices=["android://127.0.0.1:5037/emulator-5554?cap_method=JAVACAP&&ori_method=MINICAPORI&&touch_method=MINITOUCH"], logdir=True, project_root=r"D\test", compress=90) ``` ``` -------------------------------- ### Auto Setup with Default Configuration Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.api.md Automatically sets up the running environment and attempts to connect to an Android device if none is already connected. Uses the script's directory as the base. ```python >>> auto_setup(__file__) ``` -------------------------------- ### Initialize Airtest Script with auto_setup Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example.md Automatically configures the running environment, including device connection, logging, and screenshot compression. Use `__file__` to set the script's base directory. ```python auto_setup(__file__) ``` ```python auto_setup(__file__, devices=["android://127.0.0.1:5037/emulator-5554?cap_method=JAVACAP&&ori_method=MINICAPORI&&touch_method=MINITOUCH"], logdir=True, project_root=r"D:\\test", compress=90) ``` -------------------------------- ### Android Device Initialization and Properties Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.android.md Demonstrates how to initialize an Android device and access its core properties like touch method, capture method, and screen proxy. ```APIDOC ## Android Device Initialization and Properties ### Description Initialize an Android device and access its properties. ### Class `airtest.core.android.android.Android` ### Parameters - **serialno** (str) - Optional - Serial number of the device. - **host** (str) - Optional - Host address for remote debugging. - **cap_method** (str) - Optional - Method for screen capture (e.g., 'MINICAP'). Defaults to 'MINICAP'. - **touch_method** (str) - Optional - Method for touch input (e.g., 'MINITOUCH'). Defaults to 'MINITOUCH'. - **ime_method** (str) - Optional - Method for input (e.g., 'YOSEMITEIME'). Defaults to 'YOSEMITEIME'. - **ori_method** (str) - Optional - Method for orientation (e.g., 'MINICAPORI'). Defaults to 'MINICAPORI'. - **display_id** (str) - Optional - Display ID for multi-display devices. - **input_event** (str) - Optional - Input event device path. - **adb_path** (str) - Optional - Path to the ADB executable. - **name** (str) - Optional - Alias for the device. ### Properties - **touch_proxy**: Returns a proxy for performing touch operations based on `touch_method`. - **touch_method**: Returns the current touch method ('MINITOUCH' or 'MAXTOUCH'). - **cap_method**: Returns the current capture method ('MINICAP' or 'JAVACAP'). - **screen_proxy**: Returns a proxy for screen capture operations. - **uuid**: Returns the serial number of the device. ### Examples ```python >>> from airtest.core.android import Android >>> dev = Android() >>> print(dev.touch_method) # Output: MINITOUCH >>> print(dev.cap_method) # Output: MINICAP >>> img = dev.screen_proxy.get_frame_from_stream() ``` ``` -------------------------------- ### 安装Android应用 Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md 使用install()将APK文件安装到Android设备上,需传入完整的APK文件路径。仅支持Android平台。 ```default install(r"D:\demo\tutorial-blackjack-release-signed.apk") ``` -------------------------------- ### Device Initialization and Connection Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.api.md APIs for initializing, connecting to, and managing device instances. ```APIDOC ## POST /airtest/init_device ### Description Initialize device if not yet, and set as current device. ### Method POST ### Endpoint /airtest/init_device ### Parameters #### Query Parameters - **platform** (string) - Optional - Android, IOS or Windows - **uuid** (string) - Optional - uuid for target device, e.g. serialno for Android, handle for Windows, uuid for iOS - **cap_method** (string) - Optional - e.g. JAVACAP for Android - **touch_method** (string) - Optional - e.g. adb for Android ### Request Example ```json { "platform": "Android", "uuid": "SJE5T17B17", "cap_method": "JAVACAP" } ``` ### Response #### Success Response (200) - **device_instance** (object) - The initialized device instance. #### Response Example ```json { "device_instance": "" } ``` ## POST /airtest/connect_device ### Description Initialize device with uri, and set as current device. ### Method POST ### Endpoint /airtest/connect_device ### Parameters #### Request Body - **uri** (string) - Required - An URI where to connect to device, e.g. android://adbhost:adbport/serialno?param=value¶m2=value2 ### Request Example ```json { "uri": "Android:///SJE5T17B17?cap_method=javacap&touch_method=adb" } ``` ### Response #### Success Response (200) - **device_instance** (object) - The connected device instance. #### Response Example ```json { "device_instance": "" } ``` ## GET /airtest/device ### Description Return the current active device. ### Method GET ### Endpoint /airtest/device ### Response #### Success Response (200) - **device_instance** (object) - The current active device instance. #### Response Example ```json { "device_instance": "" } ``` ## POST /airtest/set_current ### Description Set current active device. ### Method POST ### Endpoint /airtest/set_current ### Parameters #### Request Body - **idx** (string or integer) - Required - uuid or index of initialized device instance ### Request Example ```json { "idx": "serialno1" } ``` ### Response #### Success Response (200) - **message** (string) - Indicates success or failure. #### Response Example ```json { "message": "Successfully set current device." } ``` ``` -------------------------------- ### 连接Windows窗口 Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md 使用connect_device()接口连接Windows窗口,需要传入窗口的URI字符串。 ```default # 连接Windows窗口 connect_device("Windows:///123456") ``` -------------------------------- ### Operate Action Arguments Example Source: https://github.com/airtestproject/airtest/blob/master/docs/all_module/airtest.core.android.touch_methods.base_touch.md Example of the arguments dictionary format for the operate method, which handles down, up, and move actions. ```default { "type" : "down", "x" : 10, "y" : 10 } ``` -------------------------------- ### Device Connection: connect_device() and init_device() Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md APIs for connecting and initializing devices. `connect_device` uses a URI string, while `init_device` takes platform, UUID, and optional arguments. ```APIDOC ## Device Connection ### connect_device(URI) Connects to a device using a URI string. ### Method `connect_device(URI)` ### Parameters - **URI** (str) - The Uniform Resource Identifier for the device. ### Request Example ```python # Connect to Android device connect_device("Android://127.0.0.1:5037/SJE5T17B17") # Connect to iOS device connect_device("iOS:///127.0.0.1:8100") # Connect to Windows window connect_device("Windows:///123456") # Connect to emulator connect_device("Android://127.0.0.1:5037/127.0.0.1:62001?cap_method=JAVACAP&&ori_method=ADBORI") ``` ### init_device(platform, uuid=None, **kwargs) Initializes a device with platform, UUID, and optional parameters. ### Method `init_device(platform='Android', uuid=None, **kwargs)` ### Parameters - **platform** (str) - The device platform (e.g., 'Android', 'Windows', 'iOS'). - **uuid** (str) - Optional - The device identifier (serial number for Android, window handle for Windows, UUID for iOS). - **kwargs** - Optional - Additional platform-specific parameters. ### Request Example ```python # Initialize Android device init_device(platform="Android", uuid="SJE5T17B17", cap_method="JAVACAP") # Initialize Windows window init_device(platform="Windows", uuid="123456") ``` ``` -------------------------------- ### Initialize Device using init_device Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example.md Initializes a device connection by specifying the platform and device UUID. Optional parameters like `cap_method` can be provided. ```python # Connect Android device init_device(platform="Android",uuid="SJE5T17B17",cap_method="JAVACAP") ``` ```python # Connect Windows window init_device(platform="Windows",uuid="123456") ``` -------------------------------- ### Airtest Configuration and Settings Source: https://github.com/airtestproject/airtest/blob/master/playground/test_blackjack.air/test_blackjack.html Explains how to configure Airtest settings, such as default timeouts, log directories, and device connection parameters. Proper configuration ensures smooth test execution. ```python from airtest.core.api import * # Default timeout for operations like wait, exists, etc. # You can set this globally or per operation # set_default_timeout(10) # seconds # Setting the log directory # log = AirtestLog(log_dir="/path/to/your/logs") # Device connection parameters can often be passed during device() call # For example, specifying ADB path or port # dev = device(platform="android", adb_path="/path/to/adb") # Airtest configuration can also be managed via a config file (e.g., airtest.conf) # Refer to Airtest documentation for details on configuration file structure. # Example: Setting a specific timeout for a wait operation # wait(Template(r"loading_spinner.png"), timeout=20) print("Configuration and settings examples.") ``` -------------------------------- ### Enable Screen Recording via Command Line Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/device/android_zh.md Add the --recording flag to the 'airtest run' command to automatically record the device screen during script execution. The output file is saved in the logs directory. ```bash airtest run "D:\test\Airtest_example.air" --device android:/// --log logs/ --recording ``` -------------------------------- ### Example Android Device Connection Strings Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/device/android_zh.md Examples of Android device connection strings: connecting to the first available device, a specific device by serial number, or a remote device via ADB. ```plaintext # Connect to the first available device Android:/// # Connect to a specific device by serial number on default port Android://127.0.0.1:5037/c2b1c2a7 # Connect to a remote device via ADB connect Android://127.0.0.1:5037/10.254.60.1:5555 ``` -------------------------------- ### Initialize Device: init_device() Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code.md Initialize the device connection. This function can be used as an alternative to connect_device() for setting up the device. ```python from airtest.core.api import * init_device("Android") ``` -------------------------------- ### Start Screen Recording with Custom Duration and Bitrate Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/device/android.md This Python snippet demonstrates how to programmatically start and stop screen recording on an Android device. It allows control over the recording duration (`max_time`) and video quality (`bit_rate_level`). Ensure `airtest.core.api` is imported. ```python from airtest.core.api import connect_device, sleep dev = connect_device("Android:///") # Record the screen with the lowest quality dev.start_recording(bit_rate_level=1) sleep(30) dev.stop_recording(output="test.mp4") ``` -------------------------------- ### Take a Screenshot with snapshot() Source: https://github.com/airtestproject/airtest/blob/master/docs/wiki/code/code_example_zh.md Capture a screenshot of the target device and save it to a file. Customize filename, description message, compression quality, and maximum size. ```python snapshot(filename="123.jpg",msg="首页截图",quality=90,max_size=800) ```