On this page
doctest
Prev: dis | Up: stdlib_module | Next: email
Rel: typing, annotationlib, pydoc, pydoc_data, unittest
Ref: docs.python.org — doctest
Tags: #public #python3 #stdlib
Import
import doctest
Overview
Extracts and executes interactive Python REPL examples (>>> ...) embedded directly inside docstrings and Markdown/text files (testmod, testfile, python -m doctest). Ideal for keeping README and docstring examples guaranteed runnable in CI without duplicating them into separate test files.
Quick Start
import doctest
def double(n: int) -> int:
'''Return twice n.
>>> double(21)
42
'''
return n * 2
res = doctest.run_docstring_examples(double, {"double": double}, verbose=False)
Implementation Walkthrough
1. Running Doctests Across a Module or Documentation File
python3 -m doctest -v my_module.py
import doctest
import sys
# Programmatic check returning (failure_count, test_count):
# result = doctest.testmod(sys.modules[__name__], optionflags=doctest.ELLIPSIS)
Gotchas & Boundaries
- Exact string matching is fragile for dicts, floats, and object addresses: Use
# doctest: +ELLIPSIS(...) or# doctest: +NORMALIZE_WHITESPACEwhen needed. - Great for documentation accuracy, not a replacement for unittest: Keep edge cases, mocks, and error-path matrices in
unittest.
Common Functions
- doctest.debug() —
debug(module, name, pm=False)— Debug a single doctest docstring. - doctest.debug_src() —
debug_src(src, pm=False, globs=None)— Debug a single doctest docstring, in argumentsrc - doctest.DocFileSuite() —
DocFileSuite(*paths, **kw)— A unittest suite for one or more doctest files. - doctest.DocTestSuite() —
DocTestSuite(module=None, globs=None, extraglobs=None, test_finder=None, **options)— Convert doctest tests for a module to a unittest test suite. - doctest.register_optionflag() —
register_optionflag(name)—doctest.register_optionflag()function. - doctest.run_docstring_examples() —
run_docstring_examples(f, globs, verbose=False, name='NoName', compileflags=None, optionflags=0)— Test examples in the given object's docstring (f), usingglobsas globals. Optional argumentnameis used in failure messages. - doctest.script_from_examples() —
script_from_examples(s)— Extract script from text with examples. - doctest.set_unittest_reportflags() —
set_unittest_reportflags(flags)— Sets the unittest option flags. - doctest.testfile() —
testfile(filename, module_relative=True, name=None, package=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, parser=<doctest.DocTestParser object at 0x109e196d0>, encoding=None)— Test examples in the given file. Return (#failures, #tests). - doctest.testmod() —
testmod(m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False)— m=None, name=None, globs=None, verbose=None, report=True, optionflags=0, extraglobs=None, raise_on_error=False, exclude_empty=False - doctest.testsource() —
testsource(module, name)— Extract the test sources from a doctest docstring as a script.
Classes & Objects
- doctest.DebugRunner — Run doc tests but raise an exception as soon as there is a failure. (Methods:
.merge(),.report_failure(),.report_start(),.report_success(),.report_unexpected_exception(),.run()) - doctest.DocTest — A collection of doctest examples that should be run in a single namespace. Each
DocTestdefines the following attributes: - examples: the list of examples. - doctest.DocTestFailure — A DocTest example has failed in debugging mode. (Methods:
.add_note(),.with_traceback()) - doctest.DocTestFinder — A class used to extract the DocTests that are relevant to a given object, from its docstring and the docstrings of its contained objects. Doctests can currently be extracted from the following (Methods:
.find()) - doctest.DocTestParser — A class used to parse strings containing doctest examples. (Methods:
.get_doctest(),.get_examples(),.parse()) - doctest.DocTestRunner — A class used to run DocTest test cases, and accumulate statistics. (Methods:
.merge(),.report_failure(),.report_start(),.report_success(),.report_unexpected_exception(),.run()) - doctest.Example — A single doctest example, consisting of source code and expected output.
Exampledefines the following attributes: - source: A single Python statement, always ending with a newline. - doctest.OutputChecker — A class used to check whether the actual output from a doctest example matches the expected output.
OutputCheckerdefines two methods:check_output, which compares a given pair of outputs, (Methods:.check_output(),.output_difference()) - doctest.UnexpectedException — A DocTest example has encountered an unexpected exception The exception instance has variables: - test: the DocTest object being run (Methods:
.add_note(),.with_traceback())
Constants & Attributes
doctest.COMPARISON_FLAGS(int) =63doctest.DONT_ACCEPT_BLANKLINE(int) =2doctest.DONT_ACCEPT_TRUE_FOR_1(int) =1doctest.ELLIPSIS(int) =8doctest.FAIL_FAST(int) =1024doctest.IGNORE_EXCEPTION_DETAIL(int) =32doctest.NORMALIZE_WHITESPACE(int) =4doctest.REPORTING_FLAGS(int) =1984doctest.REPORT_CDIFF(int) =128doctest.REPORT_NDIFF(int) =256doctest.REPORT_ONLY_FIRST_FAILURE(int) =512doctest.REPORT_UDIFF(int) =64doctest.SKIP(int) =16
Linked from
- tuts/python3/stdlib_module
- tuts/python3/stdlib_module/annotationlib
- tuts/python3/stdlib_module/bdb
- tuts/python3/stdlib_module/cProfile
- tuts/python3/stdlib_module/dis
- tuts/python3/stdlib_module/email
- tuts/python3/stdlib_module/faulthandler
- tuts/python3/stdlib_module/pdb
- tuts/python3/stdlib_module/profile
- tuts/python3/stdlib_module/pstats
- tuts/python3/stdlib_module/pydoc
- tuts/python3/stdlib_module/pydoc_data
- tuts/python3/stdlib_module/stdlib_module
- tuts/python3/stdlib_module/timeit
- tuts/python3/stdlib_module/trace
- tuts/python3/stdlib_module/tracemalloc
- tuts/python3/stdlib_module/typing
- tuts/python3/stdlib_module/unittest
- tuts/python3/tutorials/intermediate_python_and_software_engineering/testing_and_debugging
Related notes
- tuts/python3/stdlib_module/annotationlib Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/dis Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/email Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pydoc Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/pydoc_data Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/typing Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/unittest Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/doctest/testfile Linked here; shared tags: #failures, #stdlib, #tests
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib