Package src :: 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.

# UiAutomator backend

No service is started.

Instance Methods | [hide private]
__init__(self, device, serialno, adb=None, autodump=True, forceviewserveruse=False, localport=VIEW_SERVER_PORT, remoteport=VIEW_SERVER_PORT, startviewserver=True, ignoreuiautomatorkilled=False) 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) 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) Parses the View tree contained in `receivedLines`. | 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=View.__str__, stream=sys.stdout) 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
__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
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
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") Write the View image to the specified filename in the specified format. | source code
distance(self, tree) Calculates the distance between this tree 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() Obtains the ADB path attempting know locations for different OSs | source code
__mapSerialNo(serialno) | source code
__obtainDeviceSerialNumber(device) | source code
setAlarm(timeout) | source code
connectToDeviceOrExit(timeout=60, verbose=False, ignoresecuredevice=False, serialno=None) Connects to a device which serial number is obtained from the script arguments if available or using the default regex `.*`. | source code
traverseShowClassIdAndText(view, extraInfo=None, noextrainfo=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 unique id. | source code
traverseShowClassIdTextAndCenter(view) Shows the View class, id and text if available. | source code
traverseShowClassIdTextPositionAndSize(view) Shows the View class, id and text if available. | source code
TRAVERSE_CIT(view, extraInfo=None, noextrainfo=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_CITC(view) An alias for traverseShowClassIdTextAndCenter(view) | source code
TRAVERSE_CITPS(view) An alias for traverseShowClassIdTextPositionAndSize(view) | source code
sleep(secs=1.0) Sleeps for the specified number of seconds. | source code
__traverse(root, indent="", transform=View.__str__, stream=sys.stdout) | source code
__pickleable(tree) Makes the tree pickleable. | 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

Instance Variables | [hide private]
| device The `MonkeyDevice` device instance
| serialno The serial number of the device
| 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
| useUiAutomator If UIAutomator is supported by the device it will be used
| ignoreUiAutomatorKilled On some devices (i.e.
| windows The list of windows as obtained by ViewClient.list()
| 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=VIEW_SERVER_PORT, remoteport=VIEW_SERVER_PORT, startviewserver=True, ignoreuiautomatorkilled=False) (Constructor) | source code
Constructor Parameters: `device` (MonkeyDevice) - 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`

### connectToDeviceOrExit(timeout=60, verbose=False, ignoresecuredevice=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 `.*`. If the connection is not successful the script exits. `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. Parameters: `timeout` (int) - timeout for the connection `verbose` (bool) - Verbose output `ignoresecuredevice` (bool) - Ignores the check for a secure device `serialno` (str) - The device or emulator serial number Returns: the device and serialno used for the connection

### traverseShowClassIdAndText(view, extraInfo=None, noextrainfo=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` (bool) - Don't add extra info 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 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 the content description

### traverseShowClassIdTextAndCenter(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

### 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

### TRAVERSE_CIT(view, extraInfo=None, noextrainfo=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` (bool) - Don't add extra info 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_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

### 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) | 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) | 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=View.__str__, stream=sys.stdout) | 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

### 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

### 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") | 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)

### distance(self, tree) | source code
Calculates the distance between this tree and the tree passed as argument. Parameters: `tree` (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 2.3.21 that uses `/dev/tty` instead of a file may have turned this variable unnnecessary, however it has been kept for backward compatibility.

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