Best Python code snippet using Airtest
matching.py
Source:matching.py  
...245            self.add_check(self.names[varname] + " == " + item)246        else:247            set_name_var = self.register_name(varname, item)248            self.add_def(set_name_var + " = " + item)249    def match_all_in(self, matches, item):250        """Matches all matches to elements of item."""251        for i, match in enumerate(matches):252            self.match(match, item + "[" + str(i) + "]")253    def check_len_in(self, min_len, max_len, item):254        """Checks that the length of item is in range(min_len, max_len+1)."""255        if max_len is None:256            if min_len:257                self.add_check("_coconut.len(" + item + ") >= " + str(min_len))258        elif min_len == max_len:259            self.add_check("_coconut.len(" + item + ") == " + str(min_len))260        elif not min_len:261            self.add_check("_coconut.len(" + item + ") <= " + str(max_len))262        else:263            self.add_check(str(min_len) + " <= _coconut.len(" + item + ") <= " + str(max_len))264    def match_function(self, args, kwargs, pos_only_match_args=(), match_args=(), star_arg=None, kwd_only_match_args=(), dubstar_arg=None):265        """Matches a pattern-matching function."""266        # before everything, pop the FunctionMatchError from context267        self.add_def(function_match_error_var + " = _coconut_get_function_match_error()")268        with self.down_a_level():269            self.match_in_args_kwargs(pos_only_match_args, match_args, args, kwargs, allow_star_args=star_arg is not None)270            if star_arg is not None:271                self.match(star_arg, args + "[" + str(len(match_args)) + ":]")272            self.match_in_kwargs(kwd_only_match_args, kwargs)273            with self.down_a_level():274                if dubstar_arg is None:275                    self.add_check("not " + kwargs)276                else:277                    self.match(dubstar_arg, kwargs)278    def match_in_args_kwargs(self, pos_only_match_args, match_args, args, kwargs, allow_star_args=False):279        """Matches against args or kwargs."""280        req_len = 0281        arg_checks = {}282        to_match = []  # [(move_down, match, against)]283        for i, arg in enumerate(pos_only_match_args + match_args):284            if isinstance(arg, tuple):285                (match, default) = arg286            else:287                match, default = arg, None288            if i < len(pos_only_match_args):  # faster if arg in pos_only_match_args289                names = None290            else:291                names = get_match_names(match)292            if default is None:293                if not names:294                    req_len = i + 1295                    to_match.append((False, match, args + "[" + str(i) + "]"))296                else:297                    arg_checks[i] = (298                        # if i < req_len299                        " and ".join('"' + name + '" not in ' + kwargs for name in names),300                        # if i >= req_len301                        "_coconut.sum((_coconut.len(" + args + ") > " + str(i) + ", "302                        + ", ".join('"' + name + '" in ' + kwargs for name in names)303                        + ")) == 1",304                    )305                    tempvar = self.get_temp_var()306                    self.add_def(307                        tempvar + " = "308                        + args + "[" + str(i) + "] if _coconut.len(" + args + ") > " + str(i) + " else "309                        + "".join(310                            kwargs + '.pop("' + name + '") if "' + name + '" in ' + kwargs + " else "311                            for name in names[:-1]312                        )313                        + kwargs + '.pop("' + names[-1] + '")',314                    )315                    to_match.append((True, match, tempvar))316            else:317                if not names:318                    tempvar = self.get_temp_var()319                    self.add_def(tempvar + " = " + args + "[" + str(i) + "] if _coconut.len(" + args + ") > " + str(i) + " else " + default)320                    to_match.append((True, match, tempvar))321                else:322                    arg_checks[i] = (323                        # if i < req_len324                        None,325                        # if i >= req_len326                        "_coconut.sum((_coconut.len(" + args + ") > " + str(i) + ", "327                        + ", ".join('"' + name + '" in ' + kwargs for name in names)328                        + ")) <= 1",329                    )330                    tempvar = self.get_temp_var()331                    self.add_def(332                        tempvar + " = "333                        + args + "[" + str(i) + "] if _coconut.len(" + args + ") > " + str(i) + " else "334                        + "".join(335                            kwargs + '.pop("' + name + '") if "' + name + '" in ' + kwargs + " else "336                            for name in names337                        )338                        + default,339                    )340                    to_match.append((True, match, tempvar))341        max_len = None if allow_star_args else len(pos_only_match_args) + len(match_args)342        self.check_len_in(req_len, max_len, args)343        for i in sorted(arg_checks):344            lt_check, ge_check = arg_checks[i]345            if i < req_len:346                if lt_check is not None:347                    self.add_check(lt_check)348            else:349                if ge_check is not None:350                    self.add_check(ge_check)351        for move_down, match, against in to_match:352            if move_down:353                with self.down_a_level():354                    self.match(match, against)355            else:356                self.match(match, against)357    def match_in_kwargs(self, match_args, kwargs):358        """Matches against kwargs."""359        for match, default in match_args:360            names = get_match_names(match)361            if not names:362                raise CoconutDeferredSyntaxError("keyword-only pattern-matching function arguments must be named", self.loc)363            tempvar = self.get_temp_var()364            self.add_def(365                tempvar + " = "366                + "".join(367                    kwargs + '.pop("' + name + '") if "' + name + '" in ' + kwargs + " else "368                    for name in names369                )370                + (default if default is not None else "_coconut_sentinel"),371            )372            with self.down_a_level():373                if default is None:374                    self.add_check(tempvar + " is not _coconut_sentinel")375                self.match(match, tempvar)376    def match_dict(self, tokens, item):377        """Matches a dictionary."""378        internal_assert(1 <= len(tokens) <= 2, "invalid dict match tokens", tokens)379        if len(tokens) == 1:380            matches, rest = tokens[0], None381        else:382            matches, rest = tokens383        self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Mapping)")384        if rest is None:385            self.rule_conflict_warn(386                "ambiguous pattern; could be Coconut-style len-checking dict match or Python-style len-ignoring dict match",387                if_coconut='resolving to Coconut-style len-checking dict match by default',388                if_python='resolving to Python-style len-ignoring dict match due to Python-style "match: case" block',389                extra="use explicit '{..., **_}' or '{..., **{}}' syntax to dismiss",390            )391            check_len = not self.using_python_rules392        elif rest == "{}":393            check_len = True394            rest = None395        else:396            check_len = False397        if check_len:398            self.add_check("_coconut.len(" + item + ") == " + str(len(matches)))399        seen_keys = set()400        for k, v in matches:401            if k in seen_keys:402                raise CoconutDeferredSyntaxError("duplicate key {k!r} in dictionary pattern".format(k=k), self.loc)403            seen_keys.add(k)404            key_var = self.get_temp_var()405            self.add_def(key_var + " = " + item + ".get(" + k + ", _coconut_sentinel)")406            with self.down_a_level():407                self.add_check(key_var + " is not _coconut_sentinel")408                self.match(v, key_var)409        if rest is not None and rest != wildcard:410            match_keys = [k for k, v in matches]411            with self.down_a_level():412                self.add_def(413                    rest + " = dict((k, v) for k, v in "414                    + item + ".items() if k not in set(("415                    + ", ".join(match_keys) + ("," if len(match_keys) == 1 else "")416                    + ")))",417                )418    def assign_to_series(self, name, series_type, item):419        """Assign name to item converted to the given series_type."""420        if self.using_python_rules or series_type == "[":421            self.add_def(name + " = _coconut.list(" + item + ")")422        elif series_type == "(":423            self.add_def(name + " = _coconut.tuple(" + item + ")")424        else:425            raise CoconutInternalException("invalid series match type", series_type)426    def match_implicit_tuple(self, tokens, item):427        """Matches an implicit tuple."""428        return self.match_sequence(["(", tokens], item)429    def match_sequence(self, tokens, item):430        """Matches a sequence."""431        internal_assert(2 <= len(tokens) <= 3, "invalid sequence match tokens", tokens)432        tail = None433        if len(tokens) == 2:434            series_type, matches = tokens435        else:436            series_type, matches, tail = tokens437        self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")438        if tail is None:439            self.add_check("_coconut.len(" + item + ") == " + str(len(matches)))440        else:441            self.add_check("_coconut.len(" + item + ") >= " + str(len(matches)))442            if tail != wildcard:443                if len(matches) > 0:444                    splice = "[" + str(len(matches)) + ":]"445                else:446                    splice = ""447                self.assign_to_series(tail, series_type, item + splice)448        self.match_all_in(matches, item)449    def match_iterator(self, tokens, item):450        """Matches a lazy list or a chain."""451        internal_assert(2 <= len(tokens) <= 3, "invalid iterator match tokens", tokens)452        tail = None453        if len(tokens) == 2:454            _, matches = tokens455        else:456            _, matches, tail = tokens457        self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Iterable)")458        if tail is None:459            itervar = self.get_temp_var()460            self.add_def(itervar + " = _coconut.tuple(" + item + ")")461        elif matches:462            itervar = self.get_temp_var()463            if tail == wildcard:464                tail = item465            else:466                self.add_def(tail + " = _coconut.iter(" + item + ")")467            self.add_def(itervar + " = _coconut.tuple(_coconut_igetitem(" + tail + ", _coconut.slice(None, " + str(len(matches)) + ")))")468        else:469            itervar = None470            if tail != wildcard:471                self.add_def(tail + " = " + item)472        if itervar is not None:473            with self.down_a_level():474                self.add_check("_coconut.len(" + itervar + ") == " + str(len(matches)))475                self.match_all_in(matches, itervar)476    def match_star(self, tokens, item):477        """Matches starred assignment."""478        internal_assert(1 <= len(tokens) <= 3, "invalid star match tokens", tokens)479        head_matches, last_matches = None, None480        if len(tokens) == 1:481            middle = tokens[0]482        elif len(tokens) == 2:483            if isinstance(tokens[0], str):484                middle, last_matches = tokens485            else:486                head_matches, middle = tokens487        else:488            head_matches, middle, last_matches = tokens489        self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Iterable)")490        if head_matches is None and last_matches is None:491            if middle != wildcard:492                self.add_def(middle + " = _coconut.list(" + item + ")")493        else:494            itervar = self.get_temp_var()495            self.add_def(itervar + " = _coconut.list(" + item + ")")496            with self.down_a_level():497                req_length = (len(head_matches) if head_matches is not None else 0) + (len(last_matches) if last_matches is not None else 0)498                self.add_check("_coconut.len(" + itervar + ") >= " + str(req_length))499                if middle != wildcard:500                    head_splice = str(len(head_matches)) if head_matches is not None else ""501                    last_splice = "-" + str(len(last_matches)) if last_matches is not None else ""502                    self.add_def(middle + " = " + itervar + "[" + head_splice + ":" + last_splice + "]")503                if head_matches is not None:504                    self.match_all_in(head_matches, itervar)505                if last_matches is not None:506                    for x in range(1, len(last_matches) + 1):507                        self.match(last_matches[-x], itervar + "[-" + str(x) + "]")508    def match_rsequence(self, tokens, item):509        """Matches a reverse sequence."""510        front, series_type, matches = tokens511        self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")512        self.add_check("_coconut.len(" + item + ") >= " + str(len(matches)))513        if front != wildcard:514            if len(matches):515                splice = "[:" + str(-len(matches)) + "]"516            else:517                splice = ""518            self.assign_to_series(front, series_type, item + splice)519        for i, match in enumerate(matches):520            self.match(match, item + "[" + str(i - len(matches)) + "]")521    def match_msequence(self, tokens, item):522        """Matches a middle sequence."""523        series_type, head_matches, middle, _, last_matches = tokens524        self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Sequence)")525        self.add_check("_coconut.len(" + item + ") >= " + str(len(head_matches) + len(last_matches)))526        if middle != wildcard:527            if len(head_matches) and len(last_matches):528                splice = "[" + str(len(head_matches)) + ":" + str(-len(last_matches)) + "]"529            elif len(head_matches):530                splice = "[" + str(len(head_matches)) + ":]"531            elif len(last_matches):532                splice = "[:" + str(-len(last_matches)) + "]"533            else:534                splice = ""535            self.assign_to_series(middle, series_type, item + splice)536        self.match_all_in(head_matches, item)537        for i, match in enumerate(last_matches):538            self.match(match, item + "[" + str(i - len(last_matches)) + "]")539    def match_string(self, tokens, item):540        """Match prefix string."""541        prefix, name = tokens542        return self.match_mstring((prefix, name, None), item)543    def match_rstring(self, tokens, item):544        """Match suffix string."""545        name, suffix = tokens546        return self.match_mstring((None, name, suffix), item)547    def match_mstring(self, tokens, item):548        """Match prefix and suffix string."""549        prefix, name, suffix = tokens550        if prefix is None:551            use_bytes = suffix.startswith("b")552        elif suffix is None:553            use_bytes = prefix.startswith("b")554        elif prefix.startswith("b") and suffix.startswith("b"):555            use_bytes = True556        elif prefix.startswith("b") or suffix.startswith("b"):557            raise CoconutDeferredSyntaxError("string literals and byte literals cannot be added in patterns", self.loc)558        else:559            use_bytes = False560        if use_bytes:561            self.add_check("_coconut.isinstance(" + item + ", _coconut.bytes)")562        else:563            self.add_check("_coconut.isinstance(" + item + ", _coconut.str)")564        if prefix is not None:565            self.add_check(item + ".startswith(" + prefix + ")")566        if suffix is not None:567            self.add_check(item + ".endswith(" + suffix + ")")568        if name != wildcard:569            self.add_def(570                name + " = " + item + "["571                + ("" if prefix is None else self.comp.eval_now("len(" + prefix + ")")) + ":"572                + ("" if suffix is None else self.comp.eval_now("-len(" + suffix + ")")) + "]",573            )574    def match_const(self, tokens, item):575        """Matches a constant."""576        match, = tokens577        if match in const_vars:578            self.add_check(item + " is " + match)579        else:580            self.add_check(item + " == " + match)581    def match_set(self, tokens, item):582        """Matches a set."""583        match, = tokens584        self.add_check("_coconut.isinstance(" + item + ", _coconut.abc.Set)")585        self.add_check("_coconut.len(" + item + ") == " + str(len(match)))586        for const in match:587            self.add_check(const + " in " + item)588    def split_data_or_class_match(self, tokens):589        """Split data/class match tokens into cls_name, pos_matches, name_matches, star_match."""590        cls_name, matches = tokens591        pos_matches = []592        name_matches = {}593        star_match = None594        for match_arg in matches:595            if len(match_arg) == 1:596                match, = match_arg597                if star_match is not None:598                    raise CoconutDeferredSyntaxError("positional arg after starred arg in data/class match", self.loc)599                if name_matches:600                    raise CoconutDeferredSyntaxError("positional arg after named arg in data/class match", self.loc)601                pos_matches.append(match)602            elif len(match_arg) == 2:603                internal_assert(match_arg[0] == "*", "invalid starred data/class match arg tokens", match_arg)604                _, match = match_arg605                if star_match is not None:606                    raise CoconutDeferredSyntaxError("duplicate starred arg in data/class match", self.loc)607                if name_matches:608                    raise CoconutDeferredSyntaxError("both starred arg and named arg in data/class match", self.loc)609                star_match = match610            elif len(match_arg) == 3:611                internal_assert(match_arg[1] == "=", "invalid named data/class match arg tokens", match_arg)612                name, _, match = match_arg613                if star_match is not None:614                    raise CoconutDeferredSyntaxError("both named arg and starred arg in data/class match", self.loc)615                if name in name_matches:616                    raise CoconutDeferredSyntaxError("duplicate named arg {name!r} in data/class match".format(name=name), self.loc)617                name_matches[name] = match618            else:619                raise CoconutInternalException("invalid data/class match arg", match_arg)620        return cls_name, pos_matches, name_matches, star_match621    def match_class(self, tokens, item):622        """Matches a class PEP-622-style."""623        cls_name, pos_matches, name_matches, star_match = self.split_data_or_class_match(tokens)624        self.add_check("_coconut.isinstance(" + item + ", " + cls_name + ")")625        self_match_matcher, other_cls_matcher = self.branches(2)626        # handle instances of _coconut_self_match_types627        self_match_matcher.add_check("_coconut.isinstance(" + item + ", _coconut_self_match_types)")628        if pos_matches:629            if len(pos_matches) > 1:630                self_match_matcher.add_def('raise _coconut.TypeError("too many positional args in class match (got ' + str(len(pos_matches)) + '; type supports 1)")')631            else:632                self_match_matcher.match(pos_matches[0], item)633        # handle all other classes634        other_cls_matcher.add_check("not _coconut.isinstance(" + item + ", _coconut_self_match_types)")635        for i, match in enumerate(pos_matches):636            other_cls_matcher.match(match, "_coconut.getattr(" + item + ", " + item + ".__match_args__[" + str(i) + "])")637        # handle starred arg638        if star_match is not None:639            temp_var = self.get_temp_var()640            self.add_def(641                "{temp_var} = _coconut.tuple(_coconut.getattr({item}, {item}.__match_args__[i]) for i in _coconut.range({min_ind}, _coconut.len({item}.__match_args__)))".format(642                    temp_var=temp_var,643                    item=item,644                    min_ind=len(pos_matches),645                ),646            )647            with self.down_a_level():648                self.match(star_match, temp_var)649        # handle keyword args650        for name, match in name_matches.items():651            self.match(match, item + "." + name)652    def match_data(self, tokens, item):653        """Matches a data type."""654        cls_name, pos_matches, name_matches, star_match = self.split_data_or_class_match(tokens)655        self.add_check("_coconut.isinstance(" + item + ", " + cls_name + ")")656        if star_match is None:657            self.add_check(658                '_coconut.len({item}) == {total_len}'.format(659                    item=item,660                    total_len=len(pos_matches) + len(name_matches),661                ),662            )663        # avoid checking >= 0664        elif len(pos_matches):665            self.add_check(666                "_coconut.len({item}) >= {min_len}".format(667                    item=item,668                    min_len=len(pos_matches),669                ),670            )671        self.match_all_in(pos_matches, item)672        if star_match is not None:673            self.match(star_match, item + "[" + str(len(pos_matches)) + ":]")674        for name, match in name_matches.items():675            self.match(match, item + "." + name)676    def match_data_or_class(self, tokens, item):677        """Matches an ambiguous data or class match."""678        self.rule_conflict_warn(679            "ambiguous pattern; could be class match or data match",680            if_coconut='resolving to Coconut data match by default',681            if_python='resolving to Python-style class match due to Python-style "match: case" block',682            extra="use explicit 'data data_name(patterns)' or 'class cls_name(patterns)' syntax to dismiss",683        )684        if self.using_python_rules:685            return self.match_class(tokens, item)...monitor.py
Source:monitor.py  
...43def get_local_overview():44    screenshot_file_name = f'{SCREENSHOT_DIR}/screen_overview.png'45    airtest.snapshot(screenshot_file_name)46    screen = cv2.imread(screenshot_file_name, cv2.IMREAD_UNCHANGED)47    local_tab_up = Template(f"{RESOURCE_DIR}/local_overview_top.png", threshold=0.88, resolution=(1440, 1080)).match_all_in(screen)48    local_tab_bottom = Template(f"{RESOURCE_DIR}/local_overview_bottom.png", threshold=0.88, resolution=(1440, 1080)).match_all_in(screen)49    if local_tab_up and local_tab_bottom:50        (_, (local_tab_left_line, local_tab_top_line), (local_tab_right_line, _), _) = local_tab_up[0].get('rectangle')51        ((_, local_tab_bottom_line), _, _, _) = local_tab_bottom[0].get('rectangle')52        return screen[local_tab_top_line: local_tab_bottom_line, local_tab_left_line:local_tab_right_line]53    else:54        return None55def identify_standing(name_image):56    h, w = name_image.shape[:2]57    standing = None58    # Resolve wrong match_all_in for blank image.59    if is_blank_name_row(name_image):60        standing = None61    # order by possibility to improve efficiency62    elif (Template(f"{RESOURCE_DIR}/blue_plus.png", threshold=0.88, resolution=(w, h)).match_all_in(name_image) is not None or63          # matching on gray scale image. blue_star image works for green_star as well.64          Template(f"{RESOURCE_DIR}/blue_star.png", threshold=0.88, resolution=(w, h)).match_all_in(name_image) is not None):65        standing = FRIENDLY66    elif Template(f"{RESOURCE_DIR}/red_mark.png", threshold=0.82, resolution=(w, h)).match_all_in(name_image) is not None:67        standing = HOSTILE68    elif not (Template(f"{RESOURCE_DIR}/observer.png", threshold=0.92, resolution=(w, h)).match_in(name_image) or69              Template(f"{RESOURCE_DIR}/observer_name.png", threshold=0.90, resolution=(w, h)).match_in(name_image)):70        standing = NEUTRAL71    logger.debug(f'standing: {standing}')72    if logger.level <= logging.DEBUG:73        results = Template(f"{RESOURCE_DIR}/observer_name.png", threshold=0.80, resolution=(w, h)).match_all_in(name_image)74        logger.debug(results)75        show_image(name_image)76    return standing77def is_blank_name_row(name_row):78    _, name_row_bin = cv2.threshold(cv2.cvtColor(name_row, cv2.COLOR_BGR2GRAY), 100, 255, cv2.THRESH_BINARY)79    return cv2.countNonZero(name_row_bin) == 080def identify_local_in_overview():81    local_overview = get_local_overview()82    if local_overview is None:83        logger.warning('Local overview not available')84        return None85    else:86        h, w = local_overview.shape[:2]  # cv image are h x w87        divider_template = Template(f"{RESOURCE_DIR}/divider.png", threshold=0.76, resolution=(w, h))88        dividers = divider_template.match_all_in(local_overview)89        if dividers is None:90            divider_positions = []91        else:92            divider_positions = list(map(lambda divider: divider.get('result')[1], dividers))93        divider_positions.sort()94        divider_positions.append(h)95        prev_position = 096        friendly_count = 097        hostile_count = 098        neutral_count = 099        for current_position in divider_positions:100            if current_position - prev_position > 40:101                name_row = local_overview[prev_position:current_position, :]102                standing = identify_standing(name_row)...template.py
Source:template.py  
...55            return {'results': None, 'feature': self, 'screen': screen}56        else:57            focus_pos = TargetPos().getXY(result, self.target_pos)58            return {'results': [result], 'pos': focus_pos, 'feature': self, 'screen': screen}59    def match_all_in(self, screen, in_rect=None):60        image = self._imread()61        image = self._resize_image(image, screen, ST.RESIZE_METHOD)62        if in_rect is None:63            results = self._find_all_template(image, screen)64        else:65            pos_left_top = (int(in_rect[0][0] * screen.shape[1] / 2 + screen.shape[1] / 2),66                            int(in_rect[0][1] * screen.shape[0] / 2 + screen.shape[0] / 2))67            pos_right_bottom = (int(in_rect[1][0] * screen.shape[1] / 2 + screen.shape[1] / 2),68                                int(in_rect[1][1] * screen.shape[0] / 2 + screen.shape[0] / 2))69            img_part = screen[pos_left_top[1]: pos_right_bottom[1], pos_left_top[0]: pos_right_bottom[0]]70            results = self._find_all_template(image, img_part)71            if results is not None:72                for result in results:73                    result['result'] =(result['result'][0] + pos_left_top[0], result['result'][1] + pos_left_top[1])...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!!
