Skip to content
Advertisement

doctest doesn’t test classes methods in a module

I can’t manage to have doctest test my modules classes methods.

My module looks like that:

simplemod
├── A.py
└── __init__.py

A.py contains:

class A:
    def method(self):
        """This is a test

        >>> True
        False
        """
        pass

(so the tests should fail)

__init__.py contains

from .A import A

__test__ = {'A': A}

And then I run

>>> import doctest, simplemod
>>> doctest.testmod(simplemod)
TestResults(failed=0, attempted=0)

Why doesn’t doctest test A.method ?

Advertisement

Answer

I found out why.

Why it doesn’t work

doctest tries to detect which tests don’t belong to the tested module, and doesn’t run them. This prevents running all the tests of your dependencies.

Here, my doctest belongs to simplemod.A while I am testing simplemod.

Recommended solution

From the doctest documentation about testing complex packages.

Rename A.py to a.py, and replace __init__.py, with

from . import a

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

You can then run your test with a simple

$ python -m unittest

in the parent folder.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement