Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I've asked myself the same question before. I've found doctests to be of limited utility for things like views, model methods and managers because</p> <ol> <li>You need to be able to setup and teardown a test data set to actually use for testing</li> <li>Views need to take a request object. In a doctest, where does that come from?</li> </ol> <p>For that reason, I've always used the Django <a href="http://docs.djangoproject.com/en/1.1/topics/testing/#writing-unit-tests" rel="nofollow noreferrer">unit testing</a> framework which handles all this for you. Unfortunately, though, you don't get some of the benefits of the doctests and it makes TDD/BDD harder to do. What follows next is <strong>pure speculation</strong> about how you might make this work:</p> <p>I think you'd want to grab doctests from their respective modules and functions and execute them within the unit testing framework. This would take care of test data setup/teardown. If your doctests were executed from within a test method of something that subclasses Django's unittest.TestCase they'd be able to use that test DB. You'd also be able to pass a mock request object into the doc test's execution context. Here's a <a href="http://www.djangosnippets.org/snippets/963/" rel="nofollow noreferrer">Django snippet</a> that provides a mock request object and <a href="http://groups.google.com/group/django-developers/browse_thread/thread/db86050095ebe5db" rel="nofollow noreferrer">info</a> on it. Let's say you wanted to test the docstrings from all of an applications views. You could do something like this in tests.py :</p> <pre><code>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) </code></pre> <p>This <em>should</em> allow you to do something like this:</p> <pre><code>def index(request): """ returns the top 10 most clicked products &gt;&gt;&gt; response = index(REQUEST) &gt;&gt;&gt; [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}) </code></pre> <p>Again, this is just off the top of my head and not at all tested, but it's the only way that I think you could what you want without just putting all your view tests in the unit testing framework. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload