gpt4 book ai didi

python - views.py 中的 Django 文档测试

转载 作者:IT老高 更新时间:2023-10-28 20:24:33 26 4
gpt4 key购买 nike

Django 1.4 documentation on tests状态:

For a given Django application, the test runner looks for doctests in two places:

  • The models.py file. You can define module-level doctests and/or a doctest for individual models. It's common practice to put application-level doctests in the module docstring and model-level doctests in the model docstrings.

  • A file called tests.py in the application directory -- i.e., the directory that holds models.py. This file is a hook for any and all doctests you want to write that aren't necessarily related to models.

出于好奇,我想知道为什么 Django 的测试运行程序仅限于 models.py 中的文档测试,但更实际地,我想知道如何扩展测试运行程序的文档测试以包含(例如)views.py 和其他模块在运行manage.py test时。

如有任何意见,我将不胜感激。

谢谢。

布赖恩

最佳答案

您可以通过在 tests.py 中添加/编辑 suite() 函数来做到这一点,该函数定义了 django 测试运行程序将运行哪些测试。

import unittest
import doctest
from project import views

def suite():
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(views))
return suite

然后像往常一样运行你的测试,你应该在views.py中看到你的文档测试。

$ python manage.py test project

这在 django testing documentation 中有更详细的描述。

When you run your tests, the default behavior of the test utility is to find all the test cases (that is, subclasses of unittest.TestCase) in models.py and tests.py, automatically build a test suite out of those test cases, and run that suite.

There is a second way to define the test suite for a module: if you define a function called suite() in either models.py or tests.py, the Django test runner will use that function to construct the test suite for that module. This follows the suggested organization for unit tests. See the Python documentation for more details on how to construct a complex test suite.

但是,请记住,构建您自己的测试套件意味着 django 测试运行器不会自动运行您在 tests.py 中的任何测试。例如,您必须手动将这些添加到您的套件中

import unittest
import doctest
from project import views

class FooTestCase(unittest.TestCase):
def testFoo(self):
self.assertEquals('foo', 'bar')

def suite():
suite = unittest.TestSuite()
suite.addTest(doctest.DocTestSuite(views))
suite.addTest(unittest.TestLoader().loadTestsFromTestCase(FooTestCase))
return suite

关于python - views.py 中的 Django 文档测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2380527/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com