Using doctest_namespace

The doctest module is part of the standard Python library and allows you to put little code examples inside docstrings for a function and test them to make sure they work. You can have pytest look for and run doctest tests within your Python code by using the --doctest-modules flag. With the doctest_namespace builtin fixture, you can build autouse fixtures to add symbols to the namespace pytest uses while running doctest tests. This allows docstrings to be much more readable. doctest_namespace is commonly used to add module imports into the namespace, especially when Python convention is to shorten the module or package name. For instance, numpy is often imported with import numpy as np.

Let’s play with an example. Let’s ...

Get Python Testing with pytest now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.