Django CSRF protection and testing

I've recently stumbled upon the ethical need to write a test for the password reset page on one of our webapps. After upgrading Django to 1.2 beta (yeah, we track the SVN trunk), the password reset page was giving 403 errors, due to missing CSRF protection.
Some googling revealed that Django changed some parts of the csrf module and, for safety, all the contrib apps got a @csrf_protect decorator.
Tests written and ran. WTF? They pass? Can't be right. Digging in the csrf middleware revealed that Django skips this step for the test client. Quote from the comment in their source:
Mechanism to turn off CSRF checks for test suite. It comes after the creation of CSRF cookies, so that everything else continues to work exactly the same (e.g. cookies are sent etc), but before the any branches that call reject()
I've wrote a custom test client, that forces the csrf check, all fine. The sun raises again. Oh wait, this custom client doesn't mean that I won't forget to add the {% csrf_token %} template tag to my template. Shitz!
Final solution: check if the csrfmiddlewaretoken hidden input appears in the template. Kinda superficial. Better suggestions are welcome.
Category: Django



Leave a Comment :
Leave a Comment