Python Glossary Русский

all Python 3doctestfunction

doctest.testmod()

running tests

Finds >>> examples in a module's docstrings and checks that their output matches what is written. Returns TestResults(failed, attempted).

Syntax

doctest.testmod(m=None, name=None, globs=None, verbose=None, report=True, optionflags=0)

Output is compared as literal text: an extra space, a different set ordering or an object address like <... at 0x7f...> already fails. For volatile parts there are the directives # doctest: +ELLIPSIS (... matches anything) and +NORMALIZE_WHITESPACE. On success testmod() prints nothing — silence is the green result; verbose=True shows details.

Examples

import doctest
def square(x):
    """
    >>> square(3)
    9
    >>> object()  # doctest: +ELLIPSIS
    <object object at 0x...>
    >>> print("a    b")  # doctest: +NORMALIZE_WHITESPACE
    a b
    >>> sorted({"b", "a"})
    ['a', 'b']
    """
    return x * x
print(doctest.testmod())  # → TestResults(failed=0, attempted=4)
import doctest
def half(x):
    """
    >>> half(5)
    2.5
    >>> half(4)
    2
    """
    return x / 2
print(doctest.testmod())  # → TestResults(failed=1, attempted=2) — half(4) печатает 2.0

See also

Open in the full glossarydocs.python.orgReport an inaccuracy