Testing django views: RequestFactory and CSRF protection

659 views
Skip to first unread message

Vladimir Ignatev

unread,
Jul 18, 2013, 5:35:00 AM7/18/13
to django...@googlegroups.com
I need using RequestFactory instead of Client to test one of my views. So the question is how to generate proper CSRF token to provide it to my @csrf_protect'ed view? At this moment I get 403 error when generating POST request. 
I've read similar topic in this group dated 2011 year, but that topic observed solution of the problem using Client class and it's parameter enforce_csrf. 

Vladimir Ignatev

unread,
Jul 20, 2013, 3:06:55 PM7/20/13
to django...@googlegroups.com
Well, looks like I've found workaround. At first we should test if a view have CSRF protection: 
def test_csrf_protected(self):
        request = RequestFactory().post('', data={})
        response = views.register_form(request)
        self.assertEqual(response.status_code, 403)

(fix me, it is very weak test for example purpose)

Then we actually test view, providing request._dont_enforce_csrf_checks = True. And voila. Remember that you shouldn't test Django library, so it's obsolete to test "CSRF bypassing + view" chain. Test your view only and that it is protected with @csrf_protect is absolutely enough.

четверг, 18 июля 2013 г., 11:35:00 UTC+2 пользователь Vladimir Ignatev написал:
Reply all
Reply to author
Forward
0 new messages