Using doctests from within unittests in pytest

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, (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

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.

Software Engineer, LL.B., MSc in CS