Skip to content

Commit 0da5531

Browse files
authored
Merge pull request #4599 from s0undt3ch/feature/skiporfail-reason
Custom reason support for "importorskip"
2 parents 56aecfc + 0c48986 commit 0da5531

File tree

3 files changed

+30
-5
lines changed

3 files changed

+30
-5
lines changed

changelog/4599.feature.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
``pytest.importorskip`` now supports a ``reason`` parameter, which will be shown when the
2+
requested module cannot be imported.

src/_pytest/outcomes.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -137,10 +137,15 @@ def xfail(reason=""):
137137
xfail.Exception = XFailed
138138

139139

140-
def importorskip(modname, minversion=None):
141-
""" return imported module if it has at least "minversion" as its
142-
__version__ attribute. If no minversion is specified the a skip
143-
is only triggered if the module can not be imported.
140+
def importorskip(modname, minversion=None, reason=None):
141+
"""Imports and returns the requested module ``modname``, or skip the current test
142+
if the module cannot be imported.
143+
144+
:param str modname: the name of the module to import
145+
:param str minversion: if given, the imported module ``__version__`` attribute must be
146+
at least this minimal version, otherwise the test is still skipped.
147+
:param str reason: if given, this reason is shown as the message when the module
148+
cannot be imported.
144149
"""
145150
import warnings
146151

@@ -159,7 +164,9 @@ def importorskip(modname, minversion=None):
159164
# Do not raise chained exception here(#1485)
160165
should_skip = True
161166
if should_skip:
162-
raise Skipped("could not import %r" % (modname,), allow_module_level=True)
167+
if reason is None:
168+
reason = "could not import %r" % (modname,)
169+
raise Skipped(reason, allow_module_level=True)
163170
mod = sys.modules[modname]
164171
if minversion is None:
165172
return mod

testing/test_runner.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -738,6 +738,22 @@ def test_foo():
738738
result.stdout.fnmatch_lines(["*collected 0 items / 1 skipped*"])
739739

740740

741+
def test_importorskip_custom_reason(testdir):
742+
"""make sure custom reasons are used"""
743+
testdir.makepyfile(
744+
"""
745+
import pytest
746+
foobarbaz = pytest.importorskip("foobarbaz2", reason="just because")
747+
748+
def test_foo():
749+
pass
750+
"""
751+
)
752+
result = testdir.runpytest("-ra")
753+
result.stdout.fnmatch_lines(["*just because*"])
754+
result.stdout.fnmatch_lines(["*collected 0 items / 1 skipped*"])
755+
756+
741757
def test_pytest_cmdline_main(testdir):
742758
p = testdir.makepyfile(
743759
"""

0 commit comments

Comments
 (0)