doctest 不测试模块中的 类 方法
doctest doesn't test classes methods in a module
我无法让 doctest 测试我的模块 类 方法。
我的模块看起来像这样:
simplemod
├── A.py
└── __init__.py
A.py
包含:
class A:
def method(self):
"""This is a test
>>> True
False
"""
pass
(所以测试应该会失败)
__init__.py
包含
from .A import A
__test__ = {'A': A}
然后我运行
>>> import doctest, simplemod
>>> doctest.testmod(simplemod)
TestResults(failed=0, attempted=0)
为什么 doctest 不测试 A.method
?
我找到原因了。
为什么它不起作用
doctest 尝试检测哪些测试不属于被测试的模块,并且 运行 它们不属于。这会阻止 运行 对您的依赖项进行所有测试。
在这里,我的doctest属于simplemod.A
,而我正在测试simplemod
。
推荐的解决方案
来自 the doctest documentation about testing complex packages.
将 A.py
重命名为 a.py
,并将 __init__.py
替换为
from . import a
def load_tests(loader, tests, ignore):
import unittest
import doctest
tests.addTests(doctest.DocTestSuite(a))
return tests
然后你可以运行你的测试用一个简单的
$ python -m unittest
在父文件夹中。
我无法让 doctest 测试我的模块 类 方法。
我的模块看起来像这样:
simplemod
├── A.py
└── __init__.py
A.py
包含:
class A:
def method(self):
"""This is a test
>>> True
False
"""
pass
(所以测试应该会失败)
__init__.py
包含
from .A import A
__test__ = {'A': A}
然后我运行
>>> import doctest, simplemod
>>> doctest.testmod(simplemod)
TestResults(failed=0, attempted=0)
为什么 doctest 不测试 A.method
?
我找到原因了。
为什么它不起作用
doctest 尝试检测哪些测试不属于被测试的模块,并且 运行 它们不属于。这会阻止 运行 对您的依赖项进行所有测试。
在这里,我的doctest属于simplemod.A
,而我正在测试simplemod
。
推荐的解决方案
来自 the doctest documentation about testing complex packages.
将 A.py
重命名为 a.py
,并将 __init__.py
替换为
from . import a
def load_tests(loader, tests, ignore):
import unittest
import doctest
tests.addTests(doctest.DocTestSuite(a))
return tests
然后你可以运行你的测试用一个简单的
$ python -m unittest
在父文件夹中。