Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Added tests for CsrfMiddleware.

git-svn-id: http://code.djangoproject.com/svn/django/trunk@9551 bcc190cf-cafb-0310-a4f2-bffc1f526a37
  • Loading branch information...
commit f7242bb778d63e09aebaf5318244a886f123a1e0 1 parent 5ef0c03
@spookylukey spookylukey authored
Showing with 65 additions and 0 deletions.
  1. +1 −0  django/contrib/csrf/models.py
  2. +64 −0 django/contrib/csrf/tests.py
View
1  django/contrib/csrf/models.py
@@ -0,0 +1 @@
+# models.py file for tests to run.
View
64 django/contrib/csrf/tests.py
@@ -0,0 +1,64 @@
+# -*- coding: utf-8 -*-
+
+from django.test import TestCase
+from django.http import HttpRequest, HttpResponse
+from django.contrib.csrf.middleware import CsrfMiddleware, _make_token
+from django.conf import settings
+
+class CsrfMiddlewareTest(TestCase):
+
+ _session_id = "1"
+
+ def _get_no_session_request(self):
+ return HttpRequest()
+
+ def _get_session_request(self):
+ req = self._get_no_session_request()
+ req.COOKIES[settings.SESSION_COOKIE_NAME] = self._session_id
+ return req
+
+ def _get_post_form_response(self):
+ resp = HttpResponse(content="""
+<html><body><form method="POST"><input type="text" /></form></body></html>
+""", mimetype="text/html")
+ return resp
+
+ def _get_new_session_response(self):
+ resp = self._get_post_form_response()
+ resp.cookies[settings.SESSION_COOKIE_NAME] = self._session_id
+ return resp
+
+ def _check_token_present(self, response):
+ self.assertContains(response, "name='csrfmiddlewaretoken' value='%s'" % _make_token(self._session_id))
+
+ def test_process_response_no_session(self):
+ """
+ Check the the post-processor does nothing if no session active
+ """
+ req = self._get_no_session_request()
+ resp = self._get_post_form_response()
+ resp_content = resp.content
+ resp2 = CsrfMiddleware().process_response(req, resp)
+ self.assertEquals(resp_content, resp2.content)
+
+ def test_process_response_existing_session(self):
+ """
+ Check that the token is inserted if there is an existing session
+ """
+ req = self._get_session_request()
+ resp = self._get_post_form_response()
+ resp_content = resp.content
+ resp2 = CsrfMiddleware().process_response(req, resp)
+ self.assertNotEqual(resp_content, resp2.content)
+ self._check_token_present(resp2)
+
+ def test_process_response_new_session(self):
+ """
+ Check that the token is inserted if there is a new session being started
+ """
+ req = self._get_no_session_request() # no session in request
+ resp = self._get_new_session_response() # but new session started
+ resp_content = resp.content
+ resp2 = CsrfMiddleware().process_response(req, resp)
+ self.assertNotEqual(resp_content, resp2.content)
+ self._check_token_present(resp2)
Please sign in to comment.
Something went wrong with that request. Please try again.