Example #1
0
    def test_repr_tracebackentry_short(self, importasmod):
        mod = importasmod(
            """
            def func1():
                raise ValueError("hello")
            def entry():
                func1()
        """
        )
        excinfo = pytest.raises(ValueError, mod.entry)
        p = FormattedExcinfo(style="short")
        reprtb = p.repr_traceback_entry(excinfo.traceback[-2])
        lines = reprtb.lines
        basename = py.path.local(mod.__file__).basename
        assert lines[0] == "    func1()"
        assert basename in str(reprtb.reprfileloc.path)
        assert reprtb.reprfileloc.lineno == 5

        # test last entry
        p = FormattedExcinfo(style="short")
        reprtb = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
        lines = reprtb.lines
        assert lines[0] == '    raise ValueError("hello")'
        assert lines[1] == "E   ValueError: hello"
        assert basename in str(reprtb.reprfileloc.path)
        assert reprtb.reprfileloc.lineno == 3
Example #2
0
    def test_repr_tracebackentry_lines2(self, importasmod):
        mod = importasmod(
            """
            def func1(m, x, y, z):
                raise ValueError("hello\\nworld")
        """
        )
        excinfo = pytest.raises(ValueError, mod.func1, "m" * 90, 5, 13, "z" * 120)
        excinfo.traceback = excinfo.traceback.filter()
        entry = excinfo.traceback[-1]
        p = FormattedExcinfo(funcargs=True)
        reprfuncargs = p.repr_args(entry)
        assert reprfuncargs.args[0] == ("m", repr("m" * 90))
        assert reprfuncargs.args[1] == ("x", "5")
        assert reprfuncargs.args[2] == ("y", "13")
        assert reprfuncargs.args[3] == ("z", repr("z" * 120))

        p = FormattedExcinfo(funcargs=True)
        repr_entry = p.repr_traceback_entry(entry)
        assert repr_entry.reprfuncargs.args == reprfuncargs.args
        tw = TWMock()
        repr_entry.toterminal(tw)
        assert tw.lines[0] == "m = " + repr("m" * 90)
        assert tw.lines[1] == "x = 5, y = 13"
        assert tw.lines[2] == "z = " + repr("z" * 120)
Example #3
0
    def test_repr_traceback_and_excinfo(self, importasmod):
        mod = importasmod(
            """
            def f(x):
                raise ValueError(x)
            def entry():
                f(0)
        """
        )
        excinfo = pytest.raises(ValueError, mod.entry)

        for style in ("long", "short"):
            p = FormattedExcinfo(style=style)
            reprtb = p.repr_traceback(excinfo)
            assert len(reprtb.reprentries) == 2
            assert reprtb.style == style
            assert not reprtb.extraline
            repr = p.repr_excinfo(excinfo)
            assert repr.reprtraceback
            assert len(repr.reprtraceback.reprentries) == len(reprtb.reprentries)
            if sys.version_info[0] >= 3:
                assert repr.chain[0][0]
                assert len(repr.chain[0][0].reprentries) == len(reprtb.reprentries)
            assert repr.reprcrash.path.endswith("mod.py")
            assert repr.reprcrash.message == "ValueError: 0"
Example #4
0
    def test_traceback_short_no_source(self, importasmod, monkeypatch):
        mod = importasmod(
            """
            def func1():
                raise ValueError("hello")
            def entry():
                func1()
        """
        )
        excinfo = pytest.raises(ValueError, mod.entry)
        from _pytest._code.code import Code

        monkeypatch.setattr(Code, "path", "bogus")
        excinfo.traceback[0].frame.code.path = "bogus"
        p = FormattedExcinfo(style="short")
        reprtb = p.repr_traceback_entry(excinfo.traceback[-2])
        lines = reprtb.lines
        last_p = FormattedExcinfo(style="short")
        last_reprtb = last_p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
        last_lines = last_reprtb.lines
        monkeypatch.undo()
        assert lines[0] == "    func1()"

        assert last_lines[0] == '    raise ValueError("hello")'
        assert last_lines[1] == "E   ValueError: hello"
Example #5
0
    def test_repr_tracebackentry_lines(self, importasmod):
        mod = importasmod("""
            def func1():
                raise ValueError("hello\\nworld")
        """)
        excinfo = pytest.raises(ValueError, mod.func1)
        excinfo.traceback = excinfo.traceback.filter()
        p = FormattedExcinfo()
        reprtb = p.repr_traceback_entry(excinfo.traceback[-1])

        # test as intermittent entry
        lines = reprtb.lines
        assert lines[0] == '    def func1():'
        assert lines[1] == '>       raise ValueError("hello\\nworld")'

        # test as last entry
        p = FormattedExcinfo(showlocals=True)
        repr_entry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
        lines = repr_entry.lines
        assert lines[0] == '    def func1():'
        assert lines[1] == '>       raise ValueError("hello\\nworld")'
        assert lines[2] == 'E       ValueError: hello'
        assert lines[3] == 'E       world'
        assert not lines[4:]

        loc = repr_entry.reprlocals is not None
        loc = repr_entry.reprfileloc
        assert loc.path == mod.__file__
        assert loc.lineno == 3
Example #6
0
    def test_repr_source_failing_fullsource(self):
        pr = FormattedExcinfo()

        class FakeCode(object):
            class raw:
                co_filename = '?'
            path = '?'
            firstlineno = 5

            def fullsource(self):
                return None
            fullsource = property(fullsource)

        class FakeFrame(object):
            code = FakeCode()
            f_locals = {}
            f_globals = {}

        class FakeTracebackEntry(_pytest._code.Traceback.Entry):
            def __init__(self, tb, excinfo=None):
                self.lineno = 5+3

            @property
            def frame(self):
                return FakeFrame()

        class Traceback(_pytest._code.Traceback):
            Entry = FakeTracebackEntry

        class FakeExcinfo(_pytest._code.ExceptionInfo):
            typename = "Foo"
            value = Exception()
            def __init__(self):
                pass

            def exconly(self, tryshort):
                return "EXC"
            def errisinstance(self, cls):
                return False

        excinfo = FakeExcinfo()
        class FakeRawTB(object):
            tb_next = None
        tb = FakeRawTB()
        excinfo.traceback = Traceback(tb)

        fail = IOError()  # noqa
        repr = pr.repr_excinfo(excinfo)
        assert repr.reprtraceback.reprentries[0].lines[0] == ">   ???"
        if py.std.sys.version_info[0] >= 3:
            assert repr.chain[0][0].reprentries[0].lines[0] == ">   ???"


        fail = py.error.ENOENT  # noqa
        repr = pr.repr_excinfo(excinfo)
        assert repr.reprtraceback.reprentries[0].lines[0] == ">   ???"
        if py.std.sys.version_info[0] >= 3:
            assert repr.chain[0][0].reprentries[0].lines[0] == ">   ???"
Example #7
0
 def test_repr_local(self):
     p = FormattedExcinfo(showlocals=True)
     loc = {"y": 5, "z": 7, "x": 3, "@x": 2, "__builtins__": {}}
     reprlocals = p.repr_locals(loc)
     assert reprlocals.lines
     assert reprlocals.lines[0] == "__builtins__ = <builtins>"
     assert reprlocals.lines[1] == "x          = 3"
     assert reprlocals.lines[2] == "y          = 5"
     assert reprlocals.lines[3] == "z          = 7"
Example #8
0
 def test_repr_source_not_existing(self):
     pr = FormattedExcinfo()
     co = compile("raise ValueError()", "", "exec")
     try:
         exec (co)
     except ValueError:
         excinfo = _pytest._code.ExceptionInfo()
     repr = pr.repr_excinfo(excinfo)
     assert repr.reprtraceback.reprentries[1].lines[0] == ">   ???"
Example #9
0
 def test_repr_local(self):
     p = FormattedExcinfo(showlocals=True)
     loc = {'y': 5, 'z': 7, 'x': 3, '@x': 2, '__builtins__': {}}
     reprlocals = p.repr_locals(loc)
     assert reprlocals.lines
     assert reprlocals.lines[0] == '__builtins__ = <builtins>'
     assert reprlocals.lines[1] == 'x          = 3'
     assert reprlocals.lines[2] == 'y          = 5'
     assert reprlocals.lines[3] == 'z          = 7'
Example #10
0
def test_repr_traceback_with_unicode(style, encoding):
    msg = u"☹"
    if encoding is not None:
        msg = msg.encode(encoding)
    try:
        raise RuntimeError(msg)
    except RuntimeError:
        e_info = ExceptionInfo()
    formatter = FormattedExcinfo(style=style)
    repr_traceback = formatter.repr_traceback(e_info)
    assert repr_traceback is not None
Example #11
0
    def test_repr_local_truncated(self):
        loc = {"l": [i for i in range(10)]}
        p = FormattedExcinfo(showlocals=True)
        truncated_reprlocals = p.repr_locals(loc)
        assert truncated_reprlocals.lines
        assert truncated_reprlocals.lines[0] == "l          = [0, 1, 2, 3, 4, 5, ...]"

        q = FormattedExcinfo(showlocals=True, truncate_locals=False)
        full_reprlocals = q.repr_locals(loc)
        assert full_reprlocals.lines
        assert full_reprlocals.lines[0] == "l          = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
Example #12
0
 def test_repr_source(self):
     pr = FormattedExcinfo()
     source = _pytest._code.Source("""
         def f(x):
             pass
     """).strip()
     pr.flow_marker = "|"
     lines = pr.get_source(source, 0)
     assert len(lines) == 2
     assert lines[0] == "|   def f(x):"
     assert lines[1] == "        pass"
Example #13
0
 def test_repr_source_excinfo(self):
     """ check if indentation is right """
     pr = FormattedExcinfo()
     excinfo = self.excinfo_from_exec(
         """
             def f():
                 assert 0
             f()
     """
     )
     pr = FormattedExcinfo()
     source = pr._getentrysource(excinfo.traceback[-1])
     lines = pr.get_source(source, 1, excinfo)
     assert lines == ["    def f():", ">       assert 0", "E       AssertionError"]
Example #14
0
    def test_repr_many_line_source_not_existing(self):
        pr = FormattedExcinfo()
        co = compile("""
a = 1
raise ValueError()
""", "", "exec")
        try:
            exec (co)
        except ValueError:
            excinfo = _pytest._code.ExceptionInfo()
        repr = pr.repr_excinfo(excinfo)
        assert repr.reprtraceback.reprentries[1].lines[0] == ">   ???"
        if py.std.sys.version_info[0] >= 3:
            assert repr.chain[0][0].reprentries[1].lines[0] == ">   ???"
Example #15
0
 def test_repr_traceback_tbfilter(self, importasmod):
     mod = importasmod("""
         def f(x):
             raise ValueError(x)
         def entry():
             f(0)
     """)
     excinfo = pytest.raises(ValueError, mod.entry)
     p = FormattedExcinfo(tbfilter=True)
     reprtb = p.repr_traceback(excinfo)
     assert len(reprtb.reprentries) == 2
     p = FormattedExcinfo(tbfilter=False)
     reprtb = p.repr_traceback(excinfo)
     assert len(reprtb.reprentries) == 3
Example #16
0
    def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch):
        mod = importasmod("""
            def f(x):
                raise ValueError(x)
            def entry():
                f(0)
        """)
        excinfo = pytest.raises(ValueError, mod.entry)

        p = FormattedExcinfo()
        def raiseos():
            raise OSError(2)
        monkeypatch.setattr(py.std.os, 'getcwd', raiseos)
        assert p._makepath(__file__) == __file__
        p.repr_traceback(excinfo)
Example #17
0
    def test_tb_entry_AssertionError(self, importasmod):
        # probably this test is a bit redundant
        # as py/magic/testing/test_assertion.py
        # already tests correctness of
        # assertion-reinterpretation  logic
        mod = importasmod("""
            def somefunc():
                x = 1
                assert x == 2
        """)
        excinfo = pytest.raises(AssertionError, mod.somefunc)

        p = FormattedExcinfo()
        reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
        lines = reprentry.lines
        assert lines[-1] == "E       assert 1 == 2"
Example #18
0
    def test_repr_tracebackentry_no(self, importasmod):
        mod = importasmod("""
            def func1():
                raise ValueError("hello")
            def entry():
                func1()
        """)
        excinfo = pytest.raises(ValueError, mod.entry)
        p = FormattedExcinfo(style="no")
        p.repr_traceback_entry(excinfo.traceback[-2])

        p = FormattedExcinfo(style="no")
        reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
        lines = reprentry.lines
        assert lines[0] == 'E   ValueError: hello'
        assert not lines[1:]
Example #19
0
    def test_repr_traceback_recursion(self, importasmod):
        mod = importasmod("""
            def rec2(x):
                return rec1(x+1)
            def rec1(x):
                return rec2(x-1)
            def entry():
                rec1(42)
        """)
        excinfo = pytest.raises(RuntimeError, mod.entry)

        for style in ("short", "long", "no"):
            p = FormattedExcinfo(style="short")
            reprtb = p.repr_traceback(excinfo)
            assert reprtb.extraline == "!!! Recursion detected (same locals & position)"
            assert str(reprtb)
Example #20
0
    def test_repr_local_with_exception_in_class_property(self):
        class ExceptionWithBrokenClass(Exception):
            # Type ignored because it's bypassed intentionally.
            @property  # type: ignore
            def __class__(self):
                raise TypeError("boom!")

        class ObjWithErrorInRepr:
            def __repr__(self):
                raise ExceptionWithBrokenClass()

        p = FormattedExcinfo(showlocals=True, truncate_locals=False)
        loc = {"x": ObjWithErrorInRepr(), "__builtins__": {}}
        reprlocals = p.repr_locals(loc)
        assert reprlocals.lines
        assert reprlocals.lines[0] == "__builtins__ = <builtins>"
        assert '[ExceptionWithBrokenClass("") raised in repr()]' in reprlocals.lines[
            1]
Example #21
0
    def test_repr_many_line_source_not_existing(self):
        pr = FormattedExcinfo()
        co = compile(
            """
a = 1
raise ValueError()
""",
            "",
            "exec",
        )
        try:
            exec(co)
        except ValueError:
            excinfo = _pytest._code.ExceptionInfo()
        repr = pr.repr_excinfo(excinfo)
        assert repr.reprtraceback.reprentries[1].lines[0] == ">   ???"
        if sys.version_info[0] >= 3:
            assert repr.chain[0][0].reprentries[1].lines[0] == ">   ???"
Example #22
0
    def test_repr_traceback_recursion(self, importasmod):
        mod = importasmod(
            """
            def rec2(x):
                return rec1(x+1)
            def rec1(x):
                return rec2(x-1)
            def entry():
                rec1(42)
        """
        )
        excinfo = pytest.raises(RuntimeError, mod.entry)

        for style in ("short", "long", "no"):
            p = FormattedExcinfo(style="short")
            reprtb = p.repr_traceback(excinfo)
            assert reprtb.extraline == "!!! Recursion detected (same locals & position)"
            assert str(reprtb)
Example #23
0
    def toterminal(self, tw):
        """Print out a custom error message to the terminal.
        """
        exc = self.exce.value
        context = exc.context

        if context:
            for title, item in context:
                tw.line(title + ":", white=True, bold=True)
                tw.line(textwrap.indent(item, "    "), red=True)
                tw.line("")

        e = FormattedExcinfo()
        lines = e.get_exconly(self.exce)

        tw.line("Errors:", white=True, bold=True)
        for line in lines:
            tw.line(line, red=True, bold=True)
Example #24
0
    def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch):
        mod = importasmod("""
            def f(x):
                raise ValueError(x)
            def entry():
                f(0)
        """)
        excinfo = pytest.raises(ValueError, mod.entry)

        p = FormattedExcinfo(abspath=False)

        raised = 0

        orig_getcwd = os.getcwd

        def raiseos():
            nonlocal raised
            if sys._getframe().f_back.f_code.co_name == "checked_call":
                # Only raise with expected calls, but not via e.g. inspect for
                # py38-windows.
                raised += 1
                raise OSError(2, "custom_oserror")
            return orig_getcwd()

        monkeypatch.setattr(os, "getcwd", raiseos)
        assert p._makepath(__file__) == __file__
        assert raised == 1
        repr_tb = p.repr_traceback(excinfo)

        matcher = LineMatcher(str(repr_tb).splitlines())
        matcher.fnmatch_lines([
            "def entry():",
            ">       f(0)",
            "",
            "{}:5: ".format(mod.__file__),
            "_ _ *",
            "",
            "    def f(x):",
            ">       raise ValueError(x)",
            "E       ValueError: 0",
            "",
            "{}:3: ValueError".format(mod.__file__),
        ])
        assert raised == 3
Example #25
0
    def test_repr_traceback_with_invalid_cwd(self, importasmod, monkeypatch):
        mod = importasmod(
            """
            def f(x):
                raise ValueError(x)
            def entry():
                f(0)
        """
        )
        excinfo = pytest.raises(ValueError, mod.entry)

        p = FormattedExcinfo()

        def raiseos():
            raise OSError(2)

        monkeypatch.setattr(os, "getcwd", raiseos)
        assert p._makepath(__file__) == __file__
        p.repr_traceback(excinfo)
Example #26
0
    def test_repr_tracebackentry_lines_var_kw_args(self, importasmod):
        mod = importasmod("""
            def func1(x, *y, **z):
                raise ValueError("hello\\nworld")
        """)
        excinfo = pytest.raises(ValueError, mod.func1, 'a', 'b', c='d')
        excinfo.traceback = excinfo.traceback.filter()
        entry = excinfo.traceback[-1]
        p = FormattedExcinfo(funcargs=True)
        reprfuncargs = p.repr_args(entry)
        assert reprfuncargs.args[0] == ('x', repr('a'))
        assert reprfuncargs.args[1] == ('y', repr(('b',)))
        assert reprfuncargs.args[2] == ('z', repr({'c': 'd'}))

        p = FormattedExcinfo(funcargs=True)
        repr_entry = p.repr_traceback_entry(entry)
        assert repr_entry.reprfuncargs.args == reprfuncargs.args
        tw = TWMock()
        repr_entry.toterminal(tw)
        assert tw.lines[0] == "x = 'a', y = ('b',), z = {'c': 'd'}"
Example #27
0
    def test_repr_traceback_and_excinfo(self, importasmod):
        mod = importasmod("""
            def f(x):
                raise ValueError(x)
            def entry():
                f(0)
        """)
        excinfo = pytest.raises(ValueError, mod.entry)

        for style in ("long", "short"):
            p = FormattedExcinfo(style=style)
            reprtb = p.repr_traceback(excinfo)
            assert len(reprtb.reprentries) == 2
            assert reprtb.style == style
            assert not reprtb.extraline
            repr = p.repr_excinfo(excinfo)
            assert repr.reprtraceback
            assert len(repr.reprtraceback.reprentries) == len(
                reprtb.reprentries)
            assert repr.reprcrash.path.endswith("mod.py")
            assert repr.reprcrash.message == "ValueError: 0"
Example #28
0
    def test_repr_tracebackentry_lines(self, importasmod):
        mod = importasmod("""
            def func1():
                raise ValueError("hello\\nworld")
        """)
        excinfo = pytest.raises(ValueError, mod.func1)
        excinfo.traceback = excinfo.traceback.filter()
        p = FormattedExcinfo()
        reprtb = p.repr_traceback_entry(excinfo.traceback[-1])

        # test as intermittent entry
        lines = reprtb.lines
        assert lines[0] == "    def func1():"
        assert lines[1] == '>       raise ValueError("hello\\nworld")'

        # test as last entry
        p = FormattedExcinfo(showlocals=True)
        repr_entry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
        lines = repr_entry.lines
        assert lines[0] == "    def func1():"
        assert lines[1] == '>       raise ValueError("hello\\nworld")'
        assert lines[2] == "E       ValueError: hello"
        assert lines[3] == "E       world"
        assert not lines[4:]

        loc = repr_entry.reprlocals is not None
        loc = repr_entry.reprfileloc
        assert loc.path == mod.__file__
        assert loc.lineno == 3
Example #29
0
    def test_repr_tracebackentry_short(self, importasmod) -> None:
        mod = importasmod("""
            def func1():
                raise ValueError("hello")
            def entry():
                func1()
        """)
        excinfo = pytest.raises(ValueError, mod.entry)
        p = FormattedExcinfo(style="short")
        reprtb = p.repr_traceback_entry(excinfo.traceback[-2])
        lines = reprtb.lines
        basename = py.path.local(mod.__file__).basename
        assert lines[0] == "    func1()"
        assert reprtb.reprfileloc is not None
        assert basename in str(reprtb.reprfileloc.path)
        assert reprtb.reprfileloc.lineno == 5

        # test last entry
        p = FormattedExcinfo(style="short")
        reprtb = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
        lines = reprtb.lines
        assert lines[0] == '    raise ValueError("hello")'
        assert lines[1] == "E   ValueError: hello"
        assert reprtb.reprfileloc is not None
        assert basename in str(reprtb.reprfileloc.path)
        assert reprtb.reprfileloc.lineno == 3
Example #30
0
    def test_repr_tracebackentry_lines2(self, importasmod, tw_mock) -> None:
        mod = importasmod("""
            def func1(m, x, y, z):
                raise ValueError("hello\\nworld")
        """)
        excinfo = pytest.raises(ValueError, mod.func1, "m" * 90, 5, 13,
                                "z" * 120)
        excinfo.traceback = excinfo.traceback.filter()
        entry = excinfo.traceback[-1]
        p = FormattedExcinfo(funcargs=True)
        reprfuncargs = p.repr_args(entry)
        assert reprfuncargs is not None
        assert reprfuncargs.args[0] == ("m", repr("m" * 90))
        assert reprfuncargs.args[1] == ("x", "5")
        assert reprfuncargs.args[2] == ("y", "13")
        assert reprfuncargs.args[3] == ("z", repr("z" * 120))

        p = FormattedExcinfo(funcargs=True)
        repr_entry = p.repr_traceback_entry(entry)
        assert repr_entry.reprfuncargs is not None
        assert repr_entry.reprfuncargs.args == reprfuncargs.args
        repr_entry.toterminal(tw_mock)
        assert tw_mock.lines[0] == "m = " + repr("m" * 90)
        assert tw_mock.lines[1] == "x = 5, y = 13"
        assert tw_mock.lines[2] == "z = " + repr("z" * 120)
Example #31
0
    def test_traceback_short_no_source(self, importasmod, monkeypatch) -> None:
        mod = importasmod("""
            def func1():
                raise ValueError("hello")
            def entry():
                func1()
        """)
        excinfo = pytest.raises(ValueError, mod.entry)
        from _pytest._code.code import Code

        monkeypatch.setattr(Code, "path", "bogus")
        excinfo.traceback[
            0].frame.code.path = "bogus"  # type: ignore[misc] # noqa: F821
        p = FormattedExcinfo(style="short")
        reprtb = p.repr_traceback_entry(excinfo.traceback[-2])
        lines = reprtb.lines
        last_p = FormattedExcinfo(style="short")
        last_reprtb = last_p.repr_traceback_entry(excinfo.traceback[-1],
                                                  excinfo)
        last_lines = last_reprtb.lines
        monkeypatch.undo()
        assert lines[0] == "    func1()"

        assert last_lines[0] == '    raise ValueError("hello")'
        assert last_lines[1] == "E   ValueError: hello"
Example #32
0
    def test_repr_local_truncated(self):
        loc = {"l": [i for i in range(10)]}
        p = FormattedExcinfo(showlocals=True)
        truncated_reprlocals = p.repr_locals(loc)
        assert truncated_reprlocals.lines
        assert truncated_reprlocals.lines[0] == "l          = [0, 1, 2, 3, 4, 5, ...]"

        q = FormattedExcinfo(showlocals=True, truncate_locals=False)
        full_reprlocals = q.repr_locals(loc)
        assert full_reprlocals.lines
        assert full_reprlocals.lines[0] == "l          = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]"
Example #33
0
    def test_repr_tracebackentry_no(self, importasmod):
        mod = importasmod("""
            def func1():
                raise ValueError("hello")
            def entry():
                func1()
        """)
        excinfo = pytest.raises(ValueError, mod.entry)
        p = FormattedExcinfo(style="no")
        p.repr_traceback_entry(excinfo.traceback[-2])

        p = FormattedExcinfo(style="no")
        reprentry = p.repr_traceback_entry(excinfo.traceback[-1], excinfo)
        lines = reprentry.lines
        assert lines[0] == "E   ValueError: hello"
        assert not lines[1:]
Example #34
0
 def test_repr_traceback_tbfilter(self, importasmod):
     mod = importasmod("""
         def f(x):
             raise ValueError(x)
         def entry():
             f(0)
     """)
     excinfo = pytest.raises(ValueError, mod.entry)
     p = FormattedExcinfo(tbfilter=True)
     reprtb = p.repr_traceback(excinfo)
     assert len(reprtb.reprentries) == 2
     p = FormattedExcinfo(tbfilter=False)
     reprtb = p.repr_traceback(excinfo)
     assert len(reprtb.reprentries) == 3
Example #35
0
 def test_repr_source_excinfo(self):
     """ check if indentation is right """
     pr = FormattedExcinfo()
     excinfo = self.excinfo_from_exec("""
             def f():
                 assert 0
             f()
     """)
     pr = FormattedExcinfo()
     source = pr._getentrysource(excinfo.traceback[-1])
     lines = pr.get_source(source, 1, excinfo)
     assert lines == [
         "    def f():", ">       assert 0", "E       AssertionError"
     ]
Example #36
0
    def test_repr_tracebackentry_lines_var_kw_args(self, importasmod, tw_mock):
        mod = importasmod("""
            def func1(x, *y, **z):
                raise ValueError("hello\\nworld")
        """)
        excinfo = pytest.raises(ValueError, mod.func1, "a", "b", c="d")
        excinfo.traceback = excinfo.traceback.filter()
        entry = excinfo.traceback[-1]
        p = FormattedExcinfo(funcargs=True)
        reprfuncargs = p.repr_args(entry)
        assert reprfuncargs.args[0] == ("x", repr("a"))
        assert reprfuncargs.args[1] == ("y", repr(("b", )))
        assert reprfuncargs.args[2] == ("z", repr({"c": "d"}))

        p = FormattedExcinfo(funcargs=True)
        repr_entry = p.repr_traceback_entry(entry)
        assert repr_entry.reprfuncargs.args == reprfuncargs.args
        repr_entry.toterminal(tw_mock)
        assert tw_mock.lines[0] == "x = 'a', y = ('b',), z = {'c': 'd'}"
Example #37
0
    def test_repr_tracebackentry_lines_var_kw_args(self, importasmod):
        mod = importasmod("""
            def func1(x, *y, **z):
                raise ValueError("hello\\nworld")
        """)
        excinfo = pytest.raises(ValueError, mod.func1, 'a', 'b', c='d')
        excinfo.traceback = excinfo.traceback.filter()
        entry = excinfo.traceback[-1]
        p = FormattedExcinfo(funcargs=True)
        reprfuncargs = p.repr_args(entry)
        assert reprfuncargs.args[0] == ('x', repr('a'))
        assert reprfuncargs.args[1] == ('y', repr(('b', )))
        assert reprfuncargs.args[2] == ('z', repr({'c': 'd'}))

        p = FormattedExcinfo(funcargs=True)
        repr_entry = p.repr_traceback_entry(entry)
        assert repr_entry.reprfuncargs.args == reprfuncargs.args
        tw = TWMock()
        repr_entry.toterminal(tw)
        assert tw.lines[0] == "x = 'a', y = ('b',), z = {'c': 'd'}"
Example #38
0
    def test_repr_tracebackentry_lines2(self, importasmod):
        mod = importasmod("""
            def func1(m, x, y, z):
                raise ValueError("hello\\nworld")
        """)
        excinfo = pytest.raises(ValueError, mod.func1, "m" * 90, 5, 13, "z" * 120)
        excinfo.traceback = excinfo.traceback.filter()
        entry = excinfo.traceback[-1]
        p = FormattedExcinfo(funcargs=True)
        reprfuncargs = p.repr_args(entry)
        assert reprfuncargs.args[0] == ('m', repr("m" * 90))
        assert reprfuncargs.args[1] == ('x', '5')
        assert reprfuncargs.args[2] == ('y', '13')
        assert reprfuncargs.args[3] == ('z', repr("z" * 120))

        p = FormattedExcinfo(funcargs=True)
        repr_entry = p.repr_traceback_entry(entry)
        assert repr_entry.reprfuncargs.args == reprfuncargs.args
        tw = TWMock()
        repr_entry.toterminal(tw)
        assert tw.lines[0] == "m = " + repr('m' * 90)
        assert tw.lines[1] == "x = 5, y = 13"
        assert tw.lines[2] == "z = " + repr('z' * 120)
Example #39
0
    def test_repr_source_failing_fullsource(self):
        pr = FormattedExcinfo()

        class FakeCode(object):
            class raw(object):
                co_filename = "?"

            path = "?"
            firstlineno = 5

            def fullsource(self):
                return None

            fullsource = property(fullsource)

        class FakeFrame(object):
            code = FakeCode()
            f_locals = {}
            f_globals = {}

        class FakeTracebackEntry(_pytest._code.Traceback.Entry):
            def __init__(self, tb, excinfo=None):
                self.lineno = 5 + 3

            @property
            def frame(self):
                return FakeFrame()

        class Traceback(_pytest._code.Traceback):
            Entry = FakeTracebackEntry

        class FakeExcinfo(_pytest._code.ExceptionInfo):
            typename = "Foo"
            value = Exception()

            def __init__(self):
                pass

            def exconly(self, tryshort):
                return "EXC"

            def errisinstance(self, cls):
                return False

        excinfo = FakeExcinfo()

        class FakeRawTB(object):
            tb_next = None

        tb = FakeRawTB()
        excinfo.traceback = Traceback(tb)

        fail = IOError()
        repr = pr.repr_excinfo(excinfo)
        assert repr.reprtraceback.reprentries[0].lines[0] == ">   ???"
        if sys.version_info[0] >= 3:
            assert repr.chain[0][0].reprentries[0].lines[0] == ">   ???"

        fail = py.error.ENOENT  # noqa
        repr = pr.repr_excinfo(excinfo)
        assert repr.reprtraceback.reprentries[0].lines[0] == ">   ???"
        if sys.version_info[0] >= 3:
            assert repr.chain[0][0].reprentries[0].lines[0] == ">   ???"