From 3405c7e6a859c044080dc34dd7c5a66748d20cee Mon Sep 17 00:00:00 2001 From: Prakhar Gurunani Date: Sat, 28 Nov 2020 21:17:02 +0530 Subject: [PATCH] Add more info about skipping doctests (#8080) Co-authored-by: Bruno Oliveira --- AUTHORS | 1 + changelog/7429.doc.rst | 1 + doc/en/doctest.rst | 45 ++++++++++++++++++++++++++++++++++++++---- 3 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 changelog/7429.doc.rst diff --git a/AUTHORS b/AUTHORS index 85d5b90de3d..adf1894356a 100644 --- a/AUTHORS +++ b/AUTHORS @@ -239,6 +239,7 @@ Philipp Loose Pieter Mulder Piotr Banaszkiewicz Piotr Helm +Prakhar Gurunani Prashant Anand Prashant Sharma Pulkit Goyal diff --git a/changelog/7429.doc.rst b/changelog/7429.doc.rst new file mode 100644 index 00000000000..e6376b727b2 --- /dev/null +++ b/changelog/7429.doc.rst @@ -0,0 +1 @@ +Add more information and use cases about skipping doctests. diff --git a/doc/en/doctest.rst b/doc/en/doctest.rst index c6e34b2b1c8..f486d5a9b6d 100644 --- a/doc/en/doctest.rst +++ b/doc/en/doctest.rst @@ -253,12 +253,32 @@ Note that like the normal ``conftest.py``, the fixtures are discovered in the di Meaning that if you put your doctest with your source code, the relevant conftest.py needs to be in the same directory tree. Fixtures will not be discovered in a sibling directory tree! -Skipping tests dynamically -^^^^^^^^^^^^^^^^^^^^^^^^^^ +Skipping tests +^^^^^^^^^^^^^^ + +For the same reasons one might want to skip normal tests, it is also possible to skip +tests inside doctests. + +To skip a single check inside a doctest you can use the standard +`doctest.SKIP `__ directive: + +.. code-block:: python + + def test_random(y): + """ + >>> random.random() # doctest: +SKIP + 0.156231223 + + >>> 1 + 1 + 2 + """ -.. versionadded:: 4.4 +This will skip the first check, but not the second. + +pytest also allows using the standard pytest functions :func:`pytest.skip` and +:func:`pytest.xfail` inside doctests, which might be useful because you can +then skip/xfail tests based on external conditions: -You can use ``pytest.skip`` to dynamically skip doctests. For example: .. code-block:: text @@ -266,3 +286,20 @@ You can use ``pytest.skip`` to dynamically skip doctests. For example: >>> if sys.platform.startswith('win'): ... pytest.skip('this doctest does not work on Windows') ... + >>> import fcntl + >>> ... + +However using those functions is discouraged because it reduces the readability of the +docstring. + +.. note:: + + :func:`pytest.skip` and :func:`pytest.xfail` behave differently depending + if the doctests are in a Python file (in docstrings) or a text file containing + doctests intermingled with text: + + * Python modules (docstrings): the functions only act in that specific docstring, + letting the other docstrings in the same module execute as normal. + + * Text files: the functions will skip/xfail the checks for the rest of the entire + file.