Using doctests from within unittests

An update to this old question: since Python version 2.7 there is the load_tests protocol and there is no longer a need to write custom code. It allows you to add a function load_tests(), which a test loader will execute to update its collection of unit tests for the current module.

Put a function like this in your code module to package the module's own doctests into a test suite for unittest:

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite())
    return tests

Or, put a function like this into your unit test module to add the doctests from another module (for example, package.code_module) into the tests suite which is already there:

def load_tests(loader, tests, ignore):
    tests.addTests(doctest.DocTestSuite(package.code_module))
    return tests

When unittest.TestLoader methods loadTestsFromModule(), loadTestsFromName() or discover() are used unittest uses a test suite including both unit tests and doctests.


I would recommend to use pytest --doctest-modules without any load_test protocol. You can simply add both the files or directories with your normal pytests and your modules with doctests to that pytest call.

pytest --doctest-modules path/to/pytest/unittests path/to/modules

It discovers and runs all doctests as well.

See https://docs.pytest.org/en/latest/doctest.html


In this code i combined unittests and doctests from imported module

import unittest


class ts(unittest.TestCase):
    def test_null(self):
        self.assertTrue(True)


class ts1(unittest.TestCase):
    def test_null(self):
        self.assertTrue(True)

testSuite = unittest.TestSuite()    
testSuite.addTests(unittest.makeSuite(ts))
testSuite.addTest(unittest.makeSuite(ts1))

import doctest
import my_module_with_doctests

testSuite.addTest(doctest.DocTestSuite(my_module_with_doctests))
unittest.TextTestRunner(verbosity = 2).run(testSuite)

Tags:

Python