Best Python code snippet using fMBT_python
fmbtwindows.py
Source:fmbtwindows.py  
...921                  The default is "uiautomation".922                  You can define TreeWalker used by "uiautomation" by defining923                  viewSource as "uiautomation/raw", "uiautomation/control" or924                  "uiautomation/content".925                  See also setViewSource().926          items (list of view items, optional):927                  update only contents of these items in the view.928                  Works only for "uiautomation" view source.929          properties (list of property names, optional):930                  read only given properties from items, the default931                  is to read all available properties.932                  Works only for "uiautomation" view source.933                  See also setViewSource().934          area ((left, top, right, bottom), optional):935                  refresh only items that intersect the area.936                  The default is None: locations do not affect refreshed937                  items.938          filterType (string, optional):939                  specify how the widgets should be filtered.940                  Supported values are:941                  "none", which is the default, which means that all widgets942                  will be retrieved.943                  "first": only the first element which satisfy the condition944                  defined by the filterCondition parameter is returned.945                  "all": all elements which satisfy the condition defined by946                  the filterCondition parameter are returned.947                  "first" and "all" allow to specify an additional "+children"948                  qualifier, which returns also all element's children.949                  So, passing "first+children" as filterType, then the element950                  all its children are returned, if the element (and only it)951                  satisfy filterCondition.952                  It's import to underline that the conditions defined by the953                  items, properties, and area, parameters are still all954                  applied on top of filterType and filterCondition.955          filterCondition (string, optional):956                  specify the condition for filtering the widgets.957                  It only works if filterType is not "none".958                  Currently only a basic filter conditions are supported, that959                  allows to specify a property name, the == operator, and960                  a double-quoted string with the value to be compared.961                  Filter conditions can be chained together using the "and"962                  operator; this allows more fine-grained filtering.963                  For example:964                      'ClassName == "ToolBar" and Name == "Explorer"'965                  matches all widgets whose "ClassName" property is equal966                  to "ToolBar" and the Name is "Explorer".967                  The list of currently allowed properties is the following:968                  AutomationId, ClassName, HelpText, LabeledBy, Name.969          dumpChildClass (string, optional):970                if specified, only widgets of this class will be dumped /971                reported. Otherwise all widgets will be dumped (if no other972                dumping option is given. See below).973                For example, setting dumpChildClass to "TextBlock" will974                return only this kind of widgets.975                Imagine a big ListView, where a single ListViewItem is a976                complex container / panel which incorporates several widgets,977                but you don't want to dump all of them, and you're interested978                only to the ones which carry textual information.979                You can do this using the filtering options to catch the980                ListView widget and visiting all its children/descendants,981                but setting dumpChildClass will give back only the TextBlocks.982                So, this is quite different from the above filtering options,983                because filtering only defines how the UI widgets are984                traversed (and eventually cached), whereas dumping defines985                what widgets will be really reported back and collected by986                the view.987                Filtering reduces the amount of widgets that will be988                evaluated. On top of that, dumping reduces the number of989                widgets that will be returned back to the view.990          dumpChildName (string, optional):991                if specified, only widgets with this name will be dumped /992                reported. Otherwise all widgets will be dumped (if no other993                dumping option is given).994                It works exactly like dumpChildClass, but works on the Name995                property. So, the same logic applies.996                It can be combined with dumpChildClass to further reduce the997                number of returned widgets.998                For example, dumpChildName = "Foo" will give back all widgets999                which have "Foo" as Name.1000          doNotDump (boolean, optional):1001                if specified, no widgets will be dumped / reported, regarding1002                of all other dump options.1003                It's used to only cache the widgets in the server. All widgets1004                will be traversed and cached (if a cache option is defined).1005        See also setRefreshViewDefaults().1006        Returns View object.1007        """1008        if window == None:1009            window = self._refreshViewDefaults.get("window", None)1010        if forcedView == None:1011            forcedView = self._refreshViewDefaults.get("forcedView", None)1012        if viewSource == None:1013            viewSource = self.viewSource()1014        if not viewSource in _g_viewSources:1015            raise ValueError('invalid view source "%s"' % (viewSource,))1016        if items == None:1017            items = self._refreshViewDefaults.get("items", [])1018        if properties == None:1019            properties = self._refreshViewDefaults.get("properties", None)1020        if area == None:1021            area = self._refreshViewDefaults.get("area", None)1022        if forcedView != None:1023            retryCount = 01024            startTime = time.time()1025            lastStartTime = startTime1026            viewFilename = forcedView1027            if isinstance(forcedView, View):1028                self._lastView = forcedView1029            elif type(forcedView) in [str, unicode]:1030                try:1031                    self._lastView = View(1032                        forcedView, ast.literal_eval(file(viewFilename).read()),1033                        device=self, freeDumps=dumpChildClass or dumpChildName or doNotDump)1034                except Exception:1035                    self._lastView = None1036            endTime = time.time()1037        else:1038            viewFilename = self.getDumpFilename("view")1039            retryCount = 01040            startTime = time.time()1041            lastStartTime = startTime1042            while True:1043                try:1044                    topWindowBbox = self.topWindowProperties()['bbox']1045                except TypeError:1046                    topWindowBbox = None # top window unavailable1047                if area:1048                    leftTopRightBottom = (1049                        self.intCoords((area[0], area[1])) +1050                        self.intCoords((area[2], area[3])))1051                else:1052                    leftTopRightBottom = None1053                if viewSource == "enumchildwindows":1054                    viewData = self._conn.recvViewData(window)1055                else:1056                    if "/" in viewSource:1057                        walker = viewSource.split("/")[1]1058                    else:1059                        walker = "raw"1060                    if properties != None:1061                        if properties == "all":1062                            viewItemProperties = None1063                        elif properties == "fast":1064                            viewItemProperties = ["AutomationId",1065                                                   "BoundingRectangle",1066                                                   "ClassName",1067                                                   "HelpText",1068                                                   "ToggleState",1069                                                   "Value",1070                                                   "Minimum",1071                                                   "Maximum",1072                                                   "Name"]1073                        elif isinstance(properties, list) or isinstance(properties, tuple):1074                            viewItemProperties = list(properties)1075                        else:1076                            raise ValueError('invalid properties argument, expected "all", '1077                                             '"fast" or a list')1078                    else:1079                        viewItemProperties = properties1080                    viewData = self._conn.recvViewUIAutomation(1081                        window, items, viewItemProperties, leftTopRightBottom, walker,1082                        filterType, filterCondition, dumpChildClass, dumpChildName, doNotDump)1083                file(viewFilename, "w").write(repr(viewData))1084                try:1085                    self._lastView = View(1086                        viewFilename, viewData,1087                        itemOnScreen=lambda i: self.itemOnScreen(i, topWindowBbox=topWindowBbox),1088                        device=self, freeDumps=dumpChildClass or dumpChildName or doNotDump)1089                    break1090                except Exception, e:1091                    self._lastView = None1092                    _adapterLog(1093                        "refreshView %s failed (%s), source=%s topWindow=%s" %1094                        (retryCount, e, repr(viewSource), self.topWindow()))1095                    retryCount += 11096                    if retryCount < self._refreshViewRetryLimit:1097                        time.sleep(0.2)1098                    else:1099                        break1100                lastStartTime = time.time()1101            endTime = time.time()1102        itemCount = -11103        if self._lastView:1104            itemCount = len(self._lastView._viewItems)1105        self._lastViewStats = {1106            "retries": retryCount,1107            "timestamp": endTime,1108            "total time": endTime - startTime,1109            "last time": endTime - lastStartTime,1110            "filename": viewFilename,1111            "source": viewSource,1112            "forced": (forcedView != None),1113            "window": window,1114            "view": str(self._lastView),1115            "item count": itemCount}1116        return self._lastView1117    def refreshViewDefaults(self):1118        """Returns default arguments for refreshView() calls.1119        See also setRefreshViewDefaults().1120        """1121        return dict(self._refreshViewDefaults)1122    def setClipboard(self, data):1123        """1124        Set text on clipboard1125        Parameters:1126          data (string):1127                  data to be set on the clipboard.1128        Note: any type of data on clipboard will be emptied.1129        See also: getClipboard()1130        """1131        return self.existingConnection().evalPython(1132            "setClipboardText(%s)" % (repr(data),))1133    def setErrorReporting(self, settings):1134        """1135        Modify Windows error reporting settings (WER)1136        Parameters:1137          settings (dictionary):1138                  WER settings and values to be set.1139        Example: disable showing interactive crash dialogs1140          setErrorReporting({"DontShowUI": 1})1141        See also: errorReporting(),1142                  MSDN WER Settings.1143        """1144        for setting in settings:1145            self.setRegistry(1146                r"HKEY_CURRENT_USER\Software\Microsoft\Windows\Windows Error Reporting",1147                setting, settings[setting])1148        return True1149    def setDisplaySize(self, size):1150        """1151        Transform coordinates of synthesized events (like a tap) from1152        screenshot resolution to display input area size. By default1153        events are synthesized directly to screenshot coordinates.1154        Parameters:1155          size (pair of integers: (width, height)):1156                  width and height of display in pixels. If not given,1157                  values from EnumDisplayMonitors are used.1158        Returns None.1159        """1160        width, height = size1161        screenWidth, screenHeight = self.screenSize()1162        self._conn.setScreenToDisplayCoords(1163            lambda x, y: (x * width / screenWidth,1164                          y * height / screenHeight))1165        self._conn.setDisplayToScreenCoords(1166            lambda x, y: (x * screenWidth / width,1167                          y * screenHeight / height))1168    def setForegroundWindow(self, window):1169        """1170        Set a window with the title as a foreground window1171        Parameters:1172          window (title (string) or hwnd (integer):1173                  title or handle of the window to be raised1174                  foreground.1175        Returns True if the window was brought to the foreground,1176        otherwise False.1177        Notes: calls SetForegroundWindow in user32.dll.1178        """1179        return self.existingConnection().sendSetForegroundWindow(window)1180    def setRefreshViewDefaults(self, **kwargs):1181        """Set new default arguments for refreshView() calls1182        Parameters:1183          **kwargs (keyword arguments)1184                  new default values for optional refreshView() parameters.1185        Note: default arguments are overridden by arguments given1186        directly in refreshView calls.1187        Note: setViewSource() can change the default arguments.1188        Example:1189          setRefreshViewDefaults(window="My app title",1190                                 viewSource="uiautomation/content")1191        """1192        self._refreshViewDefaults = kwargs1193    def findRegistry(self, rootKey, key=None, valueName=None, limit=1):1194        """Search for key and/or valueName from the registry.1195        Returns a list of matching (fullKeyPath, valueName) pairs1196        found under the rootKey. The list has at most limit items, the1197        default is 1.1198        Parameters:1199          rootKey (string):1200                  root key path for the search. Example:1201                  "HKEY_LOCAL_MACHINE".1202          key (string, optional):1203                  key name to be searched for under the rootKey.1204                  The key is a regular expression that is searched for1205                  from full key path. Use "\\name$" to require exact1206                  match.1207                  If not given, valueName should be defined.1208          valueName (string, optional):1209                  value name to be searched for under the rootKey.1210                  The value can be a regular expression.1211                  If not given, key should be defined and1212                  returned valueName will be None.1213          limit (integer, optional):1214                  maximum number of matches to be returned. The1215                  default is 1. limit=None returns all matching1216                  pairs.1217        Example:1218          findRegistry("HKEY_LOCAL_MACHINE", key="\\Windows$")1219        """1220        if key == None and valueName == None:1221            raise ValueError("either key or valueName must be provided")1222        return self.existingConnection().evalPython(1223            'findRegistry(%s, key=%s, valueName=%s, limit=%s)' % (1224                repr(rootKey), repr(key), repr(valueName), repr(limit)))1225    def setRegistry(self, key, valueName, value, valueType=None):1226        """1227        Set Windows registry value.1228        Parameters:1229          key (string):1230                  full key name.1231          valueName (string):1232                  name of the value to be set.1233          value (string):1234                  string that specifies the new value.1235          valueType (string, optional for str and int values):1236                  REG_BINARY, REG_DWORD, REG_DWORD_LITTLE_ENDIAN,1237                  REG_DWORD_BIG_ENDIAN, REG_EXPAND_SZ, REG_LINK,1238                  REG_MULTI_SZ, REG_NONE, REG_RESOURCE_LIST or REG_SZ.1239                  Default types for storing str and int values1240                  are REG_SZ and REG_DWORD.1241        Example:1242          setRegistry(r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet"1243                       "\Control\Session Manager\Environment",1244                       "PATH", r"C:\MyExecutables", "REG_EXPAND_SZ")1245        Returns True on success.1246        """1247        return self.existingConnection().evalPython(1248            "setRegistry(%s,%s,%s,%s)" % (repr(key), repr(valueName),1249                                          repr(value), repr(valueType)))1250    def getRegistry(self, key, valueName):1251        """1252        Return Windows registry value and type1253        Parameters:1254          key (string):1255                  full key name.1256          valueName (string):1257                  name of the value to be read.1258        Returns a pair (value, valueType)1259        Example:1260          getRegistry(r"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet"1261                       "\Control\Session Manager\Environment", "PATH")1262        """1263        return self.existingConnection().evalPython(1264            "getRegistry(%s,%s)" % (repr(key), repr(valueName)))1265    def processList(self):1266        """1267        Return list of processes running on the device.1268        Returns list of dictionaries with keys:1269          "pid": process ID, and1270          "ProcessImageFileName": full path to the executable in win32 format.1271        """1272        return self.existingConnection().evalPython("processList()")1273    def processStatus(self, pid):1274        """1275        Return status of a process1276        Parameters:1277          pid (integer):1278                  Process ID of the process1279        Returns properties in a dictionary.1280        Example:1281          print "Memory usage:", processStatus(4242)["WorkingSetSize"]1282        """1283        return self.existingConnection().evalPython(1284            "processStatus(%s)" % (repr(pid),))1285    def productList(self):1286        """1287        Return list of products installed or advertised in the system1288        Returns list of dictionaries, each containing properties of a product.1289        """1290        return self.existingConnection().evalPython("products()")1291    def pycosh(self, command):1292        """1293        Run command in pycosh shell on the device.1294        Parameters:1295          command (string):1296                  pycosh command to be executed. Pycosh implements1297                  stripped-down versions of zip, tar, find, md5sum, diff,1298                  grep, head, tail, curl,... the usual handy shell utils.1299                  For information on pycosh commands, try1300                  device.pycosh("help") or run in shell:1301                  echo help | python -m pycosh.1302        """1303        return self.existingConnection().pycosh(command)1304    def setScreenshotSize(self, size):1305        """1306        Force screenshots from device to use given resolution.1307        Overrides detected monitor resolution on device.1308        Parameters:1309          size (pair of integers: (width, height)):1310                  width and height of screenshot.1311        """1312        self._conn.setScreenshotSize(size)1313    def setTopWindow(self, window):1314        """1315        Set a window as a foreground window and bring it to front.1316        Parameters:1317          window (title (string) or hwnd (integer):1318                  title or handle of the window to be raised1319                  foreground.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....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!!
