summaryrefslogtreecommitdiff
path: root/pecan/tests/test_base.py
blob: 043df3857949634b531d4cc3e9124da073af4ef4 (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
import sys
import warnings
from webtest import TestApp

if sys.version_info < (2, 7):
    import unittest2 as unittest  # pragma: nocover
else:
    import unittest  # pragma: nocover

from pecan import (
    Pecan, expose, request, response, redirect, abort, make_app,
    override_template, render
)
from pecan.templating import (
    _builtin_renderers as builtin_renderers, error_formatters
)
from pecan.decorators import accept_noncanonical

import os


class SampleRootController(object):
    pass


class TestAppRoot(unittest.TestCase):

    def test_controller_lookup_by_string_path(self):
        app = Pecan('pecan.tests.test_base.SampleRootController')
        assert app.root and isinstance(app.root, SampleRootController)


class TestIndexRouting(unittest.TestCase):

    @property
    def app_(self):
        class RootController(object):
            @expose()
            def index(self):
                return 'Hello, World!'

        return TestApp(Pecan(RootController()))

    def test_empty_root(self):
        r = self.app_.get('/')
        assert r.status_int == 200
        assert r.body == 'Hello, World!'

    def test_index(self):
        r = self.app_.get('/index')
        assert r.status_int == 200
        assert r.body == 'Hello, World!'

    def test_index_html(self):
        r = self.app_.get('/index.html')
        assert r.status_int == 200
        assert r.body == 'Hello, World!'


class TestObjectDispatch(unittest.TestCase):

    @property
    def app_(self):
        class SubSubController(object):
            @expose()
            def index(self):
                return '/sub/sub/'

            @expose()
            def deeper(self):
                return '/sub/sub/deeper'

        class SubController(object):
            @expose()
            def index(self):
                return '/sub/'

            @expose()
            def deeper(self):
                return '/sub/deeper'

            sub = SubSubController()

        class RootController(object):
            @expose()
            def index(self):
                return '/'

            @expose()
            def deeper(self):
                return '/deeper'

            sub = SubController()

        return TestApp(Pecan(RootController()))

    def test_index(self):
        r = self.app_.get('/')
        assert r.status_int == 200
        assert r.body == '/'

    def test_one_level(self):
        r = self.app_.get('/deeper')
        assert r.status_int == 200
        assert r.body == '/deeper'

    def test_one_level_with_trailing(self):
        r = self.app_.get('/sub/')
        assert r.status_int == 200
        assert r.body == '/sub/'

    def test_two_levels(self):
        r = self.app_.get('/sub/deeper')
        assert r.status_int == 200
        assert r.body == '/sub/deeper'

    def test_two_levels_with_trailing(self):
        r = self.app_.get('/sub/sub/')
        assert r.status_int == 200

    def test_three_levels(self):
        r = self.app_.get('/sub/sub/deeper')
        assert r.status_int == 200
        assert r.body == '/sub/sub/deeper'


class TestLookups(unittest.TestCase):

    @property
    def app_(self):
        class LookupController(object):
            def __init__(self, someID):
                self.someID = someID

            @expose()
            def index(self):
                return '/%s' % self.someID

            @expose()
            def name(self):
                return '/%s/name' % self.someID

        class RootController(object):
            @expose()
            def index(self):
                return '/'

            @expose()
            def _lookup(self, someID, *remainder):
                return LookupController(someID), remainder

        return TestApp(Pecan(RootController()))

    def test_index(self):
        r = self.app_.get('/')
        assert r.status_int == 200
        assert r.body == '/'

    def test_lookup(self):
        r = self.app_.get('/100/')
        assert r.status_int == 200
        assert r.body == '/100'

    def test_lookup_with_method(self):
        r = self.app_.get('/100/name')
        assert r.status_int == 200
        assert r.body == '/100/name'

    def test_lookup_with_wrong_argspec(self):
        class RootController(object):
            @expose()
            def _lookup(self, someID):
                return 'Bad arg spec'  # pragma: nocover

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            app = TestApp(Pecan(RootController()))
            r = app.get('/foo/bar', expect_errors=True)
            assert r.status_int == 404


class TestControllerArguments(unittest.TestCase):

    @property
    def app_(self):
        class RootController(object):
            @expose()
            def index(self, id):
                return 'index: %s' % id

            @expose()
            def multiple(self, one, two):
                return 'multiple: %s, %s' % (one, two)

            @expose()
            def optional(self, id=None):
                return 'optional: %s' % str(id)

            @expose()
            def multiple_optional(self, one=None, two=None, three=None):
                return 'multiple_optional: %s, %s, %s' % (one, two, three)

            @expose()
            def variable_args(self, *args):
                return 'variable_args: %s' % ', '.join(args)

            @expose()
            def variable_kwargs(self, **kwargs):
                data = [
                    '%s=%s' % (key, kwargs[key])
                    for key in sorted(kwargs.keys())
                ]
                return 'variable_kwargs: %s' % ', '.join(data)

            @expose()
            def variable_all(self, *args, **kwargs):
                data = [
                    '%s=%s' % (key, kwargs[key])
                    for key in sorted(kwargs.keys())
                ]
                return 'variable_all: %s' % ', '.join(list(args) + data)

            @expose()
            def eater(self, id, dummy=None, *args, **kwargs):
                data = [
                    '%s=%s' % (key, kwargs[key])
                    for key in sorted(kwargs.keys())
                ]
                return 'eater: %s, %s, %s' % (
                    id,
                    dummy,
                    ', '.join(list(args) + data)
                )

            @expose()
            def _route(self, args):
                if hasattr(self, args[0]):
                    return getattr(self, args[0]), args[1:]
                else:
                    return self.index, args

        return TestApp(Pecan(RootController()))

    def test_required_argument(self):
        try:
            r = self.app_.get('/')
            assert r.status_int != 200  # pragma: nocover
        except Exception, ex:
            assert type(ex) == TypeError
            assert ex.args[0] == 'index() takes exactly 2 arguments (1 given)'

    def test_single_argument(self):
        r = self.app_.get('/1')
        assert r.status_int == 200
        assert r.body == 'index: 1'

    def test_single_argument_with_encoded_url(self):
        r = self.app_.get('/This%20is%20a%20test%21')
        assert r.status_int == 200
        assert r.body == 'index: This is a test!'

    def test_two_arguments(self):
        r = self.app_.get('/1/dummy', status=404)
        assert r.status_int == 404

    def test_keyword_argument(self):
        r = self.app_.get('/?id=2')
        assert r.status_int == 200
        assert r.body == 'index: 2'

    def test_keyword_argument_with_encoded_url(self):
        r = self.app_.get('/?id=This%20is%20a%20test%21')
        assert r.status_int == 200
        assert r.body == 'index: This is a test!'

    def test_argument_and_keyword_argument(self):
        r = self.app_.get('/3?id=three')
        assert r.status_int == 200
        assert r.body == 'index: 3'

    def test_encoded_argument_and_keyword_argument(self):
        r = self.app_.get('/This%20is%20a%20test%21?id=three')
        assert r.status_int == 200
        assert r.body == 'index: This is a test!'

    def test_explicit_kwargs(self):
        r = self.app_.post('/', {'id': '4'})
        assert r.status_int == 200
        assert r.body == 'index: 4'

    def test_path_with_explicit_kwargs(self):
        r = self.app_.post('/4', {'id': 'four'})
        assert r.status_int == 200
        assert r.body == 'index: 4'

    def test_multiple_kwargs(self):
        r = self.app_.get('/?id=5&dummy=dummy')
        assert r.status_int == 200
        assert r.body == 'index: 5'

    def test_kwargs_from_root(self):
        r = self.app_.post('/', {'id': '6', 'dummy': 'dummy'})
        assert r.status_int == 200
        assert r.body == 'index: 6'

        # multiple args

    def test_multiple_positional_arguments(self):
        r = self.app_.get('/multiple/one/two')
        assert r.status_int == 200
        assert r.body == 'multiple: one, two'

    def test_multiple_positional_arguments_with_url_encode(self):
        r = self.app_.get('/multiple/One%20/Two%21')
        assert r.status_int == 200
        assert r.body == 'multiple: One , Two!'

    def test_multiple_positional_arguments_with_kwargs(self):
        r = self.app_.get('/multiple?one=three&two=four')
        assert r.status_int == 200
        assert r.body == 'multiple: three, four'

    def test_multiple_positional_arguments_with_url_encoded_kwargs(self):
        r = self.app_.get('/multiple?one=Three%20&two=Four%20%21')
        assert r.status_int == 200
        assert r.body == 'multiple: Three , Four !'

    def test_positional_args_with_dictionary_kwargs(self):
        r = self.app_.post('/multiple', {'one': 'five', 'two': 'six'})
        assert r.status_int == 200
        assert r.body == 'multiple: five, six'

    def test_positional_args_with_url_encoded_dictionary_kwargs(self):
        r = self.app_.post('/multiple', {'one': 'Five%20', 'two': 'Six%20%21'})
        assert r.status_int == 200
        assert r.body == 'multiple: Five%20, Six%20%21'

        # optional arg
    def test_optional_arg(self):
        r = self.app_.get('/optional')
        assert r.status_int == 200
        assert r.body == 'optional: None'

    def test_multiple_optional(self):
        r = self.app_.get('/optional/1')
        assert r.status_int == 200
        assert r.body == 'optional: 1'

    def test_multiple_optional_url_encoded(self):
        r = self.app_.get('/optional/Some%20Number')
        assert r.status_int == 200
        assert r.body == 'optional: Some Number'

    def test_multiple_optional_missing(self):
        r = self.app_.get('/optional/2/dummy', status=404)
        assert r.status_int == 404

    def test_multiple_with_kwargs(self):
        r = self.app_.get('/optional?id=2')
        assert r.status_int == 200
        assert r.body == 'optional: 2'

    def test_multiple_with_url_encoded_kwargs(self):
        r = self.app_.get('/optional?id=Some%20Number')
        assert r.status_int == 200
        assert r.body == 'optional: Some Number'

    def test_multiple_args_with_url_encoded_kwargs(self):
        r = self.app_.get('/optional/3?id=three')
        assert r.status_int == 200
        assert r.body == 'optional: 3'

    def test_url_encoded_positional_args(self):
        r = self.app_.get('/optional/Some%20Number?id=three')
        assert r.status_int == 200
        assert r.body == 'optional: Some Number'

    def test_optional_arg_with_kwargs(self):
        r = self.app_.post('/optional', {'id': '4'})
        assert r.status_int == 200
        assert r.body == 'optional: 4'

    def test_optional_arg_with_url_encoded_kwargs(self):
        r = self.app_.post('/optional', {'id': 'Some%20Number'})
        assert r.status_int == 200
        assert r.body == 'optional: Some%20Number'

    def test_multiple_positional_arguments_with_dictionary_kwargs(self):
        r = self.app_.post('/optional/5', {'id': 'five'})
        assert r.status_int == 200
        assert r.body == 'optional: 5'

    def test_multiple_positional_url_encoded_arguments_with_kwargs(self):
        r = self.app_.post('/optional/Some%20Number', {'id': 'five'})
        assert r.status_int == 200
        assert r.body == 'optional: Some Number'

    def test_optional_arg_with_multiple_kwargs(self):
        r = self.app_.get('/optional?id=6&dummy=dummy')
        assert r.status_int == 200
        assert r.body == 'optional: 6'

    def test_optional_arg_with_multiple_url_encoded_kwargs(self):
        r = self.app_.get('/optional?id=Some%20Number&dummy=dummy')
        assert r.status_int == 200
        assert r.body == 'optional: Some Number'

    def test_optional_arg_with_multiple_dictionary_kwargs(self):
        r = self.app_.post('/optional', {'id': '7', 'dummy': 'dummy'})
        assert r.status_int == 200
        assert r.body == 'optional: 7'

    def test_optional_arg_with_multiple_url_encoded_dictionary_kwargs(self):
        r = self.app_.post('/optional', {
            'id': 'Some%20Number',
            'dummy': 'dummy'
        })
        assert r.status_int == 200
        assert r.body == 'optional: Some%20Number'

        # multiple optional args

    def test_multiple_optional_positional_args(self):
        r = self.app_.get('/multiple_optional')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: None, None, None'

    def test_multiple_optional_positional_args_one_arg(self):
        r = self.app_.get('/multiple_optional/1')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: 1, None, None'

    def test_multiple_optional_positional_args_one_url_encoded_arg(self):
        r = self.app_.get('/multiple_optional/One%21')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: One!, None, None'

    def test_multiple_optional_positional_args_all_args(self):
        r = self.app_.get('/multiple_optional/1/2/3')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: 1, 2, 3'

    def test_multiple_optional_positional_args_all_url_encoded_args(self):
        r = self.app_.get('/multiple_optional/One%21/Two%21/Three%21')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: One!, Two!, Three!'

    def test_multiple_optional_positional_args_too_many_args(self):
        r = self.app_.get('/multiple_optional/1/2/3/dummy', status=404)
        assert r.status_int == 404

    def test_multiple_optional_positional_args_with_kwargs(self):
        r = self.app_.get('/multiple_optional?one=1')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: 1, None, None'

    def test_multiple_optional_positional_args_with_url_encoded_kwargs(self):
        r = self.app_.get('/multiple_optional?one=One%21')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: One!, None, None'

    def test_multiple_optional_positional_args_with_string_kwargs(self):
        r = self.app_.get('/multiple_optional/1?one=one')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: 1, None, None'

    def test_multiple_optional_positional_args_with_encoded_str_kwargs(self):
        r = self.app_.get('/multiple_optional/One%21?one=one')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: One!, None, None'

    def test_multiple_optional_positional_args_with_dict_kwargs(self):
        r = self.app_.post('/multiple_optional', {'one': '1'})
        assert r.status_int == 200
        assert r.body == 'multiple_optional: 1, None, None'

    def test_multiple_optional_positional_args_with_encoded_dict_kwargs(self):
        r = self.app_.post('/multiple_optional', {'one': 'One%21'})
        assert r.status_int == 200
        assert r.body == 'multiple_optional: One%21, None, None'

    def test_multiple_optional_positional_args_and_dict_kwargs(self):
        r = self.app_.post('/multiple_optional/1', {'one': 'one'})
        assert r.status_int == 200
        assert r.body == 'multiple_optional: 1, None, None'

    def test_multiple_optional_encoded_positional_args_and_dict_kwargs(self):
        r = self.app_.post('/multiple_optional/One%21', {'one': 'one'})
        assert r.status_int == 200
        assert r.body == 'multiple_optional: One!, None, None'

    def test_multiple_optional_args_with_multiple_kwargs(self):
        r = self.app_.get('/multiple_optional?one=1&two=2&three=3&four=4')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: 1, 2, 3'

    def test_multiple_optional_args_with_multiple_encoded_kwargs(self):
        r = self.app_.get(
            '/multiple_optional?one=One%21&two=Two%21&three=Three%21&four=4'
        )
        assert r.status_int == 200
        assert r.body == 'multiple_optional: One!, Two!, Three!'

    def test_multiple_optional_args_with_multiple_dict_kwargs(self):
        r = self.app_.post(
            '/multiple_optional',
            {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
        )
        assert r.status_int == 200
        assert r.body == 'multiple_optional: 1, 2, 3'

    def test_multiple_optional_args_with_multiple_encoded_dict_kwargs(self):
        r = self.app_.post(
            '/multiple_optional',
            {
                'one': 'One%21',
                'two': 'Two%21',
                'three': 'Three%21',
                'four': '4'
            }
        )
        assert r.status_int == 200
        assert r.body == 'multiple_optional: One%21, Two%21, Three%21'

    def test_multiple_optional_args_with_last_kwarg(self):
        r = self.app_.get('/multiple_optional?three=3')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: None, None, 3'

    def test_multiple_optional_args_with_last_encoded_kwarg(self):
        r = self.app_.get('/multiple_optional?three=Three%21')
        assert r.status_int == 200
        assert r.body == 'multiple_optional: None, None, Three!'

    def test_multiple_optional_args_with_middle_arg(self):
        r = self.app_.get('/multiple_optional', {'two': '2'})
        assert r.status_int == 200
        assert r.body == 'multiple_optional: None, 2, None'

    def test_variable_args(self):
        r = self.app_.get('/variable_args')
        assert r.status_int == 200
        assert r.body == 'variable_args: '

    def test_multiple_variable_args(self):
        r = self.app_.get('/variable_args/1/dummy')
        assert r.status_int == 200
        assert r.body == 'variable_args: 1, dummy'

    def test_multiple_encoded_variable_args(self):
        r = self.app_.get('/variable_args/Testing%20One%20Two/Three%21')
        assert r.status_int == 200
        assert r.body == 'variable_args: Testing One Two, Three!'

    def test_variable_args_with_kwargs(self):
        r = self.app_.get('/variable_args?id=2&dummy=dummy')
        assert r.status_int == 200
        assert r.body == 'variable_args: '

    def test_variable_args_with_dict_kwargs(self):
        r = self.app_.post('/variable_args', {'id': '3', 'dummy': 'dummy'})
        assert r.status_int == 200
        assert r.body == 'variable_args: '

    def test_variable_kwargs(self):
        r = self.app_.get('/variable_kwargs')
        assert r.status_int == 200
        assert r.body == 'variable_kwargs: '

    def test_multiple_variable_kwargs(self):
        r = self.app_.get('/variable_kwargs/1/dummy', status=404)
        assert r.status_int == 404

    def test_multiple_variable_kwargs_with_explicit_kwargs(self):
        r = self.app_.get('/variable_kwargs?id=2&dummy=dummy')
        assert r.status_int == 200
        assert r.body == 'variable_kwargs: dummy=dummy, id=2'

    def test_multiple_variable_kwargs_with_explicit_encoded_kwargs(self):
        r = self.app_.get(
            '/variable_kwargs?id=Two%21&dummy=This%20is%20a%20test'
        )
        assert r.status_int == 200
        assert r.body == 'variable_kwargs: dummy=This is a test, id=Two!'

    def test_multiple_variable_kwargs_with_dict_kwargs(self):
        r = self.app_.post('/variable_kwargs', {'id': '3', 'dummy': 'dummy'})
        assert r.status_int == 200
        assert r.body == 'variable_kwargs: dummy=dummy, id=3'

    def test_multiple_variable_kwargs_with_encoded_dict_kwargs(self):
        r = self.app_.post(
            '/variable_kwargs',
            {'id': 'Three%21', 'dummy': 'This%20is%20a%20test'}
        )
        assert r.status_int == 200
        result = 'variable_kwargs: dummy=This%20is%20a%20test, id=Three%21'
        assert r.body == result

    def test_variable_all(self):
        r = self.app_.get('/variable_all')
        assert r.status_int == 200
        assert r.body == 'variable_all: '

    def test_variable_all_with_one_extra(self):
        r = self.app_.get('/variable_all/1')
        assert r.status_int == 200
        assert r.body == 'variable_all: 1'

    def test_variable_all_with_two_extras(self):
        r = self.app_.get('/variable_all/2/dummy')
        assert r.status_int == 200
        assert r.body == 'variable_all: 2, dummy'

    def test_variable_mixed(self):
        r = self.app_.get('/variable_all/3?month=1&day=12')
        assert r.status_int == 200
        assert r.body == 'variable_all: 3, day=12, month=1'

    def test_variable_mixed_explicit(self):
        r = self.app_.get('/variable_all/4?id=four&month=1&day=12')
        assert r.status_int == 200
        assert r.body == 'variable_all: 4, day=12, id=four, month=1'

    def test_variable_post(self):
        r = self.app_.post('/variable_all/5/dummy')
        assert r.status_int == 200
        assert r.body == 'variable_all: 5, dummy'

    def test_variable_post_with_kwargs(self):
        r = self.app_.post('/variable_all/6', {'month': '1', 'day': '12'})
        assert r.status_int == 200
        assert r.body == 'variable_all: 6, day=12, month=1'

    def test_variable_post_mixed(self):
        r = self.app_.post(
            '/variable_all/7',
            {'id': 'seven', 'month': '1', 'day': '12'}
        )
        assert r.status_int == 200
        assert r.body == 'variable_all: 7, day=12, id=seven, month=1'

    def test_no_remainder(self):
        try:
            r = self.app_.get('/eater')
            assert r.status_int != 200  # pragma: nocover
        except Exception, ex:
            assert type(ex) == TypeError
            assert ex.args[0] == 'eater() takes at least 2 arguments (1 given)'

    def test_one_remainder(self):
        r = self.app_.get('/eater/1')
        assert r.status_int == 200
        assert r.body == 'eater: 1, None, '

    def test_two_remainders(self):
        r = self.app_.get('/eater/2/dummy')
        assert r.status_int == 200
        assert r.body == 'eater: 2, dummy, '

    def test_many_remainders(self):
        r = self.app_.get('/eater/3/dummy/foo/bar')
        assert r.status_int == 200
        assert r.body == 'eater: 3, dummy, foo, bar'

    def test_remainder_with_kwargs(self):
        r = self.app_.get('/eater/4?month=1&day=12')
        assert r.status_int == 200
        assert r.body == 'eater: 4, None, day=12, month=1'

    def test_remainder_with_many_kwargs(self):
        r = self.app_.get('/eater/5?id=five&month=1&day=12&dummy=dummy')
        assert r.status_int == 200
        assert r.body == 'eater: 5, dummy, day=12, month=1'

    def test_post_remainder(self):
        r = self.app_.post('/eater/6')
        assert r.status_int == 200
        assert r.body == 'eater: 6, None, '

    def test_post_three_remainders(self):
        r = self.app_.post('/eater/7/dummy')
        assert r.status_int == 200
        assert r.body == 'eater: 7, dummy, '

    def test_post_many_remainders(self):
        r = self.app_.post('/eater/8/dummy/foo/bar')
        assert r.status_int == 200
        assert r.body == 'eater: 8, dummy, foo, bar'

    def test_post_remainder_with_kwargs(self):
        r = self.app_.post('/eater/9', {'month': '1', 'day': '12'})
        assert r.status_int == 200
        assert r.body == 'eater: 9, None, day=12, month=1'

    def test_post_many_remainders_with_many_kwargs(self):
        r = self.app_.post(
            '/eater/10',
            {'id': 'ten', 'month': '1', 'day': '12', 'dummy': 'dummy'}
        )
        assert r.status_int == 200
        assert r.body == 'eater: 10, dummy, day=12, month=1'


class TestAbort(unittest.TestCase):

    def test_abort(self):
        class RootController(object):
            @expose()
            def index(self):
                abort(404)

        app = TestApp(Pecan(RootController()))
        r = app.get('/', status=404)
        assert r.status_int == 404

    def test_abort_with_detail(self):
        class RootController(object):
            @expose()
            def index(self):
                abort(status_code=401, detail='Not Authorized')

        app = TestApp(Pecan(RootController()))
        r = app.get('/', status=401)
        assert r.status_int == 401


class TestRedirect(unittest.TestCase):

    @property
    def app_(self):
        class RootController(object):
            @expose()
            def index(self):
                redirect('/testing')

            @expose()
            def internal(self):
                redirect('/testing', internal=True)

            @expose()
            def bad_internal(self):
                redirect('/testing', internal=True, code=301)

            @expose()
            def permanent(self):
                redirect('/testing', code=301)

            @expose()
            def testing(self):
                return 'it worked!'

        return TestApp(make_app(RootController(), debug=False))

    def test_index(self):
        r = self.app_.get('/')
        assert r.status_int == 302
        r = r.follow()
        assert r.status_int == 200
        assert r.body == 'it worked!'

    def test_internal(self):
        r = self.app_.get('/internal')
        assert r.status_int == 200
        assert r.body == 'it worked!'

    def test_internal_with_301(self):
        self.assertRaises(ValueError, self.app_.get, '/bad_internal')

    def test_permanent_redirect(self):
        r = self.app_.get('/permanent')
        assert r.status_int == 301
        r = r.follow()
        assert r.status_int == 200
        assert r.body == 'it worked!'

    def test_x_forward_proto(self):
        class ChildController(object):
            @expose()
            def index(self):
                redirect('/testing')  # pragma: nocover

        class RootController(object):
            @expose()
            def index(self):
                redirect('/testing')  # pragma: nocover

            @expose()
            def testing(self):
                return 'it worked!'  # pragma: nocover
            child = ChildController()

        app = TestApp(make_app(RootController(), debug=True))
        res = app.get(
            '/child', extra_environ=dict(HTTP_X_FORWARDED_PROTO='https')
        )
        ##non-canonical url will redirect, so we won't get a 301
        assert res.status_int == 302
        ##should add trailing / and changes location to https
        assert res.location == 'https://localhost/child/'
        assert res.request.environ['HTTP_X_FORWARDED_PROTO'] == 'https'


class TestStreamedResponse(unittest.TestCase):

    def test_streaming_response(self):
        import StringIO

        class RootController(object):
            @expose(content_type='text/plain')
            def test(self, foo):
                if foo == 'stream':
                    # mimic large file
                    contents = StringIO.StringIO('stream')
                    response.content_type = 'application/octet-stream'
                    contents.seek(0, os.SEEK_END)
                    response.content_length = contents.tell()
                    contents.seek(0, os.SEEK_SET)
                    response.app_iter = contents
                    return response
                else:
                    return 'plain text'

        app = TestApp(Pecan(RootController()))
        r = app.get('/test/stream')
        assert r.content_type == 'application/octet-stream'
        assert r.body == 'stream'

        r = app.get('/test/plain')
        assert r.content_type == 'text/plain'
        assert r.body == 'plain text'


class TestStateCleanup(unittest.TestCase):

    def test_request_state_cleanup(self):
        """
        After a request, the state local() should be totally clean
        except for state.app (so that objects don't leak between requests)
        """
        from pecan.core import state

        class RootController(object):
            @expose()
            def index(self):
                return '/'

        app = TestApp(Pecan(RootController()))
        r = app.get('/')
        assert r.status_int == 200
        assert r.body == '/'

        assert state.__dict__.keys() == ['app']


class TestFileTypeExtensions(unittest.TestCase):

    @property
    def app_(self):
        """
        Test extension splits
        """
        class RootController(object):
            @expose(content_type=None)
            def _default(self, *args):
                ext = request.pecan['extension']
                assert len(args) == 1
                if ext:
                    assert ext not in args[0]
                return ext or ''

        return TestApp(Pecan(RootController()))

    def test_html_extension(self):
        r = self.app_.get('/index.html')
        assert r.status_int == 200
        assert r.body == '.html'

    def test_image_extension(self):
        r = self.app_.get('/image.png')
        assert r.status_int == 200
        assert r.body == '.png'

    def test_hidden_file(self):
        r = self.app_.get('/.vimrc')
        assert r.status_int == 200
        assert r.body == ''

    def test_multi_dot_extension(self):
        r = self.app_.get('/gradient.min.js')
        assert r.status_int == 200
        assert r.body == '.js'

    def test_bad_content_type(self):
        class RootController(object):
            @expose()
            def index(self):
                return '/'

        app = TestApp(Pecan(RootController()))
        r = app.get('/')
        assert r.status_int == 200
        assert r.body == '/'

        r = app.get('/index.html', expect_errors=True)
        assert r.status_int == 200
        assert r.body == '/'

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = app.get('/index.txt', expect_errors=True)
            assert r.status_int == 404

    def test_unknown_file_extension(self):
        class RootController(object):
            @expose(content_type=None)
            def _default(self, *args):
                assert 'example:x.tiny' in args
                assert request.pecan['extension'] is None
                return 'SOME VALUE'

        app = TestApp(Pecan(RootController()))

        r = app.get('/example:x.tiny')
        assert r.status_int == 200
        assert r.body == 'SOME VALUE'


class TestContentTypeByAcceptHeaders(unittest.TestCase):

    @property
    def app_(self):
        """
        Test that content type is set appropriately based on Accept headers.
        """
        class RootController(object):

            @expose(content_type='text/html')
            @expose(content_type='application/json')
            def index(self, *args):
                return 'Foo'

        return TestApp(Pecan(RootController()))

    def test_quality(self):
        r = self.app_.get('/', headers={
            'Accept': 'text/html,application/json;q=0.9,*/*;q=0.8'
        })
        assert r.status_int == 200
        assert r.content_type == 'text/html'

        r = self.app_.get('/', headers={
            'Accept': 'application/json,text/html;q=0.9,*/*;q=0.8'
        })
        assert r.status_int == 200
        assert r.content_type == 'application/json'

    def test_file_extension_has_higher_precedence(self):
        r = self.app_.get('/index.html', headers={
            'Accept': 'application/json,text/html;q=0.9,*/*;q=0.8'
        })
        assert r.status_int == 200
        assert r.content_type == 'text/html'

    def test_not_acceptable(self):
        r = self.app_.get('/', headers={
            'Accept': 'application/xml',
        }, status=406)
        assert r.status_int == 406

    def test_accept_header_missing(self):
        r = self.app_.get('/')
        assert r.status_int == 200
        assert r.content_type == 'text/html'


class TestCanonicalRouting(unittest.TestCase):

    @property
    def app_(self):
        class ArgSubController(object):
            @expose()
            def index(self, arg):
                return arg

        class AcceptController(object):
            @accept_noncanonical
            @expose()
            def index(self):
                return 'accept'

        class SubController(object):
            @expose()
            def index(self, **kw):
                return 'subindex'

        class RootController(object):
            @expose()
            def index(self):
                return 'index'

            sub = SubController()
            arg = ArgSubController()
            accept = AcceptController()

        return TestApp(Pecan(RootController()))

    def test_root(self):
        r = self.app_.get('/')
        assert r.status_int == 200
        assert 'index' in r.body

    def test_index(self):
        r = self.app_.get('/index')
        assert r.status_int == 200
        assert 'index' in r.body

    def test_broken_clients(self):
        # for broken clients
        r = self.app_.get('', status=302)
        assert r.status_int == 302
        assert r.location == 'http://localhost/'

    def test_sub_controller_with_trailing(self):
        r = self.app_.get('/sub/')
        assert r.status_int == 200
        assert 'subindex' in r.body

    def test_sub_controller_redirect(self):
        r = self.app_.get('/sub', status=302)
        assert r.status_int == 302
        assert r.location == 'http://localhost/sub/'

    def test_with_query_string(self):
        # try with query string
        r = self.app_.get('/sub?foo=bar', status=302)
        assert r.status_int == 302
        assert r.location == 'http://localhost/sub/?foo=bar'

    def test_posts_fail(self):
        try:
            self.app_.post('/sub', dict(foo=1))
            raise Exception("Post should fail")  # pragma: nocover
        except Exception, e:
            assert isinstance(e, RuntimeError)

    def test_with_args(self):
        r = self.app_.get('/arg/index/foo')
        assert r.status_int == 200
        assert r.body == 'foo'

    def test_accept_noncanonical(self):
        r = self.app_.get('/accept/')
        assert r.status_int == 200
        assert 'accept' == r.body

    def test_accept_noncanonical_no_trailing_slash(self):
        r = self.app_.get('/accept')
        assert r.status_int == 200
        assert 'accept' == r.body


class TestNonCanonical(unittest.TestCase):

    @property
    def app_(self):
        class ArgSubController(object):
            @expose()
            def index(self, arg):
                return arg  # pragma: nocover

        class AcceptController(object):
            @accept_noncanonical
            @expose()
            def index(self):
                return 'accept'  # pragma: nocover

        class SubController(object):
            @expose()
            def index(self, **kw):
                return 'subindex'

        class RootController(object):
            @expose()
            def index(self):
                return 'index'

            sub = SubController()
            arg = ArgSubController()
            accept = AcceptController()

        return TestApp(Pecan(RootController(), force_canonical=False))

    def test_index(self):
        r = self.app_.get('/')
        assert r.status_int == 200
        assert 'index' in r.body

    def test_subcontroller(self):
        r = self.app_.get('/sub')
        assert r.status_int == 200
        assert 'subindex' in r.body

    def test_subcontroller_with_kwargs(self):
        r = self.app_.post('/sub', dict(foo=1))
        assert r.status_int == 200
        assert 'subindex' in r.body

    def test_sub_controller_with_trailing(self):
        r = self.app_.get('/sub/')
        assert r.status_int == 200
        assert 'subindex' in r.body

    def test_proxy(self):
        class RootController(object):
            @expose()
            def index(self):
                request.testing = True
                assert request.testing is True
                del request.testing
                assert hasattr(request, 'testing') is False
                return '/'

        app = TestApp(make_app(RootController(), debug=True))
        r = app.get('/')
        assert r.status_int == 200

    def test_app_wrap(self):
        class RootController(object):
            pass

        wrapped_apps = []

        def wrap(app):
            wrapped_apps.append(app)
            return app

        make_app(RootController(), wrap_app=wrap, debug=True)
        assert len(wrapped_apps) == 1


class TestLogging(unittest.TestCase):

    def test_logging_setup(self):
        class RootController(object):
            @expose()
            def index(self):
                import logging
                logging.getLogger('pecantesting').info('HELLO WORLD')
                return "HELLO WORLD"

        from cStringIO import StringIO
        f = StringIO()

        app = TestApp(make_app(RootController(), logging={
            'loggers': {
                'pecantesting': {
                    'level': 'INFO', 'handlers': ['memory']
                }
            },
            'handlers': {
                'memory': {
                    'level': 'INFO',
                    'class': 'logging.StreamHandler',
                    'stream': f
                }
            }
        }))

        app.get('/')
        assert f.getvalue() == 'HELLO WORLD\n'

    def test_logging_setup_with_config_obj(self):
        class RootController(object):
            @expose()
            def index(self):
                import logging
                logging.getLogger('pecantesting').info('HELLO WORLD')
                return "HELLO WORLD"

        from cStringIO import StringIO
        f = StringIO()

        from pecan.configuration import conf_from_dict
        app = TestApp(make_app(RootController(), logging=conf_from_dict({
            'loggers': {
                'pecantesting': {
                    'level': 'INFO', 'handlers': ['memory']
                }
            },
            'handlers': {
                'memory': {
                    'level': 'INFO',
                    'class': 'logging.StreamHandler',
                    'stream': f
                }
            }
        })))

        app.get('/')
        assert f.getvalue() == 'HELLO WORLD\n'


class TestEngines(unittest.TestCase):

    template_path = os.path.join(os.path.dirname(__file__), 'templates')

    @unittest.skipIf('genshi' not in builtin_renderers, 'Genshi not installed')
    def test_genshi(self):

        class RootController(object):
            @expose('genshi:genshi.html')
            def index(self, name='Jonathan'):
                return dict(name=name)

            @expose('genshi:genshi_bad.html')
            def badtemplate(self):
                return dict()

        app = TestApp(
            Pecan(RootController(), template_path=self.template_path)
        )
        r = app.get('/')
        assert r.status_int == 200
        assert "<h1>Hello, Jonathan!</h1>" in r.body

        r = app.get('/index.html?name=World')
        assert r.status_int == 200
        assert "<h1>Hello, World!</h1>" in r.body

        error_msg = None
        try:
            r = app.get('/badtemplate.html')
        except Exception, e:
            for error_f in error_formatters:
                error_msg = error_f(e)
                if error_msg:
                    break
        assert error_msg is not None

    @unittest.skipIf('kajiki' not in builtin_renderers, 'Kajiki not installed')
    def test_kajiki(self):

        class RootController(object):
            @expose('kajiki:kajiki.html')
            def index(self, name='Jonathan'):
                return dict(name=name)

        app = TestApp(
            Pecan(RootController(), template_path=self.template_path)
        )
        r = app.get('/')
        assert r.status_int == 200
        assert "<h1>Hello, Jonathan!</h1>" in r.body

        r = app.get('/index.html?name=World')
        assert r.status_int == 200
        assert "<h1>Hello, World!</h1>" in r.body

    @unittest.skipIf('jinja' not in builtin_renderers, 'Jinja not installed')
    def test_jinja(self):

        class RootController(object):
            @expose('jinja:jinja.html')
            def index(self, name='Jonathan'):
                return dict(name=name)

            @expose('jinja:jinja_bad.html')
            def badtemplate(self):
                return dict()

        app = TestApp(
            Pecan(RootController(), template_path=self.template_path)
        )
        r = app.get('/')
        assert r.status_int == 200
        assert "<h1>Hello, Jonathan!</h1>" in r.body

        error_msg = None
        try:
            r = app.get('/badtemplate.html')
        except Exception, e:
            for error_f in error_formatters:
                error_msg = error_f(e)
                if error_msg:
                    break
        assert error_msg is not None

    @unittest.skipIf('mako' not in builtin_renderers, 'Mako not installed')
    def test_mako(self):

        class RootController(object):
            @expose('mako:mako.html')
            def index(self, name='Jonathan'):
                return dict(name=name)

            @expose('mako:mako_bad.html')
            def badtemplate(self):
                return dict()

        app = TestApp(
            Pecan(RootController(), template_path=self.template_path)
        )
        r = app.get('/')
        assert r.status_int == 200
        assert "<h1>Hello, Jonathan!</h1>" in r.body

        r = app.get('/index.html?name=World')
        assert r.status_int == 200
        assert "<h1>Hello, World!</h1>" in r.body

        error_msg = None
        try:
            r = app.get('/badtemplate.html')
        except Exception, e:
            for error_f in error_formatters:
                error_msg = error_f(e)
                if error_msg:
                    break
        assert error_msg is not None

    def test_json(self):
        try:
            from simplejson import loads
        except:
            from json import loads  # noqa

        expected_result = dict(
            name='Jonathan',
            age=30, nested=dict(works=True)
        )

        class RootController(object):
            @expose('json')
            def index(self):
                return expected_result

        app = TestApp(Pecan(RootController()))
        r = app.get('/')
        assert r.status_int == 200
        result = dict(loads(r.body))
        assert result == expected_result

    def test_override_template(self):
        class RootController(object):
            @expose('foo.html')
            def index(self):
                override_template(None, content_type='text/plain')
                return 'Override'

        app = TestApp(Pecan(RootController()))
        r = app.get('/')
        assert r.status_int == 200
        assert 'Override' in r.body
        assert r.content_type == 'text/plain'

    def test_render(self):
        class RootController(object):
            @expose()
            def index(self, name='Jonathan'):
                return render('mako.html', dict(name=name))

        app = TestApp(
            Pecan(RootController(), template_path=self.template_path)
        )
        r = app.get('/')
        assert r.status_int == 200
        assert "<h1>Hello, Jonathan!</h1>" in r.body