Python client library for Appium mobile automation framework extending Selenium WebDriver with iOS and Android testing capabilities
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Hardware-level device interactions including keyboard management, device rotation, location services, hardware actions, and device state control. These capabilities enable comprehensive device-level testing scenarios.
Control virtual keyboard visibility and send keyboard input including platform-specific key events.
def hide_keyboard(self, key_name: str = None, key = None, strategy: str = None):
"""
Hide the virtual keyboard.
Args:
key_name (str, optional): Name of key to press to hide keyboard
key (str, optional): Key to press to hide keyboard
strategy (str, optional): Strategy to use ('press', 'pressKey', 'swipeDown', 'tapOut', 'tapOutside')
"""
def is_keyboard_shown(self) -> bool:
"""
Check if virtual keyboard is currently displayed.
Returns:
bool: True if keyboard is shown, False otherwise
"""
def keyevent(self, keycode: int, metastate: int = None):
"""
Send Android keycode event.
Args:
keycode (int): Android keycode constant
metastate (int, optional): Meta key state flags
"""
def press_keycode(self, keycode: int, metastate: int = None, flags: int = None):
"""
Press Android key with additional options.
Args:
keycode (int): Android keycode to press
metastate (int, optional): Meta key state flags (SHIFT, ALT, etc.)
flags (int, optional): Additional key event flags
"""
def long_press_keycode(self, keycode: int, metastate: int = None, flags: int = None):
"""
Long press Android key.
Args:
keycode (int): Android keycode to long press
metastate (int, optional): Meta key state flags
flags (int, optional): Additional key event flags
"""Control device hardware features including shake, device locking, and physical device interactions.
def shake(self):
"""Shake the device (triggers accelerometer event)."""
def lock(self, seconds: int = None):
"""
Lock the device screen.
Args:
seconds (int, optional): Duration to keep device locked
"""
def unlock(self):
"""Unlock the device screen."""
def is_locked(self) -> bool:
"""
Check if device screen is locked.
Returns:
bool: True if device is locked, False otherwise
"""Control biometric authentication features including Touch ID, Face ID, and fingerprint authentication for security testing.
def touch_id(self, match: bool):
"""
Simulate Touch ID authentication (iOS only).
Args:
match (bool): True to simulate successful authentication, False for failure
"""
def toggle_touch_id_enrollment(self):
"""Toggle Touch ID enrollment status (iOS only)."""
def finger_print(self, finger_id: int):
"""
Authenticate with fingerprint (Android only).
Args:
finger_id (int): Finger ID to use for authentication (1-10)
"""Control GPS location and location-based services for testing location-aware applications.
def set_location(self, latitude: float, longitude: float, altitude: float = None):
"""
Set device GPS coordinates.
Args:
latitude (float): Latitude coordinate
longitude (float): Longitude coordinate
altitude (float, optional): Altitude in meters
"""
@property
def location(self) -> dict:
"""
Get current device location.
Returns:
dict: Location data with 'latitude', 'longitude', and 'altitude' keys
"""Access and format device time information for testing time-dependent functionality.
def get_device_time(self, format: str = None) -> str:
"""
Get device time in specified format.
Args:
format (str, optional): Time format string (e.g., 'YYYY-MM-DD HH:mm:ss')
If None, returns default format
Returns:
str: Formatted device time string
"""Manage device clipboard content for testing copy/paste functionality and data sharing.
def get_clipboard(self, content_type = None) -> str:
"""
Get clipboard content.
Args:
content_type: Type of content to retrieve (ClipboardContentType enum)
If None, gets plaintext content
Returns:
str: Clipboard content (may be base64 encoded for binary data)
"""
def set_clipboard(self, content: str, content_type = None):
"""
Set clipboard content.
Args:
content (str): Content to set in clipboard
content_type: Type of content being set (ClipboardContentType enum)
If None, sets as plaintext
"""Advanced touch gesture methods for complex interactions including scrolling, dragging, tapping, and swiping.
def scroll(self, origin_el, destination_el, duration: int = None):
"""
Scroll from one element to another.
Args:
origin_el (WebElement): Element to start scroll from
destination_el (WebElement): Element to scroll to
duration (int, optional): Duration of scroll in milliseconds
"""
def drag_and_drop(self, origin_el, destination_el, pause: int = None):
"""
Drag element from origin to destination.
Args:
origin_el (WebElement): Element to drag from
destination_el (WebElement): Element to drop at
pause (int, optional): Pause duration in milliseconds
"""
def tap(self, positions: list, duration: int = None):
"""
Multi-touch tap gesture.
Args:
positions (list): List of (x, y) coordinate tuples for tap points
duration (int, optional): Duration to hold tap in milliseconds
"""
def swipe(self, start_x: int, start_y: int, end_x: int, end_y: int, duration: int = None):
"""
Swipe gesture from start to end coordinates.
Args:
start_x (int): Starting X coordinate
start_y (int): Starting Y coordinate
end_x (int): Ending X coordinate
end_y (int): Ending Y coordinate
duration (int, optional): Swipe duration in milliseconds
"""
def flick(self, start_x: int, start_y: int, end_x: int, end_y: int):
"""
Flick gesture from start to end coordinates.
Args:
start_x (int): Starting X coordinate
start_y (int): Starting Y coordinate
end_x (int): Ending X coordinate
end_y (int): Ending Y coordinate
"""from appium import webdriver
from appium.options.android import UiAutomator2Options
# Setup
options = UiAutomator2Options()
driver = webdriver.Remote("http://localhost:4723", options=options)
# Basic keyboard management
text_field = driver.find_element("id", "input_field")
text_field.click()
# Check if keyboard appeared
if driver.is_keyboard_shown():
print("Keyboard is visible")
# Type text normally
text_field.send_keys("Hello World")
# Hide keyboard
driver.hide_keyboard()
# Android-specific key events
driver.press_keycode(4) # Back key
driver.press_keycode(3) # Home key
driver.long_press_keycode(26) # Power key (long press)
# Special key combinations
driver.press_keycode(67, metastate=1) # Delete with shift# Device locking and unlocking
driver.lock(5) # Lock for 5 seconds
time.sleep(6)
if driver.is_locked():
driver.unlock()
print("Device unlocked")
# Shake device to trigger accelerometer
driver.shake()
# Useful for testing shake-to-refresh or shake gestures
shake_element = driver.find_element("id", "shake_detector")
driver.shake()
assert "Shake detected" in shake_element.text# Set GPS coordinates for testing
driver.set_location(37.7749, -122.4194, 30) # San Francisco with altitude
# Verify location in app
location_display = driver.find_element("id", "current_location")
assert "San Francisco" in location_display.text
# Get current location
current_location = driver.location
print(f"Current location: {current_location['latitude']}, {current_location['longitude']}")
# Test location-based features
driver.set_location(40.7128, -74.0060) # New York
# Trigger location-based functionality in app
location_button = driver.find_element("id", "get_weather")
location_button.click()
weather_display = driver.find_element("id", "weather_info")
assert "New York" in weather_display.text# Get device time in different formats
default_time = driver.get_device_time()
print(f"Default time: {default_time}")
formatted_time = driver.get_device_time("YYYY-MM-DD HH:mm:ss")
print(f"Formatted time: {formatted_time}")
iso_time = driver.get_device_time("YYYY-MM-DDTHH:mm:ssZ")
print(f"ISO time: {iso_time}")
# Use time for testing time-sensitive features
timestamp_element = driver.find_element("id", "timestamp")
app_time = timestamp_element.text
device_time = driver.get_device_time("HH:mm")
# Verify app shows current device timefrom appium.webdriver.common.clipboard_content_type import ClipboardContentType
# Set text in clipboard
driver.set_clipboard("Test clipboard content")
# Get clipboard content
clipboard_text = driver.get_clipboard()
print(f"Clipboard contains: {clipboard_text}")
# Test copy/paste functionality
source_text = driver.find_element("id", "source_text")
source_text.long_press() # Long press to show context menu
copy_button = driver.find_element("id", "copy")
copy_button.click()
# Verify clipboard content
copied_text = driver.get_clipboard()
assert copied_text == source_text.text
# Paste in another field
target_field = driver.find_element("id", "target_field")
target_field.click()
target_field.long_press()
paste_button = driver.find_element("id", "paste")
paste_button.click()
# Verify paste worked
assert target_field.text == copied_text# Complex keyboard interaction scenarios
def test_keyboard_with_different_strategies():
"""Test different keyboard hiding strategies."""
strategies = ['press', 'swipeDown', 'tapOut']
for strategy in strategies:
# Open keyboard
input_field = driver.find_element("id", "test_input")
input_field.click()
if driver.is_keyboard_shown():
try:
driver.hide_keyboard(strategy=strategy)
print(f"Successfully hid keyboard with strategy: {strategy}")
except Exception as e:
print(f"Strategy {strategy} failed: {e}")
# Android keycode examples
def send_navigation_keys():
"""Send various Android navigation keys."""
# Common Android keycodes
KEYCODE_BACK = 4
KEYCODE_HOME = 3
KEYCODE_MENU = 82
KEYCODE_SEARCH = 84
KEYCODE_VOLUME_UP = 24
KEYCODE_VOLUME_DOWN = 25
# Navigate using hardware keys
driver.press_keycode(KEYCODE_MENU) # Open menu
driver.press_keycode(KEYCODE_BACK) # Go back
driver.press_keycode(KEYCODE_HOME) # Go to home screendef safe_keyboard_operations():
"""Safely handle keyboard operations with error checking."""
try:
# Try to hide keyboard
if driver.is_keyboard_shown():
driver.hide_keyboard()
except Exception as e:
print(f"Could not hide keyboard: {e}")
# Try alternative method
driver.press_keycode(4) # Back key on Android
def safe_location_setting():
"""Safely set location with validation."""
try:
driver.set_location(37.7749, -122.4194)
# Verify location was set
location = driver.location
if abs(location['latitude'] - 37.7749) > 0.01:
print("Location may not have been set correctly")
except Exception as e:
print(f"Could not set location: {e}")from typing import Tuple, List, Dict, Union
# Keyboard types
KeyCode = int # Android keycode constants
MetaState = int # Key modifier flags
KeyEventFlags = int
# Location types
Latitude = float
Longitude = float
Altitude = float
LocationDict = Dict[str, float] # {'latitude': float, 'longitude': float, 'altitude': float}
# Time types
TimeFormat = str # Format string like 'YYYY-MM-DD HH:mm:ss'
DeviceTime = str # Formatted time string
# Clipboard types
class ClipboardContentType:
PLAINTEXT = "plaintext"
URL = "url"
IMAGE = "image"
ClipboardContent = str # May be base64 encoded for binary content
# Gesture types
TouchPosition = Tuple[int, int] # (x, y) coordinate tuple
TouchPositions = List[TouchPosition] # List of touch coordinates
Duration = int # Duration in milliseconds
GestureSpeed = int # Gesture speed parameter
# Biometric types
FingerID = int # Finger ID for fingerprint authentication (1-10)
BiometricMatch = bool # Authentication success/failureInstall with Tessl CLI
npx tessl i tessl/pypi-appium-python-client