Welcome to AndroidViewClient/culebra’s documentation!

Copyright (C) 2012-2022 Diego Torres Milano Created on Dec 1, 2012

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

@author: Diego Torres Milano

class com.dtmilano.android.adb.adbclient.AdbClient(serialno=None, hostname='localhost', port=5037, settransport=True, reconnect=True, ignoreversioncheck=False, timeout=15, connect=<function connect>)

Adb client.

build

Build properties

display

The map containing the device’s physical display properties: width, height and density

drag(xxx_todo_changeme1, xxx_todo_changeme2, duration, steps=1, orientation=-1)

Sends drag event in PX (actually it’s using C{input swipe} command).

@param (x0, y0): starting point in PX @param (x1, y1): ending point in PX @param duration: duration of the event in ms @param steps: number of steps (currently ignored by C{input swipe}) @param orientation: the orientation (-1: undefined)

dragDip(xxx_todo_changeme3, xxx_todo_changeme4, duration, steps=1, orientation=-1)

Sends drag event in DIP (actually it’s using C{input swipe} command.

@param (x0, y0): starting point in DIP @param (x1, y1): ending point in DIP @param duration: duration of the event in ms @param steps: number of steps (currently ignored by C{input swipe})

getFocusedWindow()

Gets the focused window.

@return: The focused L{Window}.

getFocusedWindowName()

Gets the focused window name.

This is much like monkeyRunner’s C{HierarchyView.getWindowName()}

@return: The focused window name

getLogicalDisplayInfo()

Gets C{mDefaultViewport} and then C{deviceWidth} and C{deviceHeight} values from dumpsys. This is a method to obtain display logical dimensions and density. Obtains the rotation from dumpsys.

getPhysicalDisplayInfo()

Gets C{mPhysicalDisplayInfo} values from dumpsys. This is a method to obtain display dimensions and density

getProperty(key, strip=True)

Gets the property value for key

getRestrictedScreen()

Gets C{mRestrictedScreen} values from dumpsys. This is a method to obtain display dimensions

getSdkVersion()

Gets the SDK version.

static imageInScreen(screen, image)

Checks if image is on the screen

@param screen: the screen image @param image: the partial image to look for @return: True or False

@author: Perry Tsai <ripple0129@gmail.com>

imageToData(image, output_type=None)

Helps in cases where the Views cannot be identified. Returns the text found in the image and its bounding box. :param image: the image (i.e. from takeScreenshot()) :param output_type: the output type (defualt: pytessearct.Output.DICT) :return: the data from the image

isKeyboardShown()

Whether the keyboard is displayed.

isLocked()

Checks if the device screen is locked.

@return True if the device screen is locked

isScreenOn()

Checks if the screen is ON.

@return: True if the device screen is ON

longTouch(x, y, duration=2000, orientation=-1)

Long touches at (x, y)

@param duration: duration in ms @param orientation: the orientation (-1: undefined)

This workaround was suggested by U{HaMi<http://stackoverflow.com/users/2571957/hami>}

static percentSame(image1, image2)

Returns the percent of pixels that are equal

@author: catshoes

static sameAs(image1, image2, percent=1.0)

Compares 2 images

@author: catshoes

screenshot_number

The screenshot number count

setTimer(timeout, description=None)

Sets a timer.

Parameters:
  • description

  • timeout – timeout in seconds

Returns:

the timerId

startActivity(component=None, flags=None, uri=None, package=None)

Starts an Activity. If package is specified instead of component the corresponding MAIN activity for the package will be resolved and used.

takeSnapshot(reconnect=False, box=None)

Takes a snapshot of the device and return it as a PIL Image. The snapshot is for the entire screen or can be limited to the box if specified.

Parameters:
  • reconnect – reconnects after taking the screenshot

  • box – box as a tuple indicating (left, top, right, bottom) to crop the entire screen

Returns:

the image

unlock()

Unlocks the screen of the device.

class com.dtmilano.android.adb.adbclient.Device(serialno, status, qualifiers=None)

A device.

static factory(_str)

Device factory. :param _str: :type _str: :return: :rtype:

has_qualifier(qualifier)
Parameters:

qualifier

Returns:

Return type:

class com.dtmilano.android.adb.adbclient.WifiManager(device)

Simulates Android WifiManager.

@see: http://developer.android.com/reference/android/net/wifi/WifiManager.html

getWifiState()

Gets the Wi-Fi enabled state.

@return: One of WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED, WIFI_STATE_ENABLING, WIFI_STATE_UNKNOWN

com.dtmilano.android.adb.adbclient.connect(hostname, port, timeout=15)

Connect to ADB server. :param hostname: the hostname :param port: the port :param timeout: the timeout in seconds :return:

Copyright (C) 2012-2022 Diego Torres Milano Created on Feb 2, 2015

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

@author: Diego Torres Milano

class com.dtmilano.android.uiautomator.uiautomatorhelper.RunTestsThread(group=None, target=None, name=None, args=(), kwargs=None, verbose=None, adbClient=None, testClass=None, testRunner=None)

Runs the instrumentation for the specified package in a new thread.

run()

Method representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

class com.dtmilano.android.uiautomator.uiautomatorhelper.UiAutomatorHelper(adbclient, adb=None, localport=9987, remoteport=9987, hostname='localhost', api_version='v2')

UiAutomatorHelper is a backend for AndroidViewClient.

class ApiBase(uiAutomatorHelper)

Abstract class to serve as a base for API implementations.

all(l1: list, l2: list) bool

All the elements are in both lists.

Parameters:
  • l1 (list) – list 1

  • l2 (list) – list 2

Returns:

whether all elements are in both lists

Return type:

bool

static intersection(l1: list, l2: list) list

Obtains the intersection between the two lists.

Parameters:
  • l1 (list) – list 1

  • l2 (list) – list 2

Returns:

the list containing the intersection

Return type:

list

some(l1: list, l2: list) bool

Some elements are in both lists.

Parameters:
  • l1 (list) – list 1

  • l2 (list) – list 2

Returns:

whether some elements are in both lists

Return type:

bool

class Device(uiAutomatorHelper)

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml

display_real_size()

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :return: the display real size

dumpsys(service, **kwargs) str

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml

Parameters:

service – the service

Returns:

the dumpsys output

wait_for_new_toast(timeout=10000)

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml

Returns:

the text in the Toast if found

class ObjectStore(uiAutomatorHelper)

Object Store.

clear()

Clears all the objects. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml

Returns:

the status

list()

List the objects. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml

Returns:

the list of objects

Return type:

list

remove(oid: int)

Removes an object. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml

Parameters:

oid – the object id

Returns:

the status

class TargetContext(uiAutomatorHelper)

Target Context.

start_activity(pkg, cls, **kwargs)

Starts an activity.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param pkg: the package :param cls: the Activity class :param kwargs: uri: the optional URI :return: the api response

class UiDevice(uiAutomatorHelper)

UI Device.

click(x: int, y: int)

Clicks on the specified coordinates.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :return:

dump_window_hierarchy(_format='JSON')

Dumps the window hierarchy.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param _format: the format (e.g.: JSON, XML) :return: the window hierarchy

find_objects(**kwargs)

Finds objects. Invokes GET or POST method depending on the arguments passed.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param kwargs: :return:

has_object(**kwargs) bool

Has an object. Invokes GET or POST method depending on the arguments passed.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param kwargs: :return: True or False

press_back() None

Presses BACK.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :return:

press_enter() None

Presses ENTER.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :return:

press_home() None

Presses HOME.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :return:

press_key_code(key_code: int, meta_state: int = 0) None

Presses a key code.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param key_code: :param meta_state: :return:

press_recent_apps() None

Press recent apps.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :return:

swipe(**kwargs) None

Swipes.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param kwargs: :return:

take_screenshot(scale=1.0, quality=90, filename=None, **kwargs)

Takes screenshot. Eventually save it in a file specified by filename.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param scale: the scale :param quality: the quality :param filename: if specified the image will be saved in filename :param kwargs: optional arguments :return: the response containing the image binary if the filename was not specified

wait(oid: int, timeout=10000)

Waits for a search condition.

Parameters:
  • oid – the search condition ref (oid)

  • timeout – the timeout in ms

Returns:

The final result returned by the condition, or null if the condition was not met before the timeout.

wait_for_idle(**kwargs) None

Waits for idle.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param kwargs: :return:

wait_for_window_update(timeout=5000, **kwargs) None

Waits for window update.

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param timeout: the timeout :param kwargs: :return:

class UiObject(uiAutomatorHelper)

Inner UiObject class.

Notice that this class does not require an OID in its constructor.

dump(oid: int)
Parameters:

oid

Returns:

exists(oid: int) bool

:see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: :return:

get_child_count(oid: int) int

Counts the child views immediately under the present UiObject. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :return: the child count

get_class_name(oid: int) str

Retrieves the className property of the UI element. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: :return: the class name

get_content_description(oid: int) str

Reads the content_desc property of the UI element. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :return: the content description

perform_two_pointer_gesture(oid: int, startPoint1: Tuple[int, int], startPoint2: Tuple[int, int], endPoint1: Tuple[int, int], endPoint2: Tuple[int, int], steps: int) None

Generates a two-pointer gesture with arbitrary starting and ending points. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :param startPoint1: :param startPoint2: :param endPoint1: :param endPoint2: :param steps: :return: the result of the operation

pinch_in(oid: int, percentage: int, steps: int = 50) None

Performs a two-pointer gesture, where each pointer moves diagonally toward the other, from the edges to the center of this UiObject. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :param percentage: percentage of the object’s diagonal length for the pinch gesture :param steps: the number of steps for the gesture. Steps are injected about 5 milliseconds apart, so 100 steps may take around 0.5 seconds to complete. :return: the result of the operation

pinch_out(oid: int, percentage: int, steps: int = 50) None

Performs a two-pointer gesture, where each pointer moves diagonally opposite across the other, from the center out towards the edges of the UiObject. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :param percentage: percentage of the object’s diagonal length for the pinch gesture :param steps: the number of steps for the gesture. Steps are injected about 5 milliseconds apart, so 100 steps may take around 0.5 seconds to complete. :return: the result of the operation

class UiObject2(uiAutomatorHelper)

Inner UiObject2 class.

Notice that this class does not require an OID in its constructor.

clear(oid: int) None

Clears the text content if this object is an editable field. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :return: the result of the operation

click(oid: int) None

Clicks on this object. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :return: the result of the operation

click_and_wait(oid: int, event_condition_ref, timeout=10000) None

Clicks and wait. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :param event_condition_ref: the event condition :param timeout: the timeout :return: the status response

dump(oid)

Dumps the content of an object. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :return: the content

get_content_description(oid: int) str

Returns the content description for this object. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :return: the text

get_text(oid: int) str

Returns the text value for this object. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :return: the text

long_click(oid: int) None

Performs a long click on this object. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :return: the result of the operation

set_text(oid: int, text: str)

Sets the text content if this object is an editable field. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml :param oid: the oid :param text: the text :return: the result of the operation

class Until(uiAutomatorHelper)
find_object(**kwargs) ObjectRef

Returns a SearchCondition that is satisfied when at least one element matching the selector can be found. The condition will return the first matching element. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml

Parameters:

kwargs – the arguments

Returns:

the search condition reference

find_objects(**kwargs) List[ObjectRef]

Returns a SearchCondition that is satisfied when at least one element matching the selector can be found. The condition will return the first matching element. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml

Parameters:

kwargs – the arguments

Returns:

the search condition object reference

new_window() ObjectRef

Returns a condition that depends on a new window having appeared. :see https://github.com/dtmilano/CulebraTester2-public/blob/master/openapi.yaml

Returns:

the event condition reference

Return type:

Until object reference

adb

The adb command

adbClient

The adb client (a.k.a. device)

hostname

The hostname we are connecting to.

isDarwin

Is it macOS?

osName

The OS name. We sometimes need specific behavior.

static timestamp() str

Timestamp in ISO format.

WARNING: may not be suitable to include in filenames on some platforms as it may include invalid path chars (i.e. :).

Returns:

the timestamps

com.dtmilano.android.uiautomator.uiautomatorhelper.check_response(response: StatusResponse) None

Checks if the status response is OK. Otherwise, it raises an exception.

Parameters:

response – the response

Returns:

None

Copyright (C) 2012-2022 Diego Torres Milano Created on Feb 2, 2012

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

@author: Diego Torres Milano

class com.dtmilano.android.viewclient.ConnectedDevice(device, vc, serialno)

A connected device.

class com.dtmilano.android.viewclient.CulebraOptions

Culebra options helper class

class com.dtmilano.android.viewclient.CulebraTestCase(methodName='runTest')

The base class for all CulebraTests.

Class variables

There are some class variables that can be used to change the behavior of the tests.

B{serialno}: The serial number of the device. This can also be a list of devices for I{mutli-devices} tests or the keyword C{all} to run the tests on all available devices or C{default} to run the tests only on the default (first) device.

When a I{multi-device} test is running the available devices are available in a list named L{self.devices} which has the corresponding L{ConnectedDevices} entries.

Also, in the case of I{multi-devices} tests and to be backward compatible with I{single-device} tests the default device, the first one in the devices list, is assigned to L{self.device}, L{self.vc} and L{self.serialno} too.

B{verbose}: The verbosity of the tests. This can be changed from the test command line using the command line option C{-v} or C{–verbose}.

defaultDevice = None

The default L{ConnectedDevice}. Set to the first one found for multi-device cases

device = None

The default connected device

devices = None

The list of connected devices

globalDevices = []

The list of connected devices (class instance)

helper = None

The UiAutomatoHelper instance if enabled

log(message, priority='D')

Logs a message with the specified priority.

serialno = None

The default connected device C{serialno}

setUp()

Hook method for setting up the test fixture before exercising it.

classmethod setUpClass()

Hook method for setting up class fixture before running tests in the class.

tearDown()

Hook method for deconstructing the test fixture after testing it.

classmethod tearDownClass()

Hook method for deconstructing the class fixture after running all tests in the class.

vc = None

The default connected device C{ViewClient}

class com.dtmilano.android.viewclient.EditText(_map, device, version=-1, forceviewserveruse=False, windowId=None, uiAutomatorHelper=None)

EditText class.

setText(text)

This function makes sure that any previously entered text is deleted before setting the value of the field.

class com.dtmilano.android.viewclient.Excerpt2Code

Excerpt XML to code

CharacterData(data)

Expat character data event handler

EndElement(name)

Expat end element event handler

StartElement(name, attributes)

Expat start element event handler

class com.dtmilano.android.viewclient.ListView(_map, device, version=-1, forceviewserveruse=False, windowId=None, uiAutomatorHelper=None)

ListView class.

com.dtmilano.android.viewclient.OFFSET = 25

This assumes the smallest touchable view on the screen is approximately 50px x 50px and touches it at M{(x+OFFSET, y+OFFSET)}

com.dtmilano.android.viewclient.SKIP_CERTAIN_CLASSES_IN_GET_XY_ENABLED = False

Skips some classes related with the Action Bar and the PhoneWindow$DecorView in the coordinates calculation @see: L{View.getXY()}

class com.dtmilano.android.viewclient.TextView(_map, device, version=-1, forceviewserveruse=False, windowId=None, uiAutomatorHelper=None)

TextView class.

com.dtmilano.android.viewclient.USE_ADB_CLIENT_TO_GET_BUILD_PROPERTIES = True

Use C{AdbClient} to obtain the needed properties. If this is C{False} then C{adb shell getprop} is used

com.dtmilano.android.viewclient.USE_PHYSICAL_DISPLAY_INFO = True

Use C{dumpsys display} to obtain display properties. If this is C{False} then C{USE_ADB_CLIENT_TO_GET_BUILD_PROPERTIES} is used

class com.dtmilano.android.viewclient.UiAutomator2AndroidViewClient(device, version, uiAutomatorHelper)

UiAutomator XML to AndroidViewClient

CharacterData(data)

Expat character data event handler

EndElement(name)

Expat end element event handler

StartElement(name, attributes)

Expat start element event handler

class com.dtmilano.android.viewclient.UiCollection

Used to enumerate a container’s user interface (UI) elements for the purpose of counting, or targeting a sub elements by a child’s text or description.

class com.dtmilano.android.viewclient.UiDevice(vc)

Provides access to state information about the device. You can also use this class to simulate user actions on the device, such as pressing the d-pad or pressing the Home and Menu buttons.

openNotification()

Opens the notification shade.

openQuickSettings()

Opens the Quick Settings shade.

openQuickSettingsSettings()

Opens the Quick Settings shade and then tries to open Settings from there.

class com.dtmilano.android.viewclient.UiScrollable(view)

A L{UiCollection} that supports searching for items in scrollable layout elements.

This class can be used with horizontally or vertically scrollable controls.

scrollTextIntoView(text)

Performs a forward scroll action on the scrollable layout element until the text you provided is visible, or until swipe attempts have been exhausted. See setMaxSearchSwipes(int)

com.dtmilano.android.viewclient.VIEW_CLIENT_TOUCH_WORKAROUND_ENABLED = False

Under some conditions the touch event should be longer [t(DOWN) << t(UP)]. C{True} enables a workaround to delay the events.

class com.dtmilano.android.viewclient.View(_map, device, version=-1, forceviewserveruse=False, windowId=None, uiAutomatorHelper=None)

View class

add(child)

Adds a child

@type child: View @param child: The child to add

build

Build properties

children

The children of this View

currentFocus

The current focus

device

The AdbClient

static factory(arg1, arg2, version=-1, forceviewserveruse=False, windowId=None, uiAutomatorHelper=None)

View factory

@type arg1: ClassType or dict @type arg2: View instance or AdbClient

forceviewserveruse

Force ViewServer use

getBounds()

Gets the View bounds

getCenter()

Gets the center coords of the View

@author: U{Dean Morin <https://github.com/deanmorin>}

getChildren()

Gets the children of this L{View}.

getClass()

Gets the L{View} class

@return: the L{View} class or C{None} if not defined

getContentDescription()

Gets the content description.

getCoords()

Gets the coords of the View

@return: A tuple containing the View’s coordinates ((L, T), (R, B))

getHeight()

Gets the height.

getId()

Gets the L{View} Id

@return: the L{View} C{Id} or C{None} if not defined @see: L{getUniqueId()}

getParent()

Gets the parent.

getPositionAndSize()

Gets the position and size (X,Y, W, H)

@return: A tuple containing the View’s coordinates (X, Y, W, H)

getTag()

Gets the tag.

getText()

Gets the text attribute.

@return: the text attribute or C{None} if not defined

getUniqueId()

Gets the unique Id of this View.

@see: L{ViewClient.__splitAttrs()} for a discussion on B{Unique Ids}

getVisibility()

Gets the View visibility

getWidth()

Gets the width.

getX()

Gets the View X coordinate

getXY(debug=False)

Returns the I{screen} coordinates of this C{View}.

WARNING: Don’t call self.getX() or self.getY() inside this method or it will enter an infinite loop

@return: The I{screen} coordinates of this C{View}

getY()

Gets the View Y coordinate

heightProperty

The height property depending on the View attribute format

idProperty

The id property depending on the View attribute format

isFocused()

Gets the focused value

@return: the focused value. If the property cannot be found returns C{False}

isFocusedProperty

The focused property depending on the View attribute format

leftProperty

The left property depending on the View attribute format

longTouch(duration=2000)

Long touches this C{View}

@param duration: duration in ms

map

The map that contains the C{attr},C{value} pairs

obtain_selector() Optional[Selector]

Obtains a Selector for this View.

Returns:

the Selector or None if the most important values (e.g. text, res, etc.) are not present

parent

The parent of this View

tagProperty

The tag property depending on the View attribute format

target

Is this a touch target zone

textProperty

The text property depending on the View attribute format

topProperty

The top property depending on the View attribute format

touch(eventType=2, deltaX=0, deltaY=0)

Touches the center of this C{View}. The touch can be displaced from the center by using C{deltaX} and C{deltaY} values.

@param eventType: The event type @type eventType: L{adbclient.DOWN}, L{adbclient.UP} or L{adbclient.DOWN_AND_UP} @param deltaX: Displacement from center (X axis) @type deltaX: int @param deltaY: Displacement from center (Y axis) @type deltaY: int

uiAutomatorHelper

The UiAutomatorHelper

uiScrollable

If this is a scrollable View this keeps the L{UiScrollable} object

useUiAutomator

Whether to use UIAutomator or ViewServer

version

API version number

widthProperty

The width property depending on the View attribute format

windowId

The window this view resides

writeImageToFile(filename, _format='PNG')

Write the View image to the specified filename in the specified format.

@type filename: str @param filename: Absolute path and optional filename receiving the image. If this points to a directory, then the filename is determined by this View unique ID and format extension. @type _format: str @param _format: Image format (default format is PNG)

class com.dtmilano.android.viewclient.ViewClient(device, serialno, adb=None, autodump=True, forceviewserveruse=False, localport=None, remoteport=None, startviewserver=True, ignoreuiautomatorkilled=False, compresseddump=True, useuiautomatorhelper=False, debug={})

ViewClient is a I{ViewServer} client.

ViewServer backend

If not running the ViewServer is started on the target device or emulator and then the port mapping is created.

LocalViewServer backend

ViewServer is started as an application services instead of as a system service.

UiAutomator backend

No service is started.

null backend

Allows only operations using PX or DIP as hierarchy is not dumped and thus Views not recognized.

UiAutomatorHelper backend

Requires B{CulebraTester2-public} installed on Android device.

static TRAVERSE_CIT(view, extraInfo=None, noExtraInfo=None, extraAction=None)

An alias for L{traverseShowClassIdAndText(view)}

static TRAVERSE_CITB(view)

An alias for L{traverseShowClassIdTextAndBounds(view)}

static TRAVERSE_CITC(view)

An alias for L{traverseShowClassIdTextAndCenter(view)}

static TRAVERSE_CITCD(view)

An alias for L{traverseShowClassIdTextAndContentDescription(view)}

static TRAVERSE_CITCDS(view)

An alias for L{traverseShowClassIdTextContentDescriptionAndScreenshot(view)}

static TRAVERSE_CITG(view)

An alias for L{traverseShowClassIdTextAndTag(view)}

static TRAVERSE_CITPS(view)

An alias for L{traverseShowClassIdTextPositionAndSize(view)}

static TRAVERSE_CITUI(view)

An alias for L{traverseShowClassIdTextAndUniqueId(view)}

static TRAVERSE_S(view)

An alias for L{traverseTakeScreenshot(view)}

adb

The adb command

assertServiceResponse(response)

Checks whether the response received from the server is correct or raises and Exception.

@type response: str @param response: Response received from the server

@raise Exception: If the response received from the server is invalid

build

The map containing the device’s build properties: version.sdk, version.release

click(x=-1, y=-1, selector=None)

An alias for touch.

Parameters:
  • x – x coordinate

  • y – y coordinate

  • selector – the selector, could be None

Returns:

the result of the operation

static connectToDeviceOrExit(timeout=60, verbose=False, ignoresecuredevice=False, ignoreversioncheck=False, serialno=None, adbhostname='localhost', adbport=5037, connect=<function connect>)

Connects to a device which serial number is obtained from the script arguments if available or using the default regex .* if not provided.

If the connection is not successful the script exits.

Parameters:
  • timeout (int) – timeout for the connection

  • verbose (bool) – Verbose output

  • ignoresecuredevice (bool) – ignores a secure device

  • ignoreversioncheck (bool) – ignores the version check

  • serialno (str) – the serial number of the device (can be None)

  • adbhostname (str) – The adb hostname

  • adbport (int) – The adb port

  • connect (function) – Connect method to use to connect to ADB

Returns:

the device and serialno used for the connection

Return type:

Tuple[AdbClient, str]

History

In MonkeyRunner times, this method was a way of overcoming one of its limitations. MonkeyRunner.waitForConnection() returns a MonkeyDevice even if the connection failed. Then, to detect this situation, device.wake() is attempted and if it fails then it is assumed the previous connection failed.

device

The C{AdbClient} device instance

display

The map containing the device’s display properties: width, height and density

static distance(tree1, tree2)

Calculates the distance between the two trees.

@type tree1: list of Views @param tree1: Tree of Views @type tree2: list of Views @param tree2: Tree of Views @return: the distance

distanceTo(tree)

Calculates the distance between the current state and the tree passed as argument.

@type tree: list of Views @param tree: Tree of Views @return: the distance

dump(window=-1, sleep=1)

Dumps the window content.

Sleep is useful to wait some time before obtaining the new content when something in the window has changed.

@type window: int or str @param window: the window id or name of the window to dump. The B{name} is the package name or the window name (i.e. StatusBar) for system windows. The window id can be provided as C{int} or C{str}. The C{str} should represent and C{int} in either base 10 or 16. Use -1 to dump all windows. This parameter only is used when the backend is B{ViewServer} and it’s ignored for B{UiAutomator}. @type sleep: int @param sleep: sleep in seconds before proceeding to dump the content

@return: the list of Views as C{str} received from the server after being split into lines

findViewById(viewId, root='ROOT', viewFilter=None)

Finds the View with the specified viewId.

@type viewId: str @param viewId: the ID of the view to find @type root: str @type root: View @param root: the root node of the tree where the View will be searched @type: viewFilter: function @param viewFilter: a function that will be invoked providing the candidate View as a parameter and depending on the return value (C{True} or C{False}) the View will be selected and returned as the result of C{findViewById()} or ignored. This can be C{None} and no extra filtering is applied.

@return: the C{View} found or C{None}

findViewByIdOrRaise(viewId, root='ROOT', viewFilter=None)

Finds the View or raise a ViewNotFoundException.

@type viewId: str @param viewId: the ID of the view to find @type root: str @type root: View @param root: the root node of the tree where the View will be searched @type: viewFilter: function @param viewFilter: a function that will be invoked providing the candidate View as a parameter and depending on the return value (C{True} or C{False}) the View will be selected and returned as the result of C{findViewById()} or ignored. This can be C{None} and no extra filtering is applied. @return: the View found @raise ViewNotFoundException: raise the exception if View not found

findViewByTag(tag, root='ROOT')

Finds the View with the specified tag

findViewByTagOrRaise(tag, root='ROOT')

Finds the View with the specified tag or raise a ViewNotFoundException

findViewWithAttribute(attr, val, root='ROOT')

Finds the View with the specified attribute and value

findViewWithAttributeOrRaise(attr, val, root='ROOT')

Finds the View or raise a ViewNotFoundException.

@return: the View found @raise ViewNotFoundException: raise the exception if View not found

findViewWithAttributeThatMatches(attr, regex, root='ROOT')

Finds the list of Views with the specified attribute matching regex

findViewWithContentDescription(contentdescription, root='ROOT')

Finds the View with the specified content description

findViewWithContentDescriptionOrRaise(contentdescription, root='ROOT')

Finds the View with the specified content description

findViewWithTextOrRaise(text, root='ROOT')

Finds the View or raise a ViewNotFoundException.

@return: the View found @raise ViewNotFoundException: raise the exception if View not found

findViewsContainingPoint(xxx_todo_changeme1, _filter=None)

Finds the list of Views that contain the point (x, y).

findViewsWithAttribute(attr, val, root='ROOT')

Finds the Views with the specified attribute and value. This allows you to see all items that match your criteria in the view hierarchy

Usage:

buttons = v.findViewsWithAttribute(“class”, “android.widget.Button”)

findViewsWithAttributeThatMatches(attr, regex, root='ROOT')

Finds the Views with the specified attribute matching regex. This allows you to see all items that match your criteria in the view hierarchy

forceViewServerUse

Force the use of ViewServer even if the conditions to use UiAutomator are satisfied

getRoot()

Gets the root node of the C{View} tree

@return: the root node of the C{View} tree

getSdkVersion()

Gets the SDK version.

getViewIds()

@deprecated: Use L{getViewsById} instead.

Returns the Views map.

getViewsById()

Returns the Views map. The keys are C{uniqueIds} and the values are C{View}s.

hammingDistance(tree)

Finds the Hamming distance between this tree and the one passed as argument.

ignoreUiAutomatorKilled

On some devices (i.e. Nexus 7 running 4.2.2) uiautomator is killed just after generating the dump file. In many cases the file is already complete so we can ask to ignore the ‘Killed’ message by setting L{ignoreuiautomatorkilled} to C{True}.

Changes in v2.3.21 that uses C{/dev/tty} instead of a file may have turned this variable unnecessary, however it has been kept for backward compatibility.

imageDirectory = None

The directory used to store screenshot images

isKeyboardShown()

Whether the keyboard is displayed.

levenshteinDistance(tree)

Finds the Levenshtein distance between this tree and the one passed as argument.

list(sleep=1)

List the windows.

Sleep is useful to wait some time before obtaining the new content when something in the window has changed. This also sets L{self.windows} as the list of windows.

@type sleep: int @param sleep: sleep in seconds before proceeding to dump the content

@return: the list of windows

osName = 'Darwin'

The OS name. We sometimes need specific behavior.

pressKeyCode(keycode, metaState=0)

By default no meta state

ro

The map containing the device’s ro properties: secure, debuggable

root

The root node

serialno

The serial number of the device

serviceResponse(response)

Checks the response received from the I{ViewServer}.

@return: C{True} if the response received matches L{PARCEL_TRUE}, C{False} otherwise

setViews(received, windowId=None)

Sets L{self.views} to the received value splitting it into lines.

@type received: str @param received: the string received from the I{View Server}

setViewsFromUiAutomatorDump(received)

Sets L{self.views} to the received value parsing the received XML.

@type received: str @param received: the string received from the I{UI Automator}

static sleep(secs=1.0)

Sleeps for the specified number of seconds.

@type secs: float @param secs: number of seconds

traverse(root='ROOT', indent='', transform=None, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>)

Traverses the C{View} tree and prints its nodes.

The nodes are printed converting them to string but other transformations can be specified by providing a method name as the C{transform} parameter.

@type root: L{View} @param root: the root node from where the traverse starts @type indent: str @param indent: the indentation string to use to print the nodes @type transform: method @param transform: a method to use to transform the node before is printed @param stream: the output stream

static traverseShowClassIdAndText(view, extraInfo=None, noExtraInfo=None, extraAction=None)

Shows the View class, id and text if available. This function can be used as a transform function to L{ViewClient.traverse()}

@type view: I{View} @param view: the View @type extraInfo: method @param extraInfo: the View method to add extra info @type noExtraInfo: str @param noExtraInfo: Don’t add extra info @type extraAction: method @param extraAction: An extra action to be invoked for every view

@return: the string containing class, id, and text if available

static traverseShowClassIdTextAndBounds(view)

Shows the View class, id and text if available. This function can be used as a transform function to L{ViewClient.traverse()}

@type view: I{View} @param view: the View @return: the string containing class, id, and text if available plus View bounds

static traverseShowClassIdTextAndCenter(view)

Shows the View class, id and text if available and center. This function can be used as a transform function to L{ViewClient.traverse()}

@type view: I{View} @param view: the View @return: the string containing class, id, and text if available

static traverseShowClassIdTextAndContentDescription(view)

Shows the View class, id, text if available and content description. This function can be used as a transform function to L{ViewClient.traverse()}

@type view: I{View} @param view: the View @return: the string containing class, id, and text if available and the content description

static traverseShowClassIdTextAndTag(view)

Shows the View class, id, text if available and tag. This function can be used as a transform function to L{ViewClient.traverse()}

@type view: I{View} @param view: the View @return: the string containing class, id, and text if available and tag

static traverseShowClassIdTextAndUniqueId(view)

Shows the View class, id, text if available and unique id. This function can be used as a transform function to L{ViewClient.traverse()}

@type view: I{View} @param view: the View @return: the string containing class, id, and text if available and unique Id

static traverseShowClassIdTextContentDescriptionAndScreenshot(view)

Shows the View class, id, text if available and unique id and takes the screenshot. This function can be used as a transform function to L{ViewClient.traverse()}

@type view: I{View} @param view: the View @return: the string containing class, id, and text if available and the content description

static traverseShowClassIdTextPositionAndSize(view)

Shows the View class, id and text if available. This function can be used as a transform function to L{ViewClient.traverse()}

@type view: I{View} @param view: the View @return: the string containing class, id, and text if available

static traverseTakeScreenshot(view)

Don’t show any any, just takes the screenshot. This function can be used as a transform function to L{ViewClient.traverse()}

@type view: I{View} @param view: the View @return: None

uiAutomatorHelper

The UiAutomatorHelper

uiDevice

The L{UiDevice}

viewsById

The map containing all the L{View}s indexed by their L{View.getUniqueId()}

windows

The list of windows as obtained by L{ViewClient.list()}

writeImageToFile(filename, _format='PNG', deviceart=None, dropshadow=True, screenglare=True)

Write the View image to the specified filename in the specified format.

@type filename: str @param filename: Absolute path and optional filename receiving the image. If this points to a directory, then the filename is determined by the serialno of the device and format extension. @type _format: str @param _format: Image format (default format is PNG)

static writeViewImageToFileInDir(view)

Write the View image to the directory specified in C{ViewClient.imageDirectory}.

@type view: View @param view: The view

class com.dtmilano.android.viewclient.ViewClientOptions

ViewClient options helper class

exception com.dtmilano.android.viewclient.ViewNotFoundException(attr, value, root)

ViewNotFoundException is raised when a View is not found.

Indices and tables