Package: pytest-doctestplus
This package contains a plugin for thepytestframework that provides
advanced doctest support and enables the testing of various text files, such
as reStructuredText (“.rst”), markdown (“.md”), and TeX (“.tex”).MotivationThis plugin provides advanced features for testing example Python code that is
included in Python docstrings and in standalone documentation files.Good documentation for developers contains example code. This is true of both
standalone documentation and of documentation that is integrated with the code
itself. Python provides a mechanism for testing code snippets that are provided
in Python docstrings. The unit test framework pytest provides a mechanism for
running doctests against both docstrings in source code and in standalone
documentation files.This plugin augments the functionality provided by Python and pytest by
providing the following features:approximate floating point comparison for doctests that produce floating
point results (seeFloating Point Comparison)skipping particular classes, methods, and functions when running doctests (seeSkipping Tests)handling doctests that use remote data in conjunction with thepytest-remotedataplugin (seeRemote Data)optional inclusion of*.rstfiles for doctests (seeSetup and Configuration)optional inclusion of doctests in docstrings of Numpy ufuncsFurther,pytest-doctestplussupports editing files to fix incorrect docstrings
(SeeFixing Existing Docstrings).InstallationThepytest-doctestplusplugin can be installed usingpip:$ pip install pytest-doctestplusIt is also possible to install the latest development version from the source
repository:$ git clone https://github.com/scientific-python/pytest-doctestplus
$ cd pytest-doctestplus
$ pip install .In either case, the plugin will automatically be registered for use withpytest.UsageSetup and ConfigurationThis plugin provides three command line options:--doctest-plusfor enabling
the advanced features mentioned above,--doctest-rstfor including*.rstfiles in doctest collection, and--doctest-ufuncfor including
doctests in docstrings of Numpy ufuncs.This plugin can also be enabled by default by addingdoctest_plus = enabledto the[tool:pytest]section of the package’ssetup.cfgfile.The plugin is applied to all directories and files thatpytestcollects.
This means that configuringtestpathsandnorecursedirsinsetup.cfgalso affects the files that will be discovered bypytest-doctestplus. In addition, this plugin provides adoctest_norecursedirsconfiguration variable that indicates directories
that should be ignored bypytest-doctestplusbut do not need to be ignored
by otherpytestfeatures.Usingpytest’s built-in--doctest-modulesoption will override the
behavior of this plugin, even ifdoctest_plus = enabledinsetup.cfg,
and will cause the default doctest plugin to be used. However, if for some
reason both--doctest-modulesand--doctest-plusare given, thepytest-doctestplusplugin will be used, regardless of the contents ofsetup.cfg.pytest-doctestplusrespects the--doctest-continue-on-failureflag.
If set, doctests will report all failing lines, which may be useful to detect
independent errors within the same doctest. However, it is likely to generate
false positives when an early failure causes a variable later lines access to
remain unset or have an unexpected value.This plugin respects the doctest options that are used by the built-in doctest
plugin and are set indoctest_optionflagsinsetup.cfg. By default,ELLIPSISandNORMALIZE_WHITESPACEare used. For a description of all
doctest settings, see thedoctest documentation.Running Tests in Markdown FilesTo run doctests in Markdown files, invoke pytest with the command line options--doctest-plus--doctest-glob'*.md'.If you write doctests insideGitHub-style triple backtick fenced code blocks,
then in order for pytest-doctest to find and run them you need to include an
extra trailing newline inside your code blocks, like this:```pycon
>>> 1 + 2
2

```Doctest DirectivesThepytest-doctestplusplugin definesdoctest directivesthat are used
to control the behavior of particular features. For general information on
directives and how they are used, consult thedocumentation. The specifics
of the directives that this plugin defines are described in the sections below.Sphinx Doctest DirectivesYou can usetestsetupandtestcleanupin Sphinx RST to run code that is
not visible in rendered document. However, due to howpytest-doctestplusworks, the code within needs to be prepended by>>>. For example:.. testsetup::

    >>> x = 42

.. testcleanup::

    >>> del xFloating Point ComparisonSome doctests may produce output that contains string representations of
floating point values.  Floating point representations are often not exact and
contain roundoffs in their least significant digits.  Depending on the platform
the tests are being run on (different Python versions, different OS, etc.) the
exact number of digits shown can differ.  Because doctests work by comparing
strings this can cause such tests to fail.To address this issue, thepytest-doctestplusplugin provides support for aFLOAT_CMPflag that can be used with doctests.  For example:>>>1.0/3.0# doctest: +FLOAT_CMP0.333333333333333311>>>{'a':1/3.,'b':2/3.}# doctest: +FLOAT_CMP{'a':0.333333,'b':0.666666}When this flag is used, the expected and actual outputs are both parsed to find
any floating point values in the strings.  Those are then converted to actual
Pythonfloatobjects and compared numerically.  This means that small
differences in representation of roundoff digits will be ignored by the
doctest.  The values are otherwise compared exactly, so more significant
(albeit possibly small) differences will still be caught by these tests.This flag can be enabled globally by adding it tosetup.cfgas indoctest_optionflags=NORMALIZE_WHITESPACEELLIPSISFLOAT_CMPIgnoring warningsIf code in a doctest emits a warning and you want to make sure that warning is silenced,
you can make use of theIGNORE_WARNINGSflag. For example:>>>importnumpyasnp>>>np.mean([])# doctest: +IGNORE_WARNINGSnp.nanShowing warningsIf code in a doctest emits a warning and you want to make sure that warning is
shown, you can make use of theSHOW_WARNINGSflag. This is useful when
warnings are turned into errors by pytest, and also because by default warnings
are printed to stderr. This is the opposite fromIGNORE_WARNINGSso
obviously the two flags should not be used together. For example:>>>importnumpyasnp>>>np.mean([])# doctest: +SHOW_WARNINGSRuntimeWarning:Meanofemptyslice.RuntimeWarning:invalidvalueencounteredindouble_scalarsnp.nanSkipping TestsDoctest provides the+SKIPdirective for skipping statements that should
not be executed when testing documentation.>>>open('file.txt')# doctest: +SKIPIn Sphinx.rstdocumentation, whole code example blocks can be skipped with the
directive..doctest-skip::>>> import asdf>>> asdf.open('file.asdf')However, it is often useful to be able to skip docstrings associated with
particular functions, methods, classes, or even entire files.Skipping All the TestsIt is also possible to skip all doctests below a certain line using
adoctest-skip-allcomment.  Note the lack of::at the end
of the line here... doctest-skip-all

   >>> import non_existing
   >>> non_existing.write_pseudo_code()
   All the doctests are skipped in the file belowSkip UnconditionallyThepytest-doctestplusplugin provides a way to indicate that certain
docstrings should be skipped altogether. This is configured by defining the
variable__doctest_skip__in each module where tests should be skipped. The
value of__doctest_skip__should be a list of wildcard patterns for all
functions/classes whose doctests should be skipped.  For example:__doctest_skip__ = ['myfunction', 'MyClass', 'MyClass.*']skips the doctests in a function calledmyfunction, the doctest for a
class calledMyClass, and allmethodsofMyClass.Module docstrings may contain doctests as well. To skip the module-level
doctests:__doctest_skip__  = ['.', 'myfunction', 'MyClass']To skip all doctests in a module:__doctest_skip__ = ['*']Doctest DependenciesIt is also possible to skip certain doctests depending on whether particular
dependencies are available. This is configured by defining the variable__doctest_requires__at the module level. The value of this variable is
a dictionary that indicates the modules that are required to run the doctests
associated with particular functions, classes, and methods.The keys in the dictionary are wildcard patterns like those described above, or
tuples of wildcard patterns, indicating which docstrings should be skipped. The
values in the dictionary are lists of module names that are required in order
for the given doctests to be executed.Consider the following example:__doctest_requires__ = {('func1', 'func2'): ['scipy']}Having this module-level variable will requirescipyto be importable
in order to run the doctests for functionsfunc1andfunc2in that
module.Similarly, in Sphinx.rstdocumentation, whole code example blocks can be
conditionally skipped if a dependency is not available...doctest-requires::asdf>>> import asdf>>> asdf.open('file.asdf')Furthermore, if the code only runs for specific versions of the optional dependency,
you can add a version check like this:..doctest-requires::asdf<3>>> import asdf>>> asdf.open('file.asdf')Finally, it is possible to skip collecting doctests in entire subpackages by
using thedoctest_subpackage_requiresin the[tool:pytest]section of
the package’ssetup.cfgfile. The syntax for this option is a list ofpath = requirements, e.g.:doctest_subpackage_requires =
    astropy/wcs/* = scipy>2.0;numpy>1.14
    astropy/cosmology/* = scipy>1.0Multiple requirements can be specified if separated by semicolons.Remote DataThepytest-doctestplusplugin can be used in conjunction with thepytest-remotedataplugin in order to control doctest code that requires
access to data from the internet. In order to make use of these features, thepytest-remotedataplugin must be installed, and remote data access must
be enabled using the--remote-datacommand line option topytest. See
thepytest-remotedata plugin documentationfor more details.The following example illustrates how a doctest that uses remote data should be
marked:>>>fromurlib.requestimporturlopen>>>url=urlopen('http://astropy.org')# doctest: +REMOTE_DATAThe+REMOTE_DATAdirective indicates that the marked statement should only
be executed if the--remote-dataoption is given. By default, all
statements marked with the remote data directive will be skipped.Whole code example blocks can also be marked to control access to data from the internet
this way:..doctest-remote-data::>>>importrequests>>>r=requests.get('https://www.astropy.org')Sphinx CompatibilityTo use the additional directives when building your documentation with sphinx
you may want to enable the sphinx extension which registers these directives
with sphinx. Doing so ensures that sphinx correctly ignores these directives,
running the doctests with sphinx is not supported. To do this, add'pytest_doctestplus.sphinx.doctestplus'to yourextensionslist in yourconf.pyfile.Fixing Existing DocstringsThe plugin has basic support to fix docstrings, this can be enabled by
runningpytestwith--doctest-plus-generate-diff.
Without further options, this will print out a diff and a list of files that
would be modified.  Using--doctest-plus-generate-diff=overwritewill
modify the files in-place, so it is recommended to run the check first to
verify the paths.
You may wish to review changes manually and only commit some patches e.g. usinggit commit--patch.The current diff generation is still very basic, for example, it does not account for
existing....  By default a diff is only generated forfailingdoctests.In general, a mass edit may wish to focus on a specific change and
possibly include passing tests.  So you can opt-in into the behavior by
adding a hook to yourconftest.py:@pytest.hookimpl
def pytest_doctestplus_diffhook(info):
    info["use"] = True  # Overwrite all results (even successes)
    if info["fileno"] is None:
        # E.g. NumPy has C docstrings that cannot be found, we can add
        # custom logic here to try and find these:
        info["filename"] = ...
        info["lineno"] = ...Whereinfois a dictionary containing the following items:use:TrueorFalsesignalling whether to apply the diff.  This is
set toFalseif a doctest succeeded andTrueif the doctest failed.name: The name of the test (e.g. the function being documented)filename: The file that contains the test (this can be wrong in certain
situation and in that casetest_linenowill be wrong as well).source: The source code that was executed for this testtest_lineno: The line of code where the example block (or function) starts.
In some cases, the test file cannot be found and the lineno will beNone,
you can manually try to fix these.example_lineno: The line number of the example snippet
(individual>>>).want: The current documentation.got: The result of executing the example.You can modify the dictionary in-place to modify the behavior.Please note that we assume that this API will be used only occasionally and
reserve the right to change it at any time.Development StatusQuestions, bug reports, and feature requests can be submitted ongithub.LicenseThis plugin is licensed under a 3-clause BSD style license - see theLICENSE.rstfile.