我正在尝试测试一个 python 模块,它有一个单独的测试模块:
my_module/
test/
setup.py
test 模块有my_module 的单元测试,但它还需要从my_module 加载doctests。为此,我有以下 load_tests 函数,位于 test/__init__.py 中:
import my_module
def load_tests(loader, tests, pattern):
# Load the unit tests from `test`
unittests = loader.discover(start_dir=os.path.dirname(__file__), pattern=pattern)
# Load the doctests from `my_module`
doctests = doctest.DocTestSuite(my_module)
tests.addTests(unittests)
tests.addTests(doctests)
return tests
然而,这失败并出现错误:
Error
TypeError: object of type 'NoneType' has no len()
我做错了什么?如何在此测试加载器中加载 my_module 中的所有文档测试?
请您参考如下方法:
实际上,在我的示例中,它实际上是失败的 unittest 加载器,让我认为这是 doctest 中的错误。
但是,要回答标题中的问题,您可以像这样递归运行 doctests:
import doctest
import pkgutil
import my_module
def load_tests(loader, tests, pattern):
for importer, name, ispkg in pkgutil.walk_packages(my_module.__path__, my_module.__name__ + '.'):
tests.addTests(doctest.DocTestSuite(name))
return tests
