Tech Blog

Testing and Django

Testing and Django

Recently updated on

At the last Chicago Djangonauts meeting, which we host in our office, I gave my first Python/Django talk. I spoke regarding unit-testing your code in general, but, also how unit-testing works within the context of web-applications.

The talk went smoothly and it seemed to be well recieved.

Python's standard library provides two methods of unit-testing your code but I only advocate one of them. Doctests achieve unit-testing by embedding the text of an interactive session into your docstrings but this is undesirable for reasons I wont go into here.

The suggested module for unit-testing is called unittest and is much more flexible than doctests since you write actual classes and functions to implement your tests allowing you to benefit from code reuse, encapsulation and other normal programming techniques and tooling.

Unittest enforces a strict-ish formatting on your test classes and the locations where you must place your tests. Nose is a library that extends unittest to allow for losening these contstraints on your tests making it easier for you to organize your tests and get the test-runner to find them.

Django-nose is a library for Django which integrates Nose testing into your Django project allowing you to run your tests as a management command. It also provides a few extra niceities for smoothing out some of the details specific to testing Django sites regarding your database and fixture support.

Lastly, Django itself comes with a number of features related to testing web-applications specifically. For example, it comes with a host of assertions specific to the request-response cycle, template rendering and view testing. 

In the end, it turns out that testing Django applications is not nearly as complicated or mysterious as it may appear. All the pieces are in place to allow you to adapt normal unit-testing techniques to your web-applications. Testing can ensure that you know when your code works, when you've fixed it, enforce requirement changes and overall; ensure the integrity and stability of your sites.

Do it! :)

Comments

Comments are closed.