Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/tests/test_client/tests.py
blob: 4b483320855916e66c066e21b5d5dbdd03d68aa3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
# -*- coding: utf-8 -*-
"""
Testing using the Test Client

The test client is a class that can act like a simple
browser for testing purposes.

It allows the user to compose GET and POST requests, and
obtain the response that the server gave to those requests.
The server Response objects are annotated with the details
of the contexts and templates that were rendered during the
process of serving the request.

``Client`` objects are stateful - they will retain cookie (and
thus session) details for the lifetime of the ``Client`` instance.

This is not intended as a replacement for Twill, Selenium, or
other browser automation frameworks - it is here to allow
testing against the contexts and templates produced by a view,
rather than the HTML rendered to the end-user.

"""
from __future__ import unicode_literals

import datetime

from django.contrib.auth.models import User
from django.core import mail
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponse
from django.test import (
    Client, RequestFactory, SimpleTestCase, TestCase, override_settings,
)

from .views import get_view, post_view, trace_view


@override_settings(PASSWORD_HASHERS=['django.contrib.auth.hashers.SHA1PasswordHasher'],
                   ROOT_URLCONF='test_client.urls',)
class ClientTest(TestCase):

    @classmethod
    def setUpTestData(cls):
        cls.u1 = User.objects.create(
            password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
            last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='testclient',
            first_name='Test', last_name='Client', email='testclient@example.com', is_staff=False, is_active=True,
            date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
        )
        cls.u2 = User.objects.create(
            password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
            last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='inactive',
            first_name='Inactive', last_name='User', email='testclient@example.com', is_staff=False, is_active=False,
            date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
        )
        cls.u3 = User.objects.create(
            password='sha1$6efc0$f93efe9fd7542f25a7be94871ea45aa95de57161',
            last_login=datetime.datetime(2006, 12, 17, 7, 3, 31), is_superuser=False, username='staff',
            first_name='Staff', last_name='Member', email='testclient@example.com', is_staff=True, is_active=True,
            date_joined=datetime.datetime(2006, 12, 17, 7, 3, 31)
        )

    def test_get_view(self):
        "GET a view"
        # The data is ignored, but let's check it doesn't crash the system
        # anyway.
        data = {'var': '\xf2'}
        response = self.client.get('/get_view/', data)

        # Check some response details
        self.assertContains(response, 'This is a test')
        self.assertEqual(response.context['var'], '\xf2')
        self.assertEqual(response.templates[0].name, 'GET Template')

    def test_get_post_view(self):
        "GET a view that normally expects POSTs"
        response = self.client.get('/post_view/', {})

        # Check some response details
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.templates[0].name, 'Empty GET Template')
        self.assertTemplateUsed(response, 'Empty GET Template')
        self.assertTemplateNotUsed(response, 'Empty POST Template')

    def test_empty_post(self):
        "POST an empty dictionary to a view"
        response = self.client.post('/post_view/', {})

        # Check some response details
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.templates[0].name, 'Empty POST Template')
        self.assertTemplateNotUsed(response, 'Empty GET Template')
        self.assertTemplateUsed(response, 'Empty POST Template')

    def test_post(self):
        "POST some data to a view"
        post_data = {
            'value': 37
        }
        response = self.client.post('/post_view/', post_data)

        # Check some response details
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['data'], '37')
        self.assertEqual(response.templates[0].name, 'POST Template')
        self.assertContains(response, 'Data received')

    def test_trace(self):
        """TRACE a view"""
        response = self.client.trace('/trace_view/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['method'], 'TRACE')
        self.assertEqual(response.templates[0].name, 'TRACE Template')

    def test_response_headers(self):
        "Check the value of HTTP headers returned in a response"
        response = self.client.get("/header_view/")

        self.assertEqual(response['X-DJANGO-TEST'], 'Slartibartfast')

    def test_response_attached_request(self):
        """
        Check that the returned response has a ``request`` attribute with the
        originating environ dict and a ``wsgi_request`` with the originating
        ``WSGIRequest`` instance.
        """
        response = self.client.get("/header_view/")

        self.assertTrue(hasattr(response, 'request'))
        self.assertTrue(hasattr(response, 'wsgi_request'))
        for key, value in response.request.items():
            self.assertIn(key, response.wsgi_request.environ)
            self.assertEqual(response.wsgi_request.environ[key], value)

    def test_response_resolver_match(self):
        """
        The response contains a ResolverMatch instance.
        """
        response = self.client.get('/header_view/')
        self.assertTrue(hasattr(response, 'resolver_match'))

    def test_response_resolver_match_redirect_follow(self):
        """
        The response ResolverMatch instance contains the correct
        information when following redirects.
        """
        response = self.client.get('/redirect_view/', follow=True)
        self.assertEqual(response.resolver_match.url_name, 'get_view')

    def test_response_resolver_match_regular_view(self):
        """
        The response ResolverMatch instance contains the correct
        information when accessing a regular view.
        """
        response = self.client.get('/get_view/')
        self.assertEqual(response.resolver_match.url_name, 'get_view')

    def test_raw_post(self):
        "POST raw data (with a content type) to a view"
        test_doc = """<?xml version="1.0" encoding="utf-8"?>
        <library><book><title>Blink</title><author>Malcolm Gladwell</author></book></library>
        """
        response = self.client.post("/raw_post_view/", test_doc,
                                    content_type="text/xml")
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.templates[0].name, "Book template")
        self.assertEqual(response.content, b"Blink - Malcolm Gladwell")

    def test_insecure(self):
        "GET a URL through http"
        response = self.client.get('/secure_view/', secure=False)
        self.assertFalse(response.test_was_secure_request)
        self.assertEqual(response.test_server_port, '80')

    def test_secure(self):
        "GET a URL through https"
        response = self.client.get('/secure_view/', secure=True)
        self.assertTrue(response.test_was_secure_request)
        self.assertEqual(response.test_server_port, '443')

    def test_redirect(self):
        "GET a URL that redirects elsewhere"
        response = self.client.get('/redirect_view/')
        # Check that the response was a 302 (redirect)
        self.assertRedirects(response, '/get_view/')

    def test_redirect_with_query(self):
        "GET a URL that redirects with given GET parameters"
        response = self.client.get('/redirect_view/', {'var': 'value'})

        # Check if parameters are intact
        self.assertRedirects(response, '/get_view/?var=value')

    def test_permanent_redirect(self):
        "GET a URL that redirects permanently elsewhere"
        response = self.client.get('/permanent_redirect_view/')
        # Check that the response was a 301 (permanent redirect)
        self.assertRedirects(response, '/get_view/', status_code=301)

    def test_temporary_redirect(self):
        "GET a URL that does a non-permanent redirect"
        response = self.client.get('/temporary_redirect_view/')
        # Check that the response was a 302 (non-permanent redirect)
        self.assertRedirects(response, '/get_view/', status_code=302)

    def test_redirect_to_strange_location(self):
        "GET a URL that redirects to a non-200 page"
        response = self.client.get('/double_redirect_view/')

        # Check that the response was a 302, and that
        # the attempt to get the redirection location returned 301 when retrieved
        self.assertRedirects(response, '/permanent_redirect_view/', target_status_code=301)

    def test_follow_redirect(self):
        "A URL that redirects can be followed to termination."
        response = self.client.get('/double_redirect_view/', follow=True)
        self.assertRedirects(response, '/get_view/', status_code=302, target_status_code=200)
        self.assertEqual(len(response.redirect_chain), 2)

    def test_redirect_http(self):
        "GET a URL that redirects to an http URI"
        response = self.client.get('/http_redirect_view/', follow=True)
        self.assertFalse(response.test_was_secure_request)

    def test_redirect_https(self):
        "GET a URL that redirects to an https URI"
        response = self.client.get('/https_redirect_view/', follow=True)
        self.assertTrue(response.test_was_secure_request)

    def test_notfound_response(self):
        "GET a URL that responds as '404:Not Found'"
        response = self.client.get('/bad_view/')

        # Check that the response was a 404, and that the content contains MAGIC
        self.assertContains(response, 'MAGIC', status_code=404)

    def test_valid_form(self):
        "POST valid data to a form"
        post_data = {
            'text': 'Hello World',
            'email': 'foo@example.com',
            'value': 37,
            'single': 'b',
            'multi': ('b', 'c', 'e')
        }
        response = self.client.post('/form_view/', post_data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "Valid POST Template")

    def test_valid_form_with_hints(self):
        "GET a form, providing hints in the GET data"
        hints = {
            'text': 'Hello World',
            'multi': ('b', 'c', 'e')
        }
        response = self.client.get('/form_view/', data=hints)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "Form GET Template")
        # Check that the multi-value data has been rolled out ok
        self.assertContains(response, 'Select a valid choice.', 0)

    def test_incomplete_data_form(self):
        "POST incomplete data to a form"
        post_data = {
            'text': 'Hello World',
            'value': 37
        }
        response = self.client.post('/form_view/', post_data)
        self.assertContains(response, 'This field is required.', 3)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "Invalid POST Template")

        self.assertFormError(response, 'form', 'email', 'This field is required.')
        self.assertFormError(response, 'form', 'single', 'This field is required.')
        self.assertFormError(response, 'form', 'multi', 'This field is required.')

    def test_form_error(self):
        "POST erroneous data to a form"
        post_data = {
            'text': 'Hello World',
            'email': 'not an email address',
            'value': 37,
            'single': 'b',
            'multi': ('b', 'c', 'e')
        }
        response = self.client.post('/form_view/', post_data)
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, "Invalid POST Template")

        self.assertFormError(response, 'form', 'email', 'Enter a valid email address.')

    def test_valid_form_with_template(self):
        "POST valid data to a form using multiple templates"
        post_data = {
            'text': 'Hello World',
            'email': 'foo@example.com',
            'value': 37,
            'single': 'b',
            'multi': ('b', 'c', 'e')
        }
        response = self.client.post('/form_view_with_template/', post_data)
        self.assertContains(response, 'POST data OK')
        self.assertTemplateUsed(response, "form_view.html")
        self.assertTemplateUsed(response, 'base.html')
        self.assertTemplateNotUsed(response, "Valid POST Template")

    def test_incomplete_data_form_with_template(self):
        "POST incomplete data to a form using multiple templates"
        post_data = {
            'text': 'Hello World',
            'value': 37
        }
        response = self.client.post('/form_view_with_template/', post_data)
        self.assertContains(response, 'POST data has errors')
        self.assertTemplateUsed(response, 'form_view.html')
        self.assertTemplateUsed(response, 'base.html')
        self.assertTemplateNotUsed(response, "Invalid POST Template")

        self.assertFormError(response, 'form', 'email', 'This field is required.')
        self.assertFormError(response, 'form', 'single', 'This field is required.')
        self.assertFormError(response, 'form', 'multi', 'This field is required.')

    def test_form_error_with_template(self):
        "POST erroneous data to a form using multiple templates"
        post_data = {
            'text': 'Hello World',
            'email': 'not an email address',
            'value': 37,
            'single': 'b',
            'multi': ('b', 'c', 'e')
        }
        response = self.client.post('/form_view_with_template/', post_data)
        self.assertContains(response, 'POST data has errors')
        self.assertTemplateUsed(response, "form_view.html")
        self.assertTemplateUsed(response, 'base.html')
        self.assertTemplateNotUsed(response, "Invalid POST Template")

        self.assertFormError(response, 'form', 'email', 'Enter a valid email address.')

    def test_unknown_page(self):
        "GET an invalid URL"
        response = self.client.get('/unknown_view/')

        # Check that the response was a 404
        self.assertEqual(response.status_code, 404)

    def test_url_parameters(self):
        "Make sure that URL ;-parameters are not stripped."
        response = self.client.get('/unknown_view/;some-parameter')

        # Check that the path in the response includes it (ignore that it's a 404)
        self.assertEqual(response.request['PATH_INFO'], '/unknown_view/;some-parameter')

    def test_view_with_login(self):
        "Request a page that is protected with @login_required"

        # Get the page without logging in. Should result in 302.
        response = self.client.get('/login_protected_view/')
        self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')

        # Log in
        login = self.client.login(username='testclient', password='password')
        self.assertTrue(login, 'Could not log in')

        # Request a page that requires a login
        response = self.client.get('/login_protected_view/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'testclient')

    def test_view_with_force_login(self):
        "Request a page that is protected with @login_required"
        # Get the page without logging in. Should result in 302.
        response = self.client.get('/login_protected_view/')
        self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')

        # Log in
        self.client.force_login(self.u1)

        # Request a page that requires a login
        response = self.client.get('/login_protected_view/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'testclient')

    def test_view_with_method_login(self):
        "Request a page that is protected with a @login_required method"

        # Get the page without logging in. Should result in 302.
        response = self.client.get('/login_protected_method_view/')
        self.assertRedirects(response, '/accounts/login/?next=/login_protected_method_view/')

        # Log in
        login = self.client.login(username='testclient', password='password')
        self.assertTrue(login, 'Could not log in')

        # Request a page that requires a login
        response = self.client.get('/login_protected_method_view/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'testclient')

    def test_view_with_method_force_login(self):
        "Request a page that is protected with a @login_required method"
        # Get the page without logging in. Should result in 302.
        response = self.client.get('/login_protected_method_view/')
        self.assertRedirects(response, '/accounts/login/?next=/login_protected_method_view/')

        # Log in
        self.client.force_login(self.u1)

        # Request a page that requires a login
        response = self.client.get('/login_protected_method_view/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'testclient')

    def test_view_with_login_and_custom_redirect(self):
        "Request a page that is protected with @login_required(redirect_field_name='redirect_to')"

        # Get the page without logging in. Should result in 302.
        response = self.client.get('/login_protected_view_custom_redirect/')
        self.assertRedirects(response, '/accounts/login/?redirect_to=/login_protected_view_custom_redirect/')

        # Log in
        login = self.client.login(username='testclient', password='password')
        self.assertTrue(login, 'Could not log in')

        # Request a page that requires a login
        response = self.client.get('/login_protected_view_custom_redirect/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'testclient')

    def test_view_with_force_login_and_custom_redirect(self):
        """
        Request a page that is protected with
        @login_required(redirect_field_name='redirect_to')
        """
        # Get the page without logging in. Should result in 302.
        response = self.client.get('/login_protected_view_custom_redirect/')
        self.assertRedirects(response, '/accounts/login/?redirect_to=/login_protected_view_custom_redirect/')

        # Log in
        self.client.force_login(self.u1)

        # Request a page that requires a login
        response = self.client.get('/login_protected_view_custom_redirect/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'testclient')

    def test_view_with_bad_login(self):
        "Request a page that is protected with @login, but use bad credentials"

        login = self.client.login(username='otheruser', password='nopassword')
        self.assertFalse(login)

    def test_view_with_inactive_login(self):
        "Request a page that is protected with @login, but use an inactive login"

        login = self.client.login(username='inactive', password='password')
        self.assertFalse(login)

    def test_view_with_inactive_force_login(self):
        "Request a page that is protected with @login, but use an inactive login"

        # Get the page without logging in. Should result in 302.
        response = self.client.get('/login_protected_view/')
        self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')

        # Log in
        self.client.force_login(self.u2)

        # Request a page that requires a login
        response = self.client.get('/login_protected_view/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'inactive')

    def test_logout(self):
        "Request a logout after logging in"
        # Log in
        self.client.login(username='testclient', password='password')

        # Request a page that requires a login
        response = self.client.get('/login_protected_view/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'testclient')

        # Log out
        self.client.logout()

        # Request a page that requires a login
        response = self.client.get('/login_protected_view/')
        self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')

    def test_logout_with_force_login(self):
        "Request a logout after logging in"
        # Log in
        self.client.force_login(self.u1)

        # Request a page that requires a login
        response = self.client.get('/login_protected_view/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'testclient')

        # Log out
        self.client.logout()

        # Request a page that requires a login
        response = self.client.get('/login_protected_view/')
        self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')

    @override_settings(
        AUTHENTICATION_BACKENDS=[
            'django.contrib.auth.backends.ModelBackend',
            'test_client.auth_backends.TestClientBackend',
        ],
    )
    def test_force_login_with_backend(self):
        """
        Request a page that is protected with @login_required when using
        force_login() and passing a backend.
        """
        # Get the page without logging in. Should result in 302.
        response = self.client.get('/login_protected_view/')
        self.assertRedirects(response, '/accounts/login/?next=/login_protected_view/')

        # Log in
        self.client.force_login(self.u1, backend='test_client.auth_backends.TestClientBackend')
        self.assertEqual(self.u1.backend, 'test_client.auth_backends.TestClientBackend')

        # Request a page that requires a login
        response = self.client.get('/login_protected_view/')
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response.context['user'].username, 'testclient')

    @override_settings(SESSION_ENGINE="django.contrib.sessions.backends.signed_cookies")
    def test_logout_cookie_sessions(self):
        self.test_logout()

    def test_view_with_permissions(self):
        "Request a page that is protected with @permission_required"

        # Get the page without logging in. Should result in 302.
        response = self.client.get('/permission_protected_view/')
        self.assertRedirects(response, '/accounts/login/?next=/permission_protected_view/')

        # Log in
        login = self.client.login(username='testclient', password='password')
        self.assertTrue(login, 'Could not log in')

        # Log in with wrong permissions. Should result in 302.
        response = self.client.get('/permission_protected_view/')
        self.assertRedirects(response, '/accounts/login/?next=/permission_protected_view/')

        # TODO: Log in with right permissions and request the page again

    def test_view_with_permissions_exception(self):
        "Request a page that is protected with @permission_required but raises an exception"

        # Get the page without logging in. Should result in 403.
        response = self.client.get('/permission_protected_view_exception/')
        self.assertEqual(response.status_code, 403)

        # Log in
        login = self.client.login(username='testclient', password='password')
        self.assertTrue(login, 'Could not log in')

        # Log in with wrong permissions. Should result in 403.
        response = self.client.get('/permission_protected_view_exception/')
        self.assertEqual(response.status_code, 403)

    def test_view_with_method_permissions(self):
        "Request a page that is protected with a @permission_required method"

        # Get the page without logging in. Should result in 302.
        response = self.client.get('/permission_protected_method_view/')
        self.assertRedirects(response, '/accounts/login/?next=/permission_protected_method_view/')

        # Log in
        login = self.client.login(username='testclient', password='password')
        self.assertTrue(login, 'Could not log in')

        # Log in with wrong permissions. Should result in 302.
        response = self.client.get('/permission_protected_method_view/')
        self.assertRedirects(response, '/accounts/login/?next=/permission_protected_method_view/')

        # TODO: Log in with right permissions and request the page again

    def test_external_redirect(self):
        response = self.client.get('/django_project_redirect/')
        self.assertRedirects(response, 'https://www.djangoproject.com/', fetch_redirect_response=False)

    def test_session_modifying_view(self):
        "Request a page that modifies the session"
        # Session value isn't set initially
        try:
            self.client.session['tobacconist']
            self.fail("Shouldn't have a session value")
        except KeyError:
            pass

        self.client.post('/session_view/')

        # Check that the session was modified
        self.assertEqual(self.client.session['tobacconist'], 'hovercraft')

    def test_view_with_exception(self):
        "Request a page that is known to throw an error"
        self.assertRaises(KeyError, self.client.get, "/broken_view/")

        # Try the same assertion, a different way
        try:
            self.client.get('/broken_view/')
            self.fail('Should raise an error')
        except KeyError:
            pass

    def test_mail_sending(self):
        "Test that mail is redirected to a dummy outbox during test setup"

        response = self.client.get('/mail_sending_view/')
        self.assertEqual(response.status_code, 200)

        self.assertEqual(len(mail.outbox), 1)
        self.assertEqual(mail.outbox[0].subject, 'Test message')
        self.assertEqual(mail.outbox[0].body, 'This is a test email')
        self.assertEqual(mail.outbox[0].from_email, 'from@example.com')
        self.assertEqual(mail.outbox[0].to[0], 'first@example.com')
        self.assertEqual(mail.outbox[0].to[1], 'second@example.com')

    def test_reverse_lazy_decodes(self):
        "Ensure reverse_lazy works in the test client"
        data = {'var': 'data'}
        response = self.client.get(reverse_lazy('get_view'), data)

        # Check some response details
        self.assertContains(response, 'This is a test')

    def test_mass_mail_sending(self):
        "Test that mass mail is redirected to a dummy outbox during test setup"

        response = self.client.get('/mass_mail_sending_view/')
        self.assertEqual(response.status_code, 200)

        self.assertEqual(len(mail.outbox), 2)
        self.assertEqual(mail.outbox[0].subject, 'First Test message')
        self.assertEqual(mail.outbox[0].body, 'This is the first test email')
        self.assertEqual(mail.outbox[0].from_email, 'from@example.com')
        self.assertEqual(mail.outbox[0].to[0], 'first@example.com')
        self.assertEqual(mail.outbox[0].to[1], 'second@example.com')

        self.assertEqual(mail.outbox[1].subject, 'Second Test message')
        self.assertEqual(mail.outbox[1].body, 'This is the second test email')
        self.assertEqual(mail.outbox[1].from_email, 'from@example.com')
        self.assertEqual(mail.outbox[1].to[0], 'second@example.com')
        self.assertEqual(mail.outbox[1].to[1], 'third@example.com')

    def test_exception_following_nested_client_request(self):
        """
        A nested test client request shouldn't clobber exception signals from
        the outer client request.
        """
        with self.assertRaisesMessage(Exception, 'exception message'):
            self.client.get('/nesting_exception_view/')


@override_settings(
    MIDDLEWARE_CLASSES=['django.middleware.csrf.CsrfViewMiddleware'],
    ROOT_URLCONF='test_client.urls',
)
class CSRFEnabledClientTests(SimpleTestCase):

    def test_csrf_enabled_client(self):
        "A client can be instantiated with CSRF checks enabled"
        csrf_client = Client(enforce_csrf_checks=True)

        # The normal client allows the post
        response = self.client.post('/post_view/', {})
        self.assertEqual(response.status_code, 200)

        # The CSRF-enabled client rejects it
        response = csrf_client.post('/post_view/', {})
        self.assertEqual(response.status_code, 403)


class CustomTestClient(Client):
    i_am_customized = "Yes"


class CustomTestClientTest(SimpleTestCase):
    client_class = CustomTestClient

    def test_custom_test_client(self):
        """A test case can specify a custom class for self.client."""
        self.assertEqual(hasattr(self.client, "i_am_customized"), True)


_generic_view = lambda request: HttpResponse(status=200)


@override_settings(ROOT_URLCONF='test_client.urls')
class RequestFactoryTest(SimpleTestCase):
    """Tests for the request factory."""

    # A mapping between names of HTTP/1.1 methods and their test views.
    http_methods_and_views = (
        ('get', get_view),
        ('post', post_view),
        ('put', _generic_view),
        ('patch', _generic_view),
        ('delete', _generic_view),
        ('head', _generic_view),
        ('options', _generic_view),
        ('trace', trace_view),
    )

    def setUp(self):
        self.request_factory = RequestFactory()

    def test_request_factory(self):
        """The request factory implements all the HTTP/1.1 methods."""
        for method_name, view in self.http_methods_and_views:
            method = getattr(self.request_factory, method_name)
            request = method('/somewhere/')
            response = view(request)

            self.assertEqual(response.status_code, 200)

    def test_get_request_from_factory(self):
        """
        The request factory returns a templated response for a GET request.
        """
        request = self.request_factory.get('/somewhere/')
        response = get_view(request)

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'This is a test')

    def test_trace_request_from_factory(self):
        """The request factory returns an echo response for a TRACE request."""
        url_path = '/somewhere/'
        request = self.request_factory.trace(url_path)
        response = trace_view(request)
        protocol = request.META["SERVER_PROTOCOL"]
        echoed_request_line = "TRACE {} {}".format(url_path, protocol)

        self.assertEqual(response.status_code, 200)
        self.assertContains(response, echoed_request_line)