diff --git a/AUTHORS b/AUTHORS index 85fe6aff0..d6f6ce828 100644 --- a/AUTHORS +++ b/AUTHORS @@ -222,6 +222,7 @@ Steffen Allner Stephan Obermann Sven-Hendrik Haase Tadek Teleżyński +Takafumi Arakaki Tarcisio Fischer Tareq Alayan Ted Xiao diff --git a/changelog/4911.feature.rst b/changelog/4911.feature.rst new file mode 100644 index 000000000..5aef92d76 --- /dev/null +++ b/changelog/4911.feature.rst @@ -0,0 +1 @@ +Doctests can be skipped now dynamically using ``pytest.skip()``. diff --git a/src/_pytest/doctest.py b/src/_pytest/doctest.py index d34cb638c..34b6c9d8c 100644 --- a/src/_pytest/doctest.py +++ b/src/_pytest/doctest.py @@ -15,6 +15,7 @@ from _pytest._code.code import ReprFileLocation from _pytest._code.code import TerminalRepr from _pytest.compat import safe_getattr from _pytest.fixtures import FixtureRequest +from _pytest.outcomes import Skipped DOCTEST_REPORT_CHOICE_NONE = "none" DOCTEST_REPORT_CHOICE_CDIFF = "cdiff" @@ -153,6 +154,8 @@ def _init_runner_class(): raise failure def report_unexpected_exception(self, out, test, example, exc_info): + if isinstance(exc_info[1], Skipped): + raise exc_info[1] failure = doctest.UnexpectedException(test, example, exc_info) if self.continue_on_failure: out.append(failure) diff --git a/src/_pytest/outcomes.py b/src/_pytest/outcomes.py index 14c6e9ab6..6c2dfb5ae 100644 --- a/src/_pytest/outcomes.py +++ b/src/_pytest/outcomes.py @@ -80,7 +80,8 @@ def skip(msg="", **kwargs): Skip an executing test with the given message. This function should be called only during testing (setup, call or teardown) or - during collection by using the ``allow_module_level`` flag. + during collection by using the ``allow_module_level`` flag. This function can + be called in doctests as well. :kwarg bool allow_module_level: allows this function to be called at module level, skipping the rest of the module. Default to False. @@ -89,6 +90,9 @@ def skip(msg="", **kwargs): It is better to use the :ref:`pytest.mark.skipif ref` marker when possible to declare a test to be skipped under certain conditions like mismatching platforms or dependencies. + Similarly, use the ``# doctest: +SKIP`` directive (see `doctest.SKIP + `_) + to skip a doctest statically. """ __tracebackhide__ = True allow_module_level = kwargs.pop("allow_module_level", False) diff --git a/testing/test_doctest.py b/testing/test_doctest.py index e7b6b060f..09f7c331d 100644 --- a/testing/test_doctest.py +++ b/testing/test_doctest.py @@ -188,6 +188,18 @@ class TestDoctests(object): ] ) + def test_doctest_skip(self, testdir): + testdir.maketxtfile( + """ + >>> 1 + 1 + >>> import pytest + >>> pytest.skip("") + """ + ) + result = testdir.runpytest("--doctest-modules") + result.stdout.fnmatch_lines(["*1 skipped*"]) + def test_docstring_partial_context_around_error(self, testdir): """Test that we show some context before the actual line of a failing doctest.