在Django中,我的测试是test_foo.py
内的一组my_django_app/tests/
个文件,每个文件都包含一个TestCase
子类,django会自动查找并运行这些文件。
我有一些带有简单doctests的实用程序模块,我希望将其包含在我的测试套件中。我尝试使用doctest.DocTestSuite()
在my_django_app/tests/test_doctests.py
中定义测试套件,但是django的测试运行器在该模块中找不到新的测试。
有没有办法可以创建一个调用我的doctests的TestCase类,或以某种方式定义一个新的tests/test_foo.py
模块来运行这些测试?
答案 0 :(得分:1)
Django unittests
发现的自动化在test_foo模块中查找load_tests
函数并运行它。因此,您可以使用它将您的doctests添加到测试套件中......
import doctest
import module_with_doctests
def load_tests(loader, tests, ignore):
tests.addTests(doctest.DocTestSuite(module_with_doctests))
return tests
此外,由于unittest
中的错误(?),除非您的load_tests
模块还定义了test_foo
,否则您的TestCase
函数将无法运行像这样的课:
class DoNothingTest(TestCase):
"""Encourage Django unittests to run `load_tests()`."""
def test_example(self):
self.assertTrue(True)
答案 1 :(得分:0)
我通过创建一个新模块my_django_app/tests/test_doctests.py
解决了这个问题,看起来像是:
import doctest
import unittest
# These are my modules that contain doctests:
from util import bitwise
from util import text
from util import urlutil
DOCTEST_MODULES = (
bitwise,
text,
urlutil,
)
# unittest.TestLoader will call this when it finds this module:
def load_tests(*args, **kwargs):
test_all_doctests = unittest.TestSuite()
for m in DOCTEST_MODULES:
test_all_doctests.addTest(doctest.DocTestSuite(m))
return test_all_doctests
Django使用内置单元测试TestLoader,在测试发现期间,它将在测试模块上调用load_tests()。因此,我们定义load_tests
,从所有doctests中创建一个测试套件。