Best Python code snippet using tavern
error.py
Source:error.py  
...16class ReprdError(object):17    def __init__(self, exce, item):18        self.exce = exce19        self.item = item20    def _get_available_format_keys(self):21        """Try to get the format variables for the stage22        If we can't get the variable for this specific stage, just return the23        global config which will at least have some format variables24        Returns:25            dict: variables for formatting test26        """27        try:28            # pylint: disable=protected-access29            keys = self.exce._excinfo[1].test_block_config["variables"]30        except AttributeError:31            logger.warning("Unable to read stage variables - error output may be wrong")32            keys = self.item.global_cfg33        return keys34    def _print_format_variables(self, tw, code_lines):35        """Print a list of the format variables and their value at this stage36        If the format variable is not defined, print it in red as '???'37        Args:38            tw (TerminalWriter): Pytest TW instance39            code_lines (list(str)): Source lines for this stage40        Returns:41            list(str): List of all missing format variables42        """43        def read_formatted_vars(lines):44            """Go over all lines and try to find format variables"""45            for line in lines:46                for match in re.finditer(47                    r"(.*?:\s+!raw)?(?(1).*|.*?(?P<format_var>(?<!{){[^{]*?}))", line48                ):49                    if match.group("format_var") is not None:50                        yield match.group("format_var")51        format_variables = list(read_formatted_vars(code_lines))52        keys = self._get_available_format_keys()53        missing = []54        # Print out values of format variables, like Pytest prints out the55        # values of function call variables56        tw.line("Format variables:", white=True, bold=True)57        for var in format_variables:58            # Empty dict59            if re.match(r"^\s*{}\s*", var):60                continue61            # If it's valid json, it's not a format value62            try:63                json.loads(var)64            except json.JSONDecodeError:65                pass66            else:67                continue68            try:69                value_at_call = format_keys(var, keys)70            except exceptions.MissingFormatError:71                missing.append(var)72                value_at_call = "???"73                white = False74                red = True75            else:76                white = True77                red = False78            line = "  {} = '{}'".format(var[1:-1], value_at_call)79            tw.line(line, white=white, red=red)  # pragma: no cover80        return missing81    def _print_test_stage(82        self, tw, code_lines, missing_format_vars, line_start83    ):  # pylint: disable=no-self-use84        """Print the direct source lines from this test stage85        If we couldn't get the stage for some reason, print the entire test out.86        If there are any lines which have missing format variables, higlight87        them in red.88        Args:89            tw (Termin): Pytest TW instance90            code_lines (list(str)): Raw source for this stage91            missing_format_vars (list(str)): List of all missing format92                variables for this stage93            line_start (int): Source line of this stage94        """95        if line_start:96            tw.line(97                "Source test stage (line {}):".format(line_start), white=True, bold=True98            )99        else:100            tw.line("Source test stages:", white=True, bold=True)101        for line in code_lines:102            if any(i in line for i in missing_format_vars):103                tw.line(line, red=True)104            else:105                tw.line(line, white=True)106    def _print_formatted_stage(self, tw, stage):107        """Print the 'formatted' stage that Tavern will actually use to send the108        request/process the response109        Args:110            tw (TerminalWriter): Pytest TW instance111            stage (dict): The 'final' stage used by Tavern112        """113        tw.line("Formatted stage:", white=True, bold=True)114        # This will definitely exist115        formatted_lines = yaml.dump(stage, default_flow_style=False).split("\n")116        keys = self._get_available_format_keys()117        for line in formatted_lines:118            if not line:119                continue120            if "{}" not in line:121                line = format_keys(line, keys)122            tw.line("  {}".format(line), white=True)123    def _print_errors(self, tw):124        """Print any errors in the 'normal' Pytest style125        Args:126            tw (TerminalWriter): Pytest TW instance127        """128        tw.line("Errors:", white=True, bold=True)129        # Sort of hack, just use this to directly extract the exception format.130        # If this breaks in future, just re-implement it...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!!
