Beispiel #1
0
def test_exception_repr_extraction_error_on_recursion():
    """
    Ensure we can properly detect a recursion error even
    if some locals raise error on comparision (#2459).
    """
    class numpy_like(object):
        def __eq__(self, other):
            if type(other) is numpy_like:
                raise ValueError('The truth value of an array '
                                 'with more than one element is ambiguous.')

    def a(x):
        return b(numpy_like())

    def b(x):
        return a(numpy_like())

    try:
        a(numpy_like())
    except:
        from _pytest._code.code import ExceptionInfo
        from _pytest.pytester import LineMatcher
        exc_info = ExceptionInfo()

        matcher = LineMatcher(str(exc_info.getrepr()).splitlines())
        matcher.fnmatch_lines([
            '!!! Recursion error detected, but an error occurred locating the origin of recursion.',
            '*The following exception happened*',
            '*ValueError: The truth value of an array*',
        ])
Beispiel #2
0
def run_coro_as_main(loop, coro):
    class Captured(Exception):
        def __init__(self, error):
            self.error = error

    try:

        async def runner():
            __tracebackhide__ = True

            try:
                await coro
            except:
                exc_info = sys.exc_info()
                exc_info[1].__traceback__ = exc_info[2]
                raise Captured(exc_info[1])

        task = loop.create_task(runner())
        loop.run_until_complete(task)
    except:
        exc_type, exc, tb = sys.exc_info()
        if issubclass(exc_type, Captured):
            exc = exc.error
            exc_type = type(exc)
            tb = exc.__traceback__
        info = ExceptionInfo((exc_type, exc, tb), "")
        print(info.getrepr(style="short"))
        sys.exit(1)
    finally:
        cancel_all_tasks(loop, ignore_errors_from_tasks=[task])
        loop.close()
Beispiel #3
0
def test_exception_repr_extraction_error_on_recursion():
    """
    Ensure we can properly detect a recursion error even
    if some locals raise error on comparision (#2459).
    """
    class numpy_like(object):

        def __eq__(self, other):
            if type(other) is numpy_like:
                raise ValueError('The truth value of an array '
                                 'with more than one element is ambiguous.')

    def a(x):
        return b(numpy_like())

    def b(x):
        return a(numpy_like())

    try:
        a(numpy_like())
    except:  # noqa
        from _pytest._code.code import ExceptionInfo
        from _pytest.pytester import LineMatcher
        exc_info = ExceptionInfo()

        matcher = LineMatcher(str(exc_info.getrepr()).splitlines())
        matcher.fnmatch_lines([
            '!!! Recursion error detected, but an error occurred locating the origin of recursion.',
            '*The following exception happened*',
            '*ValueError: The truth value of an array*',
        ])
Beispiel #4
0
def test_no_recursion_index_on_recursion_error():
    """
    Ensure that we don't break in case we can't find the recursion index
    during a recursion error (#2486).
    """
    try:
        class RecursionDepthError(object):
            def __getattr__(self, attr):
                return getattr(self, '_' + attr)

        RecursionDepthError().trigger
    except:
        from _pytest._code.code import ExceptionInfo
        exc_info = ExceptionInfo()
        if sys.version_info[:2] == (2, 6):
            assert "'RecursionDepthError' object has no attribute '___" in str(exc_info.getrepr())
        else:
            assert 'maximum recursion' in str(exc_info.getrepr())
    else:
        assert 0
def handle_teardowns(item):
    __tracebackhide__ = True
    case = item._location

    teardown_groups = case._teardown_groups
    for group in teardown_groups:
        if group in case._helper._level_stack:
            start_time = time()
            try:
                group._teardown_group()
            except:
                # handle error during group setup
                excinfo = ExceptionInfo()
                stop_time = time()
                nodeid = item.nodeid.split("::")[0] + "::"
                nodeid += group._inline_description
                location = group._last_location
                keywords = {}
                outcome = "failed"
                longrepr = excinfo.getrepr()
                when = "teardown"
                sections = []
                duration = stop_time - start_time
                context_lines = [
                    "Context:",
                    "",
                ]
                context_lines += str(location).split("\n")
                context_lines[-1] = ">" + context_lines[-1][1:]
                entry = ReprEntry(
                    context_lines,
                    None,
                    None,
                    None,
                    "long",
                )
                if hasattr(longrepr, "chain"):
                    reprtraceback = longrepr.chain[0][0]
                else:
                    reprtraceback = longrepr.reprtraceback
                reprtraceback.reprentries.insert(0, entry)
                report = TestReport(
                    nodeid,
                    location,
                    keywords,
                    outcome,
                    longrepr,
                    when,
                    sections,
                    duration,
                )
                item.ihook.pytest_runtest_logreport(report=report)
Beispiel #6
0
    def _importtestmodule(self):
        # we assume we are only called once per module
        importmode = self.config.getoption("--import-mode")
        try:
            mod = self.fspath.pyimport(ensuresyspath=importmode)
        except SyntaxError:
            raise self.CollectError(
                _pytest._code.ExceptionInfo().getrepr(style="short")
            )
        except self.fspath.ImportMismatchError:
            e = sys.exc_info()[1]
            raise self.CollectError(
                "import file mismatch:\n"
                "imported module %r has this __file__ attribute:\n"
                "  %s\n"
                "which is not the same as the test file we want to collect:\n"
                "  %s\n"
                "HINT: remove __pycache__ / .pyc files and/or use a "
                "unique basename for your test file modules" % e.args
            )
        except ImportError:
            from _pytest._code.code import ExceptionInfo

            exc_info = ExceptionInfo()
            if self.config.getoption("verbose") < 2:
                exc_info.traceback = exc_info.traceback.filter(filter_traceback)
            exc_repr = (
                exc_info.getrepr(style="short")
                if exc_info.traceback
                else exc_info.exconly()
            )
            formatted_tb = safe_str(exc_repr)
            raise self.CollectError(
                "ImportError while importing test module '{fspath}'.\n"
                "Hint: make sure your test modules/packages have valid Python names.\n"
                "Traceback:\n"
                "{traceback}".format(fspath=self.fspath, traceback=formatted_tb)
            )
        except _pytest.runner.Skipped as e:
            if e.allow_module_level:
                raise
            raise self.CollectError(
                "Using pytest.skip outside of a test is not allowed. "
                "To decorate a test function, use the @pytest.mark.skip "
                "or @pytest.mark.skipif decorators instead, and to skip a "
                "module use `pytestmark = pytest.mark.{skip,skipif}."
            )
        self.config.pluginmanager.consider_module(mod)
        return mod
Beispiel #7
0
    def _importtestmodule(self):
        # we assume we are only called once per module
        importmode = self.config.getoption("--import-mode")
        try:
            mod = self.fspath.pyimport(ensuresyspath=importmode)
        except SyntaxError:
            raise self.CollectError(
                _pytest._code.ExceptionInfo().getrepr(style="short")
            )
        except self.fspath.ImportMismatchError:
            e = sys.exc_info()[1]
            raise self.CollectError(
                "import file mismatch:\n"
                "imported module %r has this __file__ attribute:\n"
                "  %s\n"
                "which is not the same as the test file we want to collect:\n"
                "  %s\n"
                "HINT: remove __pycache__ / .pyc files and/or use a "
                "unique basename for your test file modules" % e.args
            )
        except ImportError:
            from _pytest._code.code import ExceptionInfo

            exc_info = ExceptionInfo()
            if self.config.getoption("verbose") < 2:
                exc_info.traceback = exc_info.traceback.filter(filter_traceback)
            exc_repr = (
                exc_info.getrepr(style="short")
                if exc_info.traceback
                else exc_info.exconly()
            )
            formatted_tb = safe_str(exc_repr)
            raise self.CollectError(
                "ImportError while importing test module '{fspath}'.\n"
                "Hint: make sure your test modules/packages have valid Python names.\n"
                "Traceback:\n"
                "{traceback}".format(fspath=self.fspath, traceback=formatted_tb)
            )
        except _pytest.runner.Skipped as e:
            if e.allow_module_level:
                raise
            raise self.CollectError(
                "Using pytest.skip outside of a test is not allowed. "
                "To decorate a test function, use the @pytest.mark.skip "
                "or @pytest.mark.skipif decorators instead, and to skip a "
                "module use `pytestmark = pytest.mark.{skip,skipif}."
            )
        self.config.pluginmanager.consider_module(mod)
        return mod
Beispiel #8
0
def test_no_recursion_index_on_recursion_error():
    """
    Ensure that we don't break in case we can't find the recursion index
    during a recursion error (#2486).
    """
    try:
        class RecursionDepthError(object):
            def __getattr__(self, attr):
                return getattr(self, '_' + attr)

        RecursionDepthError().trigger
    except:  # noqa
        from _pytest._code.code import ExceptionInfo
        exc_info = ExceptionInfo()
        assert 'maximum recursion' in str(exc_info.getrepr())
    else:
        assert 0
 def setup_contextional_groups(self, nodeid, location):
     __tracebackhide__ = True
     for group in location._group._setup_ancestry:
         if group not in group._helper._level_stack:
             if self.showlongtestinfo:
                 group._pytest_writer = self
             start_time = time()
             try:
                 group._setup_group()
             except:
                 # handle error during group setup
                 excinfo = ExceptionInfo()
                 stop_time = time()
                 nodeid = nodeid.split("::")[0] + "::"
                 nodeid += group._inline_description
                 location = group._last_location
                 keywords = {}
                 outcome = "failed"
                 longrepr = excinfo.getrepr()
                 when = "setup"
                 sections = []
                 duration = stop_time - start_time
                 context_lines = [
                     "Context:",
                     "",
                 ]
                 context_lines += str(location).split("\n")
                 context_lines[-1] = ">" + context_lines[-1][1:]
                 entry = ReprEntry(context_lines, None, None, None, "long")
                 if hasattr(longrepr, "chain"):
                     reprtraceback = longrepr.chain[0][0]
                 else:
                     reprtraceback = longrepr.reprtraceback
                 reprtraceback.reprentries.insert(0, entry)
                 report = TestReport(
                     nodeid,
                     location,
                     keywords,
                     outcome,
                     longrepr,
                     when,
                     sections,
                     duration,
                 )
                 self.pytest_runtest_logreport(report)
Beispiel #10
0
def test_no_recursion_index_on_recursion_error():
    """
    Ensure that we don't break in case we can't find the recursion index
    during a recursion error (#2486).
    """
    try:

        class RecursionDepthError(object):
            def __getattr__(self, attr):
                return getattr(self, "_" + attr)

        RecursionDepthError().trigger
    except:  # noqa
        from _pytest._code.code import ExceptionInfo

        exc_info = ExceptionInfo()
        assert "maximum recursion" in str(exc_info.getrepr())
    else:
        assert 0