Best Python code snippet using fMBT_python
fmbtgti.py
Source:fmbtgti.py  
...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 retval...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!!
