Best Python code snippet using fMBT_python
fmbtgti.py
Source:fmbtgti.py
...1844 Not all OCR engines provide this functionality.1845 """1846 self._notifyOcrEngine()1847 return self._ocrEngine.dumpOcr(self, **kwargs)1848 def dumpOcrWords(self, **kwargs):1849 """1850 Deprecated, use dumpOcr().1851 """1852 return self.dumpOcr(**kwargs)1853 def filename(self):1854 return self._filename1855 def findItemsByBitmap(self, bitmap, **oirFindArgs):1856 if self._oirEngine != None:1857 self._notifyOirEngine()1858 oirArgsList = self._paths.oirArgsList(bitmap)1859 results = []1860 if oirArgsList:1861 for oirArgs in oirArgsList:1862 oirArgs, _ = _takeOirArgs(self._oirEngine, oirArgs.copy())1863 oirArgs.update(oirFindArgs)1864 results.extend(self._oirEngine.findBitmap(1865 self, self._paths.abspath(bitmap), **oirArgs))1866 if results: break1867 else:1868 oirArgs = oirFindArgs1869 results.extend(self._oirEngine.findBitmap(1870 self, self._paths.abspath(bitmap), **oirArgs))1871 return results1872 else:1873 raise RuntimeError('Trying to use OIR on "%s" without OIR engine.' % (self.filename(),))1874 def findItemsByOcr(self, text, **ocrEngineArgs):1875 if self._ocrEngine != None:1876 self._notifyOcrEngine()1877 return self._ocrEngine.findText(self, text, **ocrEngineArgs)1878 else:1879 raise RuntimeError('Trying to use OCR on "%s" without OCR engine.' % (self.filename(),))1880 def save(self, fileOrDirName):1881 shutil.copy(self._filename, fileOrDirName)1882 def ocrEngine(self):1883 return self._ocrEngine1884 def oirEngine(self):1885 return self._oirEngine1886 def __str__(self):1887 return 'Screenshot(filename="%s")' % (self._filename,)1888class GUIItem(object):1889 """1890 GUIItem holds the information of a single GUI item.1891 """1892 def __init__(self, name, bbox, screenshot, bitmap=None, ocrFind=None, ocrFound=None):1893 self._name = name1894 self._bbox = bbox1895 self._bitmap = bitmap1896 self._screenshot = screenshot1897 self._ocrFind = ocrFind1898 self._ocrFound = ocrFound1899 def bbox(self): return self._bbox1900 def name(self): return self._name1901 def coords(self):1902 left, top, right, bottom = self.bbox()1903 return (left + (right-left)/2, top + (bottom-top)/2)1904 def dump(self): return str(self)1905 def __str__(self):1906 extras = ""1907 if self._bitmap:1908 extras += ', bitmap="%s"' % (self._bitmap,)1909 if self._ocrFind:1910 extras += ', find="%s"' % (self._ocrFind,)1911 if self._ocrFound:1912 extras += ', found="%s"' % (self._ocrFound,)1913 if self._screenshot:1914 extras += ', screenshot="%s"' % (self._screenshot,)1915 return ('GUIItem("%s", bbox=%s%s)' % (1916 self.name(), self.bbox(), extras))1917class _VisualLog:1918 def __init__(self, device, outFileObj,1919 screenshotWidth, thumbnailWidth,1920 timeFormat, delayedDrawing,1921 copyBitmapsToScreenshotDir):1922 self._device = device1923 self._outFileObj = outFileObj1924 self._testStep = -11925 self._actionName = None1926 self._callStack = []1927 self._highlightCounter = 01928 self._screenshotWidth = screenshotWidth1929 self._thumbnailWidth = thumbnailWidth1930 self._timeFormat = timeFormat1931 self._copyBitmapsToScreenshotDir = copyBitmapsToScreenshotDir1932 self._userFrameId = 01933 self._userFunction = ""1934 self._userCallCount = 01935 eyenfinger.iSetDefaultDelayedDrawing(delayedDrawing)1936 device.refreshScreenshot = self.refreshScreenshotLogger(device.refreshScreenshot)1937 device.tap = self.tapLogger(device.tap)1938 device.drag = self.dragLogger(device.drag)1939 device.visualLog = self.messageLogger(device.visualLog)1940 attrs = ['callContact', 'callNumber', 'close',1941 'loadConfig', 'platformVersion',1942 'pressAppSwitch', 'pressBack', 'pressHome',1943 'pressKey', 'pressMenu', 'pressPower',1944 'pressVolumeUp', 'pressVolumeDown',1945 'reboot', 'reconnect', 'refreshView',1946 'shell', 'shellSOE', 'smsNumber', 'supportsView',1947 'swipe', 'swipeBitmap', 'swipeItem', 'swipeOcrText',1948 'systemProperty',1949 'tapBitmap', 'tapId', 'tapItem', 'tapOcrText',1950 'tapText', 'topApp', 'topWindow', 'type',1951 'verifyOcrText', 'verifyText', 'verifyBitmap',1952 'waitAnyBitmap', 'waitBitmap', 'waitOcrText', 'waitText']1953 for a in attrs:1954 if hasattr(device, a):1955 m = getattr(device, a)1956 setattr(device, m.func_name, self.genericLogger(m))1957 self.logHeader()1958 self._blockId = 01959 def close(self):1960 if self._outFileObj != None:1961 html = []1962 for c in xrange(len(self._callStack)):1963 html.append('</table></tr>') # end call1964 html.append('</table></div></td></tr></table></ul>') # end step1965 html.append('</body></html>') # end html1966 self.write('\n'.join(html))1967 # File instance should be closed by the opener1968 self._outFileObj = None1969 def write(self, s):1970 if self._outFileObj != None:1971 self._outFileObj.write(s)1972 self._outFileObj.flush()1973 def timestamp(self, t=None):1974 if t == None: t = datetime.datetime.now()1975 return t.strftime(self._timeFormat)1976 def epochTimestamp(self, t=None):1977 if t == None: t = datetime.datetime.now()1978 return t.strftime("%s.%f")1979 def htmlTimestamp(self, t=None):1980 if t == None: t = datetime.datetime.now()1981 retval = '<div class="time" id="%s"><a id="time%s">%s</a></div>' % (1982 self.epochTimestamp(t), self.epochTimestamp(t), self.timestamp(t))1983 return retval1984 def logBlock(self):1985 ts = fmbt.getTestStep()1986 an = fmbt.getActionName()1987 if ts == -1 or an == "undefined":1988 an = self._userFunction1989 ts = self._userCallCount1990 if self._testStep != ts or self._actionName != an:1991 if self._blockId != 0: self.write('</table></div></td></tr></table></ul>')1992 actionHtml = '''\n\n<ul><li><table><tr><td>%s</td><td><div class="step"><a id="blockId%s" href="javascript:showHide('S%s')">%s. %s</a></div><div class="funccalls" id="S%s"><table>\n''' % (1993 self.htmlTimestamp(), self._blockId, self._blockId, ts, cgi.escape(an), self._blockId)1994 self.write(actionHtml)1995 self._testStep = ts1996 self._actionName = an1997 self._blockId += 11998 def logCall(self, img=None, width="", imgTip=""):1999 callee = inspect.currentframe().f_back.f_code.co_name[:-4] # cut "WRAP"2000 argv = inspect.getargvalues(inspect.currentframe().f_back)2001 # calleeArgs = str(argv.locals['args']) + " " + str(argv.locals['kwargs'])2002 args = [repr(a) for a in argv.locals['args']]2003 for key, value in argv.locals['kwargs'].iteritems():2004 args.append("%s=%s" % (key, repr(value)))2005 calleeArgs = "(%s)" % (", ".join(args),)2006 callerFrame = inspect.currentframe().f_back.f_back2007 callerFilename = callerFrame.f_code.co_filename2008 callerLineno = callerFrame.f_lineno2009 if len(self._callStack) == 0 and (self._userFunction == '<module>' or not self._userFrameId in [(id(se[0]), getattr(se[0].f_back, "f_lasti", None)) for se in inspect.stack()]):2010 self._userFunction = callerFrame.f_code.co_name2011 self._userCallCount += 12012 self._userFrameId = (id(callerFrame), getattr(callerFrame.f_back, "f_lasti", None))2013 self.logBlock()2014 imgHtml = self.imgToHtml(img, width, imgTip, "call:%s" % (callee,))2015 t = datetime.datetime.now()2016 callHtml = '''2017 <tr><td></td><td><table><tr>2018 <td>%s</td><td><a title="%s:%s"><div class="call">%s%s</div></a></td>2019 </tr>2020 %s''' % (self.htmlTimestamp(t), cgi.escape(callerFilename), callerLineno, cgi.escape(callee), cgi.escape(str(calleeArgs)), imgHtml)2021 self.write(callHtml)2022 self._callStack.append(callee)2023 return (self.timestamp(t), callerFilename, callerLineno)2024 def logReturn(self, retval, img=None, width="", imgTip="", tip=""):2025 imgHtml = self.imgToHtml(img, width, imgTip, "return:%s" % (self._callStack[-1],))2026 self._callStack.pop()2027 returnHtml = '''2028 <tr>2029 <td>%s</td><td><div class="returnvalue"><a title="%s">== %s</a></div></td>2030 </tr>%s2031 </table></tr>\n''' % (self.htmlTimestamp(), tip, cgi.escape(str(retval)), imgHtml)2032 self.write(returnHtml)2033 def logException(self):2034 einfo = sys.exc_info()2035 self._callStack.pop()2036 excHtml = '''2037 <tr>2038 <td>%s</td><td><div class="exception"><a title="%s">!! %s</a></div></td>2039 </tr>2040 </table></tr>\n''' % (self.htmlTimestamp(), cgi.escape(traceback.format_exception(*einfo)[-2].replace('"','').strip()), cgi.escape(str(traceback.format_exception_only(einfo[0], einfo[1])[0])))2041 self.write(excHtml)2042 def logMessage(self, msg):2043 callerFrame = inspect.currentframe().f_back.f_back2044 callerFilename = callerFrame.f_code.co_filename2045 callerLineno = callerFrame.f_lineno2046 self.logBlock()2047 t = datetime.datetime.now()2048 msgHtml = '''2049 <tr><td></td><td><table>2050 <tr><td>%s</td><td><a title="%s:%s"><div class="message">%s</div></a></td></tr>2051 </table></td></tr>\n''' % (self.htmlTimestamp(t), cgi.escape(callerFilename), callerLineno, cgi.escape(msg))2052 self.write(msgHtml)2053 def logHeader(self):2054 self.write('''2055 <!DOCTYPE html><html>2056 <head><meta charset="utf-8"><title>fmbtandroid visual log</title>2057 <SCRIPT><!--2058 function showHide(eid){2059 if (document.getElementById(eid).style.display != 'inline'){2060 document.getElementById(eid).style.display = 'inline';2061 } else {2062 document.getElementById(eid).style.display = 'none';2063 }2064 }2065 // --></SCRIPT>2066 <style>2067 td { vertical-align: top }2068 ul { list-style-type: none }2069 .funccalls { display: none }2070 </style>2071 </head><body>2072 ''')2073 def doCallLogException(self, origMethod, args, kwargs):2074 try: return origMethod(*args, **kwargs)2075 except:2076 self.logException()2077 raise2078 def genericLogger(loggerSelf, origMethod):2079 def origMethodWRAP(*args, **kwargs):2080 loggerSelf.logCall()2081 retval = loggerSelf.doCallLogException(origMethod, args, kwargs)2082 loggerSelf.logReturn(retval, tip=origMethod.func_name)2083 return retval2084 loggerSelf.changeCodeName(origMethodWRAP, origMethod.func_code.co_name + "WRAP")2085 return origMethodWRAP2086 def messageLogger(loggerSelf, origMethod):2087 def origMethodWRAP(*args, **kwargs):2088 loggerSelf.logMessage(" ".join([str(a) for a in args]))2089 return True2090 loggerSelf.changeCodeName(origMethodWRAP, origMethod.func_code.co_name + "WRAP")2091 return origMethodWRAP2092 def dragLogger(loggerSelf, origMethod):2093 def dragWRAP(*args, **kwargs):2094 loggerSelf.logCall()2095 x1, y1 = args[0]2096 x2, y2 = args[1]2097 retval = loggerSelf.doCallLogException(origMethod, args, kwargs)2098 try:2099 screenshotFilename = loggerSelf._device.screenshot().filename()2100 highlightFilename = loggerSelf.highlightFilename(screenshotFilename)2101 iC = loggerSelf._device.intCoords2102 eyenfinger.drawLines(screenshotFilename, highlightFilename, [], [iC((x1, y1)), iC((x2, y2))])2103 loggerSelf.logReturn(retval, img=highlightFilename, width=loggerSelf._screenshotWidth, tip=origMethod.func_name)2104 except:2105 loggerSelf.logReturn(str(retval) + " (no screenshot available)", tip=origMethod.func_name)2106 return retval2107 return dragWRAP2108 def refreshScreenshotLogger(loggerSelf, origMethod):2109 def refreshScreenshotWRAP(*args, **kwargs):2110 loggerSelf._highlightCounter = 02111 logCallReturnValue = loggerSelf.logCall()2112 retval = loggerSelf.doCallLogException(origMethod, args, kwargs)2113 retval._logCallReturnValue = logCallReturnValue2114 loggerSelf.logReturn(retval, img=retval, tip=origMethod.func_name)2115 retval.findItemsByBitmap = loggerSelf.findItemsByBitmapLogger(retval.findItemsByBitmap, retval)2116 retval.findItemsByOcr = loggerSelf.findItemsByOcrLogger(retval.findItemsByOcr, retval)2117 return retval2118 return refreshScreenshotWRAP2119 def tapLogger(loggerSelf, origMethod):2120 def tapWRAP(*args, **kwargs):2121 loggerSelf.logCall()2122 retval = loggerSelf.doCallLogException(origMethod, args, kwargs)2123 try:2124 screenshotFilename = loggerSelf._device.screenshot().filename()2125 highlightFilename = loggerSelf.highlightFilename(screenshotFilename)2126 eyenfinger.drawClickedPoint(screenshotFilename, highlightFilename, loggerSelf._device.intCoords(args[0]))2127 loggerSelf.logReturn(retval, img=highlightFilename, width=loggerSelf._screenshotWidth, tip=origMethod.func_name, imgTip=loggerSelf._device.screenshot()._logCallReturnValue)2128 except:2129 loggerSelf.logReturn(str(retval) + " (no screenshot available)", tip=origMethod.func_name)2130 return retval2131 return tapWRAP2132 def findItemsByBitmapLogger(loggerSelf, origMethod, screenshotObj):2133 def findItemsByBitmapWRAP(*args, **kwargs):2134 bitmap = args[0]2135 absPathBitmap = screenshotObj._paths.abspath(bitmap)2136 if loggerSelf._copyBitmapsToScreenshotDir:2137 screenshotDirBitmap = os.path.join(2138 os.path.dirname(screenshotObj.filename()),2139 "bitmaps",2140 bitmap.lstrip(os.sep))2141 if not os.access(screenshotDirBitmap, os.R_OK):2142 # bitmap is not yet copied under screenshotDir2143 destDir = os.path.dirname(screenshotDirBitmap)2144 if not os.access(destDir, os.W_OK):2145 try:2146 os.makedirs(destDir)2147 except IOError:2148 pass # cannot make dir / dir not writable2149 try:2150 shutil.copy(absPathBitmap, destDir)2151 absPathBitmap = screenshotDirBitmap2152 except IOError:2153 pass # cannot copy bitmap2154 else:2155 absPathBitmap = screenshotDirBitmap2156 loggerSelf.logCall(img=absPathBitmap)2157 retval = loggerSelf.doCallLogException(origMethod, args, kwargs)2158 if len(retval) == 0:2159 loggerSelf.logReturn("not found in", img=screenshotObj, tip=origMethod.func_name)2160 else:2161 foundItems = retval2162 screenshotFilename = screenshotObj.filename()2163 highlightFilename = loggerSelf.highlightFilename(screenshotFilename)2164 eyenfinger.drawIcon(screenshotFilename, highlightFilename, bitmap, [i.bbox() for i in foundItems])2165 loggerSelf.logReturn([str(quiItem) for quiItem in retval], img=highlightFilename, width=loggerSelf._screenshotWidth, tip=origMethod.func_name, imgTip=screenshotObj._logCallReturnValue)2166 return retval2167 return findItemsByBitmapWRAP2168 def findItemsByOcrLogger(loggerSelf, origMethod, screenshotObj):2169 def findItemsByOcrWRAP(*args, **kwargs):2170 loggerSelf.logCall()2171 retval = loggerSelf.doCallLogException(origMethod, args, kwargs)2172 if len(retval) == 0:2173 loggerSelf.logReturn("not found in words " + str(screenshotObj.dumpOcrWords()),2174 img=screenshotObj, tip=origMethod.func_name)2175 else:2176 foundItem = retval[0]2177 screenshotFilename = screenshotObj.filename()2178 highlightFilename = loggerSelf.highlightFilename(screenshotFilename)2179 eyenfinger.drawIcon(screenshotFilename, highlightFilename, args[0], foundItem.bbox())2180 for appearance, foundItem in enumerate(retval[1:42]):2181 eyenfinger.drawIcon(highlightFilename, highlightFilename, str(appearance+1) + ": " + args[0], foundItem.bbox())2182 loggerSelf.logReturn([str(retval[0])], img=highlightFilename, width=loggerSelf._screenshotWidth, tip=origMethod.func_name, imgTip=screenshotObj._logCallReturnValue)2183 return retval2184 return findItemsByOcrWRAP2185 def relFilePath(self, fileOrDirName, fileLikeObj):2186 if hasattr(fileLikeObj, "name"):2187 referenceDir = os.path.dirname(fileLikeObj.name)...
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!!