Notice This is a beta feature offered by Google. Also this is automatic translation, which means the results are often inacurate and/or hilarious. Enjoy.

ARCHIVES / RSS
Blog

Batch unit test URLs in Django

h3  ~  15 Apr 2008, 21:59  –  post a comment

While working on a personal project I got tired of writing tests for each of my URLs like this

from django.test import TestCase
from django.test.client import Client

class TestViews(TestCase):
    fixtures = ['initial_data']
    def setUp(self):
        self.c = Client()

    def test_home(self):
        rs = self.c.get('/home/')
        self.failUnless(rs)
        self.assertEquals(rs.status_code, 200)

    def test_submit(self):
        
        rs = self.c.post('/login/',
            {'username': 'sponge', 'password': 'bob'})
        self.assertEquals(rs.status_code, 302)
        self.failUnless(rs)

	rs = self.c.get('/submit/')
        self.failUnless(rs)
        self.assertEquals(rs.status_code, 200)

    # repeat for each URLs of the site/application

It's fine, but it could be more convenient.. so I came up with this with a little refactoring:

from django.test import TestCase
from django.test.client import Client

class TestViews(TestCase):
    fixtures = ['initial_data']
    def setUp(self):
        self.c = Client()

    def urltest(self, url, status_code):
        rs = self.c.get(url)
        self.failUnless(rs)
        self.assertEquals(rs.status_code, status_code, 
            '%s returned %s, %s was expected' % 
            (url, rs.status_code, status_code))
            

    def test_anonymous_urls(self):
        urls = [('/',        301), # permanently moved
                ('/about/',  200),
                ('/home/',   200),
                ('/submit/', 302)] #redirected
                # so on..

        for url in urls:
            self.urltest(url[0], url[1])

    def test_user_urls(self):
        rs = self.c.post('/login/', 
            {'username': 'sponge', 'password': 'bob'})
        self.failUnless(rs)
	# still have to test this one individually..
        self.assertEquals(rs.status_code, 302)


        urls = [('/',        301), # still moved..
                ('/about/',  200),
                ('/home/',   200),
                ('/submit/', 200)] # OK
                # so on..

        for url in urls:
            self.urltest(url[0], url[1])

I can probably extend this idea, but I haven't seen the need yet. Any ideas ?

post a comment Comments

no comments :|

Copyrighted stuff .. u know.