Sunday, January 30, 2011

Django Testing Views

Setting up the example:

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

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

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('/')
# we now have access to the response context and can use this
# test code in a unittest file.  (not yet shown)

Testing in a 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])

1 comment:

Anonymous said...

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__'