From d19df5efa24038267c9a3601d99152770fcfe9fd Mon Sep 17 00:00:00 2001 From: Daniel Hahler Date: Wed, 15 May 2019 15:53:23 +0200 Subject: [PATCH] importorskip: display/include ImportError This can provide useful information, e.g. > could not import 'pyrepl.readline': curses library not found --- changelog/5269.feature.rst | 1 + src/_pytest/outcomes.py | 10 +++++----- testing/test_skipping.py | 8 ++++++++ 3 files changed, 14 insertions(+), 5 deletions(-) create mode 100644 changelog/5269.feature.rst diff --git a/changelog/5269.feature.rst b/changelog/5269.feature.rst new file mode 100644 index 000000000..6247bfd5c --- /dev/null +++ b/changelog/5269.feature.rst @@ -0,0 +1 @@ +``pytest.importorskip`` includes the ``ImportError`` now in the default ``reason``. diff --git a/src/_pytest/outcomes.py b/src/_pytest/outcomes.py index f57983918..e2a21bb67 100644 --- a/src/_pytest/outcomes.py +++ b/src/_pytest/outcomes.py @@ -154,7 +154,7 @@ def importorskip(modname, minversion=None, reason=None): __tracebackhide__ = True compile(modname, "", "eval") # to catch syntaxerrors - should_skip = False + import_exc = None with warnings.catch_warnings(): # make sure to ignore ImportWarnings that might happen because @@ -163,12 +163,12 @@ def importorskip(modname, minversion=None, reason=None): warnings.simplefilter("ignore") try: __import__(modname) - except ImportError: + except ImportError as exc: # Do not raise chained exception here(#1485) - should_skip = True - if should_skip: + import_exc = exc + if import_exc: if reason is None: - reason = "could not import %r" % (modname,) + reason = "could not import %r: %s" % (modname, import_exc) raise Skipped(reason, allow_module_level=True) mod = sys.modules[modname] if minversion is None: diff --git a/testing/test_skipping.py b/testing/test_skipping.py index fb0822f8f..f1b494777 100644 --- a/testing/test_skipping.py +++ b/testing/test_skipping.py @@ -1177,3 +1177,11 @@ def test_summary_list_after_errors(testdir): "FAILED test_summary_list_after_errors.py::test_fail - assert 0", ] ) + + +def test_importorskip(): + with pytest.raises( + pytest.skip.Exception, + match="^could not import 'doesnotexist': No module named .*", + ): + pytest.importorskip("doesnotexist")