Python Glossary Русский

all Python 3doctestfunction

doctest.testfile()

running tests

Checks >>> examples in a text file (a README, a tutorial) the same way testmod() checks docstrings.

Syntax

doctest.testfile(filename, module_relative=True, name=None, globs=None, verbose=None, optionflags=0, encoding=None)

By default the path is relative to the calling module's folder, not the current directory (module_relative=True), and an absolute path in that mode is a ValueError. For a path relative to the working directory pass module_relative=False. All examples in the file share one namespace, so a variable defined at the top is visible at the end.

Examples

import doctest
with open("guide.txt", "w", encoding="utf-8") as f:
    f.write("Сначала переменная:\n\n>>> x = 6\n\nПотом она же:\n\n>>> x * 7\n42\n")
print(doctest.testfile("guide.txt", module_relative=False, encoding="utf-8"))  # → TestResults(failed=0, attempted=2)
import doctest, os
open("t.txt", "w").write(">>> 1 + 1\n2\n")
try:
    doctest.testfile(os.path.abspath("t.txt"))
except ValueError as e:
    print(e)  # → Module-relative files may not have absolute paths

See also

Open in the full glossarydocs.python.orgReport an inaccuracy