Code

Ticket #5296: easy_view_testing.diff

File easy_view_testing.diff, 6.1 KB (added by Chris H. <chris@…>, 7 years ago)

Additions to TestCase and tests to exercise those additions.

Line 
1Index: django/test/testcases.py
2===================================================================
3--- django/test/testcases.py    (revision 6023)
4+++ django/test/testcases.py    (working copy)
5@@ -6,6 +6,7 @@
6 from django.db.models import get_apps
7 from django.test import _doctest as doctest
8 from django.test.client import Client
9+from django.conf import settings
10 
11 normalize_long_ints = lambda s: re.sub(r'(?<![\w])(\d+)L(?![\w])', '\\1', s)
12 
13@@ -59,7 +60,7 @@
14         self.client = Client()
15         self._pre_setup()
16         super(TestCase, self).__call__(result)
17-
18+   
19     def assertRedirects(self, response, expected_path, status_code=302, target_status_code=200):
20         """Assert that a response redirected to a specific URL, and that the
21         redirect URL can be loaded.
22@@ -154,3 +155,33 @@
23             self.assertNotEqual(template_name, response.template.name,
24                 u"Template '%s' was used unexpectedly in rendering the response" % template_name)
25 
26+    def assertValidResponse(self, response, content_type="text/html"):
27+        "Assert that the response has a 200 status code and is of the proper content type."
28+        self.assertEqual(200, response.status_code,
29+            u"Expected a 200 status code, but %s was returned" % response.status_code)
30+       
31+        expected_content_type = "%s; charset=%s" % (content_type, settings.DEFAULT_CHARSET)
32+        actual_content_type = response.headers['Content-Type']
33+        self.assertEqual(expected_content_type, actual_content_type,
34+            u"Expected a Content-Type of %s, but %s was returned" % (expected_content_type, actual_content_type))
35+
36+    def check_response(self, response, template_name=None, text_checks=[], content_type="text/html"):
37+        """Checks that the response returns a 200, the right content_type,
38+           uses the right template, then checks the text of the response.
39+           
40+           Example:
41+           def test_my_view(self):
42+               text_checks = (
43+                    ("List of hello objects", None),
44+                    ("Hello Object", 3),
45+               )
46+               self.check_response('/hello/world/', 'hello/hello_list.html', text_checks) #Assuming text/html and settings.DEFAULT_CHARSET
47+        """
48+        self.assertValidResponse(response, content_type)
49+       
50+        if template_name:
51+            self.assertTemplateUsed(response, template_name)
52+       
53+        for check in text_checks:
54+            text, count = check
55+            self.assertContains(response, text, count)
56\ No newline at end of file
57Index: tests/modeltests/test_client/views.py
58===================================================================
59--- tests/modeltests/test_client/views.py       (revision 6023)
60+++ tests/modeltests/test_client/views.py       (working copy)
61@@ -6,6 +6,7 @@
62 from django.newforms.forms import Form
63 from django.newforms import fields
64 from django.shortcuts import render_to_response
65+from django.conf import settings
66 
67 def get_view(request):
68     "A simple view that expects a GET request, and returns a rendered template"
69@@ -14,6 +15,12 @@
70     
71     return HttpResponse(t.render(c))
72 
73+def get_xml_view(request):
74+    "A simple view that expects a GET request and returns a rendered template with a content type of text/xml"
75+    response = get_view(request)
76+    response.headers['Content-Type'] = "text/xml; charset=%s" % (settings.DEFAULT_CHARSET)
77+    return response
78+
79 def post_view(request):
80     """A view that expects a POST, and returns a different template depending
81     on whether any POST data is available
82Index: tests/modeltests/test_client/urls.py
83===================================================================
84--- tests/modeltests/test_client/urls.py        (revision 6023)
85+++ tests/modeltests/test_client/urls.py        (working copy)
86@@ -4,6 +4,7 @@
87 
88 urlpatterns = patterns('',
89     (r'^get_view/$', views.get_view),
90+    (r'^get_xml_view/$', views.get_xml_view),
91     (r'^post_view/$', views.post_view),
92     (r'^raw_post_view/$', views.raw_post_view),
93     (r'^redirect_view/$', views.redirect_view),
94Index: tests/regressiontests/test_client_regress/models.py
95===================================================================
96--- tests/regressiontests/test_client_regress/models.py (revision 6023)
97+++ tests/regressiontests/test_client_regress/models.py (working copy)
98@@ -4,6 +4,7 @@
99 """
100 from django.test import Client, TestCase
101 from django.core import mail
102+from django.conf import settings
103 import os
104 
105 class AssertContainsTests(TestCase):
106@@ -213,3 +214,39 @@
107         }
108         response = self.client.post('/test_client_regress/file_upload/', post_data)
109         self.assertEqual(response.status_code, 200)
110+
111+class AssertValidResponseTests(TestCase):
112+    def test_html_response(self):
113+        response = self.client.get('/test_client/get_view/')
114+        self.assertValidResponse(response)
115+       
116+    def test_xml_response(self):
117+        response = self.client.get('/test_client/get_xml_view/')
118+        self.assertValidResponse(response, "text/xml")
119+       
120+    def test_bad_response(self):
121+        response = self.client.get('/test_client/bad_view/')
122+        try:
123+            self.assertValidResponse(response)
124+        except AssertionError, e:
125+            self.assertEqual(str(e), "Expected a 200 status code, but 404 was returned")
126+       
127+    def test_bad_content_type(self):
128+        response = self.client.get('/test_client/get_view/')
129+        try:
130+            self.assertValidResponse(response, content_type="text/javascript")
131+        except AssertionError, e:
132+            charset = settings.DEFAULT_CHARSET
133+            self.assertEqual(str(e), "Expected a Content-Type of text/javascript; charset=%s, but text/html; charset=%s was returned" % (charset, charset))
134+
135+class CheckViewTests(TestCase):
136+    def test_simple_response(self):
137+        response = self.client.get('/test_client/get_view/')
138+        text_checks = (
139+            ('This is a test', 1),
140+            ('42', 1),
141+            ('is', 3),
142+            ('This is not a test', 0),
143+        )
144+       
145+        self.check_response(response, template_name='GET Template', text_checks=text_checks)
146\ No newline at end of file