summaryrefslogtreecommitdiff
path: root/tests/view_tests/tests/test_debug.py
blob: a0da6e1adc3ee920d489c63c0537753d7611ef34 (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
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
import importlib
import inspect
import os
import re
import sys
import tempfile
import threading
from io import StringIO
from pathlib import Path
from unittest import mock

from django.core import mail
from django.core.files.uploadedfile import SimpleUploadedFile
from django.db import DatabaseError, connection
from django.http import Http404
from django.shortcuts import render
from django.template import TemplateDoesNotExist
from django.test import RequestFactory, SimpleTestCase, override_settings
from django.test.utils import LoggingCaptureMixin
from django.urls import path, reverse
from django.urls.converters import IntConverter
from django.utils.functional import SimpleLazyObject
from django.utils.regex_helper import _lazy_re_compile
from django.utils.safestring import mark_safe
from django.views.debug import (
    CallableSettingWrapper, ExceptionCycleWarning, ExceptionReporter,
    Path as DebugPath, SafeExceptionReporterFilter, default_urlconf,
    get_default_exception_reporter_filter, technical_404_response,
    technical_500_response,
)
from django.views.decorators.debug import (
    sensitive_post_parameters, sensitive_variables,
)

from ..views import (
    custom_exception_reporter_filter_view, index_page,
    multivalue_dict_key_error, non_sensitive_view, paranoid_view,
    sensitive_args_function_caller, sensitive_kwargs_function_caller,
    sensitive_method_view, sensitive_view,
)


class User:
    def __str__(self):
        return 'jacob'


class WithoutEmptyPathUrls:
    urlpatterns = [path('url/', index_page, name='url')]


class CallableSettingWrapperTests(SimpleTestCase):
    """ Unittests for CallableSettingWrapper
    """
    def test_repr(self):
        class WrappedCallable:
            def __repr__(self):
                return "repr from the wrapped callable"

            def __call__(self):
                pass

        actual = repr(CallableSettingWrapper(WrappedCallable()))
        self.assertEqual(actual, "repr from the wrapped callable")


@override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls')
class DebugViewTests(SimpleTestCase):

    def test_files(self):
        with self.assertLogs('django.request', 'ERROR'):
            response = self.client.get('/raises/')
        self.assertEqual(response.status_code, 500)

        data = {
            'file_data.txt': SimpleUploadedFile('file_data.txt', b'haha'),
        }
        with self.assertLogs('django.request', 'ERROR'):
            response = self.client.post('/raises/', data)
        self.assertContains(response, 'file_data.txt', status_code=500)
        self.assertNotContains(response, 'haha', status_code=500)

    def test_400(self):
        # When DEBUG=True, technical_500_template() is called.
        with self.assertLogs('django.security', 'WARNING'):
            response = self.client.get('/raises400/')
        self.assertContains(response, '<div class="context" id="', status_code=400)

    def test_400_bad_request(self):
        # When DEBUG=True, technical_500_template() is called.
        with self.assertLogs('django.request', 'WARNING') as cm:
            response = self.client.get('/raises400_bad_request/')
        self.assertContains(response, '<div class="context" id="', status_code=400)
        self.assertEqual(
            cm.records[0].getMessage(),
            'Malformed request syntax: /raises400_bad_request/',
        )

    # Ensure no 403.html template exists to test the default case.
    @override_settings(TEMPLATES=[{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
    }])
    def test_403(self):
        response = self.client.get('/raises403/')
        self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403)

    # Set up a test 403.html template.
    @override_settings(TEMPLATES=[{
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'OPTIONS': {
            'loaders': [
                ('django.template.loaders.locmem.Loader', {
                    '403.html': 'This is a test template for a 403 error ({{ exception }}).',
                }),
            ],
        },
    }])
    def test_403_template(self):
        response = self.client.get('/raises403/')
        self.assertContains(response, 'test template', status_code=403)
        self.assertContains(response, '(Insufficient Permissions).', status_code=403)

    def test_404(self):
        response = self.client.get('/raises404/')
        self.assertContains(
            response,
            '<p>The current path, <code>not-in-urls</code>, didn’t match any '
            'of these.</p>',
            status_code=404,
            html=True,
        )

    def test_404_not_in_urls(self):
        response = self.client.get('/not-in-urls')
        self.assertNotContains(response, "Raised by:", status_code=404)
        self.assertContains(response, "Django tried these URL patterns", status_code=404)
        self.assertContains(
            response,
            '<p>The current path, <code>not-in-urls</code>, didn’t match any '
            'of these.</p>',
            status_code=404,
            html=True,
        )
        # Pattern and view name of a RegexURLPattern appear.
        self.assertContains(response, r"^regex-post/(?P&lt;pk&gt;[0-9]+)/$", status_code=404)
        self.assertContains(response, "[name='regex-post']", status_code=404)
        # Pattern and view name of a RoutePattern appear.
        self.assertContains(response, r"path-post/&lt;int:pk&gt;/", status_code=404)
        self.assertContains(response, "[name='path-post']", status_code=404)

    @override_settings(ROOT_URLCONF=WithoutEmptyPathUrls)
    def test_404_empty_path_not_in_urls(self):
        response = self.client.get('/')
        self.assertContains(
            response,
            '<p>The empty path didn’t match any of these.</p>',
            status_code=404,
            html=True,
        )

    def test_technical_404(self):
        response = self.client.get('/technical404/')
        self.assertContains(response, "Raised by:", status_code=404)
        self.assertContains(response, "view_tests.views.technical404", status_code=404)
        self.assertContains(
            response,
            '<p>The current path, <code>technical404/</code>, matched the '
            'last one.</p>',
            status_code=404,
            html=True,
        )

    def test_classbased_technical_404(self):
        response = self.client.get('/classbased404/')
        self.assertContains(response, "Raised by:", status_code=404)
        self.assertContains(response, "view_tests.views.Http404View", status_code=404)

    def test_non_l10ned_numeric_ids(self):
        """
        Numeric IDs and fancy traceback context blocks line numbers shouldn't be localized.
        """
        with self.settings(DEBUG=True, USE_L10N=True):
            with self.assertLogs('django.request', 'ERROR'):
                response = self.client.get('/raises500/')
            # We look for a HTML fragment of the form
            # '<div class="context" id="c38123208">', not '<div class="context" id="c38,123,208"'
            self.assertContains(response, '<div class="context" id="', status_code=500)
            match = re.search(b'<div class="context" id="(?P<id>[^"]+)">', response.content)
            self.assertIsNotNone(match)
            id_repr = match['id']
            self.assertFalse(
                re.search(b'[^c0-9]', id_repr),
                "Numeric IDs in debug response HTML page shouldn't be localized (value: %s)." % id_repr.decode()
            )

    def test_template_exceptions(self):
        with self.assertLogs('django.request', 'ERROR'):
            try:
                self.client.get(reverse('template_exception'))
            except Exception:
                raising_loc = inspect.trace()[-1][-2][0].strip()
                self.assertNotEqual(
                    raising_loc.find("raise Exception('boom')"), -1,
                    "Failed to find 'raise Exception' in last frame of "
                    "traceback, instead found: %s" % raising_loc
                )

    def test_template_loader_postmortem(self):
        """Tests for not existing file"""
        template_name = "notfound.html"
        with tempfile.NamedTemporaryFile(prefix=template_name) as tmpfile:
            tempdir = os.path.dirname(tmpfile.name)
            template_path = os.path.join(tempdir, template_name)
            with override_settings(TEMPLATES=[{
                'BACKEND': 'django.template.backends.django.DjangoTemplates',
                'DIRS': [tempdir],
            }]), self.assertLogs('django.request', 'ERROR'):
                response = self.client.get(reverse('raises_template_does_not_exist', kwargs={"path": template_name}))
            self.assertContains(response, "%s (Source does not exist)" % template_path, status_code=500, count=2)
            # Assert as HTML.
            self.assertContains(
                response,
                '<li><code>django.template.loaders.filesystem.Loader</code>: '
                '%s (Source does not exist)</li>' % os.path.join(tempdir, 'notfound.html'),
                status_code=500,
                html=True,
            )

    def test_no_template_source_loaders(self):
        """
        Make sure if you don't specify a template, the debug view doesn't blow up.
        """
        with self.assertLogs('django.request', 'ERROR'):
            with self.assertRaises(TemplateDoesNotExist):
                self.client.get('/render_no_template/')

    @override_settings(ROOT_URLCONF='view_tests.default_urls')
    def test_default_urlconf_template(self):
        """
        Make sure that the default URLconf template is shown instead of the
        technical 404 page, if the user has not altered their URLconf yet.
        """
        response = self.client.get('/')
        self.assertContains(
            response,
            "<h2>The install worked successfully! Congratulations!</h2>"
        )

    @override_settings(ROOT_URLCONF='view_tests.regression_21530_urls')
    def test_regression_21530(self):
        """
        Regression test for bug #21530.

        If the admin app include is replaced with exactly one url
        pattern, then the technical 404 template should be displayed.

        The bug here was that an AttributeError caused a 500 response.
        """
        response = self.client.get('/')
        self.assertContains(
            response,
            "Page not found <span>(404)</span>",
            status_code=404
        )

    def test_template_encoding(self):
        """
        The templates are loaded directly, not via a template loader, and
        should be opened as utf-8 charset as is the default specified on
        template engines.
        """
        with mock.patch.object(DebugPath, 'open') as m:
            default_urlconf(None)
            m.assert_called_once_with(encoding='utf-8')
            m.reset_mock()
            technical_404_response(mock.MagicMock(), mock.Mock())
            m.assert_called_once_with(encoding='utf-8')

    def test_technical_404_converter_raise_404(self):
        with mock.patch.object(IntConverter, 'to_python', side_effect=Http404):
            response = self.client.get('/path-post/1/')
            self.assertContains(response, 'Page not found', status_code=404)

    def test_exception_reporter_from_request(self):
        with self.assertLogs('django.request', 'ERROR'):
            response = self.client.get('/custom_reporter_class_view/')
        self.assertContains(response, 'custom traceback text', status_code=500)

    @override_settings(DEFAULT_EXCEPTION_REPORTER='view_tests.views.CustomExceptionReporter')
    def test_exception_reporter_from_settings(self):
        with self.assertLogs('django.request', 'ERROR'):
            response = self.client.get('/raises500/')
        self.assertContains(response, 'custom traceback text', status_code=500)

    @override_settings(DEFAULT_EXCEPTION_REPORTER='view_tests.views.TemplateOverrideExceptionReporter')
    def test_template_override_exception_reporter(self):
        with self.assertLogs('django.request', 'ERROR'):
            response = self.client.get('/raises500/')
        self.assertContains(
            response,
            '<h1>Oh no, an error occurred!</h1>',
            status_code=500,
            html=True,
        )

        with self.assertLogs('django.request', 'ERROR'):
            response = self.client.get('/raises500/', HTTP_ACCEPT='text/plain')
        self.assertContains(response, 'Oh dear, an error occurred!', status_code=500)


class DebugViewQueriesAllowedTests(SimpleTestCase):
    # May need a query to initialize MySQL connection
    databases = {'default'}

    def test_handle_db_exception(self):
        """
        Ensure the debug view works when a database exception is raised by
        performing an invalid query and passing the exception to the debug view.
        """
        with connection.cursor() as cursor:
            try:
                cursor.execute('INVALID SQL')
            except DatabaseError:
                exc_info = sys.exc_info()

        rf = RequestFactory()
        response = technical_500_response(rf.get('/'), *exc_info)
        self.assertContains(response, 'OperationalError at /', status_code=500)


@override_settings(
    DEBUG=True,
    ROOT_URLCONF='view_tests.urls',
    # No template directories are configured, so no templates will be found.
    TEMPLATES=[{
        'BACKEND': 'django.template.backends.dummy.TemplateStrings',
    }],
)
class NonDjangoTemplatesDebugViewTests(SimpleTestCase):

    def test_400(self):
        # When DEBUG=True, technical_500_template() is called.
        with self.assertLogs('django.security', 'WARNING'):
            response = self.client.get('/raises400/')
        self.assertContains(response, '<div class="context" id="', status_code=400)

    def test_400_bad_request(self):
        # When DEBUG=True, technical_500_template() is called.
        with self.assertLogs('django.request', 'WARNING') as cm:
            response = self.client.get('/raises400_bad_request/')
        self.assertContains(response, '<div class="context" id="', status_code=400)
        self.assertEqual(
            cm.records[0].getMessage(),
            'Malformed request syntax: /raises400_bad_request/',
        )

    def test_403(self):
        response = self.client.get('/raises403/')
        self.assertContains(response, '<h1>403 Forbidden</h1>', status_code=403)

    def test_404(self):
        response = self.client.get('/raises404/')
        self.assertEqual(response.status_code, 404)

    def test_template_not_found_error(self):
        # Raises a TemplateDoesNotExist exception and shows the debug view.
        url = reverse('raises_template_does_not_exist', kwargs={"path": "notfound.html"})
        with self.assertLogs('django.request', 'ERROR'):
            response = self.client.get(url)
        self.assertContains(response, '<div class="context" id="', status_code=500)


class ExceptionReporterTests(SimpleTestCase):
    rf = RequestFactory()

    def test_request_and_exception(self):
        "A simple exception report can be generated"
        try:
            request = self.rf.get('/test_view/')
            request.user = User()
            raise ValueError("Can't find my keys")
        except ValueError:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>ValueError at /test_view/</h1>', html)
        self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html)
        self.assertIn('<th>Request Method:</th>', html)
        self.assertIn('<th>Request URL:</th>', html)
        self.assertIn('<h3 id="user-info">USER</h3>', html)
        self.assertIn('<p>jacob</p>', html)
        self.assertIn('<th>Exception Type:</th>', html)
        self.assertIn('<th>Exception Value:</th>', html)
        self.assertIn('<h2>Traceback ', html)
        self.assertIn('<h2>Request information</h2>', html)
        self.assertNotIn('<p>Request data not supplied</p>', html)
        self.assertIn('<p>No POST data</p>', html)

    def test_no_request(self):
        "An exception report can be generated without request"
        try:
            raise ValueError("Can't find my keys")
        except ValueError:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>ValueError</h1>', html)
        self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html)
        self.assertNotIn('<th>Request Method:</th>', html)
        self.assertNotIn('<th>Request URL:</th>', html)
        self.assertNotIn('<h3 id="user-info">USER</h3>', html)
        self.assertIn('<th>Exception Type:</th>', html)
        self.assertIn('<th>Exception Value:</th>', html)
        self.assertIn('<h2>Traceback ', html)
        self.assertIn('<h2>Request information</h2>', html)
        self.assertIn('<p>Request data not supplied</p>', html)

    def test_sharing_traceback(self):
        try:
            raise ValueError('Oops')
        except ValueError:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertIn(
            '<form action="https://dpaste.com/" name="pasteform" '
            'id="pasteform" method="post">',
            html,
        )

    def test_eol_support(self):
        """The ExceptionReporter supports Unix, Windows and Macintosh EOL markers"""
        LINES = ['print %d' % i for i in range(1, 6)]
        reporter = ExceptionReporter(None, None, None, None)

        for newline in ['\n', '\r\n', '\r']:
            fd, filename = tempfile.mkstemp(text=False)
            os.write(fd, (newline.join(LINES) + newline).encode())
            os.close(fd)

            try:
                self.assertEqual(
                    reporter._get_lines_from_file(filename, 3, 2),
                    (1, LINES[1:3], LINES[3], LINES[4:])
                )
            finally:
                os.unlink(filename)

    def test_no_exception(self):
        "An exception report can be generated for just a request"
        request = self.rf.get('/test_view/')
        reporter = ExceptionReporter(request, None, None, None)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>Report at /test_view/</h1>', html)
        self.assertIn('<pre class="exception_value">No exception message supplied</pre>', html)
        self.assertIn('<th>Request Method:</th>', html)
        self.assertIn('<th>Request URL:</th>', html)
        self.assertNotIn('<th>Exception Type:</th>', html)
        self.assertNotIn('<th>Exception Value:</th>', html)
        self.assertNotIn('<h2>Traceback ', html)
        self.assertIn('<h2>Request information</h2>', html)
        self.assertNotIn('<p>Request data not supplied</p>', html)

    def test_suppressed_context(self):
        try:
            try:
                raise RuntimeError("Can't find my keys")
            except RuntimeError:
                raise ValueError("Can't find my keys") from None
        except ValueError:
            exc_type, exc_value, tb = sys.exc_info()

        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>ValueError</h1>', html)
        self.assertIn('<pre class="exception_value">Can&#x27;t find my keys</pre>', html)
        self.assertIn('<th>Exception Type:</th>', html)
        self.assertIn('<th>Exception Value:</th>', html)
        self.assertIn('<h2>Traceback ', html)
        self.assertIn('<h2>Request information</h2>', html)
        self.assertIn('<p>Request data not supplied</p>', html)
        self.assertNotIn('During handling of the above exception', html)

    def test_innermost_exception_without_traceback(self):
        try:
            try:
                raise RuntimeError('Oops')
            except Exception as exc:
                new_exc = RuntimeError('My context')
                exc.__context__ = new_exc
                raise
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()

        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        frames = reporter.get_traceback_frames()
        self.assertEqual(len(frames), 2)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>RuntimeError</h1>', html)
        self.assertIn('<pre class="exception_value">Oops</pre>', html)
        self.assertIn('<th>Exception Type:</th>', html)
        self.assertIn('<th>Exception Value:</th>', html)
        self.assertIn('<h2>Traceback ', html)
        self.assertIn('<h2>Request information</h2>', html)
        self.assertIn('<p>Request data not supplied</p>', html)
        self.assertIn(
            'During handling of the above exception (My context), another '
            'exception occurred',
            html,
        )
        self.assertInHTML('<li class="frame user">None</li>', html)
        self.assertIn('Traceback (most recent call last):\n  None', html)

        text = reporter.get_traceback_text()
        self.assertIn('Exception Type: RuntimeError', text)
        self.assertIn('Exception Value: Oops', text)
        self.assertIn('Traceback (most recent call last):\n  None', text)
        self.assertIn(
            'During handling of the above exception (My context), another '
            'exception occurred',
            text,
        )

    def test_mid_stack_exception_without_traceback(self):
        try:
            try:
                raise RuntimeError('Inner Oops')
            except Exception as exc:
                new_exc = RuntimeError('My context')
                new_exc.__context__ = exc
                raise RuntimeError('Oops') from new_exc
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>RuntimeError</h1>', html)
        self.assertIn('<pre class="exception_value">Oops</pre>', html)
        self.assertIn('<th>Exception Type:</th>', html)
        self.assertIn('<th>Exception Value:</th>', html)
        self.assertIn('<h2>Traceback ', html)
        self.assertInHTML('<li class="frame user">Traceback: None</li>', html)
        self.assertIn(
            'During handling of the above exception (Inner Oops), another '
            'exception occurred:\n  Traceback: None',
            html,
        )

        text = reporter.get_traceback_text()
        self.assertIn('Exception Type: RuntimeError', text)
        self.assertIn('Exception Value: Oops', text)
        self.assertIn('Traceback (most recent call last):', text)
        self.assertIn(
            'During handling of the above exception (Inner Oops), another '
            'exception occurred:\n  Traceback: None',
            text,
        )

    def test_reporting_of_nested_exceptions(self):
        request = self.rf.get('/test_view/')
        try:
            try:
                raise AttributeError(mark_safe('<p>Top level</p>'))
            except AttributeError as explicit:
                try:
                    raise ValueError(mark_safe('<p>Second exception</p>')) from explicit
                except ValueError:
                    raise IndexError(mark_safe('<p>Final exception</p>'))
        except Exception:
            # Custom exception handler, just pass it into ExceptionReporter
            exc_type, exc_value, tb = sys.exc_info()

        explicit_exc = 'The above exception ({0}) was the direct cause of the following exception:'
        implicit_exc = 'During handling of the above exception ({0}), another exception occurred:'

        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        # Both messages are twice on page -- one rendered as html,
        # one as plain text (for pastebin)
        self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;')))
        self.assertEqual(2, html.count(implicit_exc.format('&lt;p&gt;Second exception&lt;/p&gt;')))
        self.assertEqual(10, html.count('&lt;p&gt;Final exception&lt;/p&gt;'))

        text = reporter.get_traceback_text()
        self.assertIn(explicit_exc.format('<p>Top level</p>'), text)
        self.assertIn(implicit_exc.format('<p>Second exception</p>'), text)
        self.assertEqual(3, text.count('<p>Final exception</p>'))

    def test_reporting_frames_without_source(self):
        try:
            source = "def funcName():\n    raise Error('Whoops')\nfuncName()"
            namespace = {}
            code = compile(source, 'generated', 'exec')
            exec(code, namespace)
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        request = self.rf.get('/test_view/')
        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        frames = reporter.get_traceback_frames()
        last_frame = frames[-1]
        self.assertEqual(last_frame['context_line'], '<source code not available>')
        self.assertEqual(last_frame['filename'], 'generated')
        self.assertEqual(last_frame['function'], 'funcName')
        self.assertEqual(last_frame['lineno'], 2)
        html = reporter.get_traceback_html()
        self.assertIn(
            '<span class="fname">generated</span>, line 2, in funcName',
            html,
        )
        self.assertIn(
            '<code class="fname">generated</code>, line 2, in funcName',
            html,
        )
        self.assertIn(
            '"generated", line 2, in funcName\n'
            '    &lt;source code not available&gt;',
            html,
        )
        text = reporter.get_traceback_text()
        self.assertIn(
            '"generated", line 2, in funcName\n'
            '    <source code not available>',
            text,
        )

    def test_reporting_frames_source_not_match(self):
        try:
            source = "def funcName():\n    raise Error('Whoops')\nfuncName()"
            namespace = {}
            code = compile(source, 'generated', 'exec')
            exec(code, namespace)
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        with mock.patch(
            'django.views.debug.ExceptionReporter._get_source',
            return_value=['wrong source'],
        ):
            request = self.rf.get('/test_view/')
            reporter = ExceptionReporter(request, exc_type, exc_value, tb)
            frames = reporter.get_traceback_frames()
            last_frame = frames[-1]
            self.assertEqual(last_frame['context_line'], '<source code not available>')
            self.assertEqual(last_frame['filename'], 'generated')
            self.assertEqual(last_frame['function'], 'funcName')
            self.assertEqual(last_frame['lineno'], 2)
            html = reporter.get_traceback_html()
            self.assertIn(
                '<span class="fname">generated</span>, line 2, in funcName',
                html,
            )
            self.assertIn(
                '<code class="fname">generated</code>, line 2, in funcName',
                html,
            )
            self.assertIn(
                '"generated", line 2, in funcName\n'
                '    &lt;source code not available&gt;',
                html,
            )
            text = reporter.get_traceback_text()
            self.assertIn(
                '"generated", line 2, in funcName\n'
                '    <source code not available>',
                text,
            )

    def test_reporting_frames_for_cyclic_reference(self):
        try:
            def test_func():
                try:
                    raise RuntimeError('outer') from RuntimeError('inner')
                except RuntimeError as exc:
                    raise exc.__cause__
            test_func()
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        request = self.rf.get('/test_view/')
        reporter = ExceptionReporter(request, exc_type, exc_value, tb)

        def generate_traceback_frames(*args, **kwargs):
            nonlocal tb_frames
            tb_frames = reporter.get_traceback_frames()

        tb_frames = None
        tb_generator = threading.Thread(target=generate_traceback_frames, daemon=True)
        msg = (
            "Cycle in the exception chain detected: exception 'inner' "
            "encountered again."
        )
        with self.assertWarnsMessage(ExceptionCycleWarning, msg):
            tb_generator.start()
        tb_generator.join(timeout=5)
        if tb_generator.is_alive():
            # tb_generator is a daemon that runs until the main thread/process
            # exits. This is resource heavy when running the full test suite.
            # Setting the following values to None makes
            # reporter.get_traceback_frames() exit early.
            exc_value.__traceback__ = exc_value.__context__ = exc_value.__cause__ = None
            tb_generator.join()
            self.fail('Cyclic reference in Exception Reporter.get_traceback_frames()')
        if tb_frames is None:
            # can happen if the thread generating traceback got killed
            # or exception while generating the traceback
            self.fail('Traceback generation failed')
        last_frame = tb_frames[-1]
        self.assertIn('raise exc.__cause__', last_frame['context_line'])
        self.assertEqual(last_frame['filename'], __file__)
        self.assertEqual(last_frame['function'], 'test_func')

    def test_request_and_message(self):
        "A message can be provided in addition to a request"
        request = self.rf.get('/test_view/')
        reporter = ExceptionReporter(request, None, "I'm a little teapot", None)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>Report at /test_view/</h1>', html)
        self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html)
        self.assertIn('<th>Request Method:</th>', html)
        self.assertIn('<th>Request URL:</th>', html)
        self.assertNotIn('<th>Exception Type:</th>', html)
        self.assertNotIn('<th>Exception Value:</th>', html)
        self.assertIn('<h2>Traceback ', html)
        self.assertIn('<h2>Request information</h2>', html)
        self.assertNotIn('<p>Request data not supplied</p>', html)

    def test_message_only(self):
        reporter = ExceptionReporter(None, None, "I'm a little teapot", None)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>Report</h1>', html)
        self.assertIn('<pre class="exception_value">I&#x27;m a little teapot</pre>', html)
        self.assertNotIn('<th>Request Method:</th>', html)
        self.assertNotIn('<th>Request URL:</th>', html)
        self.assertNotIn('<th>Exception Type:</th>', html)
        self.assertNotIn('<th>Exception Value:</th>', html)
        self.assertIn('<h2>Traceback ', html)
        self.assertIn('<h2>Request information</h2>', html)
        self.assertIn('<p>Request data not supplied</p>', html)

    def test_non_utf8_values_handling(self):
        "Non-UTF-8 exceptions/values should not make the output generation choke."
        try:
            class NonUtf8Output(Exception):
                def __repr__(self):
                    return b'EXC\xe9EXC'
            somevar = b'VAL\xe9VAL'  # NOQA
            raise NonUtf8Output()
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertIn('VAL\\xe9VAL', html)
        self.assertIn('EXC\\xe9EXC', html)

    def test_local_variable_escaping(self):
        """Safe strings in local variables are escaped."""
        try:
            local = mark_safe('<p>Local variable</p>')
            raise ValueError(local)
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        html = ExceptionReporter(None, exc_type, exc_value, tb).get_traceback_html()
        self.assertIn('<td class="code"><pre>&#x27;&lt;p&gt;Local variable&lt;/p&gt;&#x27;</pre></td>', html)

    def test_unprintable_values_handling(self):
        "Unprintable values should not make the output generation choke."
        try:
            class OomOutput:
                def __repr__(self):
                    raise MemoryError('OOM')
            oomvalue = OomOutput()  # NOQA
            raise ValueError()
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertIn('<td class="code"><pre>Error in formatting', html)

    def test_too_large_values_handling(self):
        "Large values should not create a large HTML."
        large = 256 * 1024
        repr_of_str_adds = len(repr(''))
        try:
            class LargeOutput:
                def __repr__(self):
                    return repr('A' * large)
            largevalue = LargeOutput()  # NOQA
            raise ValueError()
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertEqual(len(html) // 1024 // 128, 0)  # still fit in 128Kb
        self.assertIn('&lt;trimmed %d bytes string&gt;' % (large + repr_of_str_adds,), html)

    def test_encoding_error(self):
        """
        A UnicodeError displays a portion of the problematic string. HTML in
        safe strings is escaped.
        """
        try:
            mark_safe('abcdefghijkl<p>mnὀp</p>qrstuwxyz').encode('ascii')
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertIn('<h2>Unicode error hint</h2>', html)
        self.assertIn('The string that could not be encoded/decoded was: ', html)
        self.assertIn('<strong>&lt;p&gt;mnὀp&lt;/p&gt;</strong>', html)

    def test_unfrozen_importlib(self):
        """
        importlib is not a frozen app, but its loader thinks it's frozen which
        results in an ImportError. Refs #21443.
        """
        try:
            request = self.rf.get('/test_view/')
            importlib.import_module('abc.def.invalid.name')
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>ModuleNotFoundError at /test_view/</h1>', html)

    def test_ignore_traceback_evaluation_exceptions(self):
        """
        Don't trip over exceptions generated by crafted objects when
        evaluating them while cleansing (#24455).
        """
        class BrokenEvaluation(Exception):
            pass

        def broken_setup():
            raise BrokenEvaluation

        request = self.rf.get('/test_view/')
        broken_lazy = SimpleLazyObject(broken_setup)
        try:
            bool(broken_lazy)
        except BrokenEvaluation:
            exc_type, exc_value, tb = sys.exc_info()

        self.assertIn(
            "BrokenEvaluation",
            ExceptionReporter(request, exc_type, exc_value, tb).get_traceback_html(),
            "Evaluation exception reason not mentioned in traceback"
        )

    @override_settings(ALLOWED_HOSTS='example.com')
    def test_disallowed_host(self):
        "An exception report can be generated even for a disallowed host."
        request = self.rf.get('/', HTTP_HOST='evil.com')
        reporter = ExceptionReporter(request, None, None, None)
        html = reporter.get_traceback_html()
        self.assertIn("http://evil.com/", html)

    def test_request_with_items_key(self):
        """
        An exception report can be generated for requests with 'items' in
        request GET, POST, FILES, or COOKIES QueryDicts.
        """
        value = '<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>'
        # GET
        request = self.rf.get('/test_view/?items=Oops')
        reporter = ExceptionReporter(request, None, None, None)
        html = reporter.get_traceback_html()
        self.assertInHTML(value, html)
        # POST
        request = self.rf.post('/test_view/', data={'items': 'Oops'})
        reporter = ExceptionReporter(request, None, None, None)
        html = reporter.get_traceback_html()
        self.assertInHTML(value, html)
        # FILES
        fp = StringIO('filecontent')
        request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp})
        reporter = ExceptionReporter(request, None, None, None)
        html = reporter.get_traceback_html()
        self.assertInHTML(
            '<td>items</td><td class="code"><pre>&lt;InMemoryUploadedFile: '
            'items (application/octet-stream)&gt;</pre></td>',
            html
        )
        # COOKIES
        rf = RequestFactory()
        rf.cookies['items'] = 'Oops'
        request = rf.get('/test_view/')
        reporter = ExceptionReporter(request, None, None, None)
        html = reporter.get_traceback_html()
        self.assertInHTML('<td>items</td><td class="code"><pre>&#x27;Oops&#x27;</pre></td>', html)

    def test_exception_fetching_user(self):
        """
        The error page can be rendered if the current user can't be retrieved
        (such as when the database is unavailable).
        """
        class ExceptionUser:
            def __str__(self):
                raise Exception()

        request = self.rf.get('/test_view/')
        request.user = ExceptionUser()

        try:
            raise ValueError('Oops')
        except ValueError:
            exc_type, exc_value, tb = sys.exc_info()

        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        self.assertInHTML('<h1>ValueError at /test_view/</h1>', html)
        self.assertIn('<pre class="exception_value">Oops</pre>', html)
        self.assertIn('<h3 id="user-info">USER</h3>', html)
        self.assertIn('<p>[unable to retrieve the current user]</p>', html)

        text = reporter.get_traceback_text()
        self.assertIn('USER: [unable to retrieve the current user]', text)

    def test_template_encoding(self):
        """
        The templates are loaded directly, not via a template loader, and
        should be opened as utf-8 charset as is the default specified on
        template engines.
        """
        reporter = ExceptionReporter(None, None, None, None)
        with mock.patch.object(DebugPath, 'open') as m:
            reporter.get_traceback_html()
            m.assert_called_once_with(encoding='utf-8')
            m.reset_mock()
            reporter.get_traceback_text()
            m.assert_called_once_with(encoding='utf-8')


class PlainTextReportTests(SimpleTestCase):
    rf = RequestFactory()

    def test_request_and_exception(self):
        "A simple exception report can be generated"
        try:
            request = self.rf.get('/test_view/')
            request.user = User()
            raise ValueError("Can't find my keys")
        except ValueError:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        text = reporter.get_traceback_text()
        self.assertIn('ValueError at /test_view/', text)
        self.assertIn("Can't find my keys", text)
        self.assertIn('Request Method:', text)
        self.assertIn('Request URL:', text)
        self.assertIn('USER: jacob', text)
        self.assertIn('Exception Type:', text)
        self.assertIn('Exception Value:', text)
        self.assertIn('Traceback (most recent call last):', text)
        self.assertIn('Request information:', text)
        self.assertNotIn('Request data not supplied', text)

    def test_no_request(self):
        "An exception report can be generated without request"
        try:
            raise ValueError("Can't find my keys")
        except ValueError:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(None, exc_type, exc_value, tb)
        text = reporter.get_traceback_text()
        self.assertIn('ValueError', text)
        self.assertIn("Can't find my keys", text)
        self.assertNotIn('Request Method:', text)
        self.assertNotIn('Request URL:', text)
        self.assertNotIn('USER:', text)
        self.assertIn('Exception Type:', text)
        self.assertIn('Exception Value:', text)
        self.assertIn('Traceback (most recent call last):', text)
        self.assertIn('Request data not supplied', text)

    def test_no_exception(self):
        "An exception report can be generated for just a request"
        request = self.rf.get('/test_view/')
        reporter = ExceptionReporter(request, None, None, None)
        reporter.get_traceback_text()

    def test_request_and_message(self):
        "A message can be provided in addition to a request"
        request = self.rf.get('/test_view/')
        reporter = ExceptionReporter(request, None, "I'm a little teapot", None)
        reporter.get_traceback_text()

    @override_settings(DEBUG=True)
    def test_template_exception(self):
        request = self.rf.get('/test_view/')
        try:
            render(request, 'debug/template_error.html')
        except Exception:
            exc_type, exc_value, tb = sys.exc_info()
        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        text = reporter.get_traceback_text()
        templ_path = Path(Path(__file__).parents[1], 'templates', 'debug', 'template_error.html')
        self.assertIn(
            'Template error:\n'
            'In template %(path)s, error at line 2\n'
            '   \'cycle\' tag requires at least two arguments\n'
            '   1 : Template with error:\n'
            '   2 :  {%% cycle %%} \n'
            '   3 : ' % {'path': templ_path},
            text
        )

    def test_request_with_items_key(self):
        """
        An exception report can be generated for requests with 'items' in
        request GET, POST, FILES, or COOKIES QueryDicts.
        """
        # GET
        request = self.rf.get('/test_view/?items=Oops')
        reporter = ExceptionReporter(request, None, None, None)
        text = reporter.get_traceback_text()
        self.assertIn("items = 'Oops'", text)
        # POST
        request = self.rf.post('/test_view/', data={'items': 'Oops'})
        reporter = ExceptionReporter(request, None, None, None)
        text = reporter.get_traceback_text()
        self.assertIn("items = 'Oops'", text)
        # FILES
        fp = StringIO('filecontent')
        request = self.rf.post('/test_view/', data={'name': 'filename', 'items': fp})
        reporter = ExceptionReporter(request, None, None, None)
        text = reporter.get_traceback_text()
        self.assertIn('items = <InMemoryUploadedFile:', text)
        # COOKIES
        rf = RequestFactory()
        rf.cookies['items'] = 'Oops'
        request = rf.get('/test_view/')
        reporter = ExceptionReporter(request, None, None, None)
        text = reporter.get_traceback_text()
        self.assertIn("items = 'Oops'", text)

    def test_message_only(self):
        reporter = ExceptionReporter(None, None, "I'm a little teapot", None)
        reporter.get_traceback_text()

    @override_settings(ALLOWED_HOSTS='example.com')
    def test_disallowed_host(self):
        "An exception report can be generated even for a disallowed host."
        request = self.rf.get('/', HTTP_HOST='evil.com')
        reporter = ExceptionReporter(request, None, None, None)
        text = reporter.get_traceback_text()
        self.assertIn("http://evil.com/", text)


class ExceptionReportTestMixin:
    # Mixin used in the ExceptionReporterFilterTests and
    # AjaxResponseExceptionReporterFilter tests below
    breakfast_data = {
        'sausage-key': 'sausage-value',
        'baked-beans-key': 'baked-beans-value',
        'hash-brown-key': 'hash-brown-value',
        'bacon-key': 'bacon-value',
    }

    def verify_unsafe_response(self, view, check_for_vars=True,
                               check_for_POST_params=True):
        """
        Asserts that potentially sensitive info are displayed in the response.
        """
        request = self.rf.post('/some_url/', self.breakfast_data)
        response = view(request)
        if check_for_vars:
            # All variables are shown.
            self.assertContains(response, 'cooked_eggs', status_code=500)
            self.assertContains(response, 'scrambled', status_code=500)
            self.assertContains(response, 'sauce', status_code=500)
            self.assertContains(response, 'worcestershire', status_code=500)
        if check_for_POST_params:
            for k, v in self.breakfast_data.items():
                # All POST parameters are shown.
                self.assertContains(response, k, status_code=500)
                self.assertContains(response, v, status_code=500)

    def verify_safe_response(self, view, check_for_vars=True,
                             check_for_POST_params=True):
        """
        Asserts that certain sensitive info are not displayed in the response.
        """
        request = self.rf.post('/some_url/', self.breakfast_data)
        response = view(request)
        if check_for_vars:
            # Non-sensitive variable's name and value are shown.
            self.assertContains(response, 'cooked_eggs', status_code=500)
            self.assertContains(response, 'scrambled', status_code=500)
            # Sensitive variable's name is shown but not its value.
            self.assertContains(response, 'sauce', status_code=500)
            self.assertNotContains(response, 'worcestershire', status_code=500)
        if check_for_POST_params:
            for k in self.breakfast_data:
                # All POST parameters' names are shown.
                self.assertContains(response, k, status_code=500)
            # Non-sensitive POST parameters' values are shown.
            self.assertContains(response, 'baked-beans-value', status_code=500)
            self.assertContains(response, 'hash-brown-value', status_code=500)
            # Sensitive POST parameters' values are not shown.
            self.assertNotContains(response, 'sausage-value', status_code=500)
            self.assertNotContains(response, 'bacon-value', status_code=500)

    def verify_paranoid_response(self, view, check_for_vars=True,
                                 check_for_POST_params=True):
        """
        Asserts that no variables or POST parameters are displayed in the response.
        """
        request = self.rf.post('/some_url/', self.breakfast_data)
        response = view(request)
        if check_for_vars:
            # Show variable names but not their values.
            self.assertContains(response, 'cooked_eggs', status_code=500)
            self.assertNotContains(response, 'scrambled', status_code=500)
            self.assertContains(response, 'sauce', status_code=500)
            self.assertNotContains(response, 'worcestershire', status_code=500)
        if check_for_POST_params:
            for k, v in self.breakfast_data.items():
                # All POST parameters' names are shown.
                self.assertContains(response, k, status_code=500)
                # No POST parameters' values are shown.
                self.assertNotContains(response, v, status_code=500)

    def verify_unsafe_email(self, view, check_for_POST_params=True):
        """
        Asserts that potentially sensitive info are displayed in the email report.
        """
        with self.settings(ADMINS=[('Admin', 'admin@fattie-breakie.com')]):
            mail.outbox = []  # Empty outbox
            request = self.rf.post('/some_url/', self.breakfast_data)
            view(request)
            self.assertEqual(len(mail.outbox), 1)
            email = mail.outbox[0]

            # Frames vars are never shown in plain text email reports.
            body_plain = str(email.body)
            self.assertNotIn('cooked_eggs', body_plain)
            self.assertNotIn('scrambled', body_plain)
            self.assertNotIn('sauce', body_plain)
            self.assertNotIn('worcestershire', body_plain)

            # Frames vars are shown in html email reports.
            body_html = str(email.alternatives[0][0])
            self.assertIn('cooked_eggs', body_html)
            self.assertIn('scrambled', body_html)
            self.assertIn('sauce', body_html)
            self.assertIn('worcestershire', body_html)

            if check_for_POST_params:
                for k, v in self.breakfast_data.items():
                    # All POST parameters are shown.
                    self.assertIn(k, body_plain)
                    self.assertIn(v, body_plain)
                    self.assertIn(k, body_html)
                    self.assertIn(v, body_html)

    def verify_safe_email(self, view, check_for_POST_params=True):
        """
        Asserts that certain sensitive info are not displayed in the email report.
        """
        with self.settings(ADMINS=[('Admin', 'admin@fattie-breakie.com')]):
            mail.outbox = []  # Empty outbox
            request = self.rf.post('/some_url/', self.breakfast_data)
            view(request)
            self.assertEqual(len(mail.outbox), 1)
            email = mail.outbox[0]

            # Frames vars are never shown in plain text email reports.
            body_plain = str(email.body)
            self.assertNotIn('cooked_eggs', body_plain)
            self.assertNotIn('scrambled', body_plain)
            self.assertNotIn('sauce', body_plain)
            self.assertNotIn('worcestershire', body_plain)

            # Frames vars are shown in html email reports.
            body_html = str(email.alternatives[0][0])
            self.assertIn('cooked_eggs', body_html)
            self.assertIn('scrambled', body_html)
            self.assertIn('sauce', body_html)
            self.assertNotIn('worcestershire', body_html)

            if check_for_POST_params:
                for k in self.breakfast_data:
                    # All POST parameters' names are shown.
                    self.assertIn(k, body_plain)
                # Non-sensitive POST parameters' values are shown.
                self.assertIn('baked-beans-value', body_plain)
                self.assertIn('hash-brown-value', body_plain)
                self.assertIn('baked-beans-value', body_html)
                self.assertIn('hash-brown-value', body_html)
                # Sensitive POST parameters' values are not shown.
                self.assertNotIn('sausage-value', body_plain)
                self.assertNotIn('bacon-value', body_plain)
                self.assertNotIn('sausage-value', body_html)
                self.assertNotIn('bacon-value', body_html)

    def verify_paranoid_email(self, view):
        """
        Asserts that no variables or POST parameters are displayed in the email report.
        """
        with self.settings(ADMINS=[('Admin', 'admin@fattie-breakie.com')]):
            mail.outbox = []  # Empty outbox
            request = self.rf.post('/some_url/', self.breakfast_data)
            view(request)
            self.assertEqual(len(mail.outbox), 1)
            email = mail.outbox[0]
            # Frames vars are never shown in plain text email reports.
            body = str(email.body)
            self.assertNotIn('cooked_eggs', body)
            self.assertNotIn('scrambled', body)
            self.assertNotIn('sauce', body)
            self.assertNotIn('worcestershire', body)
            for k, v in self.breakfast_data.items():
                # All POST parameters' names are shown.
                self.assertIn(k, body)
                # No POST parameters' values are shown.
                self.assertNotIn(v, body)


@override_settings(ROOT_URLCONF='view_tests.urls')
class ExceptionReporterFilterTests(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase):
    """
    Sensitive information can be filtered out of error reports (#14614).
    """
    rf = RequestFactory()

    def test_non_sensitive_request(self):
        """
        Everything (request info and frame variables) can bee seen
        in the default error reports for non-sensitive requests.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(non_sensitive_view)
            self.verify_unsafe_email(non_sensitive_view)

        with self.settings(DEBUG=False):
            self.verify_unsafe_response(non_sensitive_view)
            self.verify_unsafe_email(non_sensitive_view)

    def test_sensitive_request(self):
        """
        Sensitive POST parameters and frame variables cannot be
        seen in the default error reports for sensitive requests.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(sensitive_view)
            self.verify_unsafe_email(sensitive_view)

        with self.settings(DEBUG=False):
            self.verify_safe_response(sensitive_view)
            self.verify_safe_email(sensitive_view)

    def test_paranoid_request(self):
        """
        No POST parameters and frame variables can be seen in the
        default error reports for "paranoid" requests.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(paranoid_view)
            self.verify_unsafe_email(paranoid_view)

        with self.settings(DEBUG=False):
            self.verify_paranoid_response(paranoid_view)
            self.verify_paranoid_email(paranoid_view)

    def test_multivalue_dict_key_error(self):
        """
        #21098 -- Sensitive POST parameters cannot be seen in the
        error reports for if request.POST['nonexistent_key'] throws an error.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(multivalue_dict_key_error)
            self.verify_unsafe_email(multivalue_dict_key_error)

        with self.settings(DEBUG=False):
            self.verify_safe_response(multivalue_dict_key_error)
            self.verify_safe_email(multivalue_dict_key_error)

    def test_custom_exception_reporter_filter(self):
        """
        It's possible to assign an exception reporter filter to
        the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(custom_exception_reporter_filter_view)
            self.verify_unsafe_email(custom_exception_reporter_filter_view)

        with self.settings(DEBUG=False):
            self.verify_unsafe_response(custom_exception_reporter_filter_view)
            self.verify_unsafe_email(custom_exception_reporter_filter_view)

    def test_sensitive_method(self):
        """
        The sensitive_variables decorator works with object methods.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(sensitive_method_view, check_for_POST_params=False)
            self.verify_unsafe_email(sensitive_method_view, check_for_POST_params=False)

        with self.settings(DEBUG=False):
            self.verify_safe_response(sensitive_method_view, check_for_POST_params=False)
            self.verify_safe_email(sensitive_method_view, check_for_POST_params=False)

    def test_sensitive_function_arguments(self):
        """
        Sensitive variables don't leak in the sensitive_variables decorator's
        frame, when those variables are passed as arguments to the decorated
        function.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(sensitive_args_function_caller)
            self.verify_unsafe_email(sensitive_args_function_caller)

        with self.settings(DEBUG=False):
            self.verify_safe_response(sensitive_args_function_caller, check_for_POST_params=False)
            self.verify_safe_email(sensitive_args_function_caller, check_for_POST_params=False)

    def test_sensitive_function_keyword_arguments(self):
        """
        Sensitive variables don't leak in the sensitive_variables decorator's
        frame, when those variables are passed as keyword arguments to the
        decorated function.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(sensitive_kwargs_function_caller)
            self.verify_unsafe_email(sensitive_kwargs_function_caller)

        with self.settings(DEBUG=False):
            self.verify_safe_response(sensitive_kwargs_function_caller, check_for_POST_params=False)
            self.verify_safe_email(sensitive_kwargs_function_caller, check_for_POST_params=False)

    def test_callable_settings(self):
        """
        Callable settings should not be evaluated in the debug page (#21345).
        """
        def callable_setting():
            return "This should not be displayed"
        with self.settings(DEBUG=True, FOOBAR=callable_setting):
            response = self.client.get('/raises500/')
            self.assertNotContains(response, "This should not be displayed", status_code=500)

    def test_callable_settings_forbidding_to_set_attributes(self):
        """
        Callable settings which forbid to set attributes should not break
        the debug page (#23070).
        """
        class CallableSettingWithSlots:
            __slots__ = []

            def __call__(self):
                return "This should not be displayed"

        with self.settings(DEBUG=True, WITH_SLOTS=CallableSettingWithSlots()):
            response = self.client.get('/raises500/')
            self.assertNotContains(response, "This should not be displayed", status_code=500)

    def test_dict_setting_with_non_str_key(self):
        """
        A dict setting containing a non-string key should not break the
        debug page (#12744).
        """
        with self.settings(DEBUG=True, FOOBAR={42: None}):
            response = self.client.get('/raises500/')
            self.assertContains(response, 'FOOBAR', status_code=500)

    def test_sensitive_settings(self):
        """
        The debug page should not show some sensitive settings
        (password, secret key, ...).
        """
        sensitive_settings = [
            'SECRET_KEY',
            'PASSWORD',
            'API_KEY',
            'AUTH_TOKEN',
        ]
        for setting in sensitive_settings:
            with self.settings(DEBUG=True, **{setting: "should not be displayed"}):
                response = self.client.get('/raises500/')
                self.assertNotContains(response, 'should not be displayed', status_code=500)

    def test_settings_with_sensitive_keys(self):
        """
        The debug page should filter out some sensitive information found in
        dict settings.
        """
        sensitive_settings = [
            'SECRET_KEY',
            'PASSWORD',
            'API_KEY',
            'AUTH_TOKEN',
        ]
        for setting in sensitive_settings:
            FOOBAR = {
                setting: "should not be displayed",
                'recursive': {setting: "should not be displayed"},
            }
            with self.settings(DEBUG=True, FOOBAR=FOOBAR):
                response = self.client.get('/raises500/')
                self.assertNotContains(response, 'should not be displayed', status_code=500)

    def test_cleanse_setting_basic(self):
        reporter_filter = SafeExceptionReporterFilter()
        self.assertEqual(reporter_filter.cleanse_setting('TEST', 'TEST'), 'TEST')
        self.assertEqual(
            reporter_filter.cleanse_setting('PASSWORD', 'super_secret'),
            reporter_filter.cleansed_substitute,
        )

    def test_cleanse_setting_ignore_case(self):
        reporter_filter = SafeExceptionReporterFilter()
        self.assertEqual(
            reporter_filter.cleanse_setting('password', 'super_secret'),
            reporter_filter.cleansed_substitute,
        )

    def test_cleanse_setting_recurses_in_dictionary(self):
        reporter_filter = SafeExceptionReporterFilter()
        initial = {'login': 'cooper', 'password': 'secret'}
        self.assertEqual(
            reporter_filter.cleanse_setting('SETTING_NAME', initial),
            {'login': 'cooper', 'password': reporter_filter.cleansed_substitute},
        )

    def test_cleanse_setting_recurses_in_dictionary_with_non_string_key(self):
        reporter_filter = SafeExceptionReporterFilter()
        initial = {('localhost', 8000): {'login': 'cooper', 'password': 'secret'}}
        self.assertEqual(
            reporter_filter.cleanse_setting('SETTING_NAME', initial),
            {
                ('localhost', 8000): {
                    'login': 'cooper',
                    'password': reporter_filter.cleansed_substitute,
                },
            },
        )

    def test_cleanse_setting_recurses_in_list_tuples(self):
        reporter_filter = SafeExceptionReporterFilter()
        initial = [
            {
                'login': 'cooper',
                'password': 'secret',
                'apps': (
                    {'name': 'app1', 'api_key': 'a06b-c462cffae87a'},
                    {'name': 'app2', 'api_key': 'a9f4-f152e97ad808'},
                ),
                'tokens': ['98b37c57-ec62-4e39', '8690ef7d-8004-4916'],
            },
            {'SECRET_KEY': 'c4d77c62-6196-4f17-a06b-c462cffae87a'},
        ]
        cleansed = [
            {
                'login': 'cooper',
                'password': reporter_filter.cleansed_substitute,
                'apps': (
                    {'name': 'app1', 'api_key': reporter_filter.cleansed_substitute},
                    {'name': 'app2', 'api_key': reporter_filter.cleansed_substitute},
                ),
                'tokens': reporter_filter.cleansed_substitute,
            },
            {'SECRET_KEY': reporter_filter.cleansed_substitute},
        ]
        self.assertEqual(
            reporter_filter.cleanse_setting('SETTING_NAME', initial),
            cleansed,
        )
        self.assertEqual(
            reporter_filter.cleanse_setting('SETTING_NAME', tuple(initial)),
            tuple(cleansed),
        )

    def test_request_meta_filtering(self):
        request = self.rf.get('/', HTTP_SECRET_HEADER='super_secret')
        reporter_filter = SafeExceptionReporterFilter()
        self.assertEqual(
            reporter_filter.get_safe_request_meta(request)['HTTP_SECRET_HEADER'],
            reporter_filter.cleansed_substitute,
        )

    def test_exception_report_uses_meta_filtering(self):
        response = self.client.get('/raises500/', HTTP_SECRET_HEADER='super_secret')
        self.assertNotIn(b'super_secret', response.content)
        response = self.client.get(
            '/raises500/',
            HTTP_SECRET_HEADER='super_secret',
            HTTP_ACCEPT='application/json',
        )
        self.assertNotIn(b'super_secret', response.content)


class CustomExceptionReporterFilter(SafeExceptionReporterFilter):
    cleansed_substitute = 'XXXXXXXXXXXXXXXXXXXX'
    hidden_settings = _lazy_re_compile('API|TOKEN|KEY|SECRET|PASS|SIGNATURE|DATABASE_URL', flags=re.I)


@override_settings(
    ROOT_URLCONF='view_tests.urls',
    DEFAULT_EXCEPTION_REPORTER_FILTER='%s.CustomExceptionReporterFilter' % __name__,
)
class CustomExceptionReporterFilterTests(SimpleTestCase):
    def setUp(self):
        get_default_exception_reporter_filter.cache_clear()

    def tearDown(self):
        get_default_exception_reporter_filter.cache_clear()

    def test_setting_allows_custom_subclass(self):
        self.assertIsInstance(
            get_default_exception_reporter_filter(),
            CustomExceptionReporterFilter,
        )

    def test_cleansed_substitute_override(self):
        reporter_filter = get_default_exception_reporter_filter()
        self.assertEqual(
            reporter_filter.cleanse_setting('password', 'super_secret'),
            reporter_filter.cleansed_substitute,
        )

    def test_hidden_settings_override(self):
        reporter_filter = get_default_exception_reporter_filter()
        self.assertEqual(
            reporter_filter.cleanse_setting('database_url', 'super_secret'),
            reporter_filter.cleansed_substitute,
        )


class NonHTMLResponseExceptionReporterFilter(ExceptionReportTestMixin, LoggingCaptureMixin, SimpleTestCase):
    """
    Sensitive information can be filtered out of error reports.

    The plain text 500 debug-only error page is served when it has been
    detected the request doesn't accept HTML content. Don't check for
    (non)existence of frames vars in the traceback information section of the
    response content because they're not included in these error pages.
    Refs #14614.
    """
    rf = RequestFactory(HTTP_ACCEPT='application/json')

    def test_non_sensitive_request(self):
        """
        Request info can bee seen in the default error reports for
        non-sensitive requests.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(non_sensitive_view, check_for_vars=False)

        with self.settings(DEBUG=False):
            self.verify_unsafe_response(non_sensitive_view, check_for_vars=False)

    def test_sensitive_request(self):
        """
        Sensitive POST parameters cannot be seen in the default
        error reports for sensitive requests.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(sensitive_view, check_for_vars=False)

        with self.settings(DEBUG=False):
            self.verify_safe_response(sensitive_view, check_for_vars=False)

    def test_paranoid_request(self):
        """
        No POST parameters can be seen in the default error reports
        for "paranoid" requests.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(paranoid_view, check_for_vars=False)

        with self.settings(DEBUG=False):
            self.verify_paranoid_response(paranoid_view, check_for_vars=False)

    def test_custom_exception_reporter_filter(self):
        """
        It's possible to assign an exception reporter filter to
        the request to bypass the one set in DEFAULT_EXCEPTION_REPORTER_FILTER.
        """
        with self.settings(DEBUG=True):
            self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False)

        with self.settings(DEBUG=False):
            self.verify_unsafe_response(custom_exception_reporter_filter_view, check_for_vars=False)

    @override_settings(DEBUG=True, ROOT_URLCONF='view_tests.urls')
    def test_non_html_response_encoding(self):
        response = self.client.get('/raises500/', HTTP_ACCEPT='application/json')
        self.assertEqual(response.headers['Content-Type'], 'text/plain; charset=utf-8')


class DecoratorsTests(SimpleTestCase):
    def test_sensitive_variables_not_called(self):
        msg = (
            'sensitive_variables() must be called to use it as a decorator, '
            'e.g., use @sensitive_variables(), not @sensitive_variables.'
        )
        with self.assertRaisesMessage(TypeError, msg):
            @sensitive_variables
            def test_func(password):
                pass

    def test_sensitive_post_parameters_not_called(self):
        msg = (
            'sensitive_post_parameters() must be called to use it as a '
            'decorator, e.g., use @sensitive_post_parameters(), not '
            '@sensitive_post_parameters.'
        )
        with self.assertRaisesMessage(TypeError, msg):
            @sensitive_post_parameters
            def test_func(request):
                return index_page(request)