1 # -*- coding: utf-8 -*-
2 # This file is part of django-ssify, licensed under GNU Affero GPLv3 or later.
3 # Copyright © Fundacja Nowoczesna Polska. See README.md for more information.
5 from __future__ import unicode_literals
7 from django.conf import settings
8 from django.test import Client, TestCase
11 class CsrfTestCase(TestCase):
13 self.client = Client(enforce_csrf_checks=True)
15 def assertCsrfTokenOk(self, response):
16 token = response.cookies[settings.CSRF_COOKIE_NAME].value
17 self.assertTrue(token)
19 response.content.strip(),
20 ("<!--#set var='vd07f6920655622adc90dd591c545bb2a' value='%s'-->\n\n"
21 "<input type='hidden' name='csrfmiddlewaretoken' value='"
22 "<!--#echo var='vd07f6920655622adc90dd591c545bb2a' "
23 "encoding='none'-->' />" % token).encode('ascii')
27 def test_csrf_token(self):
28 response = self.client.get('/csrf')
29 token = self.assertCsrfTokenOk(response)
31 # And now for a second request, with the token cookie.
32 response = self.client.get('/csrf')
33 new_token = self.assertCsrfTokenOk(response)
34 self.assertEqual(new_token, token)
36 # Make a bad request to see that CSRF protection works.
37 response = self.client.post('/csrf_check', {
40 self.assertEqual(response.status_code, 403)
42 # Make a good request.
43 response = self.client.post('/csrf_check', {
45 'csrfmiddlewaretoken': token,
47 self.assertEqual(response.status_code, 200)
48 self.assertEqual(response.content, b'some data')
50 def test_new_csrf_token_in_cached_response(self):
52 response = Client().get('/csrf')
53 token = self.assertCsrfTokenOk(response)