Best Python code snippet using fMBT_python
fmbtgti.py
Source:fmbtgti.py
...1427 except AssertionError:1428 return False1429 return True1430 return self.existingConnection().sendPress(keyName, **extraParams)1431 def _newScreenshotFilepath(self):1432 """1433 Returns path and filename for next screenshot file.1434 Makes sure the file can be written (necessary directory1435 structure exists).1436 """1437 t = datetime.datetime.now()1438 if not self._conn:1439 target = ""1440 else:1441 target = self._conn.target()1442 filename = _filenameTimestamp(t) + "-" + target + ".png"1443 screenshotPath = self.screenshotDir()1444 if self.screenshotSubdir():1445 screenshotPath = os.path.join(screenshotPath,1446 self.screenshotSubdir())1447 screenshotPath = fmbt.formatTime(screenshotPath, t)1448 filepath = os.path.join(screenshotPath, filename)1449 necessaryDirs = os.path.dirname(filepath)1450 if necessaryDirs and not os.path.isdir(necessaryDirs):1451 try:1452 os.makedirs(necessaryDirs)1453 except Exception, e:1454 _fmbtLog('creating directory "%s" for screenshots failed: %s' %1455 (necessaryDirs, e))1456 raise1457 return filepath1458 def _archiveScreenshot(self, filepath):1459 if self._screenshotArchiveMethod == "remove":1460 try:1461 os.remove(filepath)1462 except IOError:1463 pass1464 elif self._screenshotArchiveMethod.startswith("resize"):1465 if self._screenshotArchiveMethod == "resize":1466 convertArgs = ["-resize",1467 "%sx" % (int(self.screenSize()[0]) / 4,)]1468 else:1469 widthHeight = self._screenshotArchiveMethod.split()[1]1470 convertArgs = ["-resize", widthHeight]1471 subprocess.call([fmbt_config.imagemagick_convert, filepath] + convertArgs + [filepath])1472 def _archiveScreenshots(self):1473 """1474 Archive screenshot files if screenshotLimit has been exceeded.1475 """1476 freeScreenshots = [filename1477 for (filename, refCount) in self._screenshotRefCount.iteritems()1478 if refCount == 0]1479 archiveCount = len(freeScreenshots) - self._screenshotLimit1480 if archiveCount > 0:1481 freeScreenshots.sort(reverse=True) # archive oldest1482 while archiveCount > 0:1483 toBeArchived = freeScreenshots.pop()1484 try:1485 self._archiveScreenshot(toBeArchived)1486 except IOError:1487 pass1488 del self._screenshotRefCount[toBeArchived]1489 archiveCount -= 11490 def refreshScreenshot(self, forcedScreenshot=None, rotate=None):1491 """1492 Takes new screenshot and updates the latest screenshot object.1493 Parameters:1494 forcedScreenshot (Screenshot or string, optional):1495 use given screenshot object or image file, do not1496 take new screenshot.1497 rotate (integer, optional):1498 rotate screenshot by given number of degrees. This1499 overrides constructor rotateScreenshot parameter1500 value. The default is None (no override).1501 Returns Screenshot object, and makes the same object "the1502 latest screenshot" that is used by all *Bitmap and *OcrText1503 methods. Returns None if screenshot cannot be taken.1504 """1505 if forcedScreenshot != None:1506 if type(forcedScreenshot) == str:1507 self._lastScreenshot = Screenshot(1508 screenshotFile=forcedScreenshot,1509 paths = self._paths,1510 ocrEngine=self._ocrEngine,1511 oirEngine=self._oirEngine,1512 screenshotRefCount=self._screenshotRefCount)1513 else:1514 self._lastScreenshot = forcedScreenshot1515 elif self._conn: # There is a connection, get new screenshot1516 if self.screenshotDir() == None:1517 self.setScreenshotDir(self._screenshotDirDefault)1518 if self.screenshotSubdir() == None:1519 self.setScreenshotSubdir(self._screenshotSubdirDefault)1520 screenshotFile = self._newScreenshotFilepath()1521 if self.existingConnection().recvScreenshot(screenshotFile):1522 # New screenshot successfully received from device1523 if rotate == None:1524 rotate = self._rotateScreenshot1525 if rotate != None and rotate != 0:1526 subprocess.call([fmbt_config.imagemagick_convert, screenshotFile, "-rotate", str(rotate), screenshotFile])1527 self._lastScreenshot = Screenshot(1528 screenshotFile=screenshotFile,1529 paths = self._paths,1530 ocrEngine=self._ocrEngine,1531 oirEngine=self._oirEngine,1532 screenshotRefCount=self._screenshotRefCount)1533 else:1534 self._lastScreenshot = None1535 else: # No connection, cannot get a screenshot1536 self._lastScreenshot = None1537 # Make sure unreachable Screenshot instances are released from1538 # memory.1539 gc.collect()1540 for obj in gc.garbage:1541 if isinstance(obj, Screenshot):1542 if hasattr(obj, "_logCallReturnValue"):1543 # Some methods have been wrapped by visual1544 # log. Break reference cycles to let gc collect1545 # them.1546 try:1547 del obj.findItemsByBitmap1548 except:1549 pass1550 try:1551 del obj.findItemsByOcr1552 except:1553 pass1554 del gc.garbage[:]1555 gc.collect()1556 # If screenshotLimit has been set, archive old screenshot1557 # stored on the disk.1558 if self._screenshotLimit != None and self._screenshotLimit >= 0:1559 self._archiveScreenshots()1560 return self._lastScreenshot1561 def screenshot(self):1562 """1563 Returns the latest Screenshot object.1564 Use refreshScreenshot() to get a new screenshot.1565 """1566 return self._lastScreenshot1567 def screenshotArchiveMethod(self):1568 """1569 Returns how screenshots exceeding screenshotLimit are archived.1570 """1571 return self._screenshotArchiveMethod1572 def screenshotDir(self):1573 """1574 Returns the directory under which new screenshots are saved.1575 """1576 return self._screenshotDir1577 def screenshotLimit(self):1578 """1579 Returns the limit after which unused screenshots are archived.1580 """1581 return self._screenshotLimit1582 def screenshotSubdir(self):1583 """1584 Returns the subdirectory in screenshotDir under which new1585 screenshots are stored.1586 """1587 return self._screenshotSubdir1588 def screenSize(self):1589 """1590 Returns screen size in pixels in tuple (width, height).1591 """1592 if self._lastScreenshot != None:1593 self._screenSize = self._lastScreenshot.size()1594 if self._screenSize == None:1595 if self._lastScreenshot == None:1596 try:1597 if self.refreshScreenshot():1598 self._screenSize = self._lastScreenshot.size()1599 self._lastScreenshot = None1600 except Exception:1601 pass1602 if (self._screenSize == None and1603 hasattr(self.existingConnection(), "recvScreenSize")):1604 self._screenSize = self.existingConnection().recvScreenSize()1605 else:1606 self._screenSize = self._lastScreenshot.size()1607 return self._screenSize1608 def setBitmapPath(self, bitmapPath, rootForRelativePaths=None):1609 """1610 Set new path for finding bitmaps.1611 Parameters:1612 bitmapPath (string)1613 colon-separated list of directories from which1614 bitmap methods look for bitmap files.1615 rootForRelativePaths (string, optional)1616 path that will prefix all relative paths in1617 bitmapPath.1618 Example:1619 gui.setBitmapPath("bitmaps:icons:/tmp", "/home/X")1620 gui.tapBitmap("start.png")1621 will look for /home/X/bitmaps/start.png,1622 /home/X/icons/start.png and /tmp/start.png, in this order.1623 """1624 self._paths.bitmapPath = bitmapPath1625 if rootForRelativePaths != None:1626 self._paths.relativeRoot = rootForRelativePaths1627 def setConnection(self, conn):1628 """1629 Set the connection object that performs actions on real target.1630 Parameters:1631 conn (GUITestConnection instance):1632 The connection to be used.1633 """1634 self._conn = conn1635 def setOcrEngine(self, ocrEngine):1636 """1637 Set OCR (optical character recognition) engine that will be1638 used by default in new screenshots.1639 Returns previous default.1640 """1641 prevDefault = self._ocrEngine1642 self._ocrEngine = ocrEngine1643 return prevDefault1644 def setOirEngine(self, oirEngine):1645 """1646 Set OIR (optical image recognition) engine that will be used1647 by default in new screenshots.1648 Returns previous default.1649 """1650 prevDefault = self._oirEngine1651 self._oirEngine = oirEngine1652 return prevDefault1653 def setScreenshotArchiveMethod(self, screenshotArchiveMethod):1654 """1655 Set method for archiving screenshots when screenshotLimit is exceeded.1656 Parameters:1657 screenshotArchiveMethod (string)1658 Supported methods are "resize [WxH]" and "remove"1659 where W and H are integers that define maximum width and1660 height for an archived screenshot.1661 The default method is "resize".1662 """1663 if screenshotArchiveMethod == "remove":1664 pass1665 elif screenshotArchiveMethod == "resize":1666 pass1667 elif screenshotArchiveMethod.startswith("resize"):1668 try:1669 w, h = screenshotArchiveMethod.split(" ")[1].split("x")1670 except:1671 raise ValueError("Invalid resize syntax")1672 try:1673 w, h = int(w), int(h)1674 except:1675 raise ValueError(1676 "Invalid resize width or height, integer expected")1677 else:1678 raise ValueError('Unknown archive method "%s"' %1679 (screenshotArchiveMethod,))1680 self._screenshotArchiveMethod = screenshotArchiveMethod1681 def setScreenshotDir(self, screenshotDir):1682 self._screenshotDir = screenshotDir1683 self._newScreenshotFilepath() # make directories1684 def setScreenshotLimit(self, screenshotLimit):1685 """1686 Set maximum number for unarchived screenshots.1687 Parameters:1688 screenshotLimit (integer)1689 Maximum number of unarchived screenshots that are1690 free for archiving (that is, not referenced by test code).1691 The default is None, that is, there is no limit and1692 screenshots are never archived.1693 See also:1694 setScreenshotArchiveMethod()1695 """1696 self._screenshotLimit = screenshotLimit1697 def setScreenshotSubdir(self, screenshotSubdir):...
fmbtx11.py
Source:fmbtx11.py
...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....
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!!