Code

Ticket #5333: 5333.diff

File 5333.diff, 11.9 KB (added by gwilson, 7 years ago)
Line 
1=== modified file 'django/test/testcases.py'
2--- django/test/testcases.py    2007-09-03 23:14:51 +0000
3+++ django/test/testcases.py    2007-09-04 04:46:14 +0000
4@@ -149,7 +149,27 @@
5                                 (form, i, err, list(context[form].non_field_errors())))
6         if not found_form:
7             self.fail("The form '%s' was not used to render the response" % form)
8-           
9+
10+    def assertContext(self, response, variable_name, value):
11+        """
12+        Asserts that one of the contexts used to render the response
13+        contains the context variable variable_name equal to value.
14+        """
15+        # Put context(s) into a list to simplify processing.
16+        contexts = to_list(response.context)
17+        if not contexts:
18+            self.fail('Response did not use any contexts to render the'
19+                      ' response')
20+        test_passed = False
21+        for context in contexts:
22+            if context.get(variable_name) == value:
23+                test_passed = True
24+                break
25+        if not test_passed:
26+            self.fail("The context variable '%s' with value '%s' was not"
27+                      " found in the context(s) used to render the"
28+                      " response" % (variable_name, value))
29+
30     def assertTemplateUsed(self, response, template_name):
31         "Assert that the template with the provided name was used in rendering the response"
32         template_names = [t.name for t in to_list(response.template)]
33
34=== modified file 'tests/regressiontests/test_client_regress/models.py'
35--- tests/regressiontests/test_client_regress/models.py 2007-09-03 23:14:51 +0000
36+++ tests/regressiontests/test_client_regress/models.py 2007-09-04 04:58:39 +0000
37@@ -31,12 +31,12 @@
38             self.assertContains(response, 'once', 2)
39         except AssertionError, e:
40             self.assertEquals(str(e), "Found 1 instances of 'once' in response (expected 2)")
41-       
42+
43         try:
44             self.assertContains(response, 'twice', 1)
45         except AssertionError, e:
46             self.assertEquals(str(e), "Found 2 instances of 'twice' in response (expected 1)")
47-       
48+
49         try:
50             self.assertContains(response, 'thrice')
51         except AssertionError, e:
52@@ -46,37 +46,37 @@
53             self.assertContains(response, 'thrice', 3)
54         except AssertionError, e:
55             self.assertEquals(str(e), "Found 0 instances of 'thrice' in response (expected 3)")
56-       
57+
58 class AssertTemplateUsedTests(TestCase):
59     fixtures = ['testdata.json']
60-   
61+
62     def test_no_context(self):
63         "Template usage assertions work then templates aren't in use"
64         response = self.client.get('/test_client_regress/no_template_view/')
65 
66         # Check that the no template case doesn't mess with the template assertions
67         self.assertTemplateNotUsed(response, 'GET Template')
68-       
69+
70         try:
71             self.assertTemplateUsed(response, 'GET Template')
72         except AssertionError, e:
73             self.assertEquals(str(e), "No templates used to render the response")
74 
75-    def test_single_context(self):       
76+    def test_single_context(self):
77         "Template assertions work when there is a single context"
78         response = self.client.get('/test_client/post_view/', {})
79 
80-        #
81+        #
82         try:
83             self.assertTemplateNotUsed(response, 'Empty GET Template')
84         except AssertionError, e:
85             self.assertEquals(str(e), "Template 'Empty GET Template' was used unexpectedly in rendering the response")
86-           
87+
88         try:
89-            self.assertTemplateUsed(response, 'Empty POST Template')       
90+            self.assertTemplateUsed(response, 'Empty POST Template')
91         except AssertionError, e:
92             self.assertEquals(str(e), "Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template")
93-   
94+
95     def test_multiple_context(self):
96         "Template assertions work when there are multiple contexts"
97         post_data = {
98@@ -99,20 +99,20 @@
99             self.assertEquals(str(e), "Template 'base.html' was used unexpectedly in rendering the response")
100 
101         try:
102-            self.assertTemplateUsed(response, "Valid POST Template")       
103+            self.assertTemplateUsed(response, "Valid POST Template")
104         except AssertionError, e:
105             self.assertEquals(str(e), "Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html")
106 
107 class AssertRedirectsTests(TestCase):
108     def test_redirect_page(self):
109-        "An assertion is raised if the original page couldn't be retrieved as expected"       
110+        "An assertion is raised if the original page couldn't be retrieved as expected"
111         # This page will redirect with code 301, not 302
112-        response = self.client.get('/test_client/permanent_redirect_view/')       
113+        response = self.client.get('/test_client/permanent_redirect_view/')
114         try:
115             self.assertRedirects(response, '/test_client/get_view/')
116         except AssertionError, e:
117             self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 301 (expected 302)")
118-   
119+
120     def test_lost_query(self):
121         "An assertion is raised if the redirect location doesn't preserve GET parameters"
122         response = self.client.get('/test_client/redirect_view/', {'var': 'value'})
123@@ -123,13 +123,13 @@
124 
125     def test_incorrect_target(self):
126         "An assertion is raised if the response redirects to another target"
127-        response = self.client.get('/test_client/permanent_redirect_view/')       
128+        response = self.client.get('/test_client/permanent_redirect_view/')
129         try:
130             # Should redirect to get_view
131             self.assertRedirects(response, '/test_client/some_view/')
132         except AssertionError, e:
133             self.assertEquals(str(e), "Response didn't redirect as expected: Response code was 301 (expected 302)")
134-       
135+
136     def test_target_page(self):
137         "An assertion is raised if the response redirect target cannot be retrieved as expected"
138         response = self.client.get('/test_client/double_redirect_view/')
139@@ -138,7 +138,7 @@
140             self.assertRedirects(response, '/test_client/permanent_redirect_view/')
141         except AssertionError, e:
142             self.assertEquals(str(e), "Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)")
143-           
144+
145 class AssertFormErrorTests(TestCase):
146     def test_unknown_form(self):
147         "An assertion is raised if the form name is unknown"
148@@ -157,7 +157,7 @@
149             self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.')
150         except AssertionError, e:
151             self.assertEqual(str(e), "The form 'wrong_form' was not used to render the response")
152-       
153+
154     def test_unknown_field(self):
155         "An assertion is raised if the field name is unknown"
156         post_data = {
157@@ -175,7 +175,7 @@
158             self.assertFormError(response, 'form', 'some_field', 'Some error.')
159         except AssertionError, e:
160             self.assertEqual(str(e), "The form 'form' in context 0 does not contain the field 'some_field'")
161-       
162+
163     def test_noerror_field(self):
164         "An assertion is raised if the field doesn't have any errors"
165         post_data = {
166@@ -193,7 +193,7 @@
167             self.assertFormError(response, 'form', 'value', 'Some error.')
168         except AssertionError, e:
169             self.assertEqual(str(e), "The field 'value' on form 'form' in context 0 contains no errors")
170-       
171+
172     def test_unknown_error(self):
173         "An assertion is raised if the field doesn't contain the provided error"
174         post_data = {
175@@ -212,6 +212,41 @@
176         except AssertionError, e:
177             self.assertEqual(str(e), "The field 'email' on form 'form' in context 0 does not contain the error 'Some error.' (actual errors: [u'Enter a valid e-mail address.'])")
178 
179+class AssertContextTests(TestCase):
180+    """Tests for the assertContext method."""
181+
182+    def setUp(self):
183+        self.response = self.client.get(
184+            '/test_client_regress/context_variable_view/')
185+        self.assertEqual(self.response.status_code, 200)
186+        self.assertTemplateUsed(self.response, "Context Variable Template")
187+
188+    def test_unknown_variable(self):
189+        """
190+        Checks that an assertion is raised if the variable does not exist.
191+        """
192+        try:
193+            self.assertContext(self.response, 'editor', 'A Knight')
194+        except AssertionError, e:
195+            self.assertEqual(str(e), "The context variable 'editor' with value 'A Knight' was not found in the context(s) used to render the response")
196+
197+    def test_wrong_value(self):
198+        """
199+        Checks that an assertion is raised if the context variable's value
200+        does not equal the specified value.
201+        """
202+        try:
203+            self.assertContext(self.response, 'author', 'Real McCoy')
204+        except AssertionError, e:
205+            self.assertEqual(str(e), "The context variable 'author' with value 'Real McCoy' was not found in the context(s) used to render the response")
206+
207+    def test_correct_value(self):
208+        """
209+        Checks that no assertion is raised if the context variable's value
210+        matches the specified value.
211+        """
212+        self.assertContext(self.response, 'title', 'Run Away')
213+
214 class FileUploadTests(TestCase):
215     def test_simple_upload(self):
216         fd = open(os.path.join(os.path.dirname(__file__), "views.py"))
217@@ -235,8 +270,8 @@
218 
219         # Get a redirection page with the second client.
220         response = c.get("/test_client_regress/login_protected_redirect_view/")
221-       
222-        # At this points, the self.client isn't logged in.
223-        # Check that assertRedirects uses the original client, not the
224+
225+        # At this points, the self.client isn't logged in.
226+        # Check that assertRedirects uses the original client, not the
227         # default client.
228         self.assertRedirects(response, "/test_client_regress/get_view/")
229
230=== modified file 'tests/regressiontests/test_client_regress/urls.py'
231--- tests/regressiontests/test_client_regress/urls.py   2007-09-03 11:21:40 +0000
232+++ tests/regressiontests/test_client_regress/urls.py   2007-09-04 01:46:59 +0000
233@@ -5,5 +5,6 @@
234     (r'^no_template_view/$', views.no_template_view),
235     (r'^file_upload/$', views.file_upload_view),
236     (r'^get_view/$', views.get_view),
237-    (r'^login_protected_redirect_view/$', views.login_protected_redirect_view)
238+    (r'^login_protected_redirect_view/$', views.login_protected_redirect_view),
239+    (r'^context_variable_view/$', views.context_variable_view),
240 )
241
242=== modified file 'tests/regressiontests/test_client_regress/views.py'
243--- tests/regressiontests/test_client_regress/views.py  2007-09-03 11:21:40 +0000
244+++ tests/regressiontests/test_client_regress/views.py  2007-09-04 01:46:59 +0000
245@@ -2,6 +2,7 @@
246 from django.core.mail import EmailMessage, SMTPConnection
247 from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError
248 from django.shortcuts import render_to_response
249+from django.template import Context, Template
250 
251 def no_template_view(request):
252     "A simple view that expects a GET request, and returns a rendered template"
253@@ -27,4 +28,12 @@
254 def login_protected_redirect_view(request):
255     "A view that redirects all requests to the GET view"
256     return HttpResponseRedirect('/test_client_regress/get_view/')
257-login_protected_redirect_view = login_required(login_protected_redirect_view)
258\ No newline at end of file
259+login_protected_redirect_view = login_required(login_protected_redirect_view)
260+
261+def context_variable_view(request):
262+    "A view that uses context variables."
263+    t = Template('{{ title }} by {{ author }}',
264+                 name='Context Variable Template')
265+    c = Context({'title': 'Run Away',
266+                 'author': 'Brave Sir Robin'})
267+    return HttpResponse(t.render(c))
268