Best Python code snippet using fMBT_python
fmbtgti.py
Source:fmbtgti.py  
...957                self.setOcrEngine(_g_ocrEngines[ocrEngine])958            else:959                self.setOcrEngine(ocrEngine)960        if oirEngine == None:961            self.setOirEngine(_defaultOirEngine())962        else:963            if type(oirEngine) == int:964                self.setOirEngine(_g_oirEngines[oirEngine])965            else:966                self.setOirEngine(oirEngine)967        self._screenshotDir = None968        self._screenshotDirDefault = "screenshots"969        self._screenshotSubdir = None970        self._screenshotSubdirDefault = ""971        self._screenSize = None972        self._visualLog = None973        self._visualLogFileObj = None974        self._visualLogFilenames = set()975    def bitmapPath(self):976        """977        Returns bitmapPath from which bitmaps are searched for.978        """979        return self._paths.bitmapPath980    def bitmapPathRoot(self):981        """982        Returns the path that prefixes all relative directories in983        bitmapPath.984        """985        return self._paths.relativeRoot986    def close(self):987        self._lastScreenshot = None988        if self._visualLog:989            if hasattr(self._visualLog._outFileObj, "name"):990                self._visualLogFilenames.remove(self._visualLog._outFileObj.name)991            self._visualLog.close()992            if self._visualLogFileObj:993                self._visualLogFileObj.close()994            self._visualLog = None995    def connection(self):996        """997        Returns GUITestConnection instance.998        """999        return self._conn1000    def drag(self, (x1, y1), (x2, y2), delayBetweenMoves=0.01, delayBeforeMoves=0, delayAfterMoves=0, movePoints=20):1001        """1002        Touch the screen on coordinates (x1, y1), drag along straight1003        line to coordinates (x2, y2), and raise fingertip.1004        coordinates (floats in range [0.0, 1.0] or integers):1005                floating point coordinates in range [0.0, 1.0] are1006                scaled to full screen width and height, others are1007                handled as absolute coordinate values.1008        delayBeforeMoves (float, optional):1009                seconds to wait after touching and before dragging.1010                If negative, starting touch event is not sent.1011        delayBetweenMoves (float, optional):1012                seconds to wait when moving between points when1013                dragging.1014        delayAfterMoves (float, optional):1015                seconds to wait after dragging, before raising1016                fingertip.1017                If negative, fingertip is not raised.1018        movePoints (integer, optional):1019                the number of intermediate move points between end1020                points of the line.1021        Returns True on success, False if sending input failed.1022        """1023        x1, y1 = self.intCoords((x1, y1))1024        x2, y2 = self.intCoords((x2, y2))1025        if delayBeforeMoves >= 0:1026            if not self._conn.sendTouchDown(x1, y1):1027                return False1028        if delayBeforeMoves > 0:1029            time.sleep(delayBeforeMoves)1030        else:1031            time.sleep(delayBetweenMoves)1032        for i in xrange(0, movePoints):1033            nx = x1 + int(round(((x2 - x1) / float(movePoints+1)) * (i+1)))1034            ny = y1 + int(round(((y2 - y1) / float(movePoints+1)) * (i+1)))1035            if not self._conn.sendTouchMove(nx, ny): return False1036            time.sleep(delayBetweenMoves)1037        if delayAfterMoves > 0:1038            self._conn.sendTouchMove(x2, y2)1039            time.sleep(delayAfterMoves)1040        if delayAfterMoves >= 0:1041            if self._conn.sendTouchUp(x2, y2):1042                return True1043            else:1044                return False1045        else:1046            return True1047    def enableVisualLog(self, filenameOrObj,1048                        screenshotWidth="240", thumbnailWidth="",1049                        timeFormat="%s.%f", delayedDrawing=False,1050                        copyBitmapsToScreenshotDir=False):1051        """1052        Start writing visual HTML log on this device object.1053        Parameters:1054          filenameOrObj (string or a file object)1055                  The file to which the log is written.1056          screenshotWidth (string, optional)1057                  Width of screenshot images in HTML.1058                  The default is "240".1059          thumbnailWidth (string, optional)1060                  Width of thumbnail images in HTML.1061                  The default is "", that is, original size.1062          timeFormat (string, optional)1063                  Timestamp format. The default is "%s.%f".1064                  Refer to strftime documentation.1065          delayedDrawing (boolean, optional)1066                  If True, screenshots with highlighted icons, words1067                  and gestures are not created during the1068                  test. Instead, only shell commands are stored for1069                  later execution. The value True can significantly1070                  save test execution time and disk space. The default1071                  is False.1072          copyBitmapsToScreenshotDir (boolean, optional)1073                  If True, every logged bitmap file will be copied to1074                  bitmaps directory in screenshotDir. The default is1075                  False.1076        """1077        if type(filenameOrObj) == str:1078            try:1079                outFileObj = file(filenameOrObj, "w")1080                self._visualLogFileObj = outFileObj1081            except Exception, e:1082                _fmbtLog('Failed to open file "%s" for logging.' % (filenameOrObj,))1083                raise1084        else:1085            outFileObj = filenameOrObj1086            # someone else opened the file => someone else will close it1087            self._visualLogFileObj = None1088        if hasattr(outFileObj, "name"):1089            if outFileObj.name in self._visualLogFilenames:1090                raise ValueError('Visual logging on file "%s" is already enabled' % (outFileObj.name,))1091            else:1092                self._visualLogFilenames.add(outFileObj.name)1093        self._visualLog = _VisualLog(self, outFileObj, screenshotWidth,1094                                     thumbnailWidth, timeFormat, delayedDrawing,1095                                     copyBitmapsToScreenshotDir)1096    def visualLog(self, *args):1097        """Writes parameters to the visual log, given that visual logging is1098        enabled.1099        """1100        pass1101    def intCoords(self, (x, y)):1102        """1103        Convert floating point coordinate values in range [0.0, 1.0] to1104        screen coordinates.1105        """1106        width, height = self.screenSize()1107        return _intCoords((x, y), (width, height))1108    def ocrEngine(self):1109        """1110        Returns the OCR engine that is used by default for new1111        screenshots.1112        """1113        return self._ocrEngine1114    def oirEngine(self):1115        """1116        Returns the OIR engine that is used by default for new1117        screenshots.1118        """1119        return self._oirEngine1120    def pressKey(self, keyName, long=False, hold=0.0):1121        """1122        Press a key.1123        Parameters:1124          keyName (string):1125                  the name of the key, like KEYCODE_HOME.1126          long (boolean, optional):1127                  if True, press the key for long time.1128          hold (float, optional):1129                  time in seconds to hold the key down.1130        """1131        if long and hold == 0.0:1132            hold = self._longPressHoldTime1133        if hold > 0.0:1134            try:1135                assert self._conn.sendKeyDown(keyName)1136                time.sleep(hold)1137                assert self._conn.sendKeyUp(keyName)1138            except AssertionError:1139                return False1140            return True1141        return self._conn.sendPress(keyName)1142    def _newScreenshotFilepath(self):1143        """1144        Returns path and filename for next screenshot file.1145        Makes sure the file can be written (necessary directory1146        structure exists).1147        """1148        t = datetime.datetime.now()1149        filename = _filenameTimestamp(t) + "-" + self._conn.target() + ".png"1150        filepath = os.path.join(self.screenshotDir(),1151                                t.strftime(self.screenshotSubdir()),1152                                filename)1153        necessaryDirs = os.path.dirname(filepath)1154        if necessaryDirs and not os.path.isdir(necessaryDirs):1155            try:1156                os.makedirs(necessaryDirs)1157            except Exception, e:1158                _fmbtLog('creating directory "%s" for screenshots failed: %s' %1159                         (necessaryDirs, e))1160                raise1161        return filepath1162    def _archiveScreenshot(self, filepath):1163        if self._screenshotArchiveMethod == "remove":1164            try:1165                os.remove(filepath)1166            except IOError:1167                pass1168        elif self._screenshotArchiveMethod.startswith("resize"):1169            if self._screenshotArchiveMethod == "resize":1170                convertArgs = ["-resize",1171                               "%sx" % (int(self.screenSize()[0]) / 4,)]1172            else:1173                widthHeight = self._screenshotArchiveMethod.split()[1]1174                convertArgs = ["-resize", widthHeight]1175            subprocess.call(["convert", filepath] + convertArgs + [filepath])1176    def _archiveScreenshots(self):1177        """1178        Archive screenshot files if screenshotLimit has been exceeded.1179        """1180        freeScreenshots = [filename1181                           for (filename, refCount) in self._screenshotRefCount.iteritems()1182                           if refCount == 0]1183        archiveCount = len(freeScreenshots) - self._screenshotLimit1184        if archiveCount > 0:1185            freeScreenshots.sort(reverse=True) # archive oldest1186            while archiveCount > 0:1187                toBeArchived = freeScreenshots.pop()1188                try:1189                    self._archiveScreenshot(toBeArchived)1190                except IOError:1191                    pass1192                del self._screenshotRefCount[toBeArchived]1193                archiveCount -= 11194    def refreshScreenshot(self, forcedScreenshot=None, rotate=None):1195        """1196        Takes new screenshot and updates the latest screenshot object.1197        Parameters:1198          forcedScreenshot (Screenshot or string, optional):1199                  use given screenshot object or image file, do not1200                  take new screenshot.1201          rotate (integer, optional):1202                  rotate screenshot by given number of degrees. This1203                  overrides constructor rotateScreenshot parameter1204                  value. The default is None (no override).1205        Returns Screenshot object, and makes the same object "the1206        latest screenshot" that is used by all *Bitmap and *OcrText1207        methods.1208        """1209        if forcedScreenshot != None:1210            if type(forcedScreenshot) == str:1211                self._lastScreenshot = Screenshot(1212                    screenshotFile=forcedScreenshot,1213                    paths = self._paths,1214                    ocrEngine=self._ocrEngine,1215                    oirEngine=self._oirEngine,1216                    screenshotRefCount=self._screenshotRefCount)1217            else:1218                self._lastScreenshot = forcedScreenshot1219        else:1220            if self.screenshotDir() == None:1221                self.setScreenshotDir(self._screenshotDirDefault)1222            if self.screenshotSubdir() == None:1223                self.setScreenshotSubdir(self._screenshotSubdirDefault)1224            screenshotFile = self._newScreenshotFilepath()1225            if self._conn.recvScreenshot(screenshotFile):1226                # New screenshot successfully received from device1227                if rotate == None:1228                    rotate = self._rotateScreenshot1229                if rotate != None and rotate != 0:1230                    subprocess.call(["convert", screenshotFile, "-rotate", str(rotate), screenshotFile])1231                self._lastScreenshot = Screenshot(1232                    screenshotFile=screenshotFile,1233                    paths = self._paths,1234                    ocrEngine=self._ocrEngine,1235                    oirEngine=self._oirEngine,1236                    screenshotRefCount=self._screenshotRefCount)1237            else:1238                self._lastScreenshot = None1239        # Make sure unreachable Screenshot instances are released from1240        # memory.1241        gc.collect()1242        for obj in gc.garbage:1243            if isinstance(obj, Screenshot):1244                if hasattr(obj, "_logCallReturnValue"):1245                    # Some methods have been wrapped by visual1246                    # log. Break reference cycles to let gc collect1247                    # them.1248                    del obj.findItemsByBitmap1249                    del obj.findItemsByOcr1250        del gc.garbage[:]1251        gc.collect()1252        # If screenshotLimit has been set, archive old screenshot1253        # stored on the disk.1254        if self._screenshotLimit != None and self._screenshotLimit >= 0:1255            self._archiveScreenshots()1256        return self._lastScreenshot1257    def screenshot(self):1258        """1259        Returns the latest Screenshot object.1260        Use refreshScreenshot() to get a new screenshot.1261        """1262        return self._lastScreenshot1263    def screenshotArchiveMethod(self):1264        """1265        Returns how screenshots exceeding screenshotLimit are archived.1266        """1267        return self._screenshotArchiveMethod1268    def screenshotDir(self):1269        """1270        Returns the directory under which new screenshots are saved.1271        """1272        return self._screenshotDir1273    def screenshotLimit(self):1274        """1275        Returns the limit after which unused screenshots are archived.1276        """1277        return self._screenshotLimit1278    def screenshotSubdir(self):1279        """1280        Returns the subdirectory in screenshotDir under which new1281        screenshots are stored.1282        """1283        return self._screenshotSubdir1284    def screenSize(self):1285        """1286        Returns screen size in pixels in tuple (width, height).1287        """1288        if self._screenSize == None:1289            if self._lastScreenshot == None:1290                self.refreshScreenshot()1291                self._screenSize = self._lastScreenshot.size()1292                self._lastScreenshot = None1293            else:1294                self._screenSize = self._lastScreenshot.size()1295        return self._screenSize1296    def setBitmapPath(self, bitmapPath, rootForRelativePaths=None):1297        """1298        Set new path for finding bitmaps.1299        Parameters:1300          bitmapPath (string)1301                  colon-separated list of directories from which1302                  bitmap methods look for bitmap files.1303          rootForRelativePaths (string, optional)1304                  path that will prefix all relative paths in1305                  bitmapPath.1306        Example:1307          gui.setBitmapPath("bitmaps:icons:/tmp", "/home/X")1308          gui.tapBitmap("start.png")1309          will look for /home/X/bitmaps/start.png,1310          /home/X/icons/start.png and /tmp/start.png, in this order.1311        """1312        self._paths.bitmapPath = bitmapPath1313        if rootForRelativePaths != None:1314            self._paths.relativeRoot = rootForRelativePaths1315    def setConnection(self, conn):1316        """1317        Set the connection object that performs actions on real target.1318        Parameters:1319          conn (GUITestConnection instance):1320                  The connection to be used.1321        """1322        self._conn = conn1323    def setOcrEngine(self, ocrEngine):1324        """1325        Set OCR (optical character recognition) engine that will be1326        used by default in new screenshots.1327        Returns previous default.1328        """1329        prevDefault = self._ocrEngine1330        self._ocrEngine = ocrEngine1331        return prevDefault1332    def setOirEngine(self, oirEngine):1333        """1334        Set OIR (optical image recognition) engine that will be used1335        by default in new screenshots.1336        Returns previous default.1337        """1338        prevDefault = self._oirEngine1339        self._oirEngine = oirEngine1340        return prevDefault1341    def setScreenshotArchiveMethod(self, screenshotArchiveMethod):1342        """1343        Set method for archiving screenshots when screenshotLimit is exceeded.1344        Parameters:1345          screenshotArchiveMethod (string)1346                  Supported methods are "resize [WxH]" and "remove"...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!!
