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 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 rules defined by an owner of a project) to the 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 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 module see this.
P.P.S. a full implementation can be found here.

Software Engineer, LL.B., MSc in CS

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store