Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Moved test_client_regress tests from models.py to tests.py

  • Loading branch information...
commit 4553f511557052d6f18811807ae6136f81fa86a3 1 parent 0dc9049
Claude Paroz authored May 31, 2012
1,021  tests/regressiontests/test_client_regress/models.py
... ...
@@ -1,1021 +0,0 @@
1  
-# -*- coding: utf-8 -*-
2  
-"""
3  
-Regression tests for the Test Client, especially the customized assertions.
4  
-"""
5  
-import os
6  
-
7  
-from django.conf import settings
8  
-from django.core.exceptions import SuspiciousOperation
9  
-from django.core.urlresolvers import reverse
10  
-from django.template import (TemplateDoesNotExist, TemplateSyntaxError,
11  
-    Context, Template, loader)
12  
-import django.template.context
13  
-from django.test import Client, TestCase
14  
-from django.test.client import encode_file, RequestFactory
15  
-from django.test.utils import ContextList, override_settings
16  
-from django.template.response import SimpleTemplateResponse
17  
-from django.http import HttpResponse
18  
-
19  
-
20  
-class AssertContainsTests(TestCase):
21  
-    def setUp(self):
22  
-        self.old_templates = settings.TEMPLATE_DIRS
23  
-        settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)
24  
-
25  
-    def tearDown(self):
26  
-        settings.TEMPLATE_DIRS = self.old_templates
27  
-
28  
-    def test_contains(self):
29  
-        "Responses can be inspected for content, including counting repeated substrings"
30  
-        response = self.client.get('/test_client_regress/no_template_view/')
31  
-
32  
-        self.assertNotContains(response, 'never')
33  
-        self.assertContains(response, 'never', 0)
34  
-        self.assertContains(response, 'once')
35  
-        self.assertContains(response, 'once', 1)
36  
-        self.assertContains(response, 'twice')
37  
-        self.assertContains(response, 'twice', 2)
38  
-
39  
-        try:
40  
-            self.assertContains(response, 'text', status_code=999)
41  
-        except AssertionError as e:
42  
-            self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
43  
-        try:
44  
-            self.assertContains(response, 'text', status_code=999, msg_prefix='abc')
45  
-        except AssertionError as e:
46  
-            self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
47  
-
48  
-        try:
49  
-            self.assertNotContains(response, 'text', status_code=999)
50  
-        except AssertionError as e:
51  
-            self.assertIn("Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
52  
-        try:
53  
-            self.assertNotContains(response, 'text', status_code=999, msg_prefix='abc')
54  
-        except AssertionError as e:
55  
-            self.assertIn("abc: Couldn't retrieve content: Response code was 200 (expected 999)", str(e))
56  
-
57  
-        try:
58  
-            self.assertNotContains(response, 'once')
59  
-        except AssertionError as e:
60  
-            self.assertIn("Response should not contain 'once'", str(e))
61  
-        try:
62  
-            self.assertNotContains(response, 'once', msg_prefix='abc')
63  
-        except AssertionError as e:
64  
-            self.assertIn("abc: Response should not contain 'once'", str(e))
65  
-
66  
-        try:
67  
-            self.assertContains(response, 'never', 1)
68  
-        except AssertionError as e:
69  
-            self.assertIn("Found 0 instances of 'never' in response (expected 1)", str(e))
70  
-        try:
71  
-            self.assertContains(response, 'never', 1, msg_prefix='abc')
72  
-        except AssertionError as e:
73  
-            self.assertIn("abc: Found 0 instances of 'never' in response (expected 1)", str(e))
74  
-
75  
-        try:
76  
-            self.assertContains(response, 'once', 0)
77  
-        except AssertionError as e:
78  
-            self.assertIn("Found 1 instances of 'once' in response (expected 0)", str(e))
79  
-        try:
80  
-            self.assertContains(response, 'once', 0, msg_prefix='abc')
81  
-        except AssertionError as e:
82  
-            self.assertIn("abc: Found 1 instances of 'once' in response (expected 0)", str(e))
83  
-
84  
-        try:
85  
-            self.assertContains(response, 'once', 2)
86  
-        except AssertionError as e:
87  
-            self.assertIn("Found 1 instances of 'once' in response (expected 2)", str(e))
88  
-        try:
89  
-            self.assertContains(response, 'once', 2, msg_prefix='abc')
90  
-        except AssertionError as e:
91  
-            self.assertIn("abc: Found 1 instances of 'once' in response (expected 2)", str(e))
92  
-
93  
-        try:
94  
-            self.assertContains(response, 'twice', 1)
95  
-        except AssertionError as e:
96  
-            self.assertIn("Found 2 instances of 'twice' in response (expected 1)", str(e))
97  
-        try:
98  
-            self.assertContains(response, 'twice', 1, msg_prefix='abc')
99  
-        except AssertionError as e:
100  
-            self.assertIn("abc: Found 2 instances of 'twice' in response (expected 1)", str(e))
101  
-
102  
-        try:
103  
-            self.assertContains(response, 'thrice')
104  
-        except AssertionError as e:
105  
-            self.assertIn("Couldn't find 'thrice' in response", str(e))
106  
-        try:
107  
-            self.assertContains(response, 'thrice', msg_prefix='abc')
108  
-        except AssertionError as e:
109  
-            self.assertIn("abc: Couldn't find 'thrice' in response", str(e))
110  
-
111  
-        try:
112  
-            self.assertContains(response, 'thrice', 3)
113  
-        except AssertionError as e:
114  
-            self.assertIn("Found 0 instances of 'thrice' in response (expected 3)", str(e))
115  
-        try:
116  
-            self.assertContains(response, 'thrice', 3, msg_prefix='abc')
117  
-        except AssertionError as e:
118  
-            self.assertIn("abc: Found 0 instances of 'thrice' in response (expected 3)", str(e))
119  
-
120  
-    def test_unicode_contains(self):
121  
-        "Unicode characters can be found in template context"
122  
-        #Regression test for #10183
123  
-        r = self.client.get('/test_client_regress/check_unicode/')
124  
-        self.assertContains(r, u'さかき')
125  
-        self.assertContains(r, b'\xe5\xb3\xa0'.decode('utf-8'))
126  
-
127  
-    def test_unicode_not_contains(self):
128  
-        "Unicode characters can be searched for, and not found in template context"
129  
-        #Regression test for #10183
130  
-        r = self.client.get('/test_client_regress/check_unicode/')
131  
-        self.assertNotContains(r, u'はたけ')
132  
-        self.assertNotContains(r, b'\xe3\x81\xaf\xe3\x81\x9f\xe3\x81\x91'.decode('utf-8'))
133  
-
134  
-    def test_assert_contains_renders_template_response(self):
135  
-        """ Test that we can pass in an unrendered SimpleTemplateReponse
136  
-            without throwing an error.
137  
-            Refs #15826.
138  
-        """
139  
-        response = SimpleTemplateResponse(Template('Hello'), status=200)
140  
-        self.assertContains(response, 'Hello')
141  
-
142  
-    def test_assert_contains_using_non_template_response(self):
143  
-        """ Test that auto-rendering does not affect responses that aren't
144  
-            instances (or subclasses) of SimpleTemplateResponse.
145  
-            Refs #15826.
146  
-        """
147  
-        response = HttpResponse('Hello')
148  
-        self.assertContains(response, 'Hello')
149  
-
150  
-    def test_assert_not_contains_renders_template_response(self):
151  
-        """ Test that we can pass in an unrendered SimpleTemplateReponse
152  
-            without throwing an error.
153  
-            Refs #15826.
154  
-        """
155  
-        response = SimpleTemplateResponse(Template('Hello'), status=200)
156  
-        self.assertNotContains(response, 'Bye')
157  
-
158  
-    def test_assert_not_contains_using_non_template_response(self):
159  
-        """ Test that auto-rendering does not affect responses that aren't
160  
-            instances (or subclasses) of SimpleTemplateResponse.
161  
-            Refs #15826.
162  
-        """
163  
-        response = HttpResponse('Hello')
164  
-        self.assertNotContains(response, 'Bye')
165  
-
166  
-@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
167  
-class AssertTemplateUsedTests(TestCase):
168  
-    fixtures = ['testdata.json']
169  
-
170  
-    def test_no_context(self):
171  
-        "Template usage assertions work then templates aren't in use"
172  
-        response = self.client.get('/test_client_regress/no_template_view/')
173  
-
174  
-        # Check that the no template case doesn't mess with the template assertions
175  
-        self.assertTemplateNotUsed(response, 'GET Template')
176  
-
177  
-        try:
178  
-            self.assertTemplateUsed(response, 'GET Template')
179  
-        except AssertionError as e:
180  
-            self.assertIn("No templates used to render the response", str(e))
181  
-
182  
-        try:
183  
-            self.assertTemplateUsed(response, 'GET Template', msg_prefix='abc')
184  
-        except AssertionError as e:
185  
-            self.assertIn("abc: No templates used to render the response", str(e))
186  
-
187  
-    def test_single_context(self):
188  
-        "Template assertions work when there is a single context"
189  
-        response = self.client.get('/test_client/post_view/', {})
190  
-
191  
-        try:
192  
-            self.assertTemplateNotUsed(response, 'Empty GET Template')
193  
-        except AssertionError as e:
194  
-            self.assertIn("Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
195  
-
196  
-        try:
197  
-            self.assertTemplateNotUsed(response, 'Empty GET Template', msg_prefix='abc')
198  
-        except AssertionError as e:
199  
-            self.assertIn("abc: Template 'Empty GET Template' was used unexpectedly in rendering the response", str(e))
200  
-
201  
-        try:
202  
-            self.assertTemplateUsed(response, 'Empty POST Template')
203  
-        except AssertionError as e:
204  
-            self.assertIn("Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e))
205  
-
206  
-        try:
207  
-            self.assertTemplateUsed(response, 'Empty POST Template', msg_prefix='abc')
208  
-        except AssertionError as e:
209  
-            self.assertIn("abc: Template 'Empty POST Template' was not a template used to render the response. Actual template(s) used: Empty GET Template", str(e))
210  
-
211  
-    def test_multiple_context(self):
212  
-        "Template assertions work when there are multiple contexts"
213  
-        post_data = {
214  
-            'text': 'Hello World',
215  
-            'email': 'foo@example.com',
216  
-            'value': 37,
217  
-            'single': 'b',
218  
-            'multi': ('b','c','e')
219  
-        }
220  
-        response = self.client.post('/test_client/form_view_with_template/', post_data)
221  
-        self.assertContains(response, 'POST data OK')
222  
-        try:
223  
-            self.assertTemplateNotUsed(response, "form_view.html")
224  
-        except AssertionError as e:
225  
-            self.assertIn("Template 'form_view.html' was used unexpectedly in rendering the response", str(e))
226  
-
227  
-        try:
228  
-            self.assertTemplateNotUsed(response, 'base.html')
229  
-        except AssertionError as e:
230  
-            self.assertIn("Template 'base.html' was used unexpectedly in rendering the response", str(e))
231  
-
232  
-        try:
233  
-            self.assertTemplateUsed(response, "Valid POST Template")
234  
-        except AssertionError as e:
235  
-            self.assertIn("Template 'Valid POST Template' was not a template used to render the response. Actual template(s) used: form_view.html, base.html", str(e))
236  
-
237  
-class AssertRedirectsTests(TestCase):
238  
-    def test_redirect_page(self):
239  
-        "An assertion is raised if the original page couldn't be retrieved as expected"
240  
-        # This page will redirect with code 301, not 302
241  
-        response = self.client.get('/test_client/permanent_redirect_view/')
242  
-        try:
243  
-            self.assertRedirects(response, '/test_client/get_view/')
244  
-        except AssertionError as e:
245  
-            self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
246  
-
247  
-        try:
248  
-            self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
249  
-        except AssertionError as e:
250  
-            self.assertIn("abc: Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
251  
-
252  
-    def test_lost_query(self):
253  
-        "An assertion is raised if the redirect location doesn't preserve GET parameters"
254  
-        response = self.client.get('/test_client/redirect_view/', {'var': 'value'})
255  
-        try:
256  
-            self.assertRedirects(response, '/test_client/get_view/')
257  
-        except AssertionError as e:
258  
-            self.assertIn("Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e))
259  
-
260  
-        try:
261  
-            self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
262  
-        except AssertionError as e:
263  
-            self.assertIn("abc: Response redirected to 'http://testserver/test_client/get_view/?var=value', expected 'http://testserver/test_client/get_view/'", str(e))
264  
-
265  
-    def test_incorrect_target(self):
266  
-        "An assertion is raised if the response redirects to another target"
267  
-        response = self.client.get('/test_client/permanent_redirect_view/')
268  
-        try:
269  
-            # Should redirect to get_view
270  
-            self.assertRedirects(response, '/test_client/some_view/')
271  
-        except AssertionError as e:
272  
-            self.assertIn("Response didn't redirect as expected: Response code was 301 (expected 302)", str(e))
273  
-
274  
-    def test_target_page(self):
275  
-        "An assertion is raised if the response redirect target cannot be retrieved as expected"
276  
-        response = self.client.get('/test_client/double_redirect_view/')
277  
-        try:
278  
-            # The redirect target responds with a 301 code, not 200
279  
-            self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/')
280  
-        except AssertionError as e:
281  
-            self.assertIn("Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
282  
-
283  
-        try:
284  
-            # The redirect target responds with a 301 code, not 200
285  
-            self.assertRedirects(response, 'http://testserver/test_client/permanent_redirect_view/', msg_prefix='abc')
286  
-        except AssertionError as e:
287  
-            self.assertIn("abc: Couldn't retrieve redirection page '/test_client/permanent_redirect_view/': response code was 301 (expected 200)", str(e))
288  
-
289  
-    def test_redirect_chain(self):
290  
-        "You can follow a redirect chain of multiple redirects"
291  
-        response = self.client.get('/test_client_regress/redirects/further/more/', {}, follow=True)
292  
-        self.assertRedirects(response, '/test_client_regress/no_template_view/',
293  
-            status_code=301, target_status_code=200)
294  
-
295  
-        self.assertEqual(len(response.redirect_chain), 1)
296  
-        self.assertEqual(response.redirect_chain[0], ('http://testserver/test_client_regress/no_template_view/', 301))
297  
-
298  
-    def test_multiple_redirect_chain(self):
299  
-        "You can follow a redirect chain of multiple redirects"
300  
-        response = self.client.get('/test_client_regress/redirects/', {}, follow=True)
301  
-        self.assertRedirects(response, '/test_client_regress/no_template_view/',
302  
-            status_code=301, target_status_code=200)
303  
-
304  
-        self.assertEqual(len(response.redirect_chain), 3)
305  
-        self.assertEqual(response.redirect_chain[0], ('http://testserver/test_client_regress/redirects/further/', 301))
306  
-        self.assertEqual(response.redirect_chain[1], ('http://testserver/test_client_regress/redirects/further/more/', 301))
307  
-        self.assertEqual(response.redirect_chain[2], ('http://testserver/test_client_regress/no_template_view/', 301))
308  
-
309  
-    def test_redirect_chain_to_non_existent(self):
310  
-        "You can follow a chain to a non-existent view"
311  
-        response = self.client.get('/test_client_regress/redirect_to_non_existent_view2/', {}, follow=True)
312  
-        self.assertRedirects(response, '/test_client_regress/non_existent_view/',
313  
-            status_code=301, target_status_code=404)
314  
-
315  
-    def test_redirect_chain_to_self(self):
316  
-        "Redirections to self are caught and escaped"
317  
-        response = self.client.get('/test_client_regress/redirect_to_self/', {}, follow=True)
318  
-        # The chain of redirects stops once the cycle is detected.
319  
-        self.assertRedirects(response, '/test_client_regress/redirect_to_self/',
320  
-            status_code=301, target_status_code=301)
321  
-        self.assertEqual(len(response.redirect_chain), 2)
322  
-
323  
-    def test_circular_redirect(self):
324  
-        "Circular redirect chains are caught and escaped"
325  
-        response = self.client.get('/test_client_regress/circular_redirect_1/', {}, follow=True)
326  
-        # The chain of redirects will get back to the starting point, but stop there.
327  
-        self.assertRedirects(response, '/test_client_regress/circular_redirect_2/',
328  
-            status_code=301, target_status_code=301)
329  
-        self.assertEqual(len(response.redirect_chain), 4)
330  
-
331  
-    def test_redirect_chain_post(self):
332  
-        "A redirect chain will be followed from an initial POST post"
333  
-        response = self.client.post('/test_client_regress/redirects/',
334  
-            {'nothing': 'to_send'}, follow=True)
335  
-        self.assertRedirects(response,
336  
-            '/test_client_regress/no_template_view/', 301, 200)
337  
-        self.assertEqual(len(response.redirect_chain), 3)
338  
-
339  
-    def test_redirect_chain_head(self):
340  
-        "A redirect chain will be followed from an initial HEAD request"
341  
-        response = self.client.head('/test_client_regress/redirects/',
342  
-            {'nothing': 'to_send'}, follow=True)
343  
-        self.assertRedirects(response,
344  
-            '/test_client_regress/no_template_view/', 301, 200)
345  
-        self.assertEqual(len(response.redirect_chain), 3)
346  
-
347  
-    def test_redirect_chain_options(self):
348  
-        "A redirect chain will be followed from an initial OPTIONS request"
349  
-        response = self.client.options('/test_client_regress/redirects/',
350  
-            follow=True)
351  
-        self.assertRedirects(response,
352  
-            '/test_client_regress/no_template_view/', 301, 200)
353  
-        self.assertEqual(len(response.redirect_chain), 3)
354  
-
355  
-    def test_redirect_chain_put(self):
356  
-        "A redirect chain will be followed from an initial PUT request"
357  
-        response = self.client.put('/test_client_regress/redirects/',
358  
-            follow=True)
359  
-        self.assertRedirects(response,
360  
-            '/test_client_regress/no_template_view/', 301, 200)
361  
-        self.assertEqual(len(response.redirect_chain), 3)
362  
-
363  
-    def test_redirect_chain_delete(self):
364  
-        "A redirect chain will be followed from an initial DELETE request"
365  
-        response = self.client.delete('/test_client_regress/redirects/',
366  
-            follow=True)
367  
-        self.assertRedirects(response,
368  
-            '/test_client_regress/no_template_view/', 301, 200)
369  
-        self.assertEqual(len(response.redirect_chain), 3)
370  
-
371  
-    def test_redirect_to_different_host(self):
372  
-        "The test client will preserve scheme, host and port changes"
373  
-        response = self.client.get('/test_client_regress/redirect_other_host/', follow=True)
374  
-        self.assertRedirects(response,
375  
-            'https://otherserver:8443/test_client_regress/no_template_view/',
376  
-            status_code=301, target_status_code=200)
377  
-        # We can't use is_secure() or get_host()
378  
-        # because response.request is a dictionary, not an HttpRequest
379  
-        self.assertEqual(response.request.get('wsgi.url_scheme'), 'https')
380  
-        self.assertEqual(response.request.get('SERVER_NAME'), 'otherserver')
381  
-        self.assertEqual(response.request.get('SERVER_PORT'), '8443')
382  
-
383  
-    def test_redirect_chain_on_non_redirect_page(self):
384  
-        "An assertion is raised if the original page couldn't be retrieved as expected"
385  
-        # This page will redirect with code 301, not 302
386  
-        response = self.client.get('/test_client/get_view/', follow=True)
387  
-        try:
388  
-            self.assertRedirects(response, '/test_client/get_view/')
389  
-        except AssertionError as e:
390  
-            self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
391  
-
392  
-        try:
393  
-            self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
394  
-        except AssertionError as e:
395  
-            self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
396  
-
397  
-    def test_redirect_on_non_redirect_page(self):
398  
-        "An assertion is raised if the original page couldn't be retrieved as expected"
399  
-        # This page will redirect with code 301, not 302
400  
-        response = self.client.get('/test_client/get_view/')
401  
-        try:
402  
-            self.assertRedirects(response, '/test_client/get_view/')
403  
-        except AssertionError as e:
404  
-            self.assertIn("Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
405  
-
406  
-        try:
407  
-            self.assertRedirects(response, '/test_client/get_view/', msg_prefix='abc')
408  
-        except AssertionError as e:
409  
-            self.assertIn("abc: Response didn't redirect as expected: Response code was 200 (expected 302)", str(e))
410  
-
411  
-
412  
-class AssertFormErrorTests(TestCase):
413  
-    def test_unknown_form(self):
414  
-        "An assertion is raised if the form name is unknown"
415  
-        post_data = {
416  
-            'text': 'Hello World',
417  
-            'email': 'not an email address',
418  
-            'value': 37,
419  
-            'single': 'b',
420  
-            'multi': ('b','c','e')
421  
-        }
422  
-        response = self.client.post('/test_client/form_view/', post_data)
423  
-        self.assertEqual(response.status_code, 200)
424  
-        self.assertTemplateUsed(response, "Invalid POST Template")
425  
-
426  
-        try:
427  
-            self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.')
428  
-        except AssertionError as e:
429  
-            self.assertIn("The form 'wrong_form' was not used to render the response", str(e))
430  
-        try:
431  
-            self.assertFormError(response, 'wrong_form', 'some_field', 'Some error.', msg_prefix='abc')
432  
-        except AssertionError as e:
433  
-            self.assertIn("abc: The form 'wrong_form' was not used to render the response", str(e))
434  
-
435  
-    def test_unknown_field(self):
436  
-        "An assertion is raised if the field name is unknown"
437  
-        post_data = {
438  
-            'text': 'Hello World',
439  
-            'email': 'not an email address',
440  
-            'value': 37,
441  
-            'single': 'b',
442  
-            'multi': ('b','c','e')
443  
-        }
444  
-        response = self.client.post('/test_client/form_view/', post_data)
445  
-        self.assertEqual(response.status_code, 200)
446  
-        self.assertTemplateUsed(response, "Invalid POST Template")
447  
-
448  
-        try:
449  
-            self.assertFormError(response, 'form', 'some_field', 'Some error.')
450  
-        except AssertionError as e:
451  
-            self.assertIn("The form 'form' in context 0 does not contain the field 'some_field'", str(e))
452  
-        try:
453  
-            self.assertFormError(response, 'form', 'some_field', 'Some error.', msg_prefix='abc')
454  
-        except AssertionError as e:
455  
-            self.assertIn("abc: The form 'form' in context 0 does not contain the field 'some_field'", str(e))
456  
-
457  
-    def test_noerror_field(self):
458  
-        "An assertion is raised if the field doesn't have any errors"
459  
-        post_data = {
460  
-            'text': 'Hello World',
461  
-            'email': 'not an email address',
462  
-            'value': 37,
463  
-            'single': 'b',
464  
-            'multi': ('b','c','e')
465  
-        }
466  
-        response = self.client.post('/test_client/form_view/', post_data)
467  
-        self.assertEqual(response.status_code, 200)
468  
-        self.assertTemplateUsed(response, "Invalid POST Template")
469  
-
470  
-        try:
471  
-            self.assertFormError(response, 'form', 'value', 'Some error.')
472  
-        except AssertionError as e:
473  
-            self.assertIn("The field 'value' on form 'form' in context 0 contains no errors", str(e))
474  
-        try:
475  
-            self.assertFormError(response, 'form', 'value', 'Some error.', msg_prefix='abc')
476  
-        except AssertionError as e:
477  
-            self.assertIn("abc: The field 'value' on form 'form' in context 0 contains no errors", str(e))
478  
-
479  
-    def test_unknown_error(self):
480  
-        "An assertion is raised if the field doesn't contain the provided error"
481  
-        post_data = {
482  
-            'text': 'Hello World',
483  
-            'email': 'not an email address',
484  
-            'value': 37,
485  
-            'single': 'b',
486  
-            'multi': ('b','c','e')
487  
-        }
488  
-        response = self.client.post('/test_client/form_view/', post_data)
489  
-        self.assertEqual(response.status_code, 200)
490  
-        self.assertTemplateUsed(response, "Invalid POST Template")
491  
-
492  
-        try:
493  
-            self.assertFormError(response, 'form', 'email', 'Some error.')
494  
-        except AssertionError as e:
495  
-            self.assertIn("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.'])", str(e))
496  
-        try:
497  
-            self.assertFormError(response, 'form', 'email', 'Some error.', msg_prefix='abc')
498  
-        except AssertionError as e:
499  
-            self.assertIn("abc: 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.'])", str(e))
500  
-
501  
-    def test_unknown_nonfield_error(self):
502  
-        """
503  
-        Checks that an assertion is raised if the form's non field errors
504  
-        doesn't contain the provided error.
505  
-        """
506  
-        post_data = {
507  
-            'text': 'Hello World',
508  
-            'email': 'not an email address',
509  
-            'value': 37,
510  
-            'single': 'b',
511  
-            'multi': ('b','c','e')
512  
-        }
513  
-        response = self.client.post('/test_client/form_view/', post_data)
514  
-        self.assertEqual(response.status_code, 200)
515  
-        self.assertTemplateUsed(response, "Invalid POST Template")
516  
-
517  
-        try:
518  
-            self.assertFormError(response, 'form', None, 'Some error.')
519  
-        except AssertionError as e:
520  
-            self.assertIn("The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e))
521  
-        try:
522  
-            self.assertFormError(response, 'form', None, 'Some error.', msg_prefix='abc')
523  
-        except AssertionError as e:
524  
-            self.assertIn("abc: The form 'form' in context 0 does not contain the non-field error 'Some error.' (actual errors: )", str(e))
525  
-
526  
-@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
527  
-class LoginTests(TestCase):
528  
-    fixtures = ['testdata']
529  
-
530  
-    def test_login_different_client(self):
531  
-        "Check that using a different test client doesn't violate authentication"
532  
-
533  
-        # Create a second client, and log in.
534  
-        c = Client()
535  
-        login = c.login(username='testclient', password='password')
536  
-        self.assertTrue(login, 'Could not log in')
537  
-
538  
-        # Get a redirection page with the second client.
539  
-        response = c.get("/test_client_regress/login_protected_redirect_view/")
540  
-
541  
-        # At this points, the self.client isn't logged in.
542  
-        # Check that assertRedirects uses the original client, not the
543  
-        # default client.
544  
-        self.assertRedirects(response, "http://testserver/test_client_regress/get_view/")
545  
-
546  
-
547  
-@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
548  
-class SessionEngineTests(TestCase):
549  
-    fixtures = ['testdata']
550  
-
551  
-    def setUp(self):
552  
-        self.old_SESSION_ENGINE = settings.SESSION_ENGINE
553  
-        settings.SESSION_ENGINE = 'regressiontests.test_client_regress.session'
554  
-
555  
-    def tearDown(self):
556  
-        settings.SESSION_ENGINE = self.old_SESSION_ENGINE
557  
-
558  
-    def test_login(self):
559  
-        "A session engine that modifies the session key can be used to log in"
560  
-        login = self.client.login(username='testclient', password='password')
561  
-        self.assertTrue(login, 'Could not log in')
562  
-
563  
-        # Try to access a login protected page.
564  
-        response = self.client.get("/test_client/login_protected_view/")
565  
-        self.assertEqual(response.status_code, 200)
566  
-        self.assertEqual(response.context['user'].username, 'testclient')
567  
-
568  
-
569  
-class URLEscapingTests(TestCase):
570  
-    def test_simple_argument_get(self):
571  
-        "Get a view that has a simple string argument"
572  
-        response = self.client.get(reverse('arg_view', args=['Slartibartfast']))
573  
-        self.assertEqual(response.status_code, 200)
574  
-        self.assertEqual(response.content, b'Howdy, Slartibartfast')
575  
-
576  
-    def test_argument_with_space_get(self):
577  
-        "Get a view that has a string argument that requires escaping"
578  
-        response = self.client.get(reverse('arg_view', args=['Arthur Dent']))
579  
-        self.assertEqual(response.status_code, 200)
580  
-        self.assertEqual(response.content, b'Hi, Arthur')
581  
-
582  
-    def test_simple_argument_post(self):
583  
-        "Post for a view that has a simple string argument"
584  
-        response = self.client.post(reverse('arg_view', args=['Slartibartfast']))
585  
-        self.assertEqual(response.status_code, 200)
586  
-        self.assertEqual(response.content, b'Howdy, Slartibartfast')
587  
-
588  
-    def test_argument_with_space_post(self):
589  
-        "Post for a view that has a string argument that requires escaping"
590  
-        response = self.client.post(reverse('arg_view', args=['Arthur Dent']))
591  
-        self.assertEqual(response.status_code, 200)
592  
-        self.assertEqual(response.content, b'Hi, Arthur')
593  
-
594  
-@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
595  
-class ExceptionTests(TestCase):
596  
-    fixtures = ['testdata.json']
597  
-
598  
-    def test_exception_cleared(self):
599  
-        "#5836 - A stale user exception isn't re-raised by the test client."
600  
-
601  
-        login = self.client.login(username='testclient',password='password')
602  
-        self.assertTrue(login, 'Could not log in')
603  
-        try:
604  
-            response = self.client.get("/test_client_regress/staff_only/")
605  
-            self.fail("General users should not be able to visit this page")
606  
-        except SuspiciousOperation:
607  
-            pass
608  
-
609  
-        # At this point, an exception has been raised, and should be cleared.
610  
-
611  
-        # This next operation should be successful; if it isn't we have a problem.
612  
-        login = self.client.login(username='staff', password='password')
613  
-        self.assertTrue(login, 'Could not log in')
614  
-        try:
615  
-            self.client.get("/test_client_regress/staff_only/")
616  
-        except SuspiciousOperation:
617  
-            self.fail("Staff should be able to visit this page")
618  
-
619  
-class TemplateExceptionTests(TestCase):
620  
-    def setUp(self):
621  
-        # Reset the loaders so they don't try to render cached templates.
622  
-        if loader.template_source_loaders is not None:
623  
-            for template_loader in loader.template_source_loaders:
624  
-                if hasattr(template_loader, 'reset'):
625  
-                    template_loader.reset()
626  
-        self.old_templates = settings.TEMPLATE_DIRS
627  
-        settings.TEMPLATE_DIRS = ()
628  
-
629  
-    def tearDown(self):
630  
-        settings.TEMPLATE_DIRS = self.old_templates
631  
-
632  
-    def test_no_404_template(self):
633  
-        "Missing templates are correctly reported by test client"
634  
-        try:
635  
-            response = self.client.get("/no_such_view/")
636  
-            self.fail("Should get error about missing template")
637  
-        except TemplateDoesNotExist:
638  
-            pass
639  
-
640  
-    def test_bad_404_template(self):
641  
-        "Errors found when rendering 404 error templates are re-raised"
642  
-        settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'bad_templates'),)
643  
-        try:
644  
-            response = self.client.get("/no_such_view/")
645  
-            self.fail("Should get error about syntax error in template")
646  
-        except TemplateSyntaxError:
647  
-            pass
648  
-
649  
-# We need two different tests to check URLconf substitution -  one to check
650  
-# it was changed, and another one (without self.urls) to check it was reverted on
651  
-# teardown. This pair of tests relies upon the alphabetical ordering of test execution.
652  
-class UrlconfSubstitutionTests(TestCase):
653  
-    urls = 'regressiontests.test_client_regress.urls'
654  
-
655  
-    def test_urlconf_was_changed(self):
656  
-        "TestCase can enforce a custom URLconf on a per-test basis"
657  
-        url = reverse('arg_view', args=['somename'])
658  
-        self.assertEqual(url, '/arg_view/somename/')
659  
-
660  
-# This test needs to run *after* UrlconfSubstitutionTests; the zz prefix in the
661  
-# name is to ensure alphabetical ordering.
662  
-class zzUrlconfSubstitutionTests(TestCase):
663  
-    def test_urlconf_was_reverted(self):
664  
-        "URLconf is reverted to original value after modification in a TestCase"
665  
-        url = reverse('arg_view', args=['somename'])
666  
-        self.assertEqual(url, '/test_client_regress/arg_view/somename/')
667  
-
668  
-@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
669  
-class ContextTests(TestCase):
670  
-    fixtures = ['testdata']
671  
-
672  
-    def test_single_context(self):
673  
-        "Context variables can be retrieved from a single context"
674  
-        response = self.client.get("/test_client_regress/request_data/", data={'foo':'whiz'})
675  
-        self.assertEqual(response.context.__class__, Context)
676  
-        self.assertTrue('get-foo' in response.context)
677  
-        self.assertEqual(response.context['get-foo'], 'whiz')
678  
-        self.assertEqual(response.context['request-foo'], 'whiz')
679  
-        self.assertEqual(response.context['data'], 'sausage')
680  
-
681  
-        try:
682  
-            response.context['does-not-exist']
683  
-            self.fail('Should not be able to retrieve non-existent key')
684  
-        except KeyError as e:
685  
-            self.assertEqual(e.args[0], 'does-not-exist')
686  
-
687  
-    def test_inherited_context(self):
688  
-        "Context variables can be retrieved from a list of contexts"
689  
-        response = self.client.get("/test_client_regress/request_data_extended/", data={'foo':'whiz'})
690  
-        self.assertEqual(response.context.__class__, ContextList)
691  
-        self.assertEqual(len(response.context), 2)
692  
-        self.assertTrue('get-foo' in response.context)
693  
-        self.assertEqual(response.context['get-foo'], 'whiz')
694  
-        self.assertEqual(response.context['request-foo'], 'whiz')
695  
-        self.assertEqual(response.context['data'], 'bacon')
696  
-
697  
-        try:
698  
-            response.context['does-not-exist']
699  
-            self.fail('Should not be able to retrieve non-existent key')
700  
-        except KeyError as e:
701  
-            self.assertEqual(e.args[0], 'does-not-exist')
702  
-
703  
-    def test_15368(self):
704  
-        # Need to insert a context processor that assumes certain things about
705  
-        # the request instance. This triggers a bug caused by some ways of
706  
-        # copying RequestContext.
707  
-        try:
708  
-            django.template.context._standard_context_processors = (lambda request: {'path': request.special_path},)
709  
-            response = self.client.get("/test_client_regress/request_context_view/")
710  
-            self.assertContains(response, 'Path: /test_client_regress/request_context_view/')
711  
-        finally:
712  
-            django.template.context._standard_context_processors = None
713  
-
714  
-
715  
-@override_settings(PASSWORD_HASHERS=('django.contrib.auth.hashers.SHA1PasswordHasher',))
716  
-class SessionTests(TestCase):
717  
-    fixtures = ['testdata.json']
718  
-
719  
-    def test_session(self):
720  
-        "The session isn't lost if a user logs in"
721  
-        # The session doesn't exist to start.
722  
-        response = self.client.get('/test_client_regress/check_session/')
723  
-        self.assertEqual(response.status_code, 200)
724  
-        self.assertEqual(response.content, b'NO')
725  
-
726  
-        # This request sets a session variable.
727  
-        response = self.client.get('/test_client_regress/set_session/')
728  
-        self.assertEqual(response.status_code, 200)
729  
-        self.assertEqual(response.content, b'set_session')
730  
-
731  
-        # Check that the session has been modified
732  
-        response = self.client.get('/test_client_regress/check_session/')
733  
-        self.assertEqual(response.status_code, 200)
734  
-        self.assertEqual(response.content, b'YES')
735  
-
736  
-        # Log in
737  
-        login = self.client.login(username='testclient',password='password')
738  
-        self.assertTrue(login, 'Could not log in')
739  
-
740  
-        # Session should still contain the modified value
741  
-        response = self.client.get('/test_client_regress/check_session/')
742  
-        self.assertEqual(response.status_code, 200)
743  
-        self.assertEqual(response.content, b'YES')
744  
-
745  
-    def test_logout(self):
746  
-        """Logout should work whether the user is logged in or not (#9978)."""
747  
-        self.client.logout()
748  
-        login = self.client.login(username='testclient',password='password')
749  
-        self.assertTrue(login, 'Could not log in')
750  
-        self.client.logout()
751  
-        self.client.logout()
752  
-
753  
-class RequestMethodTests(TestCase):
754  
-    def test_get(self):
755  
-        "Request a view via request method GET"
756  
-        response = self.client.get('/test_client_regress/request_methods/')
757  
-        self.assertEqual(response.status_code, 200)
758  
-        self.assertEqual(response.content, b'request method: GET')
759  
-
760  
-    def test_post(self):
761  
-        "Request a view via request method POST"
762  
-        response = self.client.post('/test_client_regress/request_methods/')
763  
-        self.assertEqual(response.status_code, 200)
764  
-        self.assertEqual(response.content, b'request method: POST')
765  
-
766  
-    def test_head(self):
767  
-        "Request a view via request method HEAD"
768  
-        response = self.client.head('/test_client_regress/request_methods/')
769  
-        self.assertEqual(response.status_code, 200)
770  
-        # A HEAD request doesn't return any content.
771  
-        self.assertNotEqual(response.content, b'request method: HEAD')
772  
-        self.assertEqual(response.content, b'')
773  
-
774  
-    def test_options(self):
775  
-        "Request a view via request method OPTIONS"
776  
-        response = self.client.options('/test_client_regress/request_methods/')
777  
-        self.assertEqual(response.status_code, 200)
778  
-        self.assertEqual(response.content, b'request method: OPTIONS')
779  
-
780  
-    def test_put(self):
781  
-        "Request a view via request method PUT"
782  
-        response = self.client.put('/test_client_regress/request_methods/')
783  
-        self.assertEqual(response.status_code, 200)
784  
-        self.assertEqual(response.content, b'request method: PUT')
785  
-
786  
-    def test_delete(self):
787  
-        "Request a view via request method DELETE"
788  
-        response = self.client.delete('/test_client_regress/request_methods/')
789  
-        self.assertEqual(response.status_code, 200)
790  
-        self.assertEqual(response.content, b'request method: DELETE')
791  
-
792  
-class RequestMethodStringDataTests(TestCase):
793  
-    def test_post(self):
794  
-        "Request a view with string data via request method POST"
795  
-        # Regression test for #11371
796  
-        data = u'{"test": "json"}'
797  
-        response = self.client.post('/test_client_regress/request_methods/', data=data, content_type='application/json')
798  
-        self.assertEqual(response.status_code, 200)
799  
-        self.assertEqual(response.content, b'request method: POST')
800  
-
801  
-    def test_put(self):
802  
-        "Request a view with string data via request method PUT"
803  
-        # Regression test for #11371
804  
-        data = u'{"test": "json"}'
805  
-        response = self.client.put('/test_client_regress/request_methods/', data=data, content_type='application/json')
806  
-        self.assertEqual(response.status_code, 200)
807  
-        self.assertEqual(response.content, b'request method: PUT')
808  
-
809  
-class QueryStringTests(TestCase):
810  
-    def test_get_like_requests(self):
811  
-        # See: https://code.djangoproject.com/ticket/10571.
812  
-        for method_name in ('get', 'head'):
813  
-            # A GET-like request can pass a query string as data
814  
-            method = getattr(self.client, method_name)
815  
-            response = method("/test_client_regress/request_data/", data={'foo':'whiz'})
816  
-            self.assertEqual(response.context['get-foo'], 'whiz')
817  
-            self.assertEqual(response.context['request-foo'], 'whiz')
818  
-
819  
-            # A GET-like request can pass a query string as part of the URL
820  
-            response = method("/test_client_regress/request_data/?foo=whiz")
821  
-            self.assertEqual(response.context['get-foo'], 'whiz')
822  
-            self.assertEqual(response.context['request-foo'], 'whiz')
823  
-
824  
-            # Data provided in the URL to a GET-like request is overridden by actual form data
825  
-            response = method("/test_client_regress/request_data/?foo=whiz", data={'foo':'bang'})
826  
-            self.assertEqual(response.context['get-foo'], 'bang')
827  
-            self.assertEqual(response.context['request-foo'], 'bang')
828  
-
829  
-            response = method("/test_client_regress/request_data/?foo=whiz", data={'bar':'bang'})
830  
-            self.assertEqual(response.context['get-foo'], None)
831  
-            self.assertEqual(response.context['get-bar'], 'bang')
832  
-            self.assertEqual(response.context['request-foo'], None)
833  
-            self.assertEqual(response.context['request-bar'], 'bang')
834  
-
835  
-    def test_post_like_requests(self):
836  
-        # A POST-like request can pass a query string as data
837  
-        response = self.client.post("/test_client_regress/request_data/", data={'foo':'whiz'})
838  
-        self.assertEqual(response.context['get-foo'], None)
839  
-        self.assertEqual(response.context['post-foo'], 'whiz')
840  
-
841  
-        # A POST-like request can pass a query string as part of the URL
842  
-        response = self.client.post("/test_client_regress/request_data/?foo=whiz")
843  
-        self.assertEqual(response.context['get-foo'], 'whiz')
844  
-        self.assertEqual(response.context['post-foo'], None)
845  
-        self.assertEqual(response.context['request-foo'], 'whiz')
846  
-
847  
-        # POST data provided in the URL augments actual form data
848  
-        response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'foo':'bang'})
849  
-        self.assertEqual(response.context['get-foo'], 'whiz')
850  
-        self.assertEqual(response.context['post-foo'], 'bang')
851  
-        self.assertEqual(response.context['request-foo'], 'bang')
852  
-
853  
-        response = self.client.post("/test_client_regress/request_data/?foo=whiz", data={'bar':'bang'})
854  
-        self.assertEqual(response.context['get-foo'], 'whiz')
855  
-        self.assertEqual(response.context['get-bar'], None)
856  
-        self.assertEqual(response.context['post-foo'], None)
857  
-        self.assertEqual(response.context['post-bar'], 'bang')
858  
-        self.assertEqual(response.context['request-foo'], 'whiz')
859  
-        self.assertEqual(response.context['request-bar'], 'bang')
860  
-
861  
-class UnicodePayloadTests(TestCase):
862  
-    def test_simple_unicode_payload(self):
863  
-        "A simple ASCII-only unicode JSON document can be POSTed"
864  
-        # Regression test for #10571
865  
-        json = u'{"english": "mountain pass"}'
866  
-        response = self.client.post("/test_client_regress/parse_unicode_json/", json,
867  
-                                    content_type="application/json")
868  
-        self.assertEqual(response.content, json)
869  
-
870  
-    def test_unicode_payload_utf8(self):
871  
-        "A non-ASCII unicode data encoded as UTF-8 can be POSTed"
872  
-        # Regression test for #10571
873  
-        json = u'{"dog": "собака"}'
874  
-        response = self.client.post("/test_client_regress/parse_unicode_json/", json,
875  
-                                    content_type="application/json; charset=utf-8")
876  
-        self.assertEqual(response.content, json.encode('utf-8'))
877  
-
878  
-    def test_unicode_payload_utf16(self):
879  
-        "A non-ASCII unicode data encoded as UTF-16 can be POSTed"
880  
-        # Regression test for #10571
881  
-        json = u'{"dog": "собака"}'
882  
-        response = self.client.post("/test_client_regress/parse_unicode_json/", json,
883  
-                                    content_type="application/json; charset=utf-16")
884  
-        self.assertEqual(response.content, json.encode('utf-16'))
885  
-
886  
-    def test_unicode_payload_non_utf(self):
887  
-        "A non-ASCII unicode data as a non-UTF based encoding can be POSTed"
888  
-        #Regression test for #10571
889  
-        json = u'{"dog": "собака"}'
890  
-        response = self.client.post("/test_client_regress/parse_unicode_json/", json,
891  
-                                    content_type="application/json; charset=koi8-r")
892  
-        self.assertEqual(response.content, json.encode('koi8-r'))
893  
-
894  
-class DummyFile(object):
895  
-    def __init__(self, filename):
896  
-        self.name = filename
897  
-    def read(self):
898  
-        return 'TEST_FILE_CONTENT'
899  
-
900  
-class UploadedFileEncodingTest(TestCase):
901  
-    def test_file_encoding(self):
902  
-        encoded_file = encode_file('TEST_BOUNDARY', 'TEST_KEY', DummyFile('test_name.bin'))
903  
-        self.assertEqual(b'--TEST_BOUNDARY', encoded_file[0])
904  
-        self.assertEqual(b'Content-Disposition: form-data; name="TEST_KEY"; filename="test_name.bin"', encoded_file[1])
905  
-        self.assertEqual(b'TEST_FILE_CONTENT', encoded_file[-1])
906  
-
907  
-    def test_guesses_content_type_on_file_encoding(self):
908  
-        self.assertEqual(b'Content-Type: application/octet-stream',
909  
-                         encode_file('IGNORE', 'IGNORE', DummyFile("file.bin"))[2])
910  
-        self.assertEqual(b'Content-Type: text/plain',
911  
-                         encode_file('IGNORE', 'IGNORE', DummyFile("file.txt"))[2])
912  
-        self.assertIn(encode_file('IGNORE', 'IGNORE', DummyFile("file.zip"))[2], (
913  
-                        b'Content-Type: application/x-compress',
914  
-                        b'Content-Type: application/x-zip',
915  
-                        b'Content-Type: application/x-zip-compressed',
916  
-                        b'Content-Type: application/zip',))
917  
-        self.assertEqual(b'Content-Type: application/octet-stream',
918  
-                         encode_file('IGNORE', 'IGNORE', DummyFile("file.unknown"))[2])
919  
-
920  
-class RequestHeadersTest(TestCase):
921  
-    def test_client_headers(self):
922  
-        "A test client can receive custom headers"
923  
-        response = self.client.get("/test_client_regress/check_headers/", HTTP_X_ARG_CHECK='Testing 123')
924  
-        self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123")
925  
-        self.assertEqual(response.status_code, 200)
926  
-
927  
-    def test_client_headers_redirect(self):
928  
-        "Test client headers are preserved through redirects"
929  
-        response = self.client.get("/test_client_regress/check_headers_redirect/", follow=True, HTTP_X_ARG_CHECK='Testing 123')
930  
-        self.assertEqual(response.content, b"HTTP_X_ARG_CHECK: Testing 123")
931  
-        self.assertRedirects(response, '/test_client_regress/check_headers/',
932  
-            status_code=301, target_status_code=200)
933  
-
934  
-
935  
-class ReadLimitedStreamTest(TestCase):
936  
-    """
937  
-    Tests that ensure that HttpRequest.body, HttpRequest.read() and
938  
-    HttpRequest.read(BUFFER) have proper LimitedStream behavior.
939  
-
940  
-    Refs #14753, #15785
941  
-    """
942  
-
943  
-    def test_body_from_empty_request(self):
944  
-        """HttpRequest.body on a test client GET request should return
945  
-        the empty string."""
946  
-        self.assertEqual(self.client.get("/test_client_regress/body/").content, b'')
947  
-
948  
-    def test_read_from_empty_request(self):
949  
-        """HttpRequest.read() on a test client GET request should return the
950  
-        empty string."""
951  
-        self.assertEqual(self.client.get("/test_client_regress/read_all/").content, b'')
952  
-
953  
-    def test_read_numbytes_from_empty_request(self):
954  
-        """HttpRequest.read(LARGE_BUFFER) on a test client GET request should
955  
-        return the empty string."""
956  
-        self.assertEqual(self.client.get("/test_client_regress/read_buffer/").content, b'')
957  
-
958  
-    def test_read_from_nonempty_request(self):
959  
-        """HttpRequest.read() on a test client PUT request with some payload
960  
-        should return that payload."""
961  
-        payload = b'foobar'
962  
-        self.assertEqual(self.client.put("/test_client_regress/read_all/",
963  
-                                          data=payload,
964  
-                                          content_type='text/plain').content, payload)
965  
-
966  
-    def test_read_numbytes_from_nonempty_request(self):
967  
-        """HttpRequest.read(LARGE_BUFFER) on a test client PUT request with
968  
-        some payload should return that payload."""
969  
-        payload = b'foobar'
970  
-        self.assertEqual(self.client.put("/test_client_regress/read_buffer/",
971  
-                                          data=payload,
972  
-                                          content_type='text/plain').content, payload)
973  
-
974  
-
975  
-class RequestFactoryStateTest(TestCase):
976  
-    """Regression tests for #15929."""
977  
-    # These tests are checking that certain middleware don't change certain
978  
-    # global state. Alternatively, from the point of view of a test, they are
979  
-    # ensuring test isolation behavior. So, unusually, it doesn't make sense to
980  
-    # run the tests individually, and if any are failing it is confusing to run
981  
-    # them with any other set of tests.
982  
-
983  
-    def setUp(self):
984  
-        self.factory = RequestFactory()
985  
-
986  
-    def common_test_that_should_always_pass(self):
987  
-        request = self.factory.get('/')
988  
-        request.session = {}
989  
-        self.assertFalse(hasattr(request, 'user'))
990  
-
991  
-    def test_request(self):
992  
-        self.common_test_that_should_always_pass()
993  
-
994  
-    def test_request_after_client(self):
995  
-        # apart from the next line the three tests are identical
996  
-        self.client.get('/')
997  
-        self.common_test_that_should_always_pass()
998  
-
999  
-    def test_request_after_client_2(self):
1000  
-        # This test is executed after the previous one
1001  
-        self.common_test_that_should_always_pass()
1002  
-
1003  
-
1004  
-class RequestFactoryEnvironmentTests(TestCase):
1005  
-    """
1006  
-    Regression tests for #8551 and #17067: ensure that environment variables
1007  
-    are set correctly in RequestFactory.
1008  
-    """
1009  
-
1010  
-    def setUp(self):
1011  
-        self.factory = RequestFactory()
1012  
-
1013  
-    def test_should_set_correct_env_variables(self):
1014  
-        request = self.factory.get('/path/')
1015  
-
1016  
-        self.assertEqual(request.META.get('REMOTE_ADDR'), '127.0.0.1')
1017  
-        self.assertEqual(request.META.get('SERVER_NAME'), 'testserver')
1018  
-        self.assertEqual(request.META.get('SERVER_PORT'), '80')
1019  
-        self.assertEqual(request.META.get('SERVER_PROTOCOL'), 'HTTP/1.1')
1020  
-        self.assertEqual(request.META.get('SCRIPT_NAME') +
1021  
-                         request.META.get('PATH_INFO'), '/path/')
1,021  tests/regressiontests/test_client_regress/tests.py
... ...
@@ -0,0 +1,1021 @@
  1
+# -*- coding: utf-8 -*-
  2
+"""
  3
+Regression tests for the Test Client, especially the customized assertions.
  4
+"""
  5
+import os
  6
+
  7
+from django.conf import settings
  8
+from django.core.exceptions import SuspiciousOperation
  9
+from django.core.urlresolvers import reverse
  10
+from django.template import (TemplateDoesNotExist, TemplateSyntaxError,
  11
+    Context, Template, loader)
  12
+import django.template.context
  13
+from django.test import Client, TestCase
  14
+from django.test.client import encode_file, RequestFactory
  15
+from django.test.utils import ContextList, override_settings
  16
+from django.template.response import SimpleTemplateResponse
  17
+from django.http import HttpResponse
  18
+
  19
+
  20
+class AssertContainsTests(TestCase):
  21
+    def setUp(self):
  22
+        self.old_templates = settings.TEMPLATE_DIRS
  23
+        settings.TEMPLATE_DIRS = (os.path.join(os.path.dirname(__file__), 'templates'),)
  24
+
  25
+    def tearDown(self):
  26
+        settings.TEMPLATE_DIRS = self.old_templates
  27
+
  28
+    def test_contains(self):
  29
+        "Responses can be inspected for content, including counting repeated substrings"
  30
+        response = self.client.get('/test_client_regress/no_template_view/')
  31
+
  32
+        self.assertNotContains(response, 'never')
  33
+        self.assertContains(response, 'never', 0)
  34
+        self.assertContains(response, 'once')
  35
+        self.assertContains(response, 'once', 1)
  36
+        self.assertContains(response, 'twice')
  37
+        self.assertContains(response, 'twice', 2)
  38
+
  39
+        try: