How to use findItemsByText method in fMBT

Best Python code snippet using fMBT_python

fmbtandroid.py

Source:fmbtandroid.py Github

copy

Full Screen

...610 refer to tap documentation.611 Returns True if successful, otherwise False.612 """613 assert self._lastView != None, "View required."614 items = self._lastView.findItemsByText(text, partial=partial, count=1)615 if len(items) == 0: return False616 return self.tapItem(items[0], **tapKwArgs)617 def topApp(self):618 """619 Returns the name of the top application.620 """621 return self._conn.recvTopAppWindow()[0]622 def topWindow(self):623 """624 Returns the name of the top window.625 """626 # the top window may be None during transitions, therefore627 # retry a couple of times if necessary.628 timeout = 0.5629 pollDelay = 0.2630 start = time.time()631 tw = self._conn.recvTopAppWindow()[1]632 while tw == None and (time.time() - start < timeout):633 time.sleep(pollDelay)634 tw = self._conn.recvTopAppWindow()[1]635 return tw636 def verifyText(self, text, partial=False):637 """638 Verify that the last view has at least one item with given639 text.640 Parameters:641 text (string):642 text to be searched for in items.643 partial (boolean, optional):644 if True, match items if item text contains given645 text, otherwise match only if item text is equal to646 the given text. The default is False (exact match).647 """648 assert self._lastView != None, "View required."649 return self._lastView.findItemsByText(text, partial=partial, count=1) != []650 def view(self):651 """652 Returns the last view (the most recently refreshed view).653 """654 return self._lastView655 def waitText(self, text, partial=False, **waitKwArgs):656 """657 Wait until text appears in any view item.658 Parameters:659 text (string):660 text to be waited for.661 partial (boolean, optional):662 refer to verifyText. The default is False.663 waitTime, pollDelay (float, optional):664 refer to wait.665 Returns True if text appeared within given time limit,666 otherwise False.667 Updates the last view.668 """669 return self.wait(self.refreshView,670 self.verifyText, (text,), {'partial': partial},671 **waitKwArgs)672 def wake(self):673 """674 Force the device to wake up.675 """676 return self._conn.sendWake()677 def _loadDeviceAndTestINIs(self, homeDir, deviceName, iniFile):678 if deviceName != None:679 _deviceIniFilename = homeDir + os.sep + "etc" + os.sep + deviceName + ".ini"680 self.loadConfig(_deviceIniFilename, override=True, level="device")681 if iniFile:682 self.loadConfig(iniFile, override=True, level="test")683class Ini:684 """685 Container for device configuration loaded from INI files.686 INI file syntax:687 [section1]688 key1 = value1689 ; commented = out690 # commented = out691 """692 def __init__(self, iniFile=None):693 """694 Initialise the container, optionally with an initial configuration.695 Parameters:696 iniFile (file object, optional):697 load the initial configuration from iniFile.698 The default is None: start with empty configuration.699 """700 # _conf is a dictionary:701 # (section, key) -> value702 self._conf = {}703 if iniFile:704 self.addFile(iniFile)705 def addFile(self, iniFile, override=True):706 """707 Add values from a file to the current configuration.708 Parameters:709 iniFile (file object):710 load values from this file object.711 override (boolean, optional):712 If True, loaded values override existing values.713 Otherwise, only currently undefined values are714 loaded. The default is True.715 """716 for line in iniFile:717 line = line.strip()718 if line.startswith('[') and line.endswith(']'):719 section = line[1:-1].strip()720 elif line.startswith(";") or line.startswith("#"):721 continue722 elif '=' in line:723 key, value = line.split('=', 1)724 if override or (section, key.strip()) not in self._conf:725 self._conf[(section, key.strip())] = value.strip()726 def sections(self):727 """728 Returns list of sections in the current configuration.729 """730 return list(set([k[0] for k in self._conf.keys()]))731 def keys(self, section):732 """733 Returns list of keys in a section in the current configuration.734 Parameters:735 section (string):736 the name of the section.737 """738 return [k[1] for k in self._conf.keys() if k[0] == section]739 def dump(self):740 """741 Returns the current configuration as a single string in the742 INI format.743 """744 lines = []745 for section in sorted(self.sections()):746 lines.append("[%s]" % (section,))747 for key in sorted(self.keys(section)):748 lines.append("%-16s = %s" % (key, self._conf[(section, key)]))749 lines.append("")750 return "\n".join(lines)751 def set(self, section, key, value):752 """753 Set new value for a key in a section.754 Parameters:755 section, key (strings):756 the section, the key.757 value (string):758 the new value. If not string already, it will be759 converted to string, and it will be loaded as a760 string when loaded from file object.761 """762 self._conf[(section, key)] = str(value)763 def value(self, section, key, default=""):764 """765 Returns the value (string) associated with a key in a section.766 Parameters:767 section, key (strings):768 the section and the key.769 default (string, optional):770 the default value to be used and stored if there is771 no value associated to the key in the section. The772 default is the empty string.773 Reading a value of an undefined key in an undefined section774 adds the key and the section to the configuration with the775 returned (the default) value. This makes all returned values776 visible in dump().777 """778 if not (section, key) in self._conf:779 self._conf[(section, key)] = default780 return self._conf[(section, key)]781# For backward compatibility, someone might be using old _DeviceConf782_DeviceConf = Ini783class ViewItem(fmbtgti.GUIItem):784 """785 ViewItem holds the information of a single GUI element.786 """787 def __init__(self, className, code, indent, properties, parent, rawProps, dumpFilename, displayToScreen):788 self._p = properties789 self._parent = parent790 self._className = className791 self._code = code792 self._indent = indent793 self._children = []794 self._rawProps = ""795 if not "scrolling:mScrollX" in self._p:796 self._p["scrolling:mScrollX"] = 0797 self._p["scrolling:mScrollY"] = 0798 fmbtgti.GUIItem.__init__(self, className, self._calculateBbox(displayToScreen), dumpFilename)799 def addChild(self, child): self._children.append(child)800 def _calculateBbox(self, displayToScreen):801 left = int(self._p["layout:mLeft"])802 top = int(self._p["layout:mTop"])803 parent = self._parent804 while parent:805 pp = parent._p806 left += int(pp["layout:mLeft"]) - int(pp["scrolling:mScrollX"])807 top += int(pp["layout:mTop"]) - int(pp["scrolling:mScrollY"])808 parent = parent._parent809 height = int(self._p["layout:getHeight()"])810 width = int(self._p["layout:getWidth()"])811 screenLeft, screenTop = displayToScreen(left, top)812 screenRight, screenBottom = displayToScreen(left + width, top + height)813 return (screenLeft, screenTop, screenRight, screenBottom)814 def children(self): return self._children815 def className(self): return self._className816 def code(self): return self._code817 def indent(self): return self._indent818 def id(self): return self.property("mID")819 def parent(self): return self._parent820 def properties(self): return self._p821 def property(self, propertyName):822 return self._p.get(propertyName, None)823 def text(self): return self.property("text:mText")824 def visible(self):825 return self._p.get("getVisibility()", "") == "VISIBLE"826 def dump(self):827 p = self._p828 return ("ViewItem(\n\tchildren = %d\n\tclassName = '%s'\n\tcode = '%s'\n\t" +829 "indent = %d\n\tproperties = {\n\t\t%s\n\t})") % (830 len(self._children), self._className, self._code, self._indent,831 '\n\t\t'.join(['"%s": %s' % (key, p[key]) for key in sorted(p.keys())]))832 def __str__(self):833 return ("ViewItem(className='%s', id=%s, bbox=%s)" % (834 self._className, self.id(), self.bbox()))835class View(object):836 """837 View provides interface to screen dumps from Android. It parses838 the dump to a hierarchy of ViewItems. find* methods enable searching839 for ViewItems based on their properties.840 """841 def __init__(self, screenshotDir, serialNumber, dump, displayToScreen=None):842 self.screenshotDir = screenshotDir843 self.serialNumber = serialNumber844 self._viewItems = []845 self._errors = []846 self._lineRegEx = re.compile("(?P<indent>\s*)(?P<class>[\w.$]+)@(?P<id>[0-9A-Fa-f]{8} )(?P<properties>.*)")847 self._olderAndroidLineRegEx = re.compile("(?P<indent>\s*)(?P<class>[\w.$]+)@(?P<id>\w)(?P<properties>.*)")848 self._propRegEx = re.compile("(?P<prop>(?P<name>[^=]+)=(?P<len>\d+),)(?P<data>[^\s]* ?)")849 self._dump = dump850 self._rawDumpFilename = self.screenshotDir + os.sep + fmbtgti._filenameTimestamp() + "-" + self.serialNumber + ".view"851 file(self._rawDumpFilename, "w").write(self._dump)852 if displayToScreen == None:853 displayToScreen = lambda x, y: (x, y)854 try: self._parseDump(dump, self._rawDumpFilename, displayToScreen)855 except Exception, e:856 self._errors.append((-1, "", "Parser error"))857 def viewItems(self): return self._viewItems858 def errors(self): return self._errors859 def dumpRaw(self): return self._dump860 def dumpItems(self, itemList = None):861 if itemList == None: itemList = self._viewItems862 l = []863 for i in itemList:864 l.append(self._dumpItem(i))865 return '\n'.join(l)866 def dumpTree(self, rootItem = None):867 l = []868 if rootItem != None:869 l.extend(self._dumpSubTree(rootItem, 0))870 else:871 for i in self._viewItems:872 if i._indent == 0:873 l.extend(self._dumpSubTree(i, 0))874 return '\n'.join(l)875 def _dumpSubTree(self, viewItem, indent):876 l = []877 i = viewItem878 l.append(" "*indent + self._dumpItem(viewItem))879 for i in viewItem.children():880 l.extend(self._dumpSubTree(i, indent + 4))881 return l882 def _dumpItem(self, viewItem):883 i = viewItem884 if i.text() != None: t = '"%s"' % (i.text(),)885 else: t = None886 return "id=%s cls=%s text=%s bbox=%s" % (887 i.id(), i.className(), t, i.bbox())888 def findItems(self, comparator, count=-1, searchRootItem=None, searchItems=None):889 foundItems = []890 if count == 0: return foundItems891 if searchRootItem != None:892 # find from searchRootItem and its children893 if comparator(searchRootItem):894 foundItems.append(searchRootItem)895 for c in searchRootItem.children():896 foundItems.extend(self.findItems(comparator, count=count-len(foundItems), searchRootItem=c))897 else:898 if searchItems != None:899 # find from listed items only900 searchDomain = searchItems901 else:902 # find from all items903 searchDomain = self._viewItems904 for i in searchDomain:905 if comparator(i):906 foundItems.append(i)907 if count > 0 and len(foundItems) >= count:908 break909 return foundItems910 def findItemsByText(self, text, partial=False, count=-1, searchRootItem=None, searchItems=None):911 """912 Searches the GUI hiearhy for a object with a given text913 """914 if partial:915 c = lambda item: (916 item.properties().get("text:mText", "").find(text) != -1 )917 else:918 c = lambda item: (919 item.properties().get("text:mText", None) == text )920 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems)921 def findItemsById(self, id, count=-1, searchRootItem=None, searchItems=None):922 c = lambda item: item.properties().get("mID", "") == id923 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems)924 def findItemsByClass(self, className, partial=True, count=-1, searchRootItem=None, searchItems=None):...

Full Screen

Full Screen

fmbtx11.py

Source:fmbtx11.py Github

copy

Full Screen

...164 foundItems.append(i)165 if count > 0 and len(foundItems) >= count:166 break167 return foundItems168 def findItemsByText(self, text, partial=False, count=-1, searchRootItem=None, searchItems=None, onScreen=False):169 if partial:170 c = lambda item: (text in item._text or text in item.properties()["name"])171 else:172 c = lambda item: (text == item._text)173 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)174 def findItemsByClass(self, className, partial=False, count=-1, searchRootItem=None, searchItems=None, onScreen=False):175 if partial:176 c = lambda item: (className in item._className)177 else:178 c = lambda item: (className == item._className)179 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)180 def findItemsById(self, itemId, count=-1, searchRootItem=None, searchItems=None, onScreen=False):181 c = lambda item: (itemId == item._itemId or itemId == item.properties().get("AutomationId", None))182 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)183 def findItemsByProperties(self, properties, count=-1, searchRootItem=None, searchItems=None, onScreen=False):184 """185 Returns ViewItems where every property matches given properties186 Parameters:187 properties (dictionary):188 names and required values of properties189 Example:190 view.findItemsByProperties({"Value": "HELLO", "Name": "File name:"})191 See also:192 viewitem.dumpProperties()193 """194 c = lambda item: 0 == len([key for key in properties195 if properties[key] != item.properties().get(key, None)])196 return self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)197 def findItemsByPos(self, pos, count=-1, searchRootItem=None, searchItems=None, onScreen=False):198 """199 Returns list of ViewItems whose bounding box contains the position.200 Parameters:201 pos (pair of floats (0.0..0.1) or integers (x, y)):202 coordinates that fall in the bounding box of found items.203 other parameters: refer to findItems documentation.204 Items are listed in ascending order based on area. They may205 or may not be from the same branch in the widget hierarchy.206 """207 x, y = self._intCoords(pos)208 c = lambda item: (item.bbox()[0] <= x <= item.bbox()[2] and item.bbox()[1] <= y <= item.bbox()[3])209 items = self.findItems(c, count=count, searchRootItem=searchRootItem, searchItems=searchItems, onScreen=onScreen)210 # sort from smallest to greatest area211 area_items = [((i.bbox()[2] - i.bbox()[0]) * (i.bbox()[3] - i.bbox()[1]), i) for i in items]212 return [i for _, i in sorted(area_items)]213 def items(self):214 """215 Returns list of all items in the view216 """217 return fmbtgti.sortItems(self._viewItems.values(), "topleft")218 def save(self, fileOrDirName):219 """220 Save view dump to a file.221 """222 shutil.copy(self._dumpFilename, fileOrDirName)223class Screen(fmbtgti.GUITestInterface):224 def __init__(self, display="", **kwargs):225 """Parameters:226 display (string, optional)227 X display to connect to.228 Example: display=":0". The default is "", that is,229 the default X display in the DISPLAY environment230 variable will be used.231 rotateScreenshot (integer, optional)232 rotate new screenshots by rotateScreenshot degrees.233 Example: rotateScreenshot=-90. The default is 0 (no234 rotation).235 """236 fmbtgti.GUITestInterface.__init__(self, **kwargs)237 self._lastView = None238 self._refreshViewDefaults = {}239 self.setConnection(X11Connection(display))240 def atspiApplicationList(self):241 """Returns list of running ATSPI applications.242 refreshView with view source "atspi" works for these243 applications.244 """245 return fmbtx11_conn.atspiApplicationList()246 def existingView(self):247 if self._lastView:248 return self._lastView249 else:250 raise FMBTWindowsError("view is not available. Missing refreshView()?")251 def itemOnScreen(self, guiItem):252 maxX, maxY = self.screenSize()253 return fmbtgti._boxOnRegion(guiItem.bbox(), (0, 0, maxX, maxY))254 def keyNames(self):255 """Returns list of key names understood by pressKey"""256 return _keyNames[:]257 def refreshView(self, window=None, forcedView=None, viewSource=None):258 """Update toolkit data"""259 self._lastView = None260 if window == None:261 window = self._refreshViewDefaults.get("window", None)262 if viewSource == None:263 viewSource = self._refreshViewDefaults.get("viewSource", "atspi")264 if viewSource == "atspi":265 foundItems = self.existingConnection().recvAtspiViewData(window)266 if self.screenshotDir() == None:267 self.setScreenshotDir(self._screenshotDirDefault)268 if self.screenshotSubdir() == None:269 self.setScreenshotSubdir(self._screenshotSubdirDefault)270 viewFilename = self._newScreenshotFilepath()[:-3] + "view"271 file(viewFilename, "w").write(repr(foundItems))272 self._lastView = View(273 viewFilename, foundItems,274 itemOnScreen=lambda i: self.itemOnScreen(i))275 else:276 raise ValueError('viewSource "%s" not supported' % (viewSource,))277 return self._lastView278 def refreshViewDefaults(self):279 return self._refreshViewDefaults280 def setRefreshViewDefaults(self, **kwargs):281 """Set default arguments for refreshView() calls282 Parameters:283 **kwargs (keyword arguments)284 new default values for optional refreshView() parameters.285 """286 self._refreshViewDefaults = kwargs287 def tapText(self, text, partial=False, **tapKwArgs):288 """289 Find an item with given text from the latest view, and tap it.290 Parameters:291 partial (boolean, optional):292 refer to verifyText documentation. The default is293 False.294 tapPos (pair of floats (x, y)):295 refer to tapItem documentation.296 button, long, hold, count, delayBetweenTaps (optional):297 refer to tap documentation.298 Returns True if successful, otherwise False.299 """300 items = self.existingView().findItemsByText(text, partial=partial, count=1, onScreen=True)301 if len(items) == 0: return False302 return self.tapItem(items[0], **tapKwArgs)303 def verifyText(self, text, partial=False):304 """305 Verify that the last view has at least one item with given306 text.307 Parameters:308 text (string):309 text to be searched for in items.310 partial (boolean, optional):311 if True, match items if item text contains given312 text, otherwise match only if item text is equal to313 the given text. The default is False (exact match).314 """315 assert self._lastView != None, "View required."316 return self._lastView.findItemsByText(text, partial=partial, count=1, onScreen=True) != []317 def view(self):318 return self._lastView319 def windowList(self):320 """321 Return list of properties of windows (dictionaries)322 Example: list window id's and names:323 for props in screen.windowList():324 print props["window"], props["name"]325 """326 return self.existingConnection().recvChildWindows(recursive=True)327class X11Connection(fmbtx11_conn.Display):328 def __init__(self, display):329 fmbtx11_conn.Display.__init__(self, display)330 def target(self):...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful