我以前也问过自己同样的问题。我发现文档测试对于视图、模型方法和管理器等内容的实用性有限,因为
- 您需要能够设置和拆卸测试数据集以实际用于测试
- 视图需要接受请求对象。在文档测试中,它来自哪里?
因此,我一直使用 Django单元测试 http://docs.djangoproject.com/en/1.1/topics/testing/#writing-unit-tests框架为您处理这一切。但不幸的是,您无法获得文档测试的一些好处,并且这使得 TDD/BDD 更难实现。接下来是纯粹的猜测关于如何完成这项工作:
我认为您希望从各自的模块和函数中获取文档测试,并在单元测试框架中执行它们。这将负责测试数据的设置/拆卸。如果您的文档测试是从 Django 的 unittest.TestCase 子类的测试方法中执行的,那么它们就能够使用该测试数据库。您还可以将模拟请求对象传递到文档测试的执行上下文中。这是一个Django 片段 http://www.djangosnippets.org/snippets/963/它提供了一个模拟请求对象并且info http://groups.google.com/group/django-developers/browse_thread/thread/db86050095ebe5db在上面。假设您想要测试所有应用程序视图中的文档字符串。你可以在tests.py中做这样的事情:
from ??? import RequestFactory
from doctest import testmod, DocTestFailure
from django.test import TestCase
from myapp import views
class MyAppTest(TestCase):
fixtures = ['test_data.json']
def test_doctests(self):
try:
testmod(views, extraglobs={
'REQUEST': RequestFactory()
}, raise_on_error=True)
except DocTestFailure, e:
self.fail(e)
This should允许你做这样的事情:
def index(request):
"""
returns the top 10 most clicked products
>>> response = index(REQUEST)
>>> [test response content here]
"""
products = Product.objects.all()[:10]
products = match_pictures_with_products( products, 10) .
return render_to_response('products/product_list.html', {'products': products})
再说一次,这只是我的想法,根本没有经过测试,但我认为这是您不需要将所有视图测试都放在单元测试框架中就可以实现您想要的效果的唯一方法。