Testing your django app with webtest

on Apr 25, 2013 by Danu

     I’ve been watching both presentations that Carl Meyer held at Pycon 2012/13 and I highly recommend them if you want a deep dive into writing tests with django. They outline some very good principles for writing effective and maintainable tests. They also highlight a suite of test utilities and frameworks which help you in writing better tests. Among the others, Webtest caught my attention via django-webtest for writing integration/functional tests.

     Why you should choose django-webtest instead of django client ?
     Well, first of all, it can better capture the user experience mainly because you can submit forms and follow links. You are not only testing the views but also the template html. Secondly, it will allow you to write more simple and readable tests, an important fact when it comes to integration or functional tests.
  1. def testLoginProcess(self):
  2.     login = self.app.get(reverse('auth_login'))
  3.     login.form['username'] = 'danu'
  4.     login.form['password'] = 'test123'
  5.     response = login.form.submit('Log in').follow()
  6.     assert_equals('200 OK', response.status)
  7.     assert_contains(response, 'Welcome danu :]', count=1, status_code=200)
  9. def testLoginWithInvalidCredentials(self):
  10.     login = self.app.get(reverse('auth_login'))
  11.     login.form['username'] = 'foo'
  12.     login.form['password'] = 'bar'
  13.     response = login.form.submit('Log in')
  14.     assert_contains(
  15.         response,
  16.         'Please enter a correct username and password. '
  17.         'Note that both fields are case-sensitive.',
  18.         count=1,
  19.         status_code=200
  20.     )
     It interacts with django via the WSGI interface so ajax, js will not be tested. For that purpose you normally use selenium (see Writing automated tests with Django&Selenium).
     I’ve set up a project on github to illustrate some automated tests with django-webtest. It uses nose test suite runner since i don’t want to to import all my tests into tests/__init__.py and for rest of the goodness that nose offers.


Tags: django functional webtest integration | Category: testing , python , django Back To Top

comments powered by Disqus