Sunday, January 30, 2011

Django Testing Views

Setting up the example:

--- views.py -------------------------------------
# define a view for testing
def index(request, template_name=''):
    context = {'things':MyThing.objects.all(),}
    return render_to_response(
           template_name,
           context, context_instance=RequestContext(request))

--- urls.py ---------------------------------------
# define a url for testing
urlpatterns = patterns('',
...
    url('^$', 'core.views.index',
        {'template_name': 'someindex.html'},
         name="index"),
)

Testing from a Dango shell:
import django
from django.test.client import Client
django.test.utils.setup_test_environment() # needed to see response context
client = Client()
response = client.get('/')
response.context[-1]['things']
# we now have access to the response context and can use this
# test code in a unittest tests.py file.  (not yet shown)

Testing in a test.py file:
class SimpleTest(TestCase):

    def test_view_list(self):
        resp = self.client.get(reverse('some_named_url'))
        self.assertEqual(resp.status_code, 200)
        self.assertTrue('somevar' in resp.context[-1])


http://ericholscher.com/blog/2008/nov/11/practical-examples-test-django/

1 comment:

Naveen Sharma said...

Hi,
I was doing the same thing and your solution worked from terminal but when i am doing the same thing using test file it is giving the same error.

self.assertTrue('info' in response.context[-1])
TypeError: 'NoneType' object has no attribute '__getitem__'