How to use sendSetTopWindow method in fMBT

Best Python code snippet using fMBT_python

fmbtwindows.py

Source:fmbtwindows.py Github

copy

Full Screen

...1320 Returns True if the window was brought to the foreground,1321 otherwise False.1322 Notes: calls SetForegroundWindow in user32.dll.1323 """1324 return self.existingConnection().sendSetTopWindow(window)1325 def setViewSource(self, source, properties=None):1326 """1327 Set default view source for refreshView()1328 Parameters:1329 source (string):1330 default source, "enumchildwindow" or "uiautomation",1331 "uiautomation/raw", "uiautomation/control",1332 "uiautomation/content".1333 properties (string or list of strings, optional):1334 set list of view item properties to be read.1335 "all" reads all available properties for each item.1336 "fast" reads a set of preselected properties.1337 list of strings reads properties in the list.1338 The default is "all".1339 Returns None.1340 See also refreshView(), viewSource(), refreshViewDefaults().1341 """1342 if not source in _g_viewSources:1343 raise ValueError(1344 'invalid view source "%s", expected one of: "%s"' %1345 (source, '", "'.join(_g_viewSources)))1346 if properties != None:1347 self._refreshViewDefaults["properties"] = properties1348 self._refreshViewDefaults["viewSource"] = source1349 def shell(self, command):1350 """1351 Execute command in Windows.1352 Parameters:1353 command (string or list of strings):1354 command to be executed. Will be forwarded directly1355 to subprocess.check_output. If command is a string,1356 then it will be executed in subshell, otherwise without1357 shell.1358 Returns what is printed by the command.1359 If you wish to receive exitstatus or standard output and error1360 separated from command, refer to shellSOE().1361 """1362 return self._conn.evalPython('shell(%s)' % (repr(command),))1363 def shellSOE(self, command, asyncStatus=None, asyncOut=None,1364 asyncError=None, cwd=None, timeout=None):1365 """Execute command on Windows.1366 Parameters:1367 command (string or list of strings):1368 command to be executed. If command is a list of1369 string, it will be executed without shell1370 (subprocess.check_output with shell=False).1371 If command is a single-line string, it will be1372 executed in shell (subprocess.check_output with1373 shell=True).1374 If command is a multiline string, it will be written1375 to a BAT file and executed as a script.1376 asyncStatus (string, True or None)1377 filename (on device) to which the status of1378 asynchronously executed shellCommand will be1379 written. If True, the command will be executed1380 asynchronously but exit status will not be1381 saved. The default is None, that is, command will be1382 run synchronously, and status will be returned in1383 the tuple.1384 asyncOut (string, True or None)1385 filename (on device) to which the standard output of1386 asynchronously executed shellCommand will be1387 written. If True, the command will be executed1388 asynchronously but output will not saved. The1389 default is None.1390 asyncError (string, True or None)1391 filename (on device) to which the standard error of1392 asynchronously executed shellCommand will be1393 written. If True, the command will be executed1394 asynchronously but standard error will not be1395 saved. The default is None.1396 cwd (string, optional)1397 current working directory in which the command1398 will be executed. If not given, the cwd defaults1399 to the current working directory of the pythonshare1400 server process on the device, or the cwd of the Python1401 process if executed on host without pythonshare-server.1402 timeout (float, optional)1403 forcefully kill child processes and return after1404 given time (in seconds). If timed out, returned output1405 and error strings contain what was printed until processes1406 were killed. Returned status is a fmbtwindows.Timeout1407 instance. Asynchronous executions cannot be timed out.1408 The default is None (no timeout).1409 Returns triplet: exit status, standard output and standard error1410 (int, str, str) from the command.1411 If executing command fails, returns (None, None, None).1412 If execution is timed out, returns (fmbtwindows.Timeout, str, str)1413 or (fmbtwindows.Timeout, None, None) if outputs could not be read.1414 """1415 if (timeout != None and1416 (asyncStatus, asyncOut, asyncError) != (None, None, None)):1417 raise NotImplementedError(1418 "timeout for asynchronous execution is not supported")1419 s, o, e = self._conn.evalPython(1420 'shellSOE(%s, asyncStatus=%s, asyncOut=%s, asyncError=%s, '1421 'cwd=%s, timeout=%s)'1422 % (repr(command),1423 repr(asyncStatus), repr(asyncOut), repr(asyncError),1424 repr(cwd), repr(timeout)))1425 if isinstance(s, str) and s.startswith("TIMEOUT"):1426 s = Timeout(command=command[:1024*8],1427 pid=int(s.split()[-1]))1428 return s, o, e1429 def showWindow(self, window, showCmd=SW_NORMAL):1430 """1431 Send showCmd to window.1432 Parameters:1433 window (window title (string) or handle (integer)):1434 window to which the command will be sent.1435 showCmd (integer or string):1436 command to be sent. Valid commands are 0..11:1437 SW_HIDE, SW_NORMAL, SW_MINIMIZED, SW_MAXIMIZE,1438 SW_NOACTIVATE, SW_SHOW SW_MINIMIZE, SW_MINNOACTIVE,1439 SW_SHOWNA, SW_RESTORE, SW_DEFAULT, SW_FORCEMINIMIZE.1440 Returns True if the window was previously visible,1441 otherwise False.1442 Notes: calls ShowWindow in user32.dll.1443 """1444 return self.existingConnection().sendShowWindow(window, showCmd)1445 def tapText(self, text, partial=False, **tapKwArgs):1446 """1447 Find an item with given text from the latest view, and tap it.1448 Parameters:1449 partial (boolean, optional):1450 refer to verifyText documentation. The default is1451 False.1452 tapPos (pair of floats (x, y)):1453 refer to tapItem documentation.1454 button, long, hold, count, delayBetweenTaps (optional):1455 refer to tap documentation.1456 Returns True if successful, otherwise False.1457 """1458 items = self.existingView().findItemsByText(text, partial=partial, count=1, onScreen=True)1459 if len(items) == 0: return False1460 return self.tapItem(items[0], **tapKwArgs)1461 def topWindow(self):1462 """1463 Returns a handle to the window.1464 """1465 return self.existingConnection().evalPython(1466 "ctypes.windll.user32.GetForegroundWindow()")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):1683 wlist = self.evalPython("windowList()")1684 for w in wlist:1685 if w["title"] == window:1686 rv = self.evalPython("windowWidgets(%s)" % (repr(w["hwnd"]),))1687 break1688 else:1689 raise ValueError('no window with title "%s"' % (window,))1690 else:1691 raise ValueError('illegal window "%s", expected integer or string (hWnd or title)' % (window,))1692 return rv1693 def _parseDumps(self, dumps, dump_suffix, error_template):1694 dumpFilename = self._device.getDumpFilename(dump_suffix) + '.log'1695 error_message = ''1696 rv = []1697 prop_data = {}1698 items = None1699 with open(dumpFilename, 'w') as f:1700 for dump in dumps:1701 f.write(dump + '\n')1702 for line in dump.split('\0'):1703 if line.startswith('!'):1704 error_message = line[1:]1705 continue1706 if line.startswith('#'): # It's a comment / debug output: skip it!1707 continue1708 if line == '[':1709 items = []1710 continue1711 if line == ']':1712 rv.append(items)1713 continue1714 if items is not None:1715 items.append(line)1716 if "=" not in line:1717 continue1718 prop_name, prop_value = line.split("=", 1)1719 if prop_name == "hash" and prop_data:1720 rv.append(prop_data)1721 prop_data = {}1722 prop_data[prop_name] = prop_value.replace(r"\r\n", "\n").replace(r"\\", "\\")1723 if prop_data:1724 rv.append(prop_data)1725 if error_message:1726 raise FMBTWindowsError(error_template % error_message)1727 return rv1728 def recvViewUIAutomation(self, window=None, items=[], properties=None, area=None, walker="raw",1729 filterType="none", filterCondition="", dumpChildClass="", dumpChildName="", doNotDump=False):1730 """returns list of dictionaries, each of which contains properties of1731 an item"""1732 if not walker in ["raw", "control", "content"]:1733 raise ValueError('invalid walker %r' % walker)1734 hwnd = self._window2hwnd(window) if window else None1735 if properties is None:1736 properties = []1737 else:1738 # make sure certain properties are always included1739 properties = list(frozenset(properties) | frozenset(["BoundingRectangle"]))1740 dumps = []1741 if items:1742 for item in items:1743 dumps.append(self.evalPython("dumpUIAutomationElements(%r, %r, %r, %r, %r, %r, %r, %r, %r, %r)" % (1744 hwnd,1745 [str(item.id()) for item in item.branch()],1746 properties,1747 area,1748 walker,1749 filterType,1750 filterCondition,1751 dumpChildClass,1752 dumpChildName,1753 doNotDump)))1754 else:1755 dumps.append(self.evalPython("dumpUIAutomationElements(%r, %r, %r, %r, %r, %r, %r, %r, %r, %r)" % (1756 hwnd,1757 [],1758 properties,1759 area,1760 walker,1761 filterType,1762 filterCondition,1763 dumpChildClass,1764 dumpChildName,1765 doNotDump)))1766 return self._parseDumps(dumps, "dumpUIAutomationElements",1767 "view is not available. An error happened while collecting UI elements with refreshView().\n%s")1768 def sendSetCacheMode(self, mode):1769 dump = self.evalPython("serverSetCacheMode(%r)" % mode)1770 self._parseDumps([dump], "serverSetCacheMode",1771 "An error happened while setting the cache mode.\n%s")1772 def sendClearCache(self):1773 dump = self.evalPython("serverClearCache()")1774 self._parseDumps([dump], "serverClearCache",1775 "An error happened while clearing the cache.\n%s")1776 def sendSetFocus(self, eltHash):1777 dump = self.evalPython("setAutomationElementFocus(%s)" % eltHash)1778 self._parseDumps([dump], "setAutomationElementFocus",1779 "An error happened while setting the focus.\n%s")1780 def sendCollapse(self, eltHash):1781 dump = self.evalPython("AutomationElementCollapse(%s)" % eltHash)1782 self._parseDumps([dump], "AutomationElementCollapse",1783 "An error happened while collapsing the viewitem.\n%s")1784 def sendExpand(self, eltHash):1785 dump = self.evalPython("AutomationElementExpand(%s)" % eltHash)1786 self._parseDumps([dump], "AutomationElementExpand",1787 "An error happened while expanding the viewitem.\n%s")1788 def recvViewCachedItem(self, eltHash):1789 dump = self.evalPython("getCachedAutomationElement(%s)" % eltHash)1790 return self._parseDumps([dump], "getCachedAutomationElement",1791 "viewitem is not available. An error happened while dumping it with cachedElement().\n%s")1792 def recvViewItemPatterns(self, eltHash):1793 dump = self.evalPython("getAutomationElementPatterns(%s)" % eltHash)1794 return self._parseDumps([dump], "getAutomationElementPatterns",1795 "viewitem patterns are not available. An error happened while collecting them with patterns().\n%s")1796 def recvViewItemProperties(self, eltHash):1797 dump = self.evalPython("getAutomationElementProperties(%s)" % eltHash)1798 return self._parseDumps([dump], "getAutomationElementProperties",1799 "viewitem properties are not available. An error happened while collecting them with refresh().\n%s")1800 def recvViewItemItems(self, eltHash, propertyName, separator, filterSubChildClassName, maxSubChildren):1801 dump = self.evalPython("getAutomationElementItems(%s, %r, %r, %r, %r)" % (1802 eltHash, propertyName, separator, filterSubChildClassName, maxSubChildren))1803 return self._parseDumps([dump], "getAutomationElementItems",1804 "viewitem items aren't available. An error happened while getting it with items().\n%s")1805 def recvViewItemContainerItems(self, eltHash, propertyName, separator, filterSubChildClassName, maxSubChildren, scroll):1806 dump = self.evalPython("getAutomationElementContainerItems(%s, %r, %r, %r, %r, %r)" % (1807 eltHash, propertyName, separator, filterSubChildClassName, maxSubChildren, scroll))1808 return self._parseDumps([dump], "getAutomationElementContainerItems",1809 "viewitem items aren't available. An error happened while getting it with containerItems().\n%s")1810 def recvViewItemSelectedItems(self, eltHash, propertyName, separator, filterSubChildClassName, maxSubChildren, scroll):1811 dump = self.evalPython("getAutomationElementSelectedItems(%s, %r, %r, %r, %r, %r)" % (1812 eltHash, propertyName, separator, filterSubChildClassName, maxSubChildren, scroll))1813 return self._parseDumps([dump], "getAutomationElementSelectedItems",1814 "viewitem selected items aren't available. An error happened while getting it with selectedItems().\n%s")1815 def recvViewItemText(self, eltHash, maxLength):1816 dump = self.evalPython("getAutomationElementText(%s, %s)" % (eltHash, maxLength))1817 return self._parseDumps([dump], "getAutomationElementText",1818 "viewitem text isn't available. An error happened while getting it with longText().\n%s")1819 def recvViewItemSetValue(self, eltHash, value):1820 dump = self.evalPython("setAutomationElementValue(%s, %r)" % (eltHash, value))1821 return self._parseDumps([dump], "setAutomationElementValue",1822 "viewitem value isn't editable. An error happened while setting it with setValue().\n%s")1823 def recvWindowList(self):1824 return self.evalPython("windowList()")1825 def _window2hwnd(self, window):1826 if isinstance(window, str) or isinstance(window, unicode):1827 windowList = self.recvWindowList()1828 hwndList = [w["hwnd"] for w in windowList if w["title"] == window]1829 if not hwndList:1830 raise ValueError('no window with title "%s"' % (window,))1831 hwnd = hwndList[0]1832 elif isinstance(window, dict) and "hwnd" in window:1833 hwnd = window["hwnd"]1834 elif isinstance(window, int) or isinstance(window, long):1835 hwnd = window1836 else:1837 raise ValueError('invalid window "%s", string, integer or dict with "hwnd" key expected' % (window,))1838 return hwnd1839 def sendCloseWindow(self, window):1840 hwnd = self._window2hwnd(window)1841 return self.evalPython("closeWindow(%s)" % (repr(hwnd),))1842 def sendSetForegroundWindow(self, window):1843 hwnd = self._window2hwnd(window)1844 return 0 != self.evalPython("ctypes.windll.user32.SetForegroundWindow(%s)" %1845 (repr(hwnd),))1846 def sendSetTopWindow(self, window):1847 hwnd = self._window2hwnd(window)1848 return 0 != self.evalPython("setTopWindow(%s)" %1849 (repr(hwnd),))1850 def sendShowWindow(self, window, showCmd):1851 hwnd = self._window2hwnd(window)1852 return self.evalPython("showWindow(%s, %s)" % (repr(hwnd), repr(showCmd)))1853 def sendType(self, text):1854 command = 'sendType(%s)' % (repr(text),)1855 self._agent.eval_in(self._agent_ns, command)1856 return True1857 def sendPress(self, keyCode, modifiers=None):1858 if modifiers == None:1859 command = 'sendKey(%r,[])' % (keyCode,)1860 else:...

Full Screen

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful