Exemple #1
0
def print_stack():
    result = ""
    options = Options(include_signature=True)
    frame = inspect.currentframe().f_back
    for frame_info in list(FrameInfo.stack_data(frame, options))[-3:]:
        result += render_frame_info(frame_info) + "\n"
    return result
Exemple #2
0
 def gather_lines():
     frame = inspect.currentframe().f_back
     frame_info = FrameInfo(frame, options)
     assert repr(frame_info) == "FrameInfo({})".format(frame)
     lines[:] = [
         line.render(strip_leading_indent=dedented) if isinstance(
             line, Line) else line for line in frame_info.lines
     ]
Exemple #3
0
 def format_stack(self, frame_or_tb) -> List[dict]:
     return list(
         self.format_stack_data(
             FrameInfo.stack_data(
                 frame_or_tb,
                 Options(before=0, after=0, pygments_formatter=pygments_formatter),
                 collapse_repeated_frames=True,
             )
         )
     )
Exemple #4
0
 def foo(arg, _arg2: str = None, *_args, **_kwargs):
     y = 123986
     str(y)
     x = {982347298304}
     str(x)
     return (
         FrameInfo(inspect.currentframe(), options),
         arg,
         arg,
     )[0]
    def format_stack(self, frame_or_tb=None) -> Iterable[str]:
        if frame_or_tb is None:
            frame_or_tb = inspect.currentframe().f_back

        yield from self.format_stack_data(
            FrameInfo.stack_data(
                frame_or_tb,
                self.options,
                collapse_repeated_frames=self.collapse_repeated_frames,
            ))
Exemple #6
0
def check_skipping_frames(collapse: bool):
    def factorial(n):
        if n <= 1:
            return 1 / 0  # exception lineno
        return n * foo(n - 1)  # factorial lineno

    def foo(n):
        return factorial(n)  # foo lineno

    try:
        factorial(20)  # check_skipping_frames lineno
    except Exception as e:
        # tb = sys.exc_info()[2]
        tb = e.__traceback__
        result = []
        for x in FrameInfo.stack_data(tb, collapse_repeated_frames=collapse):
            if isinstance(x, FrameInfo):
                result.append((x.code, x.lineno))
            else:
                result.append(repr(x))
        source = Source.for_filename(__file__)
        linenos = {}
        for lineno, line in enumerate(source.lines):
            match = re.search(r" # (\w+) lineno", line)
            if match:
                linenos[match.group(1)] = lineno + 1

        def simple_frame(func):
            return func.__code__, linenos[func.__name__]

        if collapse:
            middle = [
                simple_frame(factorial),
                simple_frame(foo),
                simple_frame(factorial),
                simple_frame(foo),
                ("<RepeatedFrames "
                 "check_skipping_frames.<locals>.factorial at line {factorial} (16 times), "
                 "check_skipping_frames.<locals>.foo at line {foo} (16 times)>"
                 ).format(**linenos),
                simple_frame(factorial),
                simple_frame(foo),
            ]
        else:
            middle = [*([
                simple_frame(factorial),
                simple_frame(foo),
            ] * 19)]

        assert result == [
            simple_frame(check_skipping_frames),
            *middle,
            (factorial.__code__, linenos["exception"]),
        ]
    def format_frame(
            self, frame: Union[FrameInfo, FrameType,
                               TracebackType]) -> Iterable[str]:
        if not isinstance(frame, FrameInfo):
            frame = FrameInfo(frame, self.options)

        yield self.format_frame_header(frame)

        for line in frame.lines:
            if isinstance(line, Line):
                yield self.format_line(line)
            else:
                assert line is LINE_GAP
                yield self.line_gap_string + "\n"

        if self.show_variables:
            yield from self.format_variables(frame)
Exemple #8
0
def test_markers():
    options = Options(before=0, after=0)
    line = only(FrameInfo(inspect.currentframe(), options).lines)
    assert line.is_current
    assert re.match(r"<Line \d+ ", repr(line))
    assert (
        " (current=True) "
        "'    line = only(FrameInfo(inspect.currentframe(), options).lines)'"
        " of " in repr(line))
    assert repr(line).endswith("test_core.py>")
    assert repr(LINE_GAP) == "LINE_GAP"

    assert '*'.join(t.string for t in line.tokens) == \
           'line*=*only*(*FrameInfo*(*inspect*.*currentframe*(*)*,*options*)*.*lines*)*\n'

    def convert_token_range(r):
        if r.data.type == token.NAME:
            return '[[', ']]'

    markers = markers_from_ranges(line.token_ranges, convert_token_range)
    assert line.render(markers) == \
           '[[line]] = [[only]]([[FrameInfo]]([[inspect]].[[currentframe]](), [[options]]).[[lines]])'
    assert line.render(markers, strip_leading_indent=False) == \
           '    [[line]] = [[only]]([[FrameInfo]]([[inspect]].[[currentframe]](), [[options]]).[[lines]])'

    def convert_variable_range(r):
        return '[[', ' of type {}]]'.format(r.data[0].value.__class__.__name__)

    markers = markers_from_ranges(line.variable_ranges, convert_variable_range)
    assert sorted(markers) == [
        (4, True, '[['),
        (8, False, ' of type Line]]'),
        (50, True, '[['),
        (57, False, ' of type Options]]'),
    ]

    line.text += '  # < > " & done'
    assert line.render(markers) == \
           '[[line of type Line]] = only(FrameInfo(inspect.currentframe(), [[options of type Options]]).lines)' \
           '  # < > " & done'

    assert line.render(markers, escape_html=True) == \
           '[[line of type Line]] = only(FrameInfo(inspect.currentframe(), [[options of type Options]]).lines)' \
           '  # &lt; &gt; &quot; &amp; done'
Exemple #9
0
def print_stack():
    result = ""
    for formatter_cls in [
            Terminal256Formatter,
            TerminalFormatter,
            TerminalTrueColorFormatter,
            HtmlFormatter,
    ]:
        for style in [
                "native",
                style_with_executing_node("native", "bg:#444400")
        ]:
            result += "{formatter_cls.__name__} {style}:\n\n".format(
                **locals())
            formatter = formatter_cls(style=style)
            options = Options(pygments_formatter=formatter)
            frame = inspect.currentframe().f_back
            for frame_info in list(FrameInfo.stack_data(frame, options))[-2:]:
                for line in frame_info.lines:
                    result += '{:4} | {}\n'.format(line.lineno,
                                                   line.render(pygmented=True))
                result += "-----\n"
            result += "\n====================\n\n"
    return result
Exemple #10
0
 def format_frame_header(self, frame_info: FrameInfo) -> str:
     # noinspection PyPropertyAccess
     frame_info.filename = os.path.basename(frame_info.filename)
     return super().format_frame_header(frame_info)