Example #1
0
def print_exc(chain=True):
    if six.PY3:
        rep = traceback.format_exc(chain=chain)
    else:
        rep = traceback.format_exc()
    out = highlight(rep, PythonTracebackLexer(), Terminal256Formatter())
    print(out)
Example #2
0
    def _setup_highlight(self):
        from pygments import highlight
        from pygments.lexers.python import PythonTracebackLexer
        from pygments.formatters.terminal import TerminalFormatter

        return partial(highlight, lexer=PythonTracebackLexer(),
                       formatter=TerminalFormatter())
Example #3
0
def highlight_code(code):
    """
    Returns highlighted via pygments version of a given source code

    :param code: string containing a source code
    :return: colorized string
    """
    return highlight(code, PythonTracebackLexer(),
                     Terminal256Formatter(style='manni'))
def traceback_highlighter_factory(
) -> Callable[[str], str]:  # pragma: no cover
    from pygments.lexers.python import PythonTracebackLexer
    lexer = PythonTracebackLexer()
    from pygments.formatters.terminal256 import Terminal256Formatter
    formatter = Terminal256Formatter(style='native')

    def inner(tb):
        return highlight(tb, lexer, formatter)

    from pygments import highlight
    return inner
Example #5
0
def traceback(message=None, caption="error_type"):
    """Raise warning with current traceback as content. It means, that error was catched, but still something crashed.

    Args:
        message (str): Any string content of traceback.
        caption (str, optional): Caption of warning. If 'error_type', than Error type (e.g. ZeroDivisionError) is used.
            Defaults to 'error_type'.
    """

    if caption == "error_type":
        try:
            caption = sys.exc_info()[1].__class__.__name__
        except Exception:
            caption = "Error"

    if config.COLOR in [True, 1] or (config.COLOR == "auto" and
                                     (not config.TO_FILE)):

        import pygments
        from pygments.lexers.python import PythonTracebackLexer
        from pygments.formatters import TerminalFormatter

        separated_traceback = pygments.highlight(
            trcbck.format_exc(),
            PythonTracebackLexer(),
            TerminalFormatter(style="friendly"),
        )
    else:
        separated_traceback = trcbck.format_exc()

    separated_traceback = separated_traceback.rstrip()

    separated_traceback = return_str(
        message=message,
        caption=caption,
        objectize=False,
        uncolored_message=f"\n\n{separated_traceback}",
    )

    log_warn(separated_traceback,
             log_type="TRACEBACK WARNING",
             showwarning_details=False)
Example #6
0
 def __exit__(self, exc_type, exc_val, exc_tb):
     if exc_type or exc_val or exc_tb:
         if exc_type == KeyboardInterrupt:
             return  # manual stop, just stop
         # an exception was raised, write the traceback into the report
         import traceback
         out = "".join(traceback.format_exception(exc_type, exc_val,
                                                  exc_tb))
         try:
             from pygments import highlight
             from pygments.formatters.html import HtmlFormatter
             from pygments.lexers.python import PythonTracebackLexer
         except ImportError:
             # write plain
             self << Elem.from_string(f"<pre>{out}</pre>")
         else:
             # write fancy
             pretty = highlight(out, PythonTracebackLexer(),
                                HtmlFormatter())
             css = HtmlFormatter().get_style_defs(".highlight")
             self << Elem.from_string(f"<style>{css}</style>{pretty}")
         return True  # suppress exception after logging, and continue
Example #7
0
def internalserver_error(context, request):
    @request.after
    def adjust_status(response):
        response.status = 500

    tb = traceback.format_exc()
    logger.error("Internal Server Error\n" + tb)

    if request.path.startswith("/api/"):
        return morepath.render_json(
            {
                "status": "error",
                "message": "Internal server error",
                "traceback": tb.split("\n"),
            },
            request,
        )
    else:
        render = request.app.config.template_engine_registry.get_template_render(
            "master/error_500.pt", morepath.render_html)
        formatter = HtmlFormatter()
        highlighted = highlight(tb, PythonTracebackLexer(), formatter)
        return render({"traceback": highlighted}, request)
Example #8
0
def _lex_python_traceback(tb):
    """ Return token list for traceback string. """
    lexer = PythonTracebackLexer()
    return lexer.get_tokens(tb)
Example #9
0
    def printErrors(self):
        """
        Print a list of all tracebacks from errors and failures, as well as
        captured stdout (even if the test passed, except with quiet_stdout
        option).
        """
        if self.dots:
            self.stream.writeln()

        # Skipped Test Report
        if not self.args.no_skip_report:
            for test, reason in self.skipped:
                self.stream.writeln("\n{} {} - {}".format(
                    self.colors.blue('Skipped'),
                    self.colors.bold(test.dotted_name), reason))

        # Captured output for non-failing tests
        if not self.args.quiet_stdout:
            failing_tests = set([x[0] for x in self.all_errors])
            for test in list(self.stdout_output):
                if test not in failing_tests:
                    self.displayStdout(test)
                    self.displayStderr(test)

        # Actual tracebacks and captured output for failing tests
        for (test, color_func, outcome, err) in self.all_errors:
            # Header Line
            self.stream.writeln('\n' + color_func(outcome) + ' in ' +
                                self.colors.bold(test.dotted_name))

            # Traceback
            if not self.args.no_tracebacks:
                relevant_frames = []
                for i, frame in enumerate(err.traceback_lines):
                    # Python2 tracebacks containing unicode need some special handling
                    # This doesn't always make it readable, but at least it doesn't
                    # crash
                    if sys.version_info[0] == 2:  # pragma: no cover
                        try:
                            ''.join([frame
                                     ])  # intentionally trigger exceptions
                        except UnicodeDecodeError:
                            frame = frame.decode('utf-8')
                    debug('\n' + '*' * 30 + "Frame {}:".format(i) + '*' * 30 +
                          "\n{}".format(self.colors.yellow(frame)),
                          level=3)
                    # Ignore useless frames
                    if self.verbose < 4:
                        if frame.strip(
                        ) == "Traceback (most recent call last):":
                            continue
                    # Done with this frame, capture it.
                    relevant_frames.append(frame)

                if self.colors.termcolor:
                    raw_output = ''.join(relevant_frames)
                    formatter = TerminalFormatter()
                    lexer = PythonTracebackLexer()
                    higlighted_output = highlight(raw_output, lexer, formatter)
                    self.stream.write(higlighted_output)
                else:
                    self.stream.write(''.join(relevant_frames))

            # Captured output for failing tests
            self.displayStdout(test)
            self.displayStderr(test)
Example #10
0
def _highlight(text):
    return highlight(text,
                     lexer=PythonTracebackLexer(),
                     formatter=TerminalFormatter())