Best Python code snippet using fMBT_python
fmbtwindows.py
Source:fmbtwindows.py  
...1467    def topWindowProperties(self):1468        """1469        Return properties of the top window as a dictionary1470        """1471        return self._conn.recvTopWindowProperties()1472    def verifyText(self, text, partial=False):1473        """1474        Verify that the last view has at least one item with given1475        text.1476        Parameters:1477          text (string):1478                  text to be searched for in items.1479          partial (boolean, optional):1480                  if True, match items if item text contains given1481                  text, otherwise match only if item text is equal to1482                  the given text. The default is False (exact match).1483        """1484        assert self._lastView != None, "View required."1485        return self._lastView.findItemsByText(text, partial=partial, count=1, onScreen=True) != []1486    def viewSource(self):1487        """1488        Returns current default view source.1489        See also refreshView(), setViewSource().1490        """1491        return self._refreshViewDefaults.get(1492            "viewSource", self._defaultViewSource)1493    def windowList(self):1494        """1495        Return list of properties of windows (dictionaries)1496        Example: list window handles and titles:1497          for props in d.windowList():1498              print props["hwnd"], props["title"]1499        """1500        return self._conn.recvWindowList()1501    def windowProperties(self, window):1502        """1503        Returns properties of a window.1504        Parameters:1505          window (title (string) or hwnd (integer):1506                  The window whose properties will be returned.1507        Returns properties in a dictionary.1508        """1509        return self.existingConnection().recvWindowProperties(window)1510    def windowStatus(self, window):1511        """1512        Returns status of a window.1513        Parameters:1514          window (title (string) or hwnd (integer):1515                  The window whose properties will be returned.1516        Returns status in a dictionary.1517        """1518        return self.existingConnection().recvWindowStatus(window)1519    def view(self):1520        return self._lastView1521    def viewStats(self):1522        return self._lastViewStats1523class _NoPythonshareConnection(object):1524    """Fake Pythonshare connection, evaluate everything locally"""1525    def __init__(self, namespace="default"):1526        self._namespaces = {}1527        self._ns = namespace1528    def exec_in(self, ns, code):1529        if not ns in self._namespaces:1530            self._namespaces[ns] = {}1531        exec code in self._namespaces[ns]1532    def eval_in(self, ns, expr):1533        if not ns in self._namespaces:1534            self._namespaces[ns] = {}1535        return eval(expr, self._namespaces[ns])1536    def namespace(self):1537        return self._ns1538class WindowsConnection(fmbtgti.GUITestConnection):1539    def __init__(self, connspec, password, device):1540        fmbtgti.GUITestConnection.__init__(self)1541        self._device = device1542        self._screenshotSize = (None, None) # autodetect1543        self._pycosh_sent_to_dut = False1544        if connspec != None:1545            self._agent = pythonshare.connect(connspec, password=password)1546        else:1547            if os.name != "nt":1548                raise ValueError("connecting to host works only on Windows")1549            self._agent = _NoPythonshareConnection()1550        self._agent_ns = self._agent.namespace()1551        agentFilename = os.path.join(1552            os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))),1553            "fmbtwindows_agent.py")1554        self._agent.exec_in(self._agent_ns, file(agentFilename).read())1555        self.setScreenToDisplayCoords(lambda x, y: (x, y))1556        self.setDisplayToScreenCoords(lambda x, y: (x, y))1557    def pycosh(self, command):1558        if not self._pycosh_sent_to_dut:1559            # upload pycosh module to DUT1560            try:1561                self.evalPython("len(_g_pycosh_source)")1562            except pythonshare.RemoteEvalError:1563                self.execPython(file(inspect.getsourcefile(pycosh)).read())1564            self._pycosh_sent_to_dut = True1565        return self.evalPython("pycosh_eval(%s)" % (repr(command),))1566    def setScreenshotSize(self, screenshotSize):1567        self._screenshotSize = screenshotSize1568        screenW, screenH = self._screenshotSize1569        inputW, inputH = self._agent.eval_in(self._agent_ns, "_mouse_input_area")1570        self.setScreenToDisplayCoords(1571            lambda x, y: (x * inputW / screenW, y * inputH / screenH))1572        self.setDisplayToScreenCoords(1573            lambda x, y: (x * screenW / inputW, y * screenH / inputH))1574    def execPython(self, code):1575        return self._agent.exec_in(self._agent_ns, code)1576    def evalPython(self, code):1577        return self._agent.eval_in(self._agent_ns, code)1578    def recvFile(self, remoteFilename, localFilename=None, compress=False):1579        if compress:1580            if isinstance(compress, int):1581                compressLevel = compress1582            else:1583                compressLevel = 31584            data_b64_z = self._agent.eval_in(1585                self._agent_ns,1586                "base64.b64encode(zlib.compress(file(%s, 'rb').read(), %s))" % (1587                    repr(remoteFilename), compressLevel))1588            data = zlib.decompress(base64.b64decode(data_b64_z))1589        else:1590            data_b64 = self._agent.eval_in(1591                self._agent_ns,1592                "base64.b64encode(file(%s, 'rb').read())" % (repr(remoteFilename),))1593            data = base64.b64decode(data_b64)1594        if localFilename:1595            file(localFilename, "wb").write(data)1596            return True1597        else:1598            return data1599    def sendFile(self, localFilename, remoteFilepath, data=None):1600        sendBlockMaxLen = 10 * 1024 * 1024 # Send at most 10 MB at a time1601        sendDataFromFile = False1602        if data == None:1603            fileSize = os.stat(localFilename).st_size1604            if fileSize < sendBlockMaxLen:1605                data = open(localFilename, "rb").read()1606            else:1607                data = ""1608                dataFile = open(localFilename, "rb")1609                sendDataFromFile = True1610        if localFilename:1611            basename = os.path.basename(localFilename)1612        else:1613            basename = localFilename1614        if sendDataFromFile:1615            dataLen = fileSize1616        else:1617            dataLen = len(data)1618        sendIndex = 01619        while sendIndex < dataLen or dataLen == 0:1620            if sendDataFromFile:1621                sendData = dataFile.read(sendBlockMaxLen)1622            else:1623                sendData = data[sendIndex:sendIndex + sendBlockMaxLen]1624            rv = self.evalPython(1625                'saveFile(%s, %s, base64.b64decode(%s), append=%s)' %1626                (repr(basename),1627                 repr(remoteFilepath),1628                 repr(base64.b64encode(sendData)),1629                 repr(sendIndex != 0)))1630            sendIndex += sendBlockMaxLen1631            if not rv or dataLen == 0:1632                break1633        if sendDataFromFile:1634            dataFile.close()1635        return rv1636    def recvMatchingPaths(self, pathnamePattern):1637        filepaths = self._agent.eval_in(1638            self._agent_ns,1639            "glob.glob(%s)" % (repr(pathnamePattern),))1640        if "/" in pathnamePattern:1641            # Unix-style directory naming in input,1642            # stick with it and fix mixed / and \ that might1643            # come out from glob.glob.1644            return [p.replace('\\', '/') for p in filepaths]1645        else:1646            # use glob output as it is1647            return filepaths1648    def recvScreenshot(self, filename, screenshotSize=(None, None)):1649        ppmfilename = filename + ".ppm"1650        if screenshotSize == (None, None):1651            screenshotSize = self._screenshotSize1652        width, height, zdata = self._agent.eval_in(1653            self._agent_ns, "screenshotZYBGR(%s)" % (repr(screenshotSize),))1654        data = zlib.decompress(zdata)1655        fmbtgti.eye4graphics.wbgr2rgb(data, width, height)1656        if fmbtpng != None:1657            file(filename, "wb").write(1658                fmbtpng.raw2png(data, width, height, 8, "RGB"))1659        else:1660            ppm_header = "P6\n%d %d\n%d\n" % (width, height, 255)1661            f = file(filename + ".ppm", "wb")1662            f.write(ppm_header)1663            f.write(data)1664            f.close()1665            _run([fmbt_config.imagemagick_convert, ppmfilename, filename], expectedExitStatus=[0])1666            os.remove(ppmfilename)1667        return True1668    def recvTopWindowProperties(self):1669        return self.evalPython("topWindowProperties()")1670    def recvWindowProperties(self, window):1671        hwnd = self._window2hwnd(window)1672        return self.evalPython("windowProperties(%s)" % (hwnd,))1673    def recvWindowStatus(self, window):1674        hwnd = self._window2hwnd(window)1675        return self.evalPython("windowStatus(%s)" % (hwnd,))1676    def recvViewData(self, window=None):1677        rv = None1678        if window == None:1679            rv = self.evalPython("topWindowWidgets()")1680        elif isinstance(window, int):1681            rv = self.evalPython("windowWidgets(%s)" % (repr(window),))1682        elif isinstance(window, str) or isinstance(window, unicode):...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!!
