Best Python code snippet using fMBT_python
fmbtwindows.py
Source:fmbtwindows.py
...200 Currently only the Value property is handled."""201 if attr == 'Value':202 self.setValue(value)203 object.__setattr__(self, attr, value)204 def _checkUIautomation(self):205 self._view._checkUIautomation()206 def branch(self):207 """Returns list of view items from the root down to this item208 Note: works only for UIAutomation backend"""209 self._checkUIautomation()210 rv = []211 itemId = self._itemId212 while itemId:213 rv.append(self._view._viewItems[itemId])214 if itemId in self._view._viewItems:215 itemId = self._view._viewItems[itemId]._parentId216 else:217 itemId = None218 rv.reverse()219 return rv220 def children(self):221 if self._view._viewSource.startswith("enumchildwindows"):222 return [self._view._viewItems[winfo[0]]223 for winfo in self._view._itemTree[self._itemId]]224 else:225 items = self._view._viewItems226 return [items[itemHash]227 for itemHash in items228 if items[itemHash]._parentId == self._itemId]229 def dump(self):230 """Dumps the most important attributes"""231 return "id=%s autid=%s cls=%s text=%r bbox=%s" % (232 self._itemId, self._properties.get('AutomationId', None),233 self._className, self._text, self._bbox)234 def parent(self):235 return self._parentId236 def parentItem(self):237 try:238 return self._view._viewItems[self._parentId]239 except KeyError:240 return None241 def id(self):242 return self._itemId243 def properties(self):244 return self._properties245 def text(self):246 return self._text247 def dumpProperties(self):248 """Dumps the properties"""249 return "\n".join("%s=%s" % (key, self._properties[key])250 for key in sorted(self._properties))251 def __str__(self):252 return "ViewItem(%s)" % self.dump()253 def cachedParentItem(self):254 """255 Returns the parent's viewitem which is cached by the server.256 """257 return self._view.cachedItem(self._parentId)258 def refresh(self):259 """Updates the properties taking their current values.260 It returns self, so other operations can chained together.261 For example, to wait until a widget is enabled:262 while not widget.refresh().IsEnabled:263 time.sleep(0.1)"""264 self._checkUIautomation()265 data = self._view._device._conn.recvViewItemProperties(self.id())266 if data:267 self._properties.update(data[0])268 return self269 def patterns(self):270 """271 Returns a frozenset of the supported patterns.272 """273 self._checkUIautomation()274 if not self._patterns:275 data = self._view._device._conn.recvViewItemPatterns(self.id())276 if data:277 self._patterns = frozenset(data[0])278 return self._patterns279 def setFocus(self):280 """281 Sets the focus to the widget.282 """283 self._checkUIautomation()284 self._view._device._conn.sendSetFocus(self.id())285 def items(self, propertyName, separator="\n", filterSubChildClassName="", maxSubChildren=0):286 """287 Returns a list of the given property from all widget's direct children.288 Only the rendered / shown / displayed widgets will be considered.289 If, for example, a ListView widget has thousands of ListViewItems, but only 50 are290 displayed, this methods retrieves only the properties values (of the sub-children which291 compose the ListViewItems) from such 50 widgets will be reported as a string list of292 exactly 50 elements.293 Parameters:294 propertyName (string):295 the property name to be retrieved.296 separator (string, optional):297 the separator to be used for all values, when a child is composed of298 other (sub-)children. All properties values will be collected from the299 sub-children, and joined using this separator.300 filterSubChildClassName (string, optional):301 Only the sub-children of this class will be dumped. All sub-children will302 be collected, if it's not defined.303 maxSubChildren (int, optional):304 How many sub-children values will be collected (and joined), at maximum.305 If a child has many sub-children, but only the first ones are wanted,306 using this parameter limits the properties collection.307 By default (0), all sub-children's properties values will be collected.308 """309 self._checkUIautomation()310 data = self._view._device._conn.recvViewItemItems(311 self.id(), propertyName, separator, filterSubChildClassName, maxSubChildren)312 return data[0]313 def collapse(self):314 """315 Collapses a widget which supports this kind of operation, like a TreeView.316 """317 self._checkUIautomation()318 self._view._device._conn.sendCollapse(self.id())319 def expand(self):320 """321 Expands a widget which supports this kind of operation, like a TreeView.322 """323 self._checkUIautomation()324 self._view._device._conn.sendExpand(self.id())325 def containerItems(self, propertyName, separator="\n", filterSubChildClassName="", maxSubChildren="0", scroll=False):326 """327 Returns a list of the given property from all widget's direct328 children.329 Like the items() method, but all children, even the currently330 not displayed ones, will be reported.331 If a child isn't displayed when it's evaluated, it will332 have no sub-children, so no information about them will be333 reported. To fully render/display a child, the new scroll334 parameter should be used, so the item display area will be335 scrolled until the child is finally rendered. After that, all336 information about its sub-children are available and will be337 retrieved.338 Parameters:339 propertyName, separator, filterSubChildClassName, maxSubChildren:340 refer to ViewItem.items() documentation.341 scroll (bool, optional):342 Allows children scrolling, to make them visible.343 By default (false), no children scrolling is made.344 Note: If a widget has many children, scrolling all of them will be slow.345 """346 self._checkUIautomation()347 data = self._view._device._conn.recvViewItemContainerItems(348 self.id(), propertyName, separator, filterSubChildClassName, maxSubChildren, scroll)349 return data[0]350 def selectedItems(self, propertyName, separator="\n", filterSubChildClassName="", maxSubChildren="0", scroll=False):351 """352 Returns a list of the given property from all widget's direct353 children which are selected.354 Like containerItems(), but only selected children will be355 reported.356 """357 self._checkUIautomation()358 data = self._view._device._conn.recvViewItemSelectedItems(359 self.id(), propertyName, separator, filterSubChildClassName, maxSubChildren, scroll)360 return data[0]361 def longText(self, maxLength=65536):362 """363 Returns the text from widgets like a RichTextEdit or a Document,364 that normally don't allow to report the text using the usual text() method.365 Parameters:366 maxLength (integer, optional):367 The maximum number of characters to be reported, to368 limit the transferred data. The default is 64K characters.369 """370 self._checkUIautomation()371 data = self._view._device._conn.recvViewItemText(self.id(), maxLength)372 return data[0].popitem()[1] if data else None373 def setValue(self, value):374 """375 Sets the value of a widget. For example the text for a TextBlock,376 or the text of a ComboBox.377 It doesn't work for more complex widgets like a RichTextEdit or a Document.378 Parameters:379 value (string):380 The value to be set.381 """382 self._checkUIautomation()383 self._view._device._conn.recvViewItemSetValue(self.id(), value)384 self._properties['Value'] = str(value)385class View(object):386 def __init__(self, dumpFilename, itemTree, itemOnScreen=None, device=None, freeDumps=False):387 self._dumpFilename = dumpFilename388 self._itemTree = itemTree389 self._rootItem = None390 self._rootItems = []391 self._viewItems = {}392 self._device = device393 self._freeDumps = freeDumps394 if itemOnScreen == None:395 self._itemOnScreen = lambda item: True396 else:397 self._itemOnScreen = itemOnScreen398 if isinstance(itemTree, dict):399 # data from enumchildwindows:400 self._viewSource = "enumchildwindows"401 for itemId, winfoList in itemTree.iteritems():402 for winfo in winfoList:403 itemId, parentId, className, text, bbox = winfo404 self._viewItems[itemId] = ViewItem(405 self, itemId, parentId, className, text, bbox, dumpFilename)406 self._rootItem = self._viewItems[self._itemTree["root"][0][0]]407 self._rootItems.append(self._rootItem)408 elif isinstance(itemTree, list):409 # data from uiautomation410 # list of dictionaries, each of which contains properties of an item411 self._viewSource = "uiautomation"412 for elt in itemTree:413 self._insertItem(elt)414 if not self._rootItem and not freeDumps:415 raise ValueError("no root item in view data")416 def _insertItem(self, elt):417 bboxString = elt.get("BoundingRectangle", "0;0;0;0")418 bboxSeparator = ";" if ";" in bboxString else ","419 try:420 bbox = [int(coord) for coord in bboxString.split(bboxSeparator)]421 bbox[2] = bbox[0] + bbox[2] # width to right422 bbox[3] = bbox[1] + bbox[3] # height to bottom423 bbox = tuple(bbox)424 except Exception, e:425 bbox = 0, 0, 0, 0426 text = elt.get("Value") or elt.get("Name", "")427 vi = ViewItem(428 self, int(elt["hash"]), int(elt["parent"]),429 elt.get("ClassName", ""),430 text,431 bbox,432 self._dumpFilename,433 elt)434 self._viewItems[int(elt["hash"])] = vi435 if not vi.parent():436 self._rootItem = vi437 self._rootItems.append(vi)438 return vi439 def _checkUIautomation(self):440 if not self._viewSource.startswith("uiautomation"):441 raise NotImplementedError(442 "This method works only for uiautomation at the moment")443 def cachedItem(self, id_):444 """445 Retrieves an automation element from the server cache, passing its id.446 If the item was already into the view, it's updated.447 """448 self._checkUIautomation()449 data = self._device._conn.recvViewCachedItem(id_)450 if data:451 return self._insertItem(data[0])452 def _intCoords(self, *args):453 # TODO: relative coordinates like (0.5, 0.9)454 return [int(c) for c in args[0]]455 def filename(self):456 return self._dumpFilename457 def rootItem(self):458 return self._rootItem459 def _dumpTree(self, rootItem, indentation=''):460 yield "%s|-- %s" % (indentation, rootItem.dump())461 indentation += '| '462 for child in rootItem.children():...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!