Using doctests from within unittests in pytest

Vladyslav Krylasov
1 min readDec 22, 2019
Photo by David Clode on Unsplash

Hello everyone. I’ve discovered for myself lately a need to run at the same time doctests alongside with pytest unit tests.

Let’s assume one’s have such structure of a project:

A structure of a project.

That person needs to cover by unit tests app package and at the same time check doctests of functions, classes, etc. by means of pytest’s invocation. How can it be achieved? We can put a file named, for instance, test_package_doctests.py (or any file named according to pytest.ini rules defined by an owner of a project) to the tests directory with the following content.

Content of test_package_doctests.py

It’s a hacky way to discover both unit tests & doctests by mimicking run of DocTestSuit inside an ordinary unit test.

Here’s an example of the output, it’s pretty smooth:

pytest output.

Simple as that. I hope this article helped you.
P.S. it’s more simple to implement such behaviour when used standard unittest module see this.
P.P.S. a full implementation can be found here.

--

--