Package com :: Package dtmilano :: Package android :: Module viewclient :: Class ViewClient |
[hide private]
[frames] | no frames]

# Class ViewClient

source code

ViewClient is a 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 Culebra Tester installed on Android device.

Instance Methods | [hide private]
__init__(self, device, serialno, adb=None, autodump=True, forceviewserveruse=False, localport=4939, remoteport=4939, startviewserver=True, ignoreuiautomatorkilled=False, compresseddump=True, useuiautomatorhelper=False, debug=`{``}`) Constructor | source code
__del__(self) | source code
assertServiceResponse(self, response) Checks whether the response received from the server is correct or raises and Exception. | source code
serviceResponse(self, response) Checks the response received from the ViewServer. | source code
setViews(self, received, windowId=None) Sets self.views to the received value splitting it into lines. | source code
setViewsFromUiAutomatorDump(self, received) Sets self.views to the received value parsing the received XML. | source code
__splitAttrs(self, strArgs) Splits the `View` attributes in `strArgs` and optionally adds the view id to the `viewsById` list. | source code
__parseTree(self, receivedLines, windowId=None) Parses the View tree contained in `receivedLines`. | source code
__updateNavButtons(self) Updates the navigation buttons that might be on the device screen. | source code
__parseTreeFromUiAutomatorDump(self, receivedXml) | source code
getRoot(self) Gets the root node of the `View` tree | source code
traverse(self, root=`'``ROOT``'`, indent=`'````'`, transform=None, stream=<epydoc.docintrospecter._DevNull object>) Traverses the `View` tree and prints its nodes. | source code
dump(self, window=-1, sleep=1) Dumps the window content. | source code
list(self, sleep=1) List the windows. | source code
findViewById(self, viewId, root=`'``ROOT``'`, viewFilter=None) Finds the View with the specified viewId. | source code
findViewByIdOrRaise(self, viewId, root=`'``ROOT``'`, viewFilter=None) Finds the View or raise a ViewNotFoundException. | source code
findViewByTag(self, tag, root=`'``ROOT``'`) Finds the View with the specified tag | source code
findViewByTagOrRaise(self, tag, root=`'``ROOT``'`) Finds the View with the specified tag or raise a ViewNotFoundException | source code
__findViewsWithAttributeInTree(self, attr, val, root) | source code
__findViewWithAttributeInTree(self, attr, val, root) | source code
__findViewWithAttributeInTreeOrRaise(self, attr, val, root) | source code
__findViewWithAttributeInTreeThatMatches(self, attr, regex, root, rlist=`[``]`) | source code
findViewWithAttribute(self, attr, val, root=`'``ROOT``'`) Finds the View with the specified attribute and value | source code
findViewsWithAttribute(self, attr, val, root=`'``ROOT``'`) Finds the Views with the specified attribute and value. | source code
findViewWithAttributeOrRaise(self, attr, val, root=`'``ROOT``'`) Finds the View or raise a ViewNotFoundException. | source code
findViewWithAttributeThatMatches(self, attr, regex, root=`'``ROOT``'`) Finds the list of Views with the specified attribute matching regex | source code
findViewWithText(self, text, root=`'``ROOT``'`) | source code
findViewWithTextOrRaise(self, text, root=`'``ROOT``'`) Finds the View or raise a ViewNotFoundException. | source code
findViewWithContentDescription(self, contentdescription, root=`'``ROOT``'`) Finds the View with the specified content description | source code
findViewWithContentDescriptionOrRaise(self, contentdescription, root=`'``ROOT``'`) Finds the View with the specified content description | source code
findViewsContainingPoint(self, (x, y), _filter=None) Finds the list of Views that contain the point (x, y). | source code
findObject(self, **kwargs) | source code
click(self, x=-1, y=-1, selector=None) An alias for touch. | source code
touch(self, x=-1, y=-1, selector=None) | source code
longTouch(self, x=-1, y=-1, selector=None) | source code
swipe(self, startX=-1, startY=-1, endX=-1, endY=-1, steps=400, segments=`[``]`, segmentSteps=5, start=None, end=None) | source code
pressBack(self) | source code
pressHome(self) | source code
pressRecentApps(self) | source code
pressKeyCode(self, keycode, metaState=0) By default no meta state | source code
setText(self, v, text) | source code
getViewIds(self) | source code
getViewsById(self) Returns the Views map. | source code
__getFocusedWindowPosition(self) | source code
getSdkVersion(self) Gets the SDK version. | source code
isKeyboardShown(self) Whether the keyboard is displayed. | source code
writeImageToFile(self, filename, _format=`'``PNG``'`, deviceart=None, dropshadow=True, screenglare=True) Write the View image to the specified filename in the specified format. | source code
pilNotInstalledWarning(self) | source code
installPackage(self, apk) | source code
distanceTo(self, tree) Calculates the distance between the current state and the tree passed as argument. | source code
hammingDistance(self, tree) Finds the Hamming distance between this tree and the one passed as argument. | source code
levenshteinDistance(self, tree) Finds the Levenshtein distance between this tree and the one passed as argument. | source code

Static Methods | [hide private]
__obtainAdbPath() | source code
__mapSerialNo(serialno) | source code
__obtainDeviceSerialNumber(device) | source code
setAlarm(timeout) | source code
connectToDeviceOrExit(timeout=60, verbose=False, ignoresecuredevice=False, ignoreversioncheck=False, serialno=None) Connects to a device which serial number is obtained from the script arguments if available or using the default regex C{.*}. | source code
traverseShowClassIdAndText(view, extraInfo=None, noExtraInfo=None, extraAction=None) Shows the View class, id and text if available. | source code
traverseShowClassIdTextAndUniqueId(view) Shows the View class, id, text if available and unique id. | source code
traverseShowClassIdTextAndContentDescription(view) Shows the View class, id, text if available and content description. | source code
traverseShowClassIdTextAndTag(view) Shows the View class, id, text if available and tag. | source code
traverseShowClassIdTextContentDescriptionAndScreenshot(view) Shows the View class, id, text if available and unique id and takes the screenshot. | source code
traverseShowClassIdTextAndCenter(view) Shows the View class, id and text if available and center. | source code
traverseShowClassIdTextPositionAndSize(view) Shows the View class, id and text if available. | source code
traverseShowClassIdTextAndBounds(view) Shows the View class, id and text if available. | source code
traverseTakeScreenshot(view) Don't show any any, just takes the screenshot. | source code
TRAVERSE_CIT(view, extraInfo=None, noExtraInfo=None, extraAction=None) An alias for traverseShowClassIdAndText(view) | source code
TRAVERSE_CITUI(view) An alias for traverseShowClassIdTextAndUniqueId(view) | source code
TRAVERSE_CITCD(view) An alias for traverseShowClassIdTextAndContentDescription(view) | source code
TRAVERSE_CITG(view) An alias for traverseShowClassIdTextAndTag(view) | source code
TRAVERSE_CITC(view) An alias for traverseShowClassIdTextAndCenter(view) | source code
TRAVERSE_CITPS(view) An alias for traverseShowClassIdTextPositionAndSize(view) | source code
TRAVERSE_CITB(view) An alias for traverseShowClassIdTextAndBounds(view) | source code
TRAVERSE_CITCDS(view) An alias for traverseShowClassIdTextContentDescriptionAndScreenshot(view) | source code
TRAVERSE_S(view) An alias for traverseTakeScreenshot(view) | source code
sleep(secs=1.0) Sleeps for the specified number of seconds. | source code
__traverse(root, indent=`'````'`, transform=<unbound method View.__str__>, stream=<epydoc.docintrospecter._DevNull object>) | source code
writeViewImageToFileInDir(view) Write the View image to the directory specified in `ViewClient.imageDirectory`. | source code
__pickleable(tree) Makes the tree pickleable. | source code
distance(tree1, tree2) Calculates the distance between the two trees. | source code
__hammingDistance(s1, s2) Finds the Hamming distance between two strings. | source code
__levenshteinDistance(s, t) Find the Levenshtein distance between two Strings. | source code
excerpt(_str, execute=False) | source code

Class Variables | [hide private]
| imageDirectory = `None` The directory used to store screenshot images

Instance Variables | [hide private]
| device The `AdbClient` device instance
| serialno The serial number of the device
| uiAutomatorHelper The UiAutomatorHelper
| adb The adb command
| root The root node
| viewsById The map containing all the Views indexed by their View.getUniqueId()
| display The map containing the device's display properties: width, height and density
| build The map containing the device's build properties: version.sdk, version.release
| ro The map containing the device's ro properties: secure, debuggable
| forceViewServerUse Force the use of ViewServer even if the conditions to use UiAutomator are satisfied
| ignoreUiAutomatorKilled On some devices (i.e.
| windows The list of windows as obtained by ViewClient.list()
| uiDevice The output of compressed dump is different than output of uncompressed one.
| views The list of Views represented as `str` obtained after splitting it into lines after being received from the server.

Method Details | [hide private]

### __init__(self, device, serialno, adb=None, autodump=True, forceviewserveruse=False, localport=4939, remoteport=4939, startviewserver=True, ignoreuiautomatorkilled=False, compresseddump=True, useuiautomatorhelper=False, debug=`{``}`) (Constructor) | source code
Constructor Parameters: `device` (AdbClient) - The device running the `View server` to which this client will connect `serialno` (str) - the serial number of the device or emulator to connect to `adb` (str) - the path of the `adb` executable or None and `ViewClient` will try to find it `autodump` (boolean) - whether an automatic dump is performed at the end of this constructor `forceviewserveruse` (boolean) - Force the use of `ViewServer` even if the conditions to use `UiAutomator` are satisfied `localport` (int) - the local port used in the redirection `remoteport` (int) - the remote port used to start the `ViewServer` in the device or emulator `startviewserver` (boolean) - Whether to start the global ViewServer `ignoreuiautomatorkilled` (boolean) - Ignores received Killed message from `uiautomator` `compresseddump` (boolean) - turns --compressed flag for uiautomator dump on/off @:type useuiautomatorhelper: boolean @:param useuiautomatorhelper: use UiAutomatorHelper Android app as backend

### connectToDeviceOrExit(timeout=60, verbose=False, ignoresecuredevice=False, ignoreversioncheck=False, serialno=None) Static Method | source code
    Connects to a device which serial number is obtained from the script arguments if available
    or using the default regex C{.*}.

    If the connection is not successful the script exits.

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

    @type timeout: int
    @param timeout: timeout for the connection
    @type verbose: bool
    @param verbose: Verbose output
    @type ignoresecuredevice: bool
    @param ignoresecuredevice: Ignores the check for a secure device
    @type ignoreversioncheck: bool
    @param ignoreversioncheck: Ignores the check for a supported ADB version
    @type serialno: str
    @param serialno: The device or emulator serial number

    @return: the device and serialno used for the connection

### traverseShowClassIdAndText(view, extraInfo=None, noExtraInfo=None, extraAction=None) Static Method | source code
Shows the View class, id and text if available. This function can be used as a transform function to ViewClient.traverse() Parameters: `view` (View) - the View `extraInfo` (method) - the View method to add extra info `noExtraInfo` (str) - Don't add extra info `extraAction` (method) - An extra action to be invoked for every view Returns: the string containing class, id, and text if available

### traverseShowClassIdTextAndUniqueId(view) Static Method | source code
Shows the View class, id, text if available and unique id. This function can be used as a transform function to ViewClient.traverse() Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available and unique Id

### traverseShowClassIdTextAndContentDescription(view) Static Method | source code
Shows the View class, id, text if available and content description. This function can be used as a transform function to ViewClient.traverse() Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available and the content description

### traverseShowClassIdTextAndTag(view) Static Method | source code
Shows the View class, id, text if available and tag. This function can be used as a transform function to ViewClient.traverse() Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available and tag

### traverseShowClassIdTextContentDescriptionAndScreenshot(view) Static Method | source code
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 ViewClient.traverse() Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available and the content description

### traverseShowClassIdTextAndCenter(view) Static Method | source code
Shows the View class, id and text if available and center. This function can be used as a transform function to ViewClient.traverse() Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available

### traverseShowClassIdTextPositionAndSize(view) Static Method | source code
Shows the View class, id and text if available. This function can be used as a transform function to ViewClient.traverse() Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available

### traverseShowClassIdTextAndBounds(view) Static Method | source code
Shows the View class, id and text if available. This function can be used as a transform function to ViewClient.traverse() Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available plus View bounds

### traverseTakeScreenshot(view) Static Method | source code
Don't show any any, just takes the screenshot. This function can be used as a transform function to ViewClient.traverse() Parameters: `view` (View) - the View Returns: None

### TRAVERSE_CIT(view, extraInfo=None, noExtraInfo=None, extraAction=None) Static Method | source code
An alias for traverseShowClassIdAndText(view) Parameters: `view` (View) - the View `extraInfo` (method) - the View method to add extra info `noExtraInfo` (str) - Don't add extra info `extraAction` (method) - An extra action to be invoked for every view Returns: the string containing class, id, and text if available

### TRAVERSE_CITUI(view) Static Method | source code
An alias for traverseShowClassIdTextAndUniqueId(view) Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available and unique Id

### TRAVERSE_CITCD(view) Static Method | source code
An alias for traverseShowClassIdTextAndContentDescription(view) Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available and the content description

### TRAVERSE_CITG(view) Static Method | source code
An alias for traverseShowClassIdTextAndTag(view) Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available and tag

### TRAVERSE_CITC(view) Static Method | source code
An alias for traverseShowClassIdTextAndCenter(view) Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available

### TRAVERSE_CITPS(view) Static Method | source code
An alias for traverseShowClassIdTextPositionAndSize(view) Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available

### TRAVERSE_CITB(view) Static Method | source code
An alias for traverseShowClassIdTextAndBounds(view) Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available plus View bounds

### TRAVERSE_CITCDS(view) Static Method | source code
An alias for traverseShowClassIdTextContentDescriptionAndScreenshot(view) Parameters: `view` (View) - the View Returns: the string containing class, id, and text if available and the content description

### TRAVERSE_S(view) Static Method | source code
An alias for traverseTakeScreenshot(view) Parameters: `view` (View) - the View Returns: None

### sleep(secs=1.0) Static Method | source code
Sleeps for the specified number of seconds. Parameters: `secs` (float) - number of seconds

### assertServiceResponse(self, response) | source code
Checks whether the response received from the server is correct or raises and Exception. Parameters: `response` (str) - Response received from the server Raises: `Exception` - If the response received from the server is invalid

### serviceResponse(self, response) | source code
Checks the response received from the ViewServer. Returns: `True` if the response received matches `PARCEL_TRUE`, `False` otherwise

### setViews(self, received, windowId=None) | source code
Sets self.views to the received value splitting it into lines. Parameters: `received` (str) - the string received from the View Server

### setViewsFromUiAutomatorDump(self, received) | source code
Sets self.views to the received value parsing the received XML. Parameters: `received` (str) - the string received from the UI Automator

### __splitAttrs(self, strArgs) | source code
Splits the `View` attributes in `strArgs` and optionally adds the view id to the `viewsById` list. # Unique Ids It is very common to find `View`s having NO_ID as the Id. This turns very difficult to use self.findViewById(). To help in this situation this method assigns unique Ids. The unique Ids are generated using the pattern `id/no_id/<number>` with `<number>` starting at 1. Parameters: `strArgs` (str) - the string containing the raw list of attributes and values Returns: Returns the attributes map.

### __parseTree(self, receivedLines, windowId=None) | source code
Parses the View tree contained in `receivedLines`. The tree is created and the root node assigned to self.root. This method also assigns self.viewsById values using View.getUniqueId as the key. Parameters: `receivedLines` (str) - the string received from View Server

### getRoot(self) | source code
Gets the root node of the `View` tree Returns: the root node of the `View` tree

### traverse(self, root=`'``ROOT``'`, indent=`'````'`, transform=None, stream=<epydoc.docintrospecter._DevNull object>) | source code
Traverses the `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 `transform` parameter. Parameters: `root` (View) - the root node from where the traverse starts `indent` (str) - the indentation string to use to print the nodes `transform` (method) - a method to use to transform the node before is printed

### dump(self, window=-1, sleep=1) | source code
Dumps the window content. Sleep is useful to wait some time before obtaining the new content when something in the window has changed. Parameters: `window` (int or str) - the window id or name of the window to dump. The name is the package name or the window name (i.e. StatusBar) for system windows. The window id can be provided as `int` or `str`. The `str` should represent and `int` in either base 10 or 16. Use -1 to dump all windows. This parameter only is used when the backend is ViewServer and it's ignored for UiAutomator. `sleep` (int) - sleep in seconds before proceeding to dump the content Returns: the list of Views as `str` received from the server after being split into lines

### list(self, sleep=1) | source code
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 self.windows as the list of windows. Parameters: `sleep` (int) - sleep in seconds before proceeding to dump the content Returns: the list of windows

### findViewById(self, viewId, root=`'``ROOT``'`, viewFilter=None) | source code
Finds the View with the specified viewId. Parameters: `viewId` (str) - the ID of the view to find `root` (str) - the root node of the tree where the View will be searched `viewFilter` - a function that will be invoked providing the candidate View as a parameter and depending on the return value (`True` or `False`) the View will be selected and returned as the result of `findViewById()` or ignored. This can be `None` and no extra filtering is applied. Returns: the `View` found or `None`

### findViewByIdOrRaise(self, viewId, root=`'``ROOT``'`, viewFilter=None) | source code
Finds the View or raise a ViewNotFoundException. Parameters: `viewId` (str) - the ID of the view to find `root` (str) - the root node of the tree where the View will be searched `viewFilter` - a function that will be invoked providing the candidate View as a parameter and depending on the return value (`True` or `False`) the View will be selected and returned as the result of `findViewById()` or ignored. This can be `None` and no extra filtering is applied. Returns: the View found Raises: `ViewNotFoundException` - raise the exception if View not found

### findViewsWithAttribute(self, attr, val, root=`'``ROOT``'`) | source code
    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")

### findViewWithAttributeOrRaise(self, attr, val, root=`'``ROOT``'`) | source code
Finds the View or raise a ViewNotFoundException. Returns: the View found Raises: `ViewNotFoundException` - raise the exception if View not found

### findViewWithTextOrRaise(self, text, root=`'``ROOT``'`) | source code
Finds the View or raise a ViewNotFoundException. Returns: the View found Raises: `ViewNotFoundException` - raise the exception if View not found

### click(self, x=-1, y=-1, selector=None) | source code
An alias for touch. :param x: :param y: :param selector: :return:

### getViewIds(self) | source code
Deprecated: Use getViewsById instead. Returns the Views map.

### getViewsById(self) | source code
Returns the Views map. The keys are `uniqueIds` and the values are `View`s.

### writeImageToFile(self, filename, _format=`'``PNG``'`, deviceart=None, dropshadow=True, screenglare=True) | source code
Write the View image to the specified filename in the specified format. Parameters: `filename` (str) - 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. `_format` (str) - Image format (default format is PNG)

### writeViewImageToFileInDir(view) Static Method | source code
Write the View image to the directory specified in `ViewClient.imageDirectory`. Parameters: `view` (View) - The view

### distanceTo(self, tree) | source code
Calculates the distance between the current state and the tree passed as argument. Parameters: `tree` (list of Views) - Tree of Views Returns: the distance

### distance(tree1, tree2) Static Method | source code
Calculates the distance between the two trees. Parameters: `tree1` (list of Views) - Tree of Views `tree2` (list of Views) - Tree of Views Returns: the distance

### __hammingDistance(s1, s2) Static Method | source code
Finds the Hamming distance between two strings. Parameters: `s1` - string `s2` - string Returns: the distance Raises: `ValueError` - if the lenght of the strings differ

### __levenshteinDistance(s, t) Static Method | source code
Find the Levenshtein distance between two Strings. Python version of Levenshtein distance method implemented in Java at http://www.java2s.com/Code/Java/Data-Type/FindtheLevenshteindistancebetweentwoStrings.htm. This is the number of changes needed to change one String into another, where each change is a single character modification (deletion, insertion or substitution). The previous implementation of the Levenshtein distance algorithm was from http://www.merriampark.com/ld.htm Chas Emerick has written an implementation in Java, which avoids an OutOfMemoryError which can occur when my Java implementation is used with very large strings. This implementation of the Levenshtein distance algorithm is from http://www.merriampark.com/ldjava.htm:
       StringUtils.getLevenshteinDistance(null, *)             = IllegalArgumentException
       StringUtils.getLevenshteinDistance(*, null)             = IllegalArgumentException
       StringUtils.getLevenshteinDistance("","")               = 0
       StringUtils.getLevenshteinDistance("","a")              = 1
       StringUtils.getLevenshteinDistance("aaapppp", "")       = 7
       StringUtils.getLevenshteinDistance("frog", "fog")       = 1
       StringUtils.getLevenshteinDistance("fly", "ant")        = 3
       StringUtils.getLevenshteinDistance("elephant", "hippo") = 7
       StringUtils.getLevenshteinDistance("hippo", "elephant") = 7
       StringUtils.getLevenshteinDistance("hippo", "zzzzzzzz") = 8
       StringUtils.getLevenshteinDistance("hello", "hallo")    = 1
Parameters: `s` - the first String, must not be null `t` - the second String, must not be null Returns: result distance Raises: `ValueError` - if either String input `null`

Instance Variable Details | [hide private]

### 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 `ignoreuiautomatorkilled` to `True`. Changes in v2.3.21 that uses `/dev/tty` instead of a file may have turned this variable unnecessary, however it has been kept for backward compatibility.

### uiDevice The output of compressed dump is different than output of uncompressed one. If one requires uncompressed output, this option should be set to False

### views The list of Views represented as `str` obtained after splitting it into lines after being received from the server. Done by self.setViews().