summaryrefslogtreecommitdiff
path: root/pecan/tests/test_base.py
blob: 785b5228a8b770bd5be5b1b87fc1f5453e18e7e6 (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
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
# -*- coding: utf-8 -*-

import sys
import os
import json
import traceback
import warnings

import webob
from webob.exc import HTTPNotFound
import mock
from webtest import TestApp
import six
from six import b as b_
from six import u as u_
from six.moves import cStringIO as StringIO

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

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


class SampleRootController(object):
    pass


class TestAppRoot(PecanTestCase):

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


class TestEmptyContent(PecanTestCase):
    @property
    def app_(self):
        class RootController(object):
            @expose()
            def index(self):
                pass

            @expose()
            def explicit_body(self):
                response.body = b_('Hello, World!')

            @expose()
            def empty_body(self):
                response.body = b_('')

            @expose()
            def explicit_text(self):
                response.text = six.text_type('Hello, World!')

            @expose()
            def empty_text(self):
                response.text = six.text_type('')

            @expose()
            def explicit_json(self):
                response.json = {'foo': 'bar'}

            @expose()
            def explicit_json_body(self):
                response.json_body = {'foo': 'bar'}

            @expose()
            def non_unicode(self):
                return chr(0xc0)

        return TestApp(Pecan(RootController()))

    def test_empty_index(self):
        r = self.app_.get('/')
        self.assertEqual(r.status_int, 204)
        self.assertNotIn('Content-Type', r.headers)
        self.assertEqual(r.headers['Content-Length'], '0')
        self.assertEqual(len(r.body), 0)

    def test_index_with_non_unicode(self):
        r = self.app_.get('/non_unicode/')
        self.assertEqual(r.status_int, 200)

    def test_explicit_body(self):
        r = self.app_.get('/explicit_body/')
        self.assertEqual(r.status_int, 200)
        self.assertEqual(r.body, b_('Hello, World!'))

    def test_empty_body(self):
        r = self.app_.get('/empty_body/')
        self.assertEqual(r.status_int, 204)
        self.assertEqual(r.body, b_(''))

    def test_explicit_text(self):
        r = self.app_.get('/explicit_text/')
        self.assertEqual(r.status_int, 200)
        self.assertEqual(r.body, b_('Hello, World!'))

    def test_empty_text(self):
        r = self.app_.get('/empty_text/')
        self.assertEqual(r.status_int, 204)
        self.assertEqual(r.body, b_(''))

    def test_explicit_json(self):
        r = self.app_.get('/explicit_json/')
        self.assertEqual(r.status_int, 200)
        json_resp = json.loads(r.body.decode())
        assert json_resp == {'foo': 'bar'}

    def test_explicit_json_body(self):
        r = self.app_.get('/explicit_json_body/')
        self.assertEqual(r.status_int, 200)
        json_resp = json.loads(r.body.decode())
        assert json_resp == {'foo': 'bar'}


class TestAppIterFile(PecanTestCase):
    @property
    def app_(self):
        class RootController(object):
            @expose()
            def index(self):
                body = six.BytesIO(b_('Hello, World!'))
                response.body_file = body

            @expose()
            def empty(self):
                body = six.BytesIO(b_(''))
                response.body_file = body

        return TestApp(Pecan(RootController()))

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

    def test_empty_body_generator(self):
        r = self.app_.get('/empty')
        self.assertEqual(r.status_int, 204)
        assert len(r.body) == 0


class TestInvalidURLEncoding(PecanTestCase):

    @property
    def app_(self):
        class RootController(object):

            @expose()
            def _route(self, args, request):
                assert request.path

        return TestApp(Pecan(RootController()))

    def test_rest_with_non_utf_8_body(self):
        r = self.app_.get('/%aa/', expect_errors=True)
        assert r.status_int == 400


class TestIndexRouting(PecanTestCase):

    @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 == b_('Hello, World!')

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

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


class TestObjectDispatch(PecanTestCase):

    @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 == b_('/')

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

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

    def test_two_levels(self):
        r = self.app_.get('/sub/deeper')
        assert r.status_int == 200
        assert r.body == b_('/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 == b_('/sub/sub/deeper')


@unittest.skipIf(not six.PY3, "tests are Python3 specific")
class TestUnicodePathSegments(PecanTestCase):

    def test_unicode_methods(self):
        class RootController(object):
            pass
        setattr(RootController, '🌰', expose()(lambda self: 'Hello, World!'))
        app = TestApp(Pecan(RootController()))

        resp = app.get('/%F0%9F%8C%B0/')
        assert resp.status_int == 200
        assert resp.body == b_('Hello, World!')

    def test_unicode_child(self):
        class ChildController(object):
            @expose()
            def index(self):
                return 'Hello, World!'

        class RootController(object):
            pass
        setattr(RootController, '🌰', ChildController())
        app = TestApp(Pecan(RootController()))

        resp = app.get('/%F0%9F%8C%B0/')
        assert resp.status_int == 200
        assert resp.body == b_('Hello, World!')


class TestLookups(PecanTestCase):

    @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 == b_('/')

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

    def test_lookup_with_method(self):
        r = self.app_.get('/100/name')
        assert r.status_int == 200
        assert r.body == b_('/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 TestCanonicalLookups(PecanTestCase):

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

            @expose()
            def index(self):
                return self.someID

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

        class RootController(object):
            users = UserController()

        return TestApp(Pecan(RootController()))

    def test_canonical_lookup(self):
        assert self.app_.get('/users', expect_errors=404).status_int == 404
        assert self.app_.get('/users/', expect_errors=404).status_int == 404
        assert self.app_.get('/users/100').status_int == 302
        assert self.app_.get('/users/100/').body == b_('100')


class TestControllerArguments(PecanTestCase):

    @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)
                )

            @staticmethod
            @expose()
            def static(id):
                return "id is %s" % id

            @expose()
            def _route(self, args, request):
                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 as ex:
            assert type(ex) == TypeError
            assert ex.args[0] in (
                "index() takes exactly 2 arguments (1 given)",
                "index() missing 1 required positional argument: 'id'"
            )  # this messaging changed in Python 3.3

    def test_single_argument(self):
        r = self.app_.get('/1')
        assert r.status_int == 200
        assert r.body == b_('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 == b_('index: This is a test!')

    def test_single_argument_with_plus(self):
        r = self.app_.get('/foo+bar')
        assert r.status_int == 200
        assert r.body == b_('index: foo+bar')

    def test_single_argument_with_encoded_plus(self):
        r = self.app_.get('/foo%2Bbar')
        assert r.status_int == 200
        assert r.body == b_('index: foo+bar')

    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 == b_('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 == b_('index: This is a test!')

    def test_keyword_argument_with_plus(self):
        r = self.app_.get('/?id=foo+bar')
        assert r.status_int == 200
        assert r.body == b_('index: foo bar')

    def test_keyword_argument_with_encoded_plus(self):
        r = self.app_.get('/?id=foo%2Bbar')
        assert r.status_int == 200
        assert r.body == b_('index: foo+bar')

    def test_argument_and_keyword_argument(self):
        r = self.app_.get('/3?id=three')
        assert r.status_int == 200
        assert r.body == b_('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 == b_('index: This is a test!')

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

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

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

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

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

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

    def test_json_kwargs_from_root(self):
        r = self.app_.post_json('/', {'id': '6', 'dummy': 'dummy'})
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('multiple: five, six')

    def test_positional_args_with_json_kwargs(self):
        r = self.app_.post_json('/multiple', {'one': 'five', 'two': 'six'})
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('optional: None')

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

    def test_multiple_optional_url_encoded(self):
        r = self.app_.get('/optional/Some%20Number')
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('optional: 4')

    def test_optional_arg_with_json_kwargs(self):
        r = self.app_.post_json('/optional', {'id': '4'})
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('optional: 5')

    def test_multiple_positional_arguments_with_json_kwargs(self):
        r = self.app_.post_json('/optional/5', {'id': 'five'})
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('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 == b_('optional: 7')

    def test_optional_arg_with_multiple_json_kwargs(self):
        r = self.app_.post_json('/optional', {'id': '7', 'dummy': 'dummy'})
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('multiple_optional: 1, None, None')

    def test_multiple_optional_positional_args_with_json_kwargs(self):
        r = self.app_.post_json('/multiple_optional', {'one': '1'})
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('multiple_optional: 1, None, None')

    def test_multiple_optional_positional_args_and_json_kwargs(self):
        r = self.app_.post_json('/multiple_optional/1', {'one': 'one'})
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('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 == b_('multiple_optional: 1, 2, 3')

    def test_multiple_optional_args_with_multiple_json_kwargs(self):
        r = self.app_.post_json(
            '/multiple_optional',
            {'one': '1', 'two': '2', 'three': '3', 'four': '4'}
        )
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('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 == b_('multiple_optional: None, 2, None')

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

    def test_multiple_variable_args(self):
        r = self.app_.get('/variable_args/1/dummy')
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('variable_args: ')

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

    def test_variable_kwargs(self):
        r = self.app_.get('/variable_kwargs')
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('variable_kwargs: dummy=dummy, id=3')

    def test_multiple_variable_kwargs_with_json_kwargs(self):
        r = self.app_.post_json(
            '/variable_kwargs',
            {'id': '3', 'dummy': 'dummy'}
        )
        assert r.status_int == 200
        assert r.body == b_('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 == b_(result)

    def test_variable_all(self):
        r = self.app_.get('/variable_all')
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('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 == b_('variable_all: 6, day=12, month=1')

    def test_variable_post_with_json_kwargs(self):
        r = self.app_.post_json(
            '/variable_all/6',
            {'month': '1', 'day': '12'}
        )
        assert r.status_int == 200
        assert r.body == b_('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 == b_('variable_all: 7, day=12, id=seven, month=1')

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

    def test_duplicate_query_parameters_GET(self):
        r = self.app_.get('/variable_kwargs?list=1&list=2')
        l = [u_('1'), u_('2')]
        assert r.status_int == 200
        assert r.body == b_('variable_kwargs: list=%s' % l)

    def test_duplicate_query_parameters_POST(self):
        r = self.app_.post('/variable_kwargs',
                           {'list': ['1', '2']})
        l = [u_('1'), u_('2')]
        assert r.status_int == 200
        assert r.body == b_('variable_kwargs: list=%s' % l)

    def test_duplicate_query_parameters_POST_mixed(self):
        r = self.app_.post('/variable_kwargs?list=1&list=2',
                           {'list': ['3', '4']})
        l = [u_('1'), u_('2'), u_('3'), u_('4')]
        assert r.status_int == 200
        assert r.body == b_('variable_kwargs: list=%s' % l)

    def test_duplicate_query_parameters_POST_mixed_json(self):
        r = self.app_.post('/variable_kwargs?list=1&list=2',
                           {'list': 3})
        l = [u_('1'), u_('2'), u_('3')]
        assert r.status_int == 200
        assert r.body == b_('variable_kwargs: list=%s' % l)

    def test_staticmethod(self):
        r = self.app_.get('/static/foobar')
        assert r.status_int == 200
        assert r.body == b_('id is foobar')

    def test_no_remainder(self):
        try:
            r = self.app_.get('/eater')
            assert r.status_int != 200  # pragma: nocover
        except Exception as ex:
            assert type(ex) == TypeError
            assert ex.args[0] in (
                "eater() takes at least 2 arguments (1 given)",
                "eater() missing 1 required positional argument: 'id'"
            )  # this messaging changed in Python 3.3

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

    def test_two_remainders(self):
        r = self.app_.get('/eater/2/dummy')
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('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 == b_('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 == b_('eater: 6, None, ')

    def test_post_three_remainders(self):
        r = self.app_.post('/eater/7/dummy')
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 == b_('eater: 9, None, day=12, month=1')

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

    def test_post_remainder_with_json_kwargs(self):
        r = self.app_.post_json('/eater/9', {'month': '1', 'day': '12'})
        assert r.status_int == 200
        assert r.body == b_('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 == b_('eater: 10, dummy, day=12, month=1')

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


class TestDefaultErrorRendering(PecanTestCase):

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

        app = TestApp(Pecan(RootController()))
        r = app.get('/', status=404)
        assert r.status_int == 404
        assert r.content_type == 'text/plain'
        assert r.body == b_(HTTPNotFound().plain_body({}))

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

        app = TestApp(Pecan(RootController()))
        r = app.get('/', headers={'Accept': 'text/html'}, status=404)
        assert r.status_int == 404
        assert r.content_type == 'text/html'
        assert r.body == b_(HTTPNotFound().html_body({}))

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

        app = TestApp(Pecan(RootController()))
        r = app.get('/', headers={'Accept': 'application/json'}, status=404)
        assert r.status_int == 404
        json_resp = json.loads(r.body.decode())
        assert json_resp['code'] == 404
        assert json_resp['description'] is None
        assert json_resp['title'] == 'Not Found'
        assert r.content_type == 'application/json'


class TestAbort(PecanTestCase):

    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

    def test_abort_keeps_traceback(self):
        last_exc, last_traceback = None, None

        try:
            try:
                raise Exception('Bottom Exception')
            except:
                abort(404)
        except Exception:
            last_exc, _, last_traceback = sys.exc_info()

        assert last_exc is HTTPNotFound
        assert 'Bottom Exception' in traceback.format_tb(last_traceback)[-1]


class TestScriptName(PecanTestCase):

    def setUp(self):
        super(TestScriptName, self).setUp()
        self.environ = {'SCRIPT_NAME': '/foo'}

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

        app = TestApp(Pecan(RootController()), extra_environ=self.environ)
        r = app.get('/foo/')
        assert r.status_int == 200


class TestRedirect(PecanTestCase):

    @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 == b_('it worked!')

    def test_internal(self):
        r = self.app_.get('/internal')
        assert r.status_int == 200
        assert r.body == b_('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 == b_('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 TestInternalRedirectContext(PecanTestCase):

    @property
    def app_(self):
        class RootController(object):

            @expose()
            def redirect_with_context(self):
                request.context['foo'] = 'bar'
                redirect('/testing')

            @expose()
            def internal_with_context(self):
                request.context['foo'] = 'bar'
                redirect('/testing', internal=True)

            @expose('json')
            def testing(self):
                return request.context

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

    def test_internal_with_request_context(self):
        r = self.app_.get('/internal_with_context')
        assert r.status_int == 200
        assert json.loads(r.body.decode()) == {'foo': 'bar'}

    def test_context_does_not_bleed(self):
        r = self.app_.get('/redirect_with_context').follow()
        assert r.status_int == 200
        assert json.loads(r.body.decode()) == {}


class TestStreamedResponse(PecanTestCase):

    def test_streaming_response(self):

        class RootController(object):
            @expose(content_type='text/plain')
            def test(self, foo):
                if foo == 'stream':
                    # mimic large file
                    contents = six.BytesIO(b_('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 == b_('stream')

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


class TestManualResponse(PecanTestCase):

    def test_manual_response(self):

        class RootController(object):
            @expose()
            def index(self):
                resp = webob.Response(response.environ)
                resp.body = b_('Hello, World!')
                return resp

        app = TestApp(Pecan(RootController()))
        r = app.get('/')
        assert r.body == b_('Hello, World!')


class TestCustomResponseandRequest(PecanTestCase):

    def test_custom_objects(self):

        class CustomRequest(Request):

            @property
            def headers(self):
                headers = super(CustomRequest, self).headers
                headers['X-Custom-Request'] = 'ABC'
                return headers

        class CustomResponse(Response):

            @property
            def headers(self):
                headers = super(CustomResponse, self).headers
                headers['X-Custom-Response'] = 'XYZ'
                return headers

        class RootController(object):
            @expose()
            def index(self):
                return request.headers.get('X-Custom-Request')

        app = TestApp(Pecan(
            RootController(),
            request_cls=CustomRequest,
            response_cls=CustomResponse
        ))
        r = app.get('/')
        assert r.body == b_('ABC')
        assert r.headers.get('X-Custom-Response') == 'XYZ'


class TestThreadLocalState(PecanTestCase):

    def test_thread_local_dir(self):
        """
        Threadlocal proxies for request and response should properly
        proxy ``dir()`` calls to the underlying webob class.
        """
        class RootController(object):
            @expose()
            def index(self):
                assert 'method' in dir(request)
                assert 'status' in dir(response)
                return '/'

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

    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 == b_('/')

        assert state.__dict__ == {}


class TestFileTypeExtensions(PecanTestCase):

    @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 == b_('.html')

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

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

    def test_multi_dot_extension(self):
        r = self.app_.get('/gradient.min.js')
        assert r.status_int == 200
        assert r.body == b_('.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 == b_('/')

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

        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 == b_('SOME VALUE')

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

        app = TestApp(Pecan(RootController(),
                            guess_content_type_from_ext=False))

        r = app.get('/index.html')
        assert r.status_int == 200
        assert r.body == b_('SOME VALUE')


class TestContentTypeByAcceptHeaders(PecanTestCase):

    @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(PecanTestCase):

    @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 b_('index') in r.body

    def test_index(self):
        r = self.app_.get('/index')
        assert r.status_int == 200
        assert b_('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 b_('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 as 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 == b_('foo')

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

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


class TestNonCanonical(PecanTestCase):

    @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 b_('index') in r.body

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

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

    def test_sub_controller_with_trailing(self):
        r = self.app_.get('/sub/')
        assert r.status_int == 200
        assert b_('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 TestDebugging(PecanTestCase):
    def test_debugger_setup(self):
        class RootController(object):
            pass

        def debugger():
            pass

        app_conf = dict(
            debug=True,
            debugger=debugger
        )
        with mock.patch('pecan.middleware.debug.DebugMiddleware') \
                as patched_debug_middleware:
            app = make_app(RootController(), **app_conf)
            args, kwargs = patched_debug_middleware.call_args
            assert kwargs.get('debugger') == debugger

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

        debugger = 'not_a_valid_entry_point'

        app_conf = dict(
            debug=True,
            debugger=debugger
        )
        with mock.patch('pecan.middleware.debug.DebugMiddleware') \
                as patched_debug_middleware:
            app = make_app(RootController(), **app_conf)
            args, kwargs = patched_debug_middleware.call_args
            assert kwargs.get('debugger') is None


class TestLogging(PecanTestCase):

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

        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"

        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(PecanTestCase):

    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 b_("<h1>Hello, Jonathan!</h1>") in r.body

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

        error_msg = None
        try:
            r = app.get('/badtemplate.html')
        except Exception as 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 b_("<h1>Hello, Jonathan!</h1>") in r.body

        r = app.get('/index.html?name=World')
        assert r.status_int == 200
        assert b_("<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 b_("<h1>Hello, Jonathan!</h1>") in r.body

        error_msg = None
        try:
            r = app.get('/badtemplate.html')
        except Exception as 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 b_("<h1>Hello, Jonathan!</h1>") in r.body

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

        error_msg = None
        try:
            r = app.get('/badtemplate.html')
        except Exception as 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.decode()))
        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 b_('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 b_("<h1>Hello, Jonathan!</h1>") in r.body

    def test_default_json_renderer(self):

        class RootController(object):
            @expose()
            def index(self, name='Bill'):
                return dict(name=name)

        app = TestApp(Pecan(RootController(), default_renderer='json'))
        r = app.get('/')
        assert r.status_int == 200
        result = dict(json.loads(r.body.decode()))
        assert result == {'name': 'Bill'}


class TestDeprecatedRouteMethod(PecanTestCase):

    @property
    def app_(self):
        class RootController(object):

            @expose()
            def index(self, *args):
                return ', '.join(args)

            @expose()
            def _route(self, args):
                return self.index, args

        return TestApp(Pecan(RootController()))

    def test_required_argument(self):
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            r = self.app_.get('/foo/bar/')
            assert r.status_int == 200
            assert b_('foo, bar') in r.body


class TestExplicitRoute(PecanTestCase):

    def test_alternate_route(self):

        class RootController(object):

            @expose(route='some-path')
            def some_path(self):
                return 'Hello, World!'

        app = TestApp(Pecan(RootController()))

        r = app.get('/some-path/')
        assert r.status_int == 200
        assert r.body == b_('Hello, World!')

        r = app.get('/some_path/', expect_errors=True)
        assert r.status_int == 404

    def test_manual_route(self):

        class SubController(object):

            @expose(route='some-path')
            def some_path(self):
                return 'Hello, World!'

        class RootController(object):
            pass

        route(RootController, 'some-controller', SubController())

        app = TestApp(Pecan(RootController()))

        r = app.get('/some-controller/some-path/')
        assert r.status_int == 200
        assert r.body == b_('Hello, World!')

        r = app.get('/some-controller/some_path/', expect_errors=True)
        assert r.status_int == 404

    def test_manual_route_conflict(self):

        class SubController(object):
            pass

        class RootController(object):

            @expose()
            def hello(self):
                return 'Hello, World!'

        self.assertRaises(
            RuntimeError,
            route,
            RootController,
            'hello',
            SubController()
        )

    def test_custom_route_on_index(self):

        class RootController(object):

            @expose(route='some-path')
            def index(self):
                return 'Hello, World!'

        app = TestApp(Pecan(RootController()))

        r = app.get('/some-path/')
        assert r.status_int == 200
        assert r.body == b_('Hello, World!')

        r = app.get('/')
        assert r.status_int == 200
        assert r.body == b_('Hello, World!')

        r = app.get('/index/', expect_errors=True)
        assert r.status_int == 404

    def test_custom_route_with_attribute_conflict(self):

        class RootController(object):

            @expose(route='mock')
            def greet(self):
                return 'Hello, World!'

            @expose()
            def mock(self):
                return 'You are not worthy!'

        app = TestApp(Pecan(RootController()))

        self.assertRaises(
            RuntimeError,
            app.get,
            '/mock/'
        )

    def test_conflicting_custom_routes(self):

        class RootController(object):

            @expose(route='testing')
            def foo(self):
                return 'Foo!'

            @expose(route='testing')
            def bar(self):
                return 'Bar!'

        app = TestApp(Pecan(RootController()))

        self.assertRaises(
            RuntimeError,
            app.get,
            '/testing/'
        )

    def test_conflicting_custom_routes_in_subclass(self):

        class BaseController(object):

            @expose(route='testing')
            def foo(self):
                return request.path

        class ChildController(BaseController):
            pass

        class RootController(BaseController):
            child = ChildController()

        app = TestApp(Pecan(RootController()))

        r = app.get('/testing/')
        assert r.body == b_('/testing/')

        r = app.get('/child/testing/')
        assert r.body == b_('/child/testing/')

    def test_custom_route_prohibited_on_lookup(self):
        try:
            class RootController(object):

                @expose(route='some-path')
                def _lookup(self):
                    return 'Hello, World!'
        except ValueError:
            pass
        else:
            raise AssertionError(
                '_lookup cannot be used with a custom path segment'
            )

    def test_custom_route_prohibited_on_default(self):
        try:
            class RootController(object):

                @expose(route='some-path')
                def _default(self):
                    return 'Hello, World!'
        except ValueError:
            pass
        else:
            raise AssertionError(
                '_default cannot be used with a custom path segment'
            )

    def test_custom_route_prohibited_on_route(self):
        try:
            class RootController(object):

                @expose(route='some-path')
                def _route(self):
                    return 'Hello, World!'
        except ValueError:
            pass
        else:
            raise AssertionError(
                '_route cannot be used with a custom path segment'
            )

    def test_custom_route_with_generic_controllers(self):

        class RootController(object):

            @expose(route='some-path', generic=True)
            def foo(self):
                return 'Hello, World!'

            @foo.when(method='POST')
            def handle_post(self):
                return 'POST!'

        app = TestApp(Pecan(RootController()))

        r = app.get('/some-path/')
        assert r.status_int == 200
        assert r.body == b_('Hello, World!')

        r = app.get('/foo/', expect_errors=True)
        assert r.status_int == 404

        r = app.post('/some-path/')
        assert r.status_int == 200
        assert r.body == b_('POST!')

        r = app.post('/foo/', expect_errors=True)
        assert r.status_int == 404

    def test_custom_route_prohibited_on_generic_controllers(self):
        try:
            class RootController(object):

                @expose(generic=True)
                def foo(self):
                    return 'Hello, World!'

                @foo.when(method='POST', route='some-path')
                def handle_post(self):
                    return 'POST!'
        except ValueError:
            pass
        else:
            raise AssertionError(
                'generic controllers cannot be used with a custom path segment'
            )

    def test_invalid_route_arguments(self):
        class C(object):

            def secret(self):
                return {}

        self.assertRaises(TypeError, route)
        self.assertRaises(TypeError, route, 'some-path', lambda x: x)
        self.assertRaises(TypeError, route, 'some-path', C.secret)
        self.assertRaises(TypeError, route, C, {}, C())

        for path in (
            'VARIED-case-PATH',
            'this,custom,path',
            '123-path',
            'path(with-parens)',
            'path;with;semicolons',
            'path:with:colons',
        ):
            handler = C()
            route(C, path, handler)
            assert getattr(C, path, handler)

        self.assertRaises(ValueError, route, C, '/path/', C())
        self.assertRaises(ValueError, route, C, '.', C())
        self.assertRaises(ValueError, route, C, '..', C())
        self.assertRaises(ValueError, route, C, 'path?', C())
        self.assertRaises(ValueError, route, C, 'percent%20encoded', C())