### Setup Development Environment with uv (Bash) Source: https://github.com/appium/python-client/blob/master/README.md Provides bash commands to set up a Python virtual environment using `uv`, a fast Python package installer and virtual environment manager. It covers installing uv, syncing dependencies, and activating the environment. ```bash make install-uv exec $SHELL make sync-dev ``` -------------------------------- ### Install Appium Python Client from GitHub Source Source: https://github.com/appium/python-client/blob/master/README.md Installs the Appium Python Client directly from its GitHub repository. This method clones the repository and then installs the package using the setup script. ```shell git clone git@github.com:appium/python-client.git cd python-client python setup.py install ``` -------------------------------- ### Appium Python Client v2.3.0+ iOS Options Setup Source: https://github.com/appium/python-client/blob/master/README.md This example shows how to configure iOS-specific options for Appium using `XCUITestOptions` in Python. This approach is available from Appium client version 2.3.0 onwards; for older versions, `desired_capabilities` should be used. ```python from appium.options.ios import XCUITestOptions # Example usage with XCUITestOptions options = XCUITestOptions() # options.platform_name = 'iOS' # options.automation_name = 'XCUITest' # options.app = '/path/to/your/app.ipa' # driver = webdriver.Remote('http://127.0.0.1:4723', options=options) ``` -------------------------------- ### Start Screen Recording Options (Python) Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.md Defines various options for starting screen recording in Appium. These options are platform-specific and control aspects like pixel format, video size, bit rate, and bug reporting. ```python driver.start_recording_screen(pixelFormat='yuv420p', videoType='libx264') driver.start_recording_screen(videoSize='1280x720') driver.start_recording_screen(bitRate=4000000) driver.start_recording_screen(bugReport=True) driver.start_recording_screen(fps=30) driver.start_recording_screen(captureCursor=True) driver.start_recording_screen(captureClick=True) driver.start_recording_screen(deviceId=0) driver.start_recording_screen(preset='medium') ``` -------------------------------- ### Install Appium Python Client from PyPI Source: https://github.com/appium/python-client/blob/master/README.md Installs the Appium Python Client using pip from the Python Package Index (PyPI). This is the most common and straightforward installation method. ```shell pip install Appium-Python-Client ``` -------------------------------- ### Direct Connect URL Setup (Python) Source: https://github.com/appium/python-client/blob/master/README.md Example of configuring the Appium Python Client to use direct connect URLs based on server capabilities. It utilizes AppiumClientConfig for remote server address and direct connection settings. ```python from appium import webdriver from appium.options.ios import XCUITestOptions from appium.webdriver.client_config import AppiumClientConfig options = XCUITestOptions().load_capabilities({ 'platformVersion': '13.4', 'deviceName': 'iPhone Simulator', 'app': '/full/path/to/app/UICatalog.app.zip', }) client_config = AppiumClientConfig( remote_server_addr='http://127.0.0.1:4723', direct_connection=True ) driver = webdriver.Remote( 'http://127.0.0.1:4723', options=options, client_config=client_config ) ``` -------------------------------- ### Install Appium Python Client from Source Tarball Source: https://github.com/appium/python-client/blob/master/README.md Installs the Appium Python Client from a downloaded source tarball. This method involves downloading the archive, extracting it, and then running the installation script. ```shell tar -xvf Appium-Python-Client-X.X.tar.gz cd Appium-Python-Client-X.X python setup.py install ``` -------------------------------- ### Appium Python Client v2.3.0+ Android Options Setup Source: https://github.com/appium/python-client/blob/master/README.md This example demonstrates how to set up Android-specific options for Appium using `UiAutomator2Options` in Python. It requires Appium client version 2.3.0 or later; older versions should use `desired_capabilities`. ```python from appium.options.android import UiAutomator2Options # Example usage with UiAutomator2Options options = UiAutomator2Options() # options.platform_name = 'Android' # options.automation_name = 'UiAutomator2' # options.app = '/path/to/your/app.apk' # driver = webdriver.Remote('http://127.0.0.1:4723', options=options) ``` -------------------------------- ### Record Screen Activity with Appium Python Client Source: https://context7.com/appium/python-client/llms.txt This example shows how to record the device screen during test execution using Appium's Python client. It covers starting and stopping recording with various options for Android and iOS, including direct upload to a remote server. Requires WebDriver initialization. ```python from appium import webdriver from appium.options.android import UiAutomator2Options import base64 options = UiAutomator2Options() options.app = '/path/to/app.apk' driver = webdriver.Remote('http://127.0.0.1:4723', options=options) # Start recording on Android driver.start_recording_screen( videoSize='1280x720', # Resolution bitRate=4000000, # 4 Mbps timeLimit=180, # Max 3 minutes on Android forceRestart=True # Ignore previous recording ) # Perform test actions driver.find_element(by='accessibility id', value='login').click() driver.find_element(by='accessibility id', value='username').send_keys('testuser') driver.find_element(by='accessibility id', value='password').send_keys('password123') driver.find_element(by='accessibility id', value='submit').click() # Stop and get recording video_base64 = driver.stop_recording_screen() with open('test_recording.mp4', 'wb') as f: f.write(base64.b64decode(video_base64)) # iOS recording with different options # driver.start_recording_screen( # videoType='libx264', # Video codec # videoQuality='medium', # 'low', 'medium', 'high', 'photo' # videoFps=30, # Frames per second # timeLimit=600, # Max 10 minutes on iOS # videoScale='1280:720' # Scale output # ) # Upload recording directly to remote server driver.start_recording_screen( remotePath='https://storage.example.com/recordings/', user='upload_user', password='upload_pass', method='PUT', timeLimit=180 ) # ... perform tests ... driver.stop_recording_screen() # Uploads automatically driver.quit() ``` -------------------------------- ### POST /session/{session_id}/appium/start_recording_screen Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.md Starts an asynchronous screen recording process. This endpoint supports various options for configuring the recording and uploading the output. ```APIDOC ## POST /session/{session_id}/appium/start_recording_screen ### Description Starts an asynchronous screen recording process. This endpoint supports various options for configuring the recording and uploading the output. ### Method POST ### Endpoint /session/{session_id}/appium/start_recording_screen ### Parameters #### Query Parameters None #### Request Body - **remotePath** (str) - Optional - The remotePath upload option is the path to the remote location, where the resulting video from the previous screen recording should be uploaded. Supported protocols: http/https (multipart), ftp. - **user** (str) - Optional - The name of the user for the remote authentication. Only has an effect if both remotePath and password are set. - **password** (str) - Optional - The password for the remote authentication. Only has an effect if both remotePath and user are set. - **method** (str) - Optional - The HTTP method name (‘PUT’/’POST’). PUT method is used by default. Only has an effect if remotePath is set. - **timeLimit** (int) - Optional - The actual time limit of the recorded video in seconds. Defaults: iOS/Android: 180s, macOS: 600s. Max: Android: 3m, iOS: 10m, macOS: 10000s. - **forceRestart** (bool) - Optional - Whether to ignore the result of previous capture and start a new recording immediately (True value). By default (False) the endpoint will try to catch and return the result of the previous capture if it’s still available. - **fileFieldName** (str) - Optional - [multipart/form-data requests] The name of the form field containing the binary payload. “file” by default. (Since Appium 1.18.0) - **formFields** (dict) - Optional - [multipart/form-data requests] Additional form fields mapping. If any entry has the same key as fileFieldName then it is going to be ignored. (Since Appium 1.18.0) - **headers** (dict) - Optional - [multipart/form-data requests] Headers mapping (Since Appium 1.18.0) - **videoQuality** (str) - Optional - [iOS] The video encoding quality: ‘low’, ‘medium’, ‘high’, ‘photo’. Defaults to ‘medium’. - **videoType** (str) - Optional - [iOS] The format of the screen capture to be recorded. Available formats: Execute ffmpeg -codecs in the terminal to see the list of supported video codecs. ‘mjpeg’ by default. (Since Appium 1.10.0) - **videoFps** (int) - Optional - [iOS] The Frames Per Second rate of the recorded video. Defaults to 10. - **videoFilters** (str) - Optional - [iOS, Win, macOS] The FFMPEG video filters to apply. The format must comply with https://ffmpeg.org/ffmpeg-filters.html. (Since Appium 1.15) - **videoScale** (str) - Optional - [iOS] The scaling value to apply. Read https://trac.ffmpeg.org/wiki/Scaling for possible values. - **pixelFormat** (str) - Optional - [iOS] The pixel format of the recorded video. - **videoSize** (str) - Optional - [Android] The size of the video, e.g. 1280x720. - **bitRate** (str) - Optional - [Android] The video bit rate in kbps, e.g. 4000. - **bugReport** (bool) - Optional - [Android] If true, the screen recording will be part of a bug report. - **fps** (int) - Optional - [Win, macOS] The Frames Per Second rate of the recorded video. - **captureCursor** (bool) - Optional - [Win, macOS] Whether to capture the cursor. - **captureClicks** (bool) - Optional - [Win, macOS] Whether to capture mouse clicks. - **deviceId** (str) - Optional - [macOS] The device ID to record. - **preset** (str) - Optional - [Win, macOS] The FFmpeg preset to use for encoding. - **audioInput** (str) - Optional - [Win] The audio input device to use for recording. ### Request Example ```json { "remotePath": "http://example.com/upload", "timeLimit": 60, "videoQuality": "high" } ``` ### Response #### Success Response (200) - **bytes** - The screen recording data as bytes if remotePath is not set. - **str** - The screen recording data as a string (Base64 encoded) if remotePath is not set and the data is too large for memory. #### Response Example ```json "SGVsbG8gV29ybGQ=" ``` ``` -------------------------------- ### Manage Application Lifecycle with Appium Python Client Source: https://context7.com/appium/python-client/llms.txt This code demonstrates managing application states like installation, activation, querying status, backgrounding, retrieving strings, terminating, and uninstalling apps using Appium's Python client. It requires an Android UiAutomator2 driver setup. ```python from appium import webdriver from appium.options.android import UiAutomator2Options options = UiAutomator2Options() driver = webdriver.Remote('http://127.0.0.1:4723', options=options) # Check if app is installed is_installed = driver.is_app_installed('com.example.app') print(f"App installed: {is_installed}") # Install application with options driver.install_app( app_path='/path/to/app.apk', replace=True, # Reinstall if exists timeout=120000, # 2 minute timeout allowTestPackages=True, # Allow test APKs grantPermissions=True # Auto-grant permissions ) # Activate (bring to foreground) an app driver.activate_app('com.example.app') # Query application state # Returns: 0=not installed, 1=not running, 2=running background, # 3=running background suspended, 4=running foreground state = driver.query_app_state('com.example.app') print(f"App state: {state}") # Put app in background for specified seconds # Negative value returns immediately after backgrounding driver.background_app(seconds=5) # Get application strings (localization) strings = driver.app_strings(language='en', string_file='strings.xml') print(f"Welcome message: {strings.get('welcome_message')}") # Terminate a running app was_terminated = driver.terminate_app('com.example.app', timeout=500) print(f"App terminated: {was_terminated}") # Remove/uninstall app driver.remove_app( app_id='com.example.app', keepData=False, # Remove app data timeout=20000 ) driver.quit() ``` -------------------------------- ### Applications Source: https://github.com/appium/python-client/blob/master/docs/webdriver.md Manages application lifecycle and information, including activation, installation, and removal. ```APIDOC ## Applications API ### Description Manages application lifecycle and information, including activation, installation, and removal. ### Methods * **activate_app(app_id)**: Activates the specified application. * **app_strings(language=None, string_file=None)**: Retrieves application strings for a given language. * **background_app(seconds)**: Sends the application to the background for a specified duration. * **install_app(app_path, options=None)**: Installs an application on the device. * **is_app_installed(app_id)**: Checks if an application is installed on the device. * **query_app_state(app_id)**: Queries the state of an application. * **remove_app(app_id, options=None)**: Removes an application from the device. * **terminate_app(app_id, options=None)**: Terminates an application. ``` -------------------------------- ### AppiumService: Managing Appium Server Lifecycle Source: https://context7.com/appium/python-client/llms.txt Provides examples of using the AppiumService class to programmatically start, stop, and check the status of the Appium server. This is crucial for managing the server environment within test automation scripts, including integration with pytest fixtures. ```python from appium import webdriver from appium.webdriver.appium_service import AppiumService from appium.options.android import UiAutomator2Options import subprocess # Create and start Appium service service = AppiumService() service.start( args=['--address', '127.0.0.1', '-p', '4723', '--base-path', '/'], timeout_ms=30000, # Wait up to 30 seconds for startup stdout=subprocess.PIPE, # Capture stdout stderr=subprocess.PIPE # Capture stderr ) # Check service status print(f"Service is running: {service.is_running}") print(f"Service is listening: {service.is_listening}") # Create driver using the started service options = UiAutomator2Options() options.app = '/path/to/app.apk' driver = webdriver.Remote('http://127.0.0.1:4723', options=options) # Run your tests element = driver.find_element(by='accessibility id', value='greeting') print(f"Text: {element.text}") # Cleanup driver.quit() was_running = service.stop(timeout=5.0) # 5 second timeout for graceful stop print(f"Service was running before stop: {was_running}") # Using with pytest fixtures import pytest @pytest.fixture(scope='session') def appium_service(): service = AppiumService() service.start( args=['--address', '127.0.0.1', '-p', '4723'], timeout_ms=20000, ) yield service service.stop() @pytest.fixture def driver(appium_service): options = UiAutomator2Options() options.app = '/path/to/app.apk' driver = webdriver.Remote('http://127.0.0.1:4723', options=options) yield driver driver.quit() def test_app(driver): assert driver.is_app_installed('com.example.app') ``` -------------------------------- ### Application Management API Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.md Manage applications on the device, including installation, uninstallation, checking installation status, and querying application state. ```APIDOC ## POST /app/install ### Description Installs an application on the device from a local or remote path. ### Method POST ### Endpoint /session/{session_id}/appium/device/install ### Parameters #### Path Parameters - **session_id** (string) - Required - The ID of the current session. #### Query Parameters None #### Request Body - **app_path** (string) - Required - The local or remote path to the application to install. - **replace** (boolean) - Optional - [Android only] Whether to reinstall/upgrade the package if it is already present. True by default. - **timeout** (integer) - Optional - [Android only] How much time to wait for the installation to complete. 60000ms by default. - **allowTestPackages** (boolean) - Optional - [Android only] Whether to allow installation of packages marked as test in the manifest. False by default. - **useSdcard** (boolean) - Optional - [Android only] Whether to use the SD card to install the app. False by default. - **grantPermissions** (boolean) - Optional - [Android only] Whether to automatically grant application permissions on Android 6+ after installation. False by default. ### Request Example ```json { "app_path": "/path/to/your/app.apk", "replace": true, "grantPermissions": true } ``` ### Response #### Success Response (200) - **value** (object) - An empty object indicating success. #### Response Example ```json { "value": {} } ``` ## GET /app/is_installed ### Description Checks if a specified application is installed on the device. ### Method GET ### Endpoint /session/{session_id}/appium/device/app_installed ### Parameters #### Path Parameters - **session_id** (string) - Required - The ID of the current session. #### Query Parameters - **bundleId** (string) - Required - The ID of the application to query. #### Request Body None ### Request Example ``` GET /session/12345/appium/device/app_installed?bundleId=com.example.app ``` ### Response #### Success Response (200) - **value** (boolean) - True if the app is installed, false otherwise. #### Response Example ```json { "value": true } ``` ## GET /app/query ### Description Queries the state of a specified application on the device. ### Method GET ### Endpoint /session/{session_id}/appium/device/query_app_state ### Parameters #### Path Parameters - **session_id** (string) - Required - The ID of the current session. #### Query Parameters - **appId** (string) - Required - The application ID to be queried. #### Request Body None ### Request Example ``` GET /session/12345/appium/device/query_app_state?appId=com.example.app ``` ### Response #### Success Response (200) - **value** (integer) - One of the possible application state constants (e.g., 0 for not installed, 1 for running, 2 for background, etc.). Refer to the ApplicationState class for details. #### Response Example ```json { "value": 1 } ``` ## DELETE /app/remove ### Description Removes a specified application from the device. ### Method DELETE ### Endpoint /session/{session_id}/appium/device/remove ### Parameters #### Path Parameters - **session_id** (string) - Required - The ID of the current session. #### Query Parameters - **appId** (string) - Required - The application ID to be removed. - **keepData** (boolean) - Optional - [Android only] Whether to keep application data and caches after uninstallation. False by default. - **timeout** (integer) - Optional - [Android only] How much time to wait for the uninstall to complete. 20000ms by default. #### Request Body None ### Request Example ``` DELETE /session/12345/appium/device/remove?appId=com.example.app&keepData=true ``` ### Response #### Success Response (200) - **value** (object) - An empty object indicating success. #### Response Example ```json { "value": {} } ``` ## POST /app/terminate ### Description Terminates the specified application if it is running. ### Method POST ### Endpoint /session/{session_id}/appium/device/terminate ### Parameters #### Path Parameters - **session_id** (string) - Required - The ID of the current session. #### Query Parameters - **appId** (string) - Required - The application ID to be terminated. - **timeout** (integer) - Optional - [Android only] How much time to wait for the termination to complete. 500ms by default. #### Request Body None ### Request Example ``` POST /session/12345/appium/device/terminate?appId=com.example.app ``` ### Response #### Success Response (200) - **value** (boolean) - True if the app has been successfully terminated, false otherwise. #### Response Example ```json { "value": true } ``` ``` -------------------------------- ### Start Appium Session Source: https://github.com/appium/python-client/blob/master/docs/webdriver.md Initiates a new session with the Appium server using specified capabilities. This method overrides the default behavior to accommodate Appium's specific requirements for session creation, including browser profiles. ```python def start_session(capabilities: Dict | AppiumOptions, browser_profile: str | None = None) -> None: """ Creates a new session with the desired capabilities. Override for Appium * **Parameters:** * **capabilities** – Read [https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md](https://github.com/appium/appium/blob/master/docs/en/writing-running-appium/caps.md) for more details. * **browser_profile** – Browser profile """ pass ``` -------------------------------- ### Appium Python Client Test Environment Setup Source: https://github.com/appium/python-client/blob/master/README.md This Python code snippet sets up a basic test environment using `pytest` and Appium's webdriver. It includes necessary imports for `webdriver`, options classes, `AppiumService`, and `AppiumBy`, along with constants for the Appium server host and port. ```python import pytest from appium import webdriver from appium.options.android import UiAutomator2Options from appium.options.ios import XCUITestOptions from appium.webdriver.appium_service import AppiumService from appium.webdriver.common.appiumby import AppiumBy APPIUM_PORT = 4723 APPIUM_HOST = '127.0.0.1' # HINT: fixtures below could be extracted into conftest.py ``` -------------------------------- ### Generate and Serve Appium Python Client Docs Locally Source: https://github.com/appium/python-client/blob/master/docs/README.md This snippet details the process of generating the project's documentation and then serving it using Python's built-in HTTP server. It requires navigating to the docs directory, executing a generation script, and then starting a local server. The generated documentation can then be accessed via a web browser. ```bash cd python-client/docs bash generate.sh cd python-client/docs/_build/html python -m http.server 1234 ``` -------------------------------- ### Device Settings Management (Python) Source: https://context7.com/appium/python-client/llms.txt Demonstrates how to retrieve and update Appium driver settings that control test behavior. This includes getting current settings, updating them with new values, and verifying the changes. It covers general settings and provides examples for Android and iOS specific configurations. Requires an active Appium driver session. ```python from appium import webdriver from appium.options.android import UiAutomator2Options options = UiAutomator2Options() options.app = '/path/to/app.apk' driver = webdriver.Remote('http://127.0.0.1:4723', options=options) # Get current settings settings = driver.get_settings() print(f"Current settings: {settings}") # Output: {'shouldUseCompactResponses': True, 'elementResponseAttributes': 'type,label', ...} # Update settings driver.update_settings({ 'waitForIdleTimeout': 500, 'waitForSelectorTimeout': 10000, 'shouldUseCompactResponses': False, 'ignoreUnimportantViews': True, 'allowInvisibleElements': True }) # Platform-specific settings examples # Android UiAutomator2 settings driver.update_settings({ 'actionAcknowledgmentTimeout': 3000, 'keyInjectionDelay': 100, 'scrollAcknowledgmentTimeout': 200, 'waitForIdleTimeout': 10000 }) # iOS XCUITest settings # driver.update_settings({ # 'snapshotMaxDepth': 50, # 'screenshotQuality': 2, # 'mjpegServerScreenshotQuality': 50, # 'mjpegScalingFactor': 50 # }) # Verify settings were applied updated_settings = driver.get_settings() print(f"Updated wait timeout: {updated_settings.get('waitForIdleTimeout')}") driver.quit() ``` -------------------------------- ### Start and Stop Appium Service (Python) Source: https://github.com/appium/python-client/blob/master/README.md Fixture to start and stop an Appium service for testing. It configures the service with host and port, and ensures it's stopped after the session. ```python import pytest from appium.webdriver.appium_service import AppiumService APPIUM_HOST = '127.0.0.1' APPIUM_PORT = 4723 @pytest.fixture(scope='session') def appium_service(): service = AppiumService() service.start( args=['--address', APPIUM_HOST, '-p', str(APPIUM_PORT)], timeout_ms=20000, ) yield service service.stop() ``` -------------------------------- ### AppiumService Class Source: https://github.com/appium/python-client/blob/master/docs/webdriver.md Provides functionality to start, stop, and check the status of the Appium server service. ```APIDOC ## Class: AppiumService ### Description Manages the Appium server process, allowing for starting, stopping, and checking its operational status. ### Properties - **is_listening**: bool - Returns True if the service is running and listening on the configured host and port. - **is_running**: bool - Returns True if the Appium service process is running. ### Methods #### start(**kwargs: Any) -> Popen Starts the Appium service with the provided arguments. The service will be forcefully restarted if already running. ### Parameters - **env** (dict) - Environment variables for the service process. Defaults to the parent process's environment. - **node** (str) - Path to the Node.js executable. Auto-detected if not provided. - **npm** (str) - Path to the npm script. Auto-detected if not provided. - **stdout** (int) - File descriptor for standard output. Defaults to DEVNULL on Windows, PIPE otherwise. - **stderr** (int) - File descriptor for standard error. Defaults to DEVNULL on Windows, PIPE otherwise. - **timeout_ms** (int) - Maximum time in milliseconds to wait for the Appium process to start listening. 0 or negative means no wait. Defaults to 60000. - **main_script** (str) - Path to the main Appium executable script. Auto-detected if not provided. - **args** (str) - A list of string arguments to pass to the Appium server. See Appium documentation for available arguments. ### Returns A Popen object that can be used to interact with the running process (e.g., communicate, access stdout/stderr). #### stop(timeout: float = 5.5) -> bool Stops the Appium service if it is running. The call is ignored if the service is not running or already stopped. ### Parameters - **timeout** (float) - Maximum time in seconds to wait for the server process to terminate. Defaults to 5.5. ### Returns True if the service was running before being stopped, False otherwise. ``` -------------------------------- ### AppiumService Module Source: https://github.com/appium/python-client/blob/master/docs/index.md Information on managing the Appium service, including starting, stopping, and checking its status, as well as utility functions. ```APIDOC ## AppiumService Module ### Description This module handles the management of the Appium server process. ### Class: AppiumService #### Methods - **start()** - Starts the Appium service. - **stop()** - Stops the Appium service. #### Attributes - **is_listening** (bool) - True if the service is listening for connections, False otherwise. - **is_running** (bool) - True if the service is running, False otherwise. ### Utility Functions - **find_executable(name)** - Finds an executable in the system's PATH. - **get_main_script()** - Gets the main script path for the Appium service. - **get_node()** - Gets the path to the Node.js executable. - **get_npm()** - Gets the path to the npm executable. - **is_service_listening()** - Checks if the Appium service is currently listening. ### Exceptions - **AppiumServiceError** - Base exception for Appium service errors. - **AppiumStartupError** - Exception raised when the Appium service fails to start. ``` -------------------------------- ### Screen Recording Source: https://github.com/appium/python-client/blob/master/docs/webdriver.md Allows for starting and stopping screen recording on the device. ```APIDOC ## ScreenRecord API ### Description This API enables you to record the device's screen programmatically. You can start and stop the recording as needed. ### Methods * **start_recording_screen()**: Starts recording the device's screen. * **stop_recording_screen()**: Stops the screen recording and returns the recorded video data. ``` -------------------------------- ### WebElement Interactions Source: https://github.com/appium/python-client/blob/master/docs/index.md Documentation for interacting with WebElement objects, including clearing fields, getting attributes, checking visibility, and sending input. ```APIDOC ## WebElement Interactions ### Description Methods for interacting with individual elements on the mobile application's UI. ### Class `webdriver.webelement.WebElement` ### Methods - **clear()**: Clears the text from an input element. - **get_attribute(name)**: Gets the value of a specified attribute for the element. - **is_displayed()**: Checks if the element is currently displayed. - **location_in_view**: Gets the element's location within the viewport. - **send_keys(value)**: Sends a sequence of keys to the element. ``` -------------------------------- ### Get Appium Server Status and Control Device Orientation Source: https://context7.com/appium/python-client/llms.txt Shows how to retrieve the Appium server's status information, including build details and readiness, using the `get_status` method. It also demonstrates how to get and set the device's orientation (portrait or landscape) and take a screenshot. This functionality is available through the standard Appium client methods. ```python from appium import webdriver from appium.options.android import UiAutomator2Options options = UiAutomator2Options() options.app = '/path/to/app.apk' driver = webdriver.Remote('http://127.0.0.1:4723', options=options) # Get server status status = driver.get_status() print(f"Server status: {status}") # Output example: # { # 'build': { # 'version': '2.4.1', # 'git-sha': 'abc123...', # 'built': '2024-01-15T10:30:00Z' # }, # 'sessionId': None, # 'ready': True # } # Device orientation print(f"Current orientation: {driver.orientation}") # 'PORTRAIT' or 'LANDSCAPE' # Change orientation driver.orientation = 'LANDSCAPE' # Take a screenshot in landscape screenshot = driver.get_screenshot_as_base64() driver.orientation = 'PORTRAIT' driver.quit() ``` -------------------------------- ### Keyboard Interactions (Python) Source: https://context7.com/appium/python-client/llms.txt Provides examples of using the Keyboard extension to manage the software keyboard. This includes checking visibility, hiding the keyboard using different strategies, and sending hardware key events specific to Android. Dependencies include the Appium driver and Android keycode constants. ```python from appium import webdriver from appium.options.android import UiAutomator2Options options = UiAutomator2Options() options.app = '/path/to/app.apk' driver = webdriver.Remote('http://127.0.0.1:4723', options=options) # Check if keyboard is shown if driver.is_keyboard_shown(): print("Keyboard is visible") # Hide keyboard (iOS can specify key or strategy) driver.hide_keyboard() # driver.hide_keyboard(key_name='Done') # driver.hide_keyboard(strategy='tapOutside') # Android keycode events # See: https://developer.android.com/reference/android/view/KeyEvent # Press hardware back button driver.press_keycode(4) # KEYCODE_BACK # Press home button driver.press_keycode(3) # KEYCODE_HOME # Press with meta state (e.g., Shift+A) driver.press_keycode( keycode=29, # KEYCODE_A metastate=1, # META_SHIFT_ON flags=0 ) # Long press power button driver.long_press_keycode(26) # KEYCODE_POWER # Press volume keys driver.press_keycode(24) # KEYCODE_VOLUME_UP driver.press_keycode(25) # KEYCODE_VOLUME_DOWN # Press Enter/Search driver.press_keycode(66) # KEYCODE_ENTER # Type in a field and submit search_field = driver.find_element(by='accessibility id', value='search_input') search_field.send_keys('appium testing') driver.press_keycode(84) # KEYCODE_SEARCH driver.quit() ``` -------------------------------- ### GET /appium/settings Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.md Retrieves the current Appium server settings for the active session. Settings are distinct from Desired Capabilities and control various aspects of the Appium server's behavior. ```APIDOC ## GET /appium/settings ### Description Retrieves the current Appium server settings for the active session. Settings are distinct from Desired Capabilities and control various aspects of the Appium server's behavior. ### Method GET ### Endpoint /appium/settings ### Parameters #### Query Parameters None #### Request Body None ### Response #### Success Response (200) - **settings** (Dict[str, Any]) - A dictionary containing the current Appium server settings. #### Response Example ```json { "settings": { "someSetting": "someValue", "anotherSetting": 123 } } ``` ``` -------------------------------- ### Get Application Strings with Applications Module in Python Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.md Retrieves the application strings for a given language and optionally a specific string file. This is useful for internationalization testing. The returned dictionary maps string IDs to their content. This method is part of the Applications class. ```python from appium.webdriver.extensions.applications import Applications # Assuming 'driver' is an instance of WebDriver applications = Applications(driver) strings = driver.app_strings(language='en', string_file='Localizable.strings') print(strings) ``` -------------------------------- ### Execute Mobile Commands with Appium Python Client Source: https://context7.com/appium/python-client/llms.txt Demonstrates how to execute various mobile commands using the Appium Python client, including pressing physical buttons, retrieving battery information, and executing driver-specific scripts for Android and iOS. It requires the Appium server to be running and the specified application to be installed on the device. ```python from appium import webdriver from appium.options.ios import XCUITestOptions options = XCUITestOptions() options.bundle_id = 'com.example.app' driver = webdriver.Remote('http://127.0.0.1:4723', options=options) # Press physical iOS buttons driver.press_button('home') driver.press_button('volumeup') driver.press_button('volumedown') # Get battery information (works on iOS and Android) battery = driver.battery_info print(f"Battery level: {battery['level'] * 100}%") print(f"Battery state: {battery['state']}") # iOS states: 1=Unplugged, 2=Charging, 3=Full # Android states: 2=Charging, 3=Discharging, 4=Not charging, 5=Full # Execute arbitrary mobile commands # Android example: shell command result = driver.execute_script('mobile: shell', { 'command': 'dumpsys', 'args': ['battery'] }) # iOS example: get device info # device_info = driver.execute_script('mobile: deviceInfo') # Android: start activity driver.execute_script('mobile: startActivity', { 'component': 'com.example.app/.SettingsActivity', 'wait': True }) # iOS: terminate app driver.execute_script('mobile: terminateApp', { 'bundleId': 'com.example.app' }) driver.quit() ``` -------------------------------- ### Create WebDriver Session for Android and iOS with Appium Python Client Source: https://context7.com/appium/python-client/llms.txt Demonstrates how to create WebDriver sessions for both Android and iOS platforms using Appium Python Client. It shows configuration for UiAutomator2 (Android) and XCUITest (iOS), including platform version, device ID, and application paths. The example also illustrates using a context manager for automatic session cleanup. ```python from appium import webdriver from appium.options.android import UiAutomator2Options from appium.options.ios import XCUITestOptions # Android session with UiAutomator2 android_options = UiAutomator2Options() android_options.platform_version = '13' android_options.udid = 'emulator-5554' android_options.app = '/path/to/app.apk' android_options.app_package = 'com.example.app' android_options.app_activity = '.MainActivity' android_driver = webdriver.Remote( 'http://127.0.0.1:4723', options=android_options ) # iOS session with XCUITest ios_options = XCUITestOptions() ios_options.platform_version = '16.4' ios_options.udid = '00008030-001234567890ABCD' ios_options.app = '/path/to/App.app' ios_options.bundle_id = 'com.example.app' ios_driver = webdriver.Remote( 'http://127.0.0.1:4723', options=ios_options ) # Using context manager for automatic cleanup with webdriver.Remote('http://127.0.0.1:4723', options=android_options) as driver: element = driver.find_element(by='accessibility id', value='login_button') element.click() # Driver is automatically quit when exiting the context ``` -------------------------------- ### Activate Virtual Environment (Bash) Source: https://github.com/appium/python-client/blob/master/README.md Provides instructions on how to activate a Python virtual environment created with `uv`, either by sourcing the activation script or by adding the environment's bin directory to the PATH. ```bash source /venv/root/folder/bin/activate # or export "PATH=/venv/root/folder/bin:$PATH" ``` -------------------------------- ### Customize Virtual Environment Folder Location (Bash) Source: https://github.com/appium/python-client/blob/master/README.md Demonstrates how to specify a custom directory for storing the virtual environment created by `uv`. This offers flexibility in managing project dependencies. ```bash uv venv /venv/root/folder ``` -------------------------------- ### Get Available Log Types (Python) Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.md Gets a list of available log types for the current session. This functionality is primarily for W3C compliant browsers. ```python available_log_types = driver.log_types ``` -------------------------------- ### Instantiate WebDriver with AppiumOptions (Python) Source: https://github.com/appium/python-client/blob/master/README.md Demonstrates how to create an AppiumOptions object, set platform and automation names, and then use it to instantiate a WebDriver. This method is suitable for basic configurations. ```python from appium.options.common import AppiumOptions from appium import webdriver options = AppiumOptions() options.platform_name = 'mac' options.automation_name = 'safari' options.set_capability('browser_name', 'safari') driver = webdriver.Remote('http://127.0.0.1:4723/wd/hub', options=options, strict_ssl=False) ``` -------------------------------- ### Client Configuration Source: https://github.com/appium/python-client/blob/master/docs/index.md Configuration options for the Appium client, including direct connection settings. ```APIDOC ## Class: AppiumClientConfig ### Description Configuration class for the Appium client. ### Attributes - **direct_connection** (boolean) - Whether to establish a direct connection to the Appium server. ``` -------------------------------- ### Get Android Device Information with Appium Python Client Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.android.md Offers utilities to retrieve common information about the Android device. This includes getting the current running package and the display density (DPI). These are Android-specific functionalities. ```python from appium.webdriver.extensions.android.common import Common from appium.webdriver.extensions.android.display import Display # Assuming 'driver' is an initialized Appium WebDriver instance current_package = driver.current_package print(f"Current package: {current_package}") display_density = driver.get_display_density() print(f"Display density: {display_density} dpi") ``` -------------------------------- ### Touch Actions and Gestures with ActionHelpers Source: https://context7.com/appium/python-client/llms.txt Demonstrates various touch actions and gestures supported by Appium's ActionHelpers mixin, including single and multi-finger taps, swipes, scrolls, drag-and-drop, and flicks. It also shows how to perform complex gestures using W3C WebDriver Actions. ```python from appium import webdriver from appium.webdriver.common.appiumby import AppiumBy from appium.options.android import UiAutomator2Options from selenium.webdriver.common.action_chains import ActionChains from selenium.webdriver.common.actions import interaction from selenium.webdriver.common.actions.action_builder import ActionBuilder from selenium.webdriver.common.actions.pointer_input import PointerInput options = UiAutomator2Options() options.app = '/path/to/app.apk' driver = webdriver.Remote('http://127.0.0.1:4723', options=options) # Single tap at coordinates driver.tap([(100, 200)]) # Multi-finger tap (up to 5 fingers) driver.tap([(100, 200), (200, 200), (300, 200)], duration=500) # Swipe from point to point driver.swipe( start_x=500, start_y=1500, end_x=500, end_y=500, duration=800 # milliseconds ) # Scroll between elements list_start = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value='list_top') list_end = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value='list_bottom') driver.scroll(origin_el=list_start, destination_el=list_end, duration=600) # Drag and drop source = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value='draggable') target = driver.find_element(by=AppiumBy.ACCESSIBILITY_ID, value='drop_zone') driver.drag_and_drop(origin_el=source, destination_el=target, pause=0.5) # Flick gesture (fast swipe without duration) driver.flick(start_x=500, start_y=1500, end_x=500, end_y=500) # Custom W3C Actions for complex gestures actions = ActionChains(driver) touch_input = PointerInput(interaction.POINTER_TOUCH, 'touch') actions.w3c_actions = ActionBuilder(driver, mouse=touch_input) # Long press gesture actions.w3c_actions.pointer_action.move_to_location(300, 400) actions.w3c_actions.pointer_action.pointer_down() actions.w3c_actions.pointer_action.pause(2) # Hold for 2 seconds actions.w3c_actions.pointer_action.release() actions.perform() ``` -------------------------------- ### Customize Python Version for Virtual Environment (Bash) Source: https://github.com/appium/python-client/blob/master/README.md Shows how to specify a particular Python version when creating a virtual environment using `uv`. This allows developers to ensure compatibility with specific Python releases. ```bash uv venv --python ``` -------------------------------- ### Run Unit Tests (Bash) Source: https://github.com/appium/python-client/blob/master/README.md Command to execute the project's unit tests. This is crucial for verifying the correctness of individual components. ```bash make unittest ``` -------------------------------- ### Access Session Events (Python) Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.md Demonstrates how to retrieve event timing information from the current Appium session. ```python events = driver.events ``` -------------------------------- ### ActionHelpers Source: https://github.com/appium/python-client/blob/master/docs/webdriver.md Provides helper methods for performing common actions like flicking, scrolling, swiping, and tapping. ```APIDOC ## ActionHelpers API ### Description Provides helper methods for performing common actions like flicking, scrolling, swiping, and tapping. ### Methods * **flick()**: Performs a flick gesture. * **scroll()**: Scrolls the screen. * **swipe()**: Performs a swipe gesture. * **tap()**: Performs a tap gesture. ``` -------------------------------- ### Settings Source: https://github.com/appium/python-client/blob/master/docs/webdriver.md Allows for retrieving and updating device settings. ```APIDOC ## Settings API ### Description This API allows you to manage various settings on the device. You can retrieve the current settings and update them as required. ### Methods * **get_settings()**: Retrieves the current device settings. * **update_settings()**: Updates one or more device settings. ``` -------------------------------- ### Get Device Location (Python) Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.md Retrieves the current geographical location of the device. The returned value is a dictionary containing latitude, longitude, and altitude. ```python current_location = driver.location ``` -------------------------------- ### Get Battery Information in Python Source: https://github.com/appium/python-client/blob/master/docs/webdriver.extensions.md Retrieves the battery level and state of the device. The format of the returned dictionary varies between iOS and Android platforms. ```python # Example usage (actual retrieval is a property access): # battery_info = self.driver.battery_info ``` -------------------------------- ### WebDriver Base Functionality Source: https://github.com/appium/python-client/blob/master/docs/index.md Details core functionalities of the WebDriver class, including adding commands, executing commands, managing extensions, and starting sessions. ```APIDOC ## WebDriver Base Functionality ### Description Core methods for WebDriver interaction, including command management, session handling, and extension management. ### Class `webdriver.webdriver.WebDriver` ### Methods - **add_command(name, command)**: Adds a custom command to the WebDriver. - **execute(command, params)**: Executes a given command with specified parameters. - **method_name()**: Retrieves the name of the current method. - **assert_extension_exists(name)**: Asserts that a given extension exists. - **create_web_element(id)**: Creates a WebElement object from an element ID. - **delete_extensions()**: Deletes all active extensions. - **get_status()**: Retrieves the current status of the WebDriver session. - **mark_extension_absence(name)**: Marks an extension as absent. - **orientation**: Gets or sets the device orientation. - **start_session(capabilities, w3c=None)**: Starts a new WebDriver session with the given capabilities. - **switch_to**: Provides access to context switching functionalities. ```