Best Python code snippet using pyatom_python
utils.py
Source:utils.py
...433 label = ''434 return abbreviated_roles.get(role, 'ukn'), \435 label, \436 label_by437 def _glob_match(self, pattern, string):438 """439 Match given string, by escaping regex characters440 """441 # regex flags Multi-line, Unicode, Locale442 return bool(re_match(glob_trans(pattern), string,443 re.M | re.U | re.L))444 def _match_name_to_acc(self, name, acc, classType = None):445 """446 Match given name with acc.name / acc.associate name447 and also class type448 @param name: Label to be matched449 @type name: string450 @param acc: Accessibility handle451 @type acc: object452 @param classType: role name453 @type classType: string454 @return: Return 0 on failure, 1 on successful match455 @rtype: integer456 """457 if not acc or not name:458 return 0459 try:460 if classType:461 # Accessibility role type returns space, when multiple462 # words exist in object type. ex: 'push button'463 # User might mistype with multiple space, to avoid464 # any confusion, using _. So, user will be inputing465 # push_button466 roleName = acc.getRoleName().replace(' ', '_')467 else:468 roleName = None469 if roleName != classType:470 # If type doesn't match, don't proceed further471 return 0472 if acc.name:473 try:474 _acc_name="%s" % acc.name475 except UnicodeDecodeError:476 _acc_name=acc.name.decode('utf-8')477 if acc.name and re.match(fnmatch.translate(name), _acc_name, re.M | re.U):478 # Since, type already matched and now the given name479 # and accessibile name matched, mission accomplished480 return 1481 except:482 # In at-spi2 gi._glib.GError exception is thrown483 return 0484 # Get LDTP format accessibile name485 _ldtpize_accessible_name = self._ldtpize_accessible(acc)486 # Concat object type and object name487 # ex: 'frmUnsavedDocument1-gedit' for Gedit application488 # frm - Frame, Window title - 'Unsaved Document 1 - gedit'489 try:490 _object_name = '%s%s' % (_ldtpize_accessible_name[0],491 _ldtpize_accessible_name[1])492 except UnicodeDecodeError:493 _object_name = '%s%s' % (_ldtpize_accessible_name[0],494 _ldtpize_accessible_name[1].decode('utf-8'))495 if self._glob_match(name, acc.name):496 # If given name match object name with regexp497 return 1498 if self._glob_match(name, _object_name):499 # If given name match LDTPized name format with regexp500 return 1501 try:502 role = acc.getRole()503 except:504 # In at-spi2 acc doesn't exist505 # which raises exception gi._glib.GError506 return 0507 if role == pyatspi.ROLE_FRAME or role == pyatspi.ROLE_DIALOG or \508 role == pyatspi.ROLE_WINDOW or \509 role == pyatspi.ROLE_FONT_CHOOSER or \510 role == pyatspi.ROLE_FILE_CHOOSER or \511 role == pyatspi.ROLE_ALERT or \512 role == pyatspi.ROLE_COLOR_CHOOSER:513 # If window type, strip using this format514 strip = '( |\n)'515 else:516 # If any other type, strip using this format517 strip = '( |:|\.|_|\n)'518 # Strip given name too, as per window type or other type519 _tmp_name = re.sub(strip, '', name)520 if self._glob_match(_tmp_name, _object_name):521 # Match stripped given name and LDTPized name522 return 1523 if self._glob_match(_tmp_name, _ldtpize_accessible_name[1]):524 # Match stripped given name and LDTPized name, without object type525 # ex: UnsavedDocument1-gedit, without frm at start526 return 1527 # If nothing matches, the search criteria fails, to find the object528 return 0529 def _match_obj_type(self, class_type, obj_types):530 if not obj_types:531 # obj_types is []532 return True533 for obj_type in obj_types:534 if obj_type == class_type:535 return True536 return False537 def _match_name_to_appmap(self, name, acc, obj_type=[]):538 if not name:539 return 0540 is_obj_type=self._match_obj_type(acc['class'], obj_type)541 if not is_obj_type:542 return 0543 if self._glob_match(name, acc['key']):544 return 1545 if self._glob_match(name, acc['obj_index']):546 return 1547 if self._glob_match(name, acc['label_by']):548 return 1549 if self._glob_match(name, acc['label']):550 return 1551 # Strip space and look for object552 obj_name = '%s' % re.sub(' ', '', name)553 role = acc['class']554 if role == 'frame' or role == 'dialog' or \555 role == 'window' or \556 role == 'font_chooser' or \557 role == 'file_chooser' or \558 role == 'alert' or \559 role == 'color_chooser':560 strip = '( |\n)'561 else:562 strip = '( |:|\.|_|\n)'563 obj_name = re.sub(strip, '', name)564 if acc['label_by']:565 _tmp_name = re.sub(strip, '', acc['label_by'])566 if self._glob_match(obj_name, _tmp_name):567 return 1568 if acc['label']:569 _tmp_name = re.sub(strip, '', acc['label'])570 if self._glob_match(obj_name, _tmp_name):571 return 1572 if self._glob_match(obj_name, acc['key']):573 return 1574 return 0575 def _list_objects(self, obj):576 if obj:577 yield obj578 for child in obj:579 if not self._handle_table_cell and \580 child.getRole() == pyatspi.ROLE_TABLE_CELL:581 # In OO.o navigating table cells consumes more time582 # resource583 break584 for c in self._list_objects(child):585 # Don't include separators in the list586 if c.getRole() != pyatspi.ROLE_SEPARATOR:587 yield c588 def _get_combo_child_object_type(self, obj):589 """590 This function will check for all levels and returns the first591 matching LIST / MENU type592 """593 if not obj:594 return595 for child in obj:596 if not child:597 continue598 if child.childCount > 0:599 child_obj = self._get_combo_child_object_type(child)600 if child_obj:601 return child_obj602 if child.getRole() == pyatspi.ROLE_LIST:603 return child604 elif child.getRole() == pyatspi.ROLE_MENU:605 return child606 def _get_child_object_type(self, obj, role_type):607 """608 This function will check for all levels and returns the first609 matching role_type610 """611 if not obj or not role_type:612 return613 for child in obj:614 if not child:615 continue616 if child.childCount > 0:617 child_obj = self._get_child_object_type(child, role_type)618 if child_obj:619 return child_obj620 if child.getRole() == role_type:621 return child622 def _add_appmap_data(self, obj, parent, child_index):623 if not obj:624 return None625 abbrev_role, abbrev_name, label_by = self._ldtpize_accessible(obj)626 if abbrev_role in self.ldtpized_obj_index:627 self.ldtpized_obj_index[abbrev_role] += 1628 else:629 self.ldtpized_obj_index[abbrev_role] = 0630 if abbrev_name == '':631 ldtpized_name_base = abbrev_role632 ldtpized_name = '%s%d' % (ldtpized_name_base,633 self.ldtpized_obj_index[abbrev_role])634 else:635 ldtpized_name_base = '%s%s' % (abbrev_role, abbrev_name)636 ldtpized_name = ldtpized_name_base637 i = 0638 while ldtpized_name in self.ldtpized_list:639 i += 1640 ldtpized_name = '%s%d' % (ldtpized_name_base, i)641 if parent in self.ldtpized_list:642 _current_children = self.ldtpized_list[parent]['children']643 if _current_children:644 _current_children = '%s %s' % (_current_children, ldtpized_name)645 else:646 _current_children = ldtpized_name647 self.ldtpized_list[parent]['children'] = _current_children648 if not label_by:649 label_by = ''650 key_binding = ''651 try:652 iaction = obj.queryAction()653 for j in xrange(iaction.nActions):654 if iaction.getKeyBinding(j) != '':655 key_binding = iaction.getKeyBinding(j)656 break657 except NotImplementedError:658 pass659 role = obj.getRole()660 if role == pyatspi.ROLE_FRAME or role == pyatspi.ROLE_DIALOG or \661 role == pyatspi.ROLE_WINDOW or \662 role == pyatspi.ROLE_FONT_CHOOSER or \663 role == pyatspi.ROLE_FILE_CHOOSER or \664 role == pyatspi.ROLE_ALERT or \665 role == pyatspi.ROLE_COLOR_CHOOSER:666 obj_index = '%s#%d' % (obj.getApplication().name,667 obj.getIndexInParent())668 else:669 obj_index = '%s#%d' % (abbrev_role,670 self.ldtpized_obj_index[abbrev_role])671 self.ldtpized_list[ldtpized_name] = {'key' : ldtpized_name,672 'parent' : parent,673 'class' : obj.getRoleName().replace(' ', '_'),674 'child_index' : child_index,675 'children' : '',676 'obj_index' : obj_index,677 'label' : obj.name,678 'label_by' : label_by,679 'description' : obj.description,680 'key_binding' : key_binding681 }682 return ldtpized_name683 def _populate_appmap(self, obj, parent, child_index):684 index = -1685 if obj:686 if child_index != -1:687 parent = self._add_appmap_data(obj, parent, child_index)688 # Have noticed using obj.getIndexInParent()689 # returns -1, let the loop counts the child index690 for child in obj:691 index += 1692 if not child:693 continue694 try:695 if not self._handle_table_cell and \696 child.getRole() == pyatspi.ROLE_TABLE_CELL:697 break698 except:699 # Some object bailed out700 continue701 self._populate_appmap(child, parent, index)702 def _appmap_pairs(self, gui, window_name, force_remap = False):703 self.ldtpized_list = {}704 self.ldtpized_obj_index = {}705 if not force_remap:706 self._atspi2_workaround()707 for app in self.cached_apps:708 try:709 if app[0] and gui and app[0] == gui.parent and \710 app[1] == True:711 # Means force_remap712 force_remap = True713 index = self.cached_apps.index(app)714 if index != -1:715 # Reset force_remap to False716 self.cached_apps[index][1] = False717 break718 except NameError:719 continue720 # If force_remap set in the above condition, skip the721 # following lookup and do force remap722 if not force_remap:723 for key in self._appmap.keys():724 if self._match_name_to_acc(key, gui):725 return self._appmap[key]726 if gui and gui.parent:727 abbrev_role, abbrev_name, label_by = self._ldtpize_accessible(gui.parent)728 _parent = abbrev_name729 else:730 _parent = ''731 try:732 self._populate_appmap(gui, _parent, gui.getIndexInParent())733 except LookupError:734 raise LdtpServerException("Unable to find window/object")735 self._appmap[window_name] = self.ldtpized_list736 return self.ldtpized_list737 def _get_menu_hierarchy(self, window_name, object_name,738 strict_hierarchy = False, wait = True):739 _menu_hierarchy = re.split(';', object_name)740 if strict_hierarchy and len(_menu_hierarchy) <= 1:741 # If strict_hierarchy is set and _menu_hierarchy doesn't have742 # hierarchy menu's with ; seperated, then raise exception743 # Fixes bug #590111 - It would be nice if doesmenuexist could744 # search for strict hierarchies745 raise LdtpServerException("Invalid menu hierarchy input")746 if not re.search('^mnu', _menu_hierarchy[0], re.M | re.U):747 # Add mnu to the first object, if it doesn't exist748 _menu_hierarchy[0] = 'mnu%s' % _menu_hierarchy[0]749 obj = self._get_object(window_name, _menu_hierarchy[0], wait)750 for _menu in _menu_hierarchy[1:]:751 _flag = False752 for _child in self._list_objects(obj):753 if obj == _child:754 # if the given object and child object matches, as755 # the _list_objects return object as one of the _child756 continue757 if self._match_name_to_acc(_menu, _child):758 _flag = True759 obj = _child760 break761 if not _flag:762 raise LdtpServerException(763 'Menu item "%s" doesn\'t exist in hierarchy' % _menu)764 return obj765 def _click_object(self, obj, action = '(click|press|activate)'):766 try:767 iaction = obj.queryAction()768 except NotImplementedError:769 raise LdtpServerException(770 'Object does not have an Action interface')771 else:772 for i in xrange(iaction.nActions):773 if self._ldtp_debug:774 print(iaction.getName(i))775 if re.match(action, iaction.getName(i), re.I):776 iaction.doAction(i)777 return778 raise LdtpServerException('Object does not have a "%s" action' % action)779 def _get_object_in_window(self, appmap, obj_name, obj_type=[]):780 """781 Get object in appmap dict format, eg: {'class' : 'menu', 'key': 'mnu0'}782 @param appmap: application map of window (list of dict)783 @type appmap: object784 @param obj_name: Object name785 @type obj_name: string786 @return: object in appmap dict format787 @rtype: object788 """789 for name in appmap.keys():790 obj = appmap[name]791 if self._match_name_to_appmap(obj_name, obj, obj_type):792 return obj793 return None794 def _get_window_handle(self, window_name, wait=False):795 """796 Get window handle of given window name797 @param window_name: window name, as provided by the caller798 @type window_name: string799 @return: window handle, window name in appmap format800 @rtype: object, string801 """802 if wait:803 retry=self._gui_timeout804 else:805 retry=1806 for i in range(retry):807 gui, name = self._internal_get_window_handle(window_name)808 if gui:809 return gui, name810 if wait:811 time.sleep(1)812 return None, None813 def _internal_get_window_handle(self, window_name):814 """815 Get internal window handle of given window name816 @param window_name: window name, as provided by the caller817 @type window_name: string818 @return: window handle, window name in appmap format819 @rtype: object, string820 """821 window_list = []822 window_type = {}823 for gui in self._list_guis():824 if not gui:825 continue826 obj_name = self._ldtpize_accessible(gui)827 if obj_name[1] == '':828 # If label / label_by is empty string829 # use index830 if obj_name[0] in window_type:831 # If the same window type repeats832 # eg: multiple dialog window with empty title833 # then use, dlg0, dlg1, dlg2 etc834 window_type[obj_name[0]] += 1835 else:836 # Initialize the first window in a type as 0837 # and increment this counter838 window_type[obj_name[0]] = 0839 tmp_name = '%d' % window_type[obj_name[0]]840 else:841 # If window has title, use that842 tmp_name = obj_name[1]843 # Append window type and window title844 try:845 w_name = name = '%s%s' % (obj_name[0], tmp_name)846 except UnicodeDecodeError:847 w_name = name = '%s%s' % (obj_name[0], tmp_name.decode('utf-8'))848 # If multiple window with same title, increment the index849 index = 1850 while name in window_list:851 # If window name already exist in list, increase852 # the index, so that we will have the window name853 # always unique854 name = '%s%d' % (w_name, index)855 index += 1856 window_list.append(name)857 if self._match_name_to_acc(window_name, gui):858 return gui, name859 # Search with LDTP appmap format860 if window_name.find('#') != -1:861 obj_index = '%s#%d' % (gui.getApplication().name,862 gui.getIndexInParent())863 if self._ldtp_debug:864 print('Window name has #', window_name, obj_index)865 if self._ldtp_debug_file:866 with open(self._ldtp_debug_file, "a") as fp:867 fp.write('Window name has # %s %d', window_name, obj_index)868 if window_name == obj_index:869 if self._ldtp_debug:870 print('Window found', gui, name)871 return gui, name872 if window_name == name:873 if self._ldtp_debug:874 print('Window found', gui, name)875 return gui, name876 if self._glob_match(window_name, name):877 if self._ldtp_debug:878 print('Window found', gui, name)879 return gui, name880 if self._glob_match(re.sub(' ', '', window_name),881 re.sub(' ', '', name)):882 if self._ldtp_debug:883 print('Window found', gui, name)884 return gui, name885 return None, None886 def _get_object(self, window_name, obj_name, wait=True,887 obj_type = []):888 _window_handle, _window_name = \889 self._get_window_handle(window_name, wait)890 if not _window_handle:891 raise LdtpServerException('Unable to find window "%s"' % \892 window_name)893 if wait:894 retry=self._obj_timeout...
maskmatch2.py
Source:maskmatch2.py
...28 if pattern[i:]:29 out += pattern[i]30 i += 131 return out32def _glob_match(pattern, s):33 i, j = 0, 034 i_backup = -135 j_backup = -136 while j < len(s):37 p = (pattern[i:] or [None])[0]38 if p == "*":39 i += 140 i_backup = i41 j_backup = j42 elif p in ["?", s[j]]:43 i += 144 j += 145 else:46 if i_backup == -1:47 return False48 else:49 j_backup += 150 j = j_backup51 i = i_backup52 return i == len(pattern)53def _multi_replace(s, upper, lower):54 s_l = list(s)55 for i, char in enumerate(s):56 if char in upper:57 s_l[i] = lower[upper.index(char)]58 return "".join(s_l)59ASCII_UPPER = list(string.ascii_uppercase)60ASCII_LOWER = list(string.ascii_lowercase)61RFC1459_UPPER = ASCII_UPPER+list("[]~\\")62RFC1459_LOWER = ASCII_LOWER+list("{}^|")63def _fold_rfc1459(s):64 return _multi_replace(s, RFC1459_UPPER, RFC1459_LOWER)65def _fold_ascii(s):66 return _multi_replace(s, ASCII_UPPER, ASCII_LOWER)67def _fold(casemap, s):68 if casemap == "rfc1459":69 return _fold_rfc1459(s)70 elif casemap == "ascii":71 return _fold_ascii(s)72 else:73 raise ValueError(f"Unknown casemap {casemap}")74def _mode_tokens(modes, args, prefix, chanmodes):75 mode_a, mode_b, mode_c, mode_d = chanmodes76 arg_add = mode_a+mode_b+mode_c77 arg_remove = mode_a+mode_b78 add = True79 out = []80 for char in modes:81 if char in "+-":82 add = char == "+"83 elif char in prefix:84 args.pop(0) # discard!85 elif args:86 if add:87 has_arg = char in arg_add88 else:89 has_arg = char in arg_remove90 if has_arg:91 if char in mode_a:92 out.append((add, char, args.pop(0)))93 else:94 args.pop(0)95 return out96def _user_masks(server, channel, casemap):97 infolist = w.infolist_get("irc_nick", "", f"{server},{channel}")98 out = {}99 while w.infolist_next(infolist):100 name = w.infolist_string(infolist, "name")101 host = w.infolist_string(infolist, "host")102 user, host = host.split("@", 1)103 real = w.infolist_string(infolist, "realname")104 acc = w.infolist_string(infolist, "account")105 masks = []106 fold_name = _fold(casemap, f"{name}!{user}")107 fold_host = _fold(casemap, host)108 fold_real = _fold(casemap, real)109 masks.append((False, fold_name, fold_host))110 masks.append((True, f"$x:{fold_name}#{fold_real}", fold_host))111 masks.append((True, f"$r:{fold_real}", None))112 if acc:113 fold_account = _fold(casemap, acc)114 masks.append((True, f"$a:{fold_account}", None))115 out[name] = masks116 w.infolist_free(infolist)117 return out118def _unique_masks(casemap, masks):119 seen = set([])120 unique_masks = []121 for orig_mask in masks:122 extban = False123 if orig_mask[0] == "$":124 extban = True125 prefix, sep, mask = orig_mask.partition(":")126 mask = prefix + sep + _fold(casemap, mask)127 else:128 mask = _fold(casemap, orig_mask)129 if "@" in mask:130 mask, _, host = mask.partition("@")131 host, sep, real = host.partition("#")132 mask += sep + real133 else:134 host = None135 mask = _glob_collapse(mask)136 if not (mask, host) in seen:137 seen.add((mask, host))138 unique_masks.append((extban, mask, host, orig_mask))139 return unique_masks140def _unique_mode_masks(casemap, mode_tokens):141 masks = []142 for add, mode, mode_arg in mode_tokens:143 masks.append(mode_arg)144 return _unique_masks(casemap, masks)145def _try_ip(ip):146 try:147 return ip_address(ip)148 except ValueError:149 return None150def _to_cidr(host):151 if (host is not None and152 host.count("/") == 1):153 host, cidr = host.split("/")154 if cidr.isdigit():155 cidr = int(cidr)156 ip = _try_ip(host)157 if ip is not None:158 rcidr = ip.max_prefixlen-cidr159 return int(ip)>>rcidr, rcidr160 return None, None161def _match_one(extban, mask, host, users_masks):162 affected = []163 cidr_ip, rcidr = _to_cidr(host)164 for nickname in sorted(users_masks.keys()):165 user_masks = users_masks[nickname]166 for user_extban, user_mask, user_host in user_masks:167 if ((not extban or user_extban) and168 _glob_match(mask, user_mask)):169 if cidr_ip is not None:170 ip = _try_ip(user_host)171 if (ip is not None and172 int(ip)>>rcidr == cidr_ip):173 affected.append(nickname)174 break175 elif (host is not None and176 user_host is not None and177 _glob_match(host, user_host)):178 affected.append(nickname)179 break180 elif (host is None and181 user_host is None):182 affected.append(nickname)183 break184 return affected185def _match_many(masks, users_masks):186 matches = {}187 for extban, mask, host, orig_mask in masks:188 affected = _match_one(extban, mask, host, users_masks)189 for nickname in affected:190 if not orig_mask in matches:191 matches[orig_mask] = []...
source.py
Source:source.py
...33 val = getattr(item, key)34 return val == value35 except KeyError:36 return False37 def _glob_match(self, key, value, item):38 try:39 val = getattr(item, key)40 return fnmatch.fnmatch(val.lower(), value)41 except KeyError:42 return False43 def _type_match(self, key, value, item):44 _map = {45 'source': lambda x: isinstance(x, arroyo.Source),46 'episode': lambda x: x.entity and isinstance(x.entity, arroyo.Episode),47 'movie': lambda x: x.entity and isinstance(x.entity, arroyo.Movie),48 }49 try:50 return _map[value](item)51 except KeyError:...
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!!