File: test_request.py

package info (click to toggle)
python-webob 1.6.0-1~bpo8%2B1
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 1,184 kB
  • sloc: python: 14,004; makefile: 168
file content (3680 lines) | stat: -rw-r--r-- 142,922 bytes parent folder | download | duplicates (2)
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
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
# -*- coding: utf-8 -*-

import collections
import sys
import unittest
import warnings

from io import (
    BytesIO,
    StringIO,
    )

from webob.compat import (
    bytes_,
    native_,
    text_type,
    text_,
    PY3,
    )

class TestRequestCommon(unittest.TestCase):
    # unit tests of non-bytes-vs-text-specific methods of request object
    def _getTargetClass(self):
        from webob.request import Request
        return Request

    def _makeOne(self, *arg, **kw):
        cls = self._getTargetClass()
        return cls(*arg, **kw)

    def _blankOne(self, *arg, **kw):
        cls = self._getTargetClass()
        return cls.blank(*arg, **kw)

    def test_ctor_environ_getter_raises_WTF(self):
        self.assertRaises(TypeError,
                          self._makeOne, {}, environ_getter=object())

    def test_ctor_wo_environ_raises_WTF(self):
        self.assertRaises(TypeError, self._makeOne, None)

    def test_ctor_w_environ(self):
        environ = {}
        req = self._makeOne(environ)
        self.assertEqual(req.environ, environ)

    def test_ctor_w_non_utf8_charset(self):
        environ = {}
        self.assertRaises(DeprecationWarning, self._makeOne, environ,
                          charset='latin-1')

    def test_scheme(self):
        environ = {'wsgi.url_scheme': 'something:',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.scheme, 'something:')

    def test_body_file_getter(self):
        body = b'input'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT,
            'CONTENT_LENGTH': len(body),
            'REQUEST_METHOD': 'POST',
        }
        req = self._makeOne(environ)
        self.assertTrue(req.body_file is not INPUT)

    def test_body_file_getter_seekable(self):
        body = b'input'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT,
            'CONTENT_LENGTH': len(body),
            'REQUEST_METHOD': 'POST',
            'webob.is_body_seekable': True,
        }
        req = self._makeOne(environ)
        self.assertTrue(req.body_file is INPUT)

    def test_body_file_getter_cache(self):
        body = b'input'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT,
            'CONTENT_LENGTH': len(body),
            'REQUEST_METHOD': 'POST',
        }
        req = self._makeOne(environ)
        self.assertTrue(req.body_file is req.body_file)

    def test_body_file_getter_unreadable(self):
        body = b'input'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT, 'REQUEST_METHOD': 'FOO'}
        req = self._makeOne(environ)
        assert req.body_file_raw is INPUT
        assert req.body_file is not INPUT
        assert req.body_file.read() == b''

    def test_body_file_setter_w_bytes(self):
        req = self._blankOne('/')
        self.assertRaises(DeprecationWarning,
                          setattr, req, 'body_file', b'foo')

    def test_body_file_setter_non_bytes(self):
        BEFORE = BytesIO(b'before')
        AFTER =  BytesIO(b'after')
        environ = {'wsgi.input': BEFORE,
                   'CONTENT_LENGTH': len('before'),
                   'REQUEST_METHOD': 'POST'
                  }
        req = self._makeOne(environ)
        req.body_file = AFTER
        self.assertTrue(req.body_file is AFTER)
        self.assertEqual(req.content_length, None)

    def test_body_file_deleter(self):
        body = b'input'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT,
                   'CONTENT_LENGTH': len(body),
                   'REQUEST_METHOD': 'POST',
                  }
        req = self._makeOne(environ)
        del req.body_file
        self.assertEqual(req.body_file.getvalue(), b'')
        self.assertEqual(req.content_length, 0)

    def test_body_file_raw(self):
        INPUT = BytesIO(b'input')
        environ = {'wsgi.input': INPUT,
                   'CONTENT_LENGTH': len('input'),
                   'REQUEST_METHOD': 'POST',
                  }
        req = self._makeOne(environ)
        self.assertTrue(req.body_file_raw is INPUT)

    def test_body_file_seekable_input_not_seekable(self):
        data = b'input'
        INPUT = BytesIO(data)
        INPUT.seek(1, 0) # consume
        environ = {'wsgi.input': INPUT,
                   'webob.is_body_seekable': False,
                   'CONTENT_LENGTH': len(data)-1,
                   'REQUEST_METHOD': 'POST',
                  }
        req = self._makeOne(environ)
        seekable = req.body_file_seekable
        self.assertTrue(seekable is not INPUT)
        self.assertEqual(seekable.getvalue(), b'nput')

    def test_body_file_seekable_input_is_seekable(self):
        INPUT = BytesIO(b'input')
        INPUT.seek(1, 0) # consume
        environ = {'wsgi.input': INPUT,
                   'webob.is_body_seekable': True,
                   'CONTENT_LENGTH': len('input')-1,
                   'REQUEST_METHOD': 'POST',
                  }
        req = self._makeOne(environ)
        seekable = req.body_file_seekable
        self.assertTrue(seekable is INPUT)

    def test_urlvars_getter_w_paste_key(self):
        environ = {'paste.urlvars': {'foo': 'bar'},
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.urlvars, {'foo': 'bar'})

    def test_urlvars_getter_w_wsgiorg_key(self):
        environ = {'wsgiorg.routing_args': ((), {'foo': 'bar'}),
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.urlvars, {'foo': 'bar'})

    def test_urlvars_getter_wo_keys(self):
        environ = {}
        req = self._makeOne(environ)
        self.assertEqual(req.urlvars, {})
        self.assertEqual(environ['wsgiorg.routing_args'], ((), {}))

    def test_urlvars_setter_w_paste_key(self):
        environ = {'paste.urlvars': {'foo': 'bar'},
                  }
        req = self._makeOne(environ)
        req.urlvars = {'baz': 'bam'}
        self.assertEqual(req.urlvars, {'baz': 'bam'})
        self.assertEqual(environ['paste.urlvars'], {'baz': 'bam'})
        self.assertTrue('wsgiorg.routing_args' not in environ)

    def test_urlvars_setter_w_wsgiorg_key(self):
        environ = {'wsgiorg.routing_args': ((), {'foo': 'bar'}),
                   'paste.urlvars': {'qux': 'spam'},
                  }
        req = self._makeOne(environ)
        req.urlvars = {'baz': 'bam'}
        self.assertEqual(req.urlvars, {'baz': 'bam'})
        self.assertEqual(environ['wsgiorg.routing_args'], ((), {'baz': 'bam'}))
        self.assertTrue('paste.urlvars' not in environ)

    def test_urlvars_setter_wo_keys(self):
        environ = {}
        req = self._makeOne(environ)
        req.urlvars = {'baz': 'bam'}
        self.assertEqual(req.urlvars, {'baz': 'bam'})
        self.assertEqual(environ['wsgiorg.routing_args'], ((), {'baz': 'bam'}))
        self.assertTrue('paste.urlvars' not in environ)

    def test_urlvars_deleter_w_paste_key(self):
        environ = {'paste.urlvars': {'foo': 'bar'},
                  }
        req = self._makeOne(environ)
        del req.urlvars
        self.assertEqual(req.urlvars, {})
        self.assertTrue('paste.urlvars' not in environ)
        self.assertEqual(environ['wsgiorg.routing_args'], ((), {}))

    def test_urlvars_deleter_w_wsgiorg_key_non_empty_tuple(self):
        environ = {'wsgiorg.routing_args': (('a', 'b'), {'foo': 'bar'}),
                   'paste.urlvars': {'qux': 'spam'},
                  }
        req = self._makeOne(environ)
        del req.urlvars
        self.assertEqual(req.urlvars, {})
        self.assertEqual(environ['wsgiorg.routing_args'], (('a', 'b'), {}))
        self.assertTrue('paste.urlvars' not in environ)

    def test_urlvars_deleter_w_wsgiorg_key_empty_tuple(self):
        environ = {'wsgiorg.routing_args': ((), {'foo': 'bar'}),
                   'paste.urlvars': {'qux': 'spam'},
                  }
        req = self._makeOne(environ)
        del req.urlvars
        self.assertEqual(req.urlvars, {})
        self.assertEqual(environ['wsgiorg.routing_args'], ((), {}))
        self.assertTrue('paste.urlvars' not in environ)

    def test_urlvars_deleter_wo_keys(self):
        environ = {}
        req = self._makeOne(environ)
        del req.urlvars
        self.assertEqual(req.urlvars, {})
        self.assertEqual(environ['wsgiorg.routing_args'], ((), {}))
        self.assertTrue('paste.urlvars' not in environ)

    def test_urlargs_getter_w_paste_key(self):
        environ = {'paste.urlvars': {'foo': 'bar'},
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.urlargs, ())

    def test_urlargs_getter_w_wsgiorg_key(self):
        environ = {'wsgiorg.routing_args': (('a', 'b'), {'foo': 'bar'}),
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.urlargs, ('a', 'b'))

    def test_urlargs_getter_wo_keys(self):
        environ = {}
        req = self._makeOne(environ)
        self.assertEqual(req.urlargs, ())
        self.assertTrue('wsgiorg.routing_args' not in environ)

    def test_urlargs_setter_w_paste_key(self):
        environ = {'paste.urlvars': {'foo': 'bar'},
                  }
        req = self._makeOne(environ)
        req.urlargs = ('a', 'b')
        self.assertEqual(req.urlargs, ('a', 'b'))
        self.assertEqual(environ['wsgiorg.routing_args'],
                         (('a', 'b'), {'foo': 'bar'}))
        self.assertTrue('paste.urlvars' not in environ)

    def test_urlargs_setter_w_wsgiorg_key(self):
        environ = {'wsgiorg.routing_args': ((), {'foo': 'bar'}),
                  }
        req = self._makeOne(environ)
        req.urlargs = ('a', 'b')
        self.assertEqual(req.urlargs, ('a', 'b'))
        self.assertEqual(environ['wsgiorg.routing_args'],
                         (('a', 'b'), {'foo': 'bar'}))

    def test_urlargs_setter_wo_keys(self):
        environ = {}
        req = self._makeOne(environ)
        req.urlargs = ('a', 'b')
        self.assertEqual(req.urlargs, ('a', 'b'))
        self.assertEqual(environ['wsgiorg.routing_args'],
                         (('a', 'b'), {}))
        self.assertTrue('paste.urlvars' not in environ)

    def test_urlargs_deleter_w_wsgiorg_key(self):
        environ = {'wsgiorg.routing_args': (('a', 'b'), {'foo': 'bar'}),
                  }
        req = self._makeOne(environ)
        del req.urlargs
        self.assertEqual(req.urlargs, ())
        self.assertEqual(environ['wsgiorg.routing_args'],
                         ((), {'foo': 'bar'}))

    def test_urlargs_deleter_w_wsgiorg_key_empty(self):
        environ = {'wsgiorg.routing_args': ((), {}),
                  }
        req = self._makeOne(environ)
        del req.urlargs
        self.assertEqual(req.urlargs, ())
        self.assertTrue('paste.urlvars' not in environ)
        self.assertTrue('wsgiorg.routing_args' not in environ)

    def test_urlargs_deleter_wo_keys(self):
        environ = {}
        req = self._makeOne(environ)
        del req.urlargs
        self.assertEqual(req.urlargs, ())
        self.assertTrue('paste.urlvars' not in environ)
        self.assertTrue('wsgiorg.routing_args' not in environ)

    def test_cookies_empty_environ(self):
        req = self._makeOne({})
        self.assertEqual(req.cookies, {})

    def test_cookies_is_mutable(self):
        req = self._makeOne({})
        cookies = req.cookies
        cookies['a'] = '1'
        self.assertEqual(req.cookies['a'], '1')

    def test_cookies_w_webob_parsed_cookies_matching_source(self):
        environ = {
            'HTTP_COOKIE': 'a=b',
            'webob._parsed_cookies': ('a=b', {'a': 'b'}),
        }
        req = self._makeOne(environ)
        self.assertEqual(req.cookies, {'a': 'b'})

    def test_cookies_w_webob_parsed_cookies_mismatched_source(self):
        environ = {
            'HTTP_COOKIE': 'a=b',
            'webob._parsed_cookies': ('a=b;c=d', {'a': 'b', 'c': 'd'}),
        }
        req = self._makeOne(environ)
        self.assertEqual(req.cookies, {'a': 'b'})

    def test_set_cookies(self):
        environ = {
            'HTTP_COOKIE': 'a=b',
        }
        req = self._makeOne(environ)
        req.cookies = {'a':'1', 'b': '2'}
        self.assertEqual(req.cookies, {'a': '1', 'b':'2'})
        rcookies = [x.strip() for x in environ['HTTP_COOKIE'].split(';')]
        self.assertEqual(sorted(rcookies), ['a=1', 'b=2'])

    # body
    def test_body_getter(self):
        INPUT = BytesIO(b'input')
        environ = {'wsgi.input': INPUT,
                   'webob.is_body_seekable': True,
                   'CONTENT_LENGTH': len('input'),
                   'REQUEST_METHOD': 'POST'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.body, b'input')
        self.assertEqual(req.content_length, len(b'input'))

    def test_body_setter_None(self):
        INPUT = BytesIO(b'input')
        environ = {'wsgi.input': INPUT,
                   'webob.is_body_seekable': True,
                   'CONTENT_LENGTH': len(b'input'),
                   'REQUEST_METHOD': 'POST'
                  }
        req = self._makeOne(environ)
        req.body = None
        self.assertEqual(req.body, b'')
        self.assertEqual(req.content_length, 0)
        self.assertTrue(req.is_body_seekable)

    def test_body_setter_non_string_raises(self):
        req = self._makeOne({})
        def _test():
            req.body = object()
        self.assertRaises(TypeError, _test)

    def test_body_setter_value(self):
        BEFORE = BytesIO(b'before')
        environ = {'wsgi.input': BEFORE,
                   'webob.is_body_seekable': True,
                   'CONTENT_LENGTH': len('before'),
                   'REQUEST_METHOD': 'POST'
                  }
        req = self._makeOne(environ)
        req.body = b'after'
        self.assertEqual(req.body, b'after')
        self.assertEqual(req.content_length, len(b'after'))
        self.assertTrue(req.is_body_seekable)

    def test_body_deleter_None(self):
        data = b'input'
        INPUT = BytesIO(data)
        environ = {'wsgi.input': INPUT,
                   'webob.is_body_seekable': True,
                   'CONTENT_LENGTH': len(data),
                   'REQUEST_METHOD': 'POST',
                  }
        req = self._makeOne(environ)
        del req.body
        self.assertEqual(req.body, b'')
        self.assertEqual(req.content_length, 0)
        self.assertTrue(req.is_body_seekable)

    # JSON

    def test_json_body(self):
        body = b'{"a":1}'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT, 'CONTENT_LENGTH': str(len(body))}
        req = self._makeOne(environ)
        self.assertEqual(req.json, {"a": 1})
        self.assertEqual(req.json_body, {"a": 1})
        req.json = {"b": 2}
        self.assertEqual(req.body, b'{"b":2}')
        del req.json
        self.assertEqual(req.body, b'')

    def test_json_body_array(self):
        body = b'[{"a":1}, {"b":2}]'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT, 'CONTENT_LENGTH': str(len(body))}
        req = self._makeOne(environ)
        self.assertEqual(req.json, [{"a": 1}, {"b": 2}])
        self.assertEqual(req.json_body, [{"a": 1}, {"b": 2}])
        req.json = [{"b": 2}]
        self.assertEqual(req.body, b'[{"b":2}]')
        del req.json
        self.assertEqual(req.body, b'')

    # .text

    def test_text_body(self):
        body = b'test'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT, 'CONTENT_LENGTH': str(len(body))}
        req = self._makeOne(environ)
        self.assertEqual(req.body, b'test')
        self.assertEqual(req.text, 'test')
        req.text = text_('\u1000')
        self.assertEqual(req.body, '\u1000'.encode(req.charset))
        del req.text
        self.assertEqual(req.body, b'')
        def set_bad_text():
            req.text = 1
        self.assertRaises(TypeError, set_bad_text)

    def test__text_get_without_charset(self):
        body = b'test'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT, 'CONTENT_LENGTH': str(len(body))}
        req = self._makeOne(environ)
        req._charset = ''
        self.assertRaises(AttributeError, getattr, req, 'text')

    def test__text_set_without_charset(self):
        body = b'test'
        INPUT = BytesIO(body)
        environ = {'wsgi.input': INPUT, 'CONTENT_LENGTH': str(len(body))}
        req = self._makeOne(environ)
        req._charset = ''
        self.assertRaises(AttributeError, setattr, req, 'text', 'abc')

    # POST
    def test_POST_not_POST_or_PUT(self):
        from webob.multidict import NoVars
        environ = {'REQUEST_METHOD': 'GET',
                  }
        req = self._makeOne(environ)
        result = req.POST
        self.assertTrue(isinstance(result, NoVars))
        self.assertTrue(result.reason.startswith('Not a form request'))

    def test_POST_existing_cache_hit(self):
        data = b'input'
        INPUT = BytesIO(data)
        environ = {'wsgi.input': INPUT,
                   'REQUEST_METHOD': 'POST',
                   'webob._parsed_post_vars': ({'foo': 'bar'}, INPUT),
                  }
        req = self._makeOne(environ)
        result = req.POST
        self.assertEqual(result, {'foo': 'bar'})

    def test_PUT_missing_content_type(self):
        from webob.multidict import NoVars
        data = b'input'
        INPUT = BytesIO(data)
        environ = {'wsgi.input': INPUT,
                   'REQUEST_METHOD': 'PUT',
                  }
        req = self._makeOne(environ)
        result = req.POST
        self.assertTrue(isinstance(result, NoVars))
        self.assertTrue(result.reason.startswith(
                                        'Not an HTML form submission'))

    def test_PATCH_missing_content_type(self):
        from webob.multidict import NoVars
        data = b'input'
        INPUT = BytesIO(data)
        environ = {'wsgi.input': INPUT,
                   'REQUEST_METHOD': 'PATCH',
                  }
        req = self._makeOne(environ)
        result = req.POST
        self.assertTrue(isinstance(result, NoVars))
        self.assertTrue(result.reason.startswith(
                                        'Not an HTML form submission'))

    def test_POST_missing_content_type(self):
        data = b'var1=value1&var2=value2&rep=1&rep=2'
        INPUT = BytesIO(data)
        environ = {'wsgi.input': INPUT,
                   'REQUEST_METHOD': 'POST',
                   'CONTENT_LENGTH':len(data),
                   'webob.is_body_seekable': True,
                  }
        req = self._makeOne(environ)
        result = req.POST
        self.assertEqual(result['var1'], 'value1')

    def test_POST_json_no_content_type(self):
        data = b'{"password": "last centurion", "email": "rory@wiggy.net"}'
        INPUT = BytesIO(data)
        environ = {'wsgi.input': INPUT,
                   'REQUEST_METHOD': 'POST',
                   'CONTENT_LENGTH':len(data),
                   'webob.is_body_seekable': True,
                  }
        req = self._makeOne(environ)
        r_1 = req.body
        r_2 = req.POST
        r_3 = req.body
        self.assertEqual(r_1, b'{"password": "last centurion", "email": "rory@wiggy.net"}')
        self.assertEqual(r_3, b'{"password": "last centurion", "email": "rory@wiggy.net"}')

    def test_PUT_bad_content_type(self):
        from webob.multidict import NoVars
        data = b'input'
        INPUT = BytesIO(data)
        environ = {'wsgi.input': INPUT,
                   'REQUEST_METHOD': 'PUT',
                   'CONTENT_TYPE': 'text/plain',
                  }
        req = self._makeOne(environ)
        result = req.POST
        self.assertTrue(isinstance(result, NoVars))
        self.assertTrue(result.reason.startswith(
                                        'Not an HTML form submission'))

    def test_POST_multipart(self):
        BODY_TEXT = (
            b'------------------------------deb95b63e42a\n'
            b'Content-Disposition: form-data; name="foo"\n'
            b'\n'
            b'foo\n'
            b'------------------------------deb95b63e42a\n'
            b'Content-Disposition: form-data; name="bar"; filename="bar.txt"\n'
            b'Content-type: application/octet-stream\n'
            b'\n'
            b'these are the contents of the file "bar.txt"\n'
            b'\n'
            b'------------------------------deb95b63e42a--\n')
        INPUT = BytesIO(BODY_TEXT)
        environ = {'wsgi.input': INPUT,
                   'webob.is_body_seekable': True,
                   'REQUEST_METHOD': 'POST',
                   'CONTENT_TYPE': 'multipart/form-data; '
                      'boundary=----------------------------deb95b63e42a',
                   'CONTENT_LENGTH': len(BODY_TEXT),
                  }
        req = self._makeOne(environ)
        result = req.POST
        self.assertEqual(result['foo'], 'foo')
        bar = result['bar']
        self.assertEqual(bar.name, 'bar')
        self.assertEqual(bar.filename, 'bar.txt')
        self.assertEqual(bar.file.read(),
                         b'these are the contents of the file "bar.txt"\n')

    # GET
    def test_GET_reflects_query_string(self):
        environ = {
            'QUERY_STRING': 'foo=123',
        }
        req = self._makeOne(environ)
        result = req.GET
        self.assertEqual(result, {'foo': '123'})
        req.query_string = 'foo=456'
        result = req.GET
        self.assertEqual(result, {'foo': '456'})
        req.query_string = ''
        result = req.GET
        self.assertEqual(result, {})

    def test_GET_updates_query_string(self):
        req = self._makeOne({})
        result = req.query_string
        self.assertEqual(result, '')
        req.GET['foo'] = '123'
        result = req.query_string
        self.assertEqual(result, 'foo=123')
        del req.GET['foo']
        result = req.query_string
        self.assertEqual(result, '')

    # cookies
    def test_cookies_wo_webob_parsed_cookies(self):
        environ = {
            'HTTP_COOKIE': 'a=b',
        }
        req = self._blankOne('/', environ)
        self.assertEqual(req.cookies, {'a': 'b'})

    # copy
    def test_copy_get(self):
        environ = {
            'HTTP_COOKIE': 'a=b',
        }
        req = self._blankOne('/', environ)
        clone = req.copy_get()
        for k, v in req.environ.items():
            if k in ('CONTENT_LENGTH', 'webob.is_body_seekable'):
                self.assertTrue(k not in clone.environ)
            elif k == 'wsgi.input':
                self.assertTrue(clone.environ[k] is not v)
            else:
                self.assertEqual(clone.environ[k], v)

    def test_remove_conditional_headers_accept_encoding(self):
        req = self._blankOne('/')
        req.accept_encoding='gzip,deflate'
        req.remove_conditional_headers()
        self.assertEqual(bool(req.accept_encoding), False)

    def test_remove_conditional_headers_if_modified_since(self):
        from webob.datetime_utils import UTC
        from datetime import datetime
        req = self._blankOne('/')
        req.if_modified_since = datetime(2006, 1, 1, 12, 0, tzinfo=UTC)
        req.remove_conditional_headers()
        self.assertEqual(req.if_modified_since, None)

    def test_remove_conditional_headers_if_none_match(self):
        req = self._blankOne('/')
        req.if_none_match = 'foo'
        assert req.if_none_match
        req.remove_conditional_headers()
        assert not req.if_none_match

    def test_remove_conditional_headers_if_range(self):
        req = self._blankOne('/')
        req.if_range = 'foo, bar'
        req.remove_conditional_headers()
        self.assertEqual(bool(req.if_range), False)

    def test_remove_conditional_headers_range(self):
        req = self._blankOne('/')
        req.range = 'bytes=0-100'
        req.remove_conditional_headers()
        self.assertEqual(req.range, None)

    def test_is_body_readable_POST(self):
        req = self._blankOne('/', environ={'REQUEST_METHOD':'POST'})
        self.assertTrue(req.is_body_readable)

    def test_is_body_readable_PATCH(self):
        req = self._blankOne('/', environ={'REQUEST_METHOD':'PATCH'})
        self.assertTrue(req.is_body_readable)

    def test_is_body_readable_GET(self):
        req = self._blankOne('/', environ={'REQUEST_METHOD':'GET'})
        self.assertFalse(req.is_body_readable)

    def test_is_body_readable_unknown_method_and_content_length(self):
        req = self._blankOne('/', environ={'REQUEST_METHOD':'WTF'})
        req.content_length = 10
        self.assertTrue(req.is_body_readable)

    def test_is_body_readable_special_flag(self):
        req = self._blankOne('/', environ={'REQUEST_METHOD':'WTF',
                                          'webob.is_body_readable': True})
        self.assertTrue(req.is_body_readable)


    # is_body_seekable
    # make_body_seekable
    # copy_body
    # make_tempfile
    # remove_conditional_headers
    # accept
    # accept_charset
    # accept_encoding
    # accept_language
    # authorization

    # cache_control
    def test_cache_control_reflects_environ(self):
        environ = {
            'HTTP_CACHE_CONTROL': 'max-age=5',
        }
        req = self._makeOne(environ)
        result = req.cache_control
        self.assertEqual(result.properties, {'max-age': 5})
        req.environ.update(HTTP_CACHE_CONTROL='max-age=10')
        result = req.cache_control
        self.assertEqual(result.properties, {'max-age': 10})
        req.environ.update(HTTP_CACHE_CONTROL='')
        result = req.cache_control
        self.assertEqual(result.properties, {})

    def test_cache_control_updates_environ(self):
        environ = {}
        req = self._makeOne(environ)
        req.cache_control.max_age = 5
        result = req.environ['HTTP_CACHE_CONTROL']
        self.assertEqual(result, 'max-age=5')
        req.cache_control.max_age = 10
        result = req.environ['HTTP_CACHE_CONTROL']
        self.assertEqual(result, 'max-age=10')
        req.cache_control = None
        result = req.environ['HTTP_CACHE_CONTROL']
        self.assertEqual(result, '')
        del req.cache_control
        self.assertTrue('HTTP_CACHE_CONTROL' not in req.environ)

    def test_cache_control_set_dict(self):
        environ = {}
        req = self._makeOne(environ)
        req.cache_control = {'max-age': 5}
        result = req.cache_control
        self.assertEqual(result.max_age, 5)

    def test_cache_control_set_object(self):
        from webob.cachecontrol import CacheControl
        environ = {}
        req = self._makeOne(environ)
        req.cache_control = CacheControl({'max-age': 5}, type='request')
        result = req.cache_control
        self.assertEqual(result.max_age, 5)

    def test_cache_control_gets_cached(self):
        environ = {}
        req = self._makeOne(environ)
        self.assertTrue(req.cache_control is req.cache_control)

    #if_match
    #if_none_match

    #date
    #if_modified_since
    #if_unmodified_since
    #if_range
    #max_forwards
    #pragma
    #range
    #referer
    #referrer
    #user_agent
    #__repr__
    #__str__
    #from_file

    #call_application
    def test_call_application_calls_application(self):
        environ = {}
        req = self._makeOne(environ)
        def application(environ, start_response):
            start_response('200 OK', [('content-type', 'text/plain')])
            return ['...\n']
        status, headers, output = req.call_application(application)
        self.assertEqual(status, '200 OK')
        self.assertEqual(headers, [('content-type', 'text/plain')])
        self.assertEqual(''.join(output), '...\n')

    def test_call_application_provides_write(self):
        environ = {}
        req = self._makeOne(environ)
        def application(environ, start_response):
            write = start_response('200 OK', [('content-type', 'text/plain')])
            write('...\n')
            return []
        status, headers, output = req.call_application(application)
        self.assertEqual(status, '200 OK')
        self.assertEqual(headers, [('content-type', 'text/plain')])
        self.assertEqual(''.join(output), '...\n')

    def test_call_application_closes_iterable_when_mixed_w_write_calls(self):
        environ = {
            'test._call_application_called_close': False
        }
        req = self._makeOne(environ)
        def application(environ, start_response):
            write = start_response('200 OK', [('content-type', 'text/plain')])
            class AppIter(object):
                def __iter__(self):
                    yield '...\n'
                def close(self):
                    environ['test._call_application_called_close'] = True
            write('...\n')
            return AppIter()
        status, headers, output = req.call_application(application)
        self.assertEqual(''.join(output), '...\n...\n')
        self.assertEqual(environ['test._call_application_called_close'], True)

    def test_call_application_raises_exc_info(self):
        environ = {}
        req = self._makeOne(environ)
        def application(environ, start_response):
            try:
                raise RuntimeError('OH NOES')
            except:
                exc_info = sys.exc_info()
            start_response('200 OK',
                           [('content-type', 'text/plain')], exc_info)
            return ['...\n']
        self.assertRaises(RuntimeError, req.call_application, application)

    def test_call_application_returns_exc_info(self):
        environ = {}
        req = self._makeOne(environ)
        def application(environ, start_response):
            try:
                raise RuntimeError('OH NOES')
            except:
                exc_info = sys.exc_info()
            start_response('200 OK',
                           [('content-type', 'text/plain')], exc_info)
            return ['...\n']
        status, headers, output, exc_info = req.call_application(
            application, True)
        self.assertEqual(status, '200 OK')
        self.assertEqual(headers, [('content-type', 'text/plain')])
        self.assertEqual(''.join(output), '...\n')
        self.assertEqual(exc_info[0], RuntimeError)

    #get_response
    def test_blank__method_subtitution(self):
        request = self._blankOne('/', environ={'REQUEST_METHOD': 'PUT'})
        self.assertEqual(request.method, 'PUT')

        request = self._blankOne(
            '/', environ={'REQUEST_METHOD': 'PUT'}, POST={})
        self.assertEqual(request.method, 'PUT')

        request = self._blankOne(
            '/', environ={'REQUEST_METHOD': 'HEAD'}, POST={})
        self.assertEqual(request.method, 'POST')

    def test_blank__ctype_in_env(self):
        request = self._blankOne(
            '/', environ={'CONTENT_TYPE': 'application/json'})
        self.assertEqual(request.content_type, 'application/json')
        self.assertEqual(request.method, 'GET')

        request = self._blankOne(
            '/', environ={'CONTENT_TYPE': 'application/json'}, POST='')
        self.assertEqual(request.content_type, 'application/json')
        self.assertEqual(request.method, 'POST')

    def test_blank__ctype_in_headers(self):
        request = self._blankOne(
            '/', headers={'Content-type': 'application/json'})
        self.assertEqual(request.content_type, 'application/json')
        self.assertEqual(request.method, 'GET')

        request = self._blankOne(
            '/', headers={'Content-Type': 'application/json'}, POST='')
        self.assertEqual(request.content_type, 'application/json')
        self.assertEqual(request.method, 'POST')

    def test_blank__ctype_as_kw(self):
        request = self._blankOne('/', content_type='application/json')
        self.assertEqual(request.content_type, 'application/json')
        self.assertEqual(request.method, 'GET')

        request = self._blankOne('/', content_type='application/json',
                                         POST='')
        self.assertEqual(request.content_type, 'application/json')
        self.assertEqual(request.method, 'POST')

    def test_blank__str_post_data_for_unsupported_ctype(self):
        self.assertRaises(ValueError,
                          self._blankOne,
                          '/', content_type='application/json', POST={})

    def test_blank__post_urlencoded(self):
        from webob.multidict import MultiDict
        POST = MultiDict()
        POST["first"] = 1
        POST["second"] = 2

        request = self._blankOne('/', POST=POST)
        self.assertEqual(request.method, 'POST')
        self.assertEqual(request.content_type,
                         'application/x-www-form-urlencoded')
        self.assertEqual(request.body, b'first=1&second=2')
        self.assertEqual(request.content_length, 16)

    def test_blank__post_multipart(self):
        from webob.multidict import MultiDict
        POST = MultiDict()
        POST["first"] = "1"
        POST["second"] = "2"


        request = self._blankOne('/',
                                 POST=POST,
                                 content_type='multipart/form-data; '
                                              'boundary=boundary')
        self.assertEqual(request.method, 'POST')
        self.assertEqual(request.content_type, 'multipart/form-data')
        expected = (
            b'--boundary\r\n'
            b'Content-Disposition: form-data; name="first"\r\n\r\n'
            b'1\r\n'
            b'--boundary\r\n'
            b'Content-Disposition: form-data; name="second"\r\n\r\n'
            b'2\r\n'
            b'--boundary--')
        self.assertEqual(request.body, expected)
        self.assertEqual(request.content_length, 139)

    def test_blank__post_files(self):
        import cgi
        from webob.request import _get_multipart_boundary
        from webob.multidict import MultiDict
        POST = MultiDict()
        POST["first"] = ('filename1', BytesIO(b'1'))
        POST["second"] = ('filename2', '2')
        POST["third"] = "3"
        request = self._blankOne('/', POST=POST)
        self.assertEqual(request.method, 'POST')
        self.assertEqual(request.content_type, 'multipart/form-data')
        boundary = bytes_(
            _get_multipart_boundary(request.headers['content-type']))
        body_norm = request.body.replace(boundary, b'boundary')
        expected = (
            b'--boundary\r\n'
            b'Content-Disposition: form-data; name="first"; '
                    b'filename="filename1"\r\n\r\n'
            b'1\r\n'
            b'--boundary\r\n'
            b'Content-Disposition: form-data; name="second"; '
                    b'filename="filename2"\r\n\r\n'
            b'2\r\n'
            b'--boundary\r\n'
            b'Content-Disposition: form-data; name="third"\r\n\r\n'
            b'3\r\n'
            b'--boundary--'
            )
        self.assertEqual(body_norm, expected)
        self.assertEqual(request.content_length, 294)
        self.assertTrue(isinstance(request.POST['first'], cgi.FieldStorage))
        self.assertTrue(isinstance(request.POST['second'], cgi.FieldStorage))
        self.assertEqual(request.POST['first'].value, b'1')
        self.assertEqual(request.POST['second'].value, b'2')
        self.assertEqual(request.POST['third'], '3')

    def test_blank__post_file_w_wrong_ctype(self):
        self.assertRaises(
            ValueError, self._blankOne, '/', POST={'first':('filename1', '1')},
            content_type='application/x-www-form-urlencoded')

    #from_bytes
    def test_from_bytes_extra_data(self):
        _test_req_copy = _test_req.replace(
            b'Content-Type',
            b'Content-Length: 337\r\nContent-Type')
        cls = self._getTargetClass()
        self.assertRaises(ValueError, cls.from_bytes,
                _test_req_copy+b'EXTRA!')

    #as_bytes
    def test_as_bytes_skip_body(self):
        cls = self._getTargetClass()
        req = cls.from_bytes(_test_req)
        body = req.as_bytes(skip_body=True)
        self.assertEqual(body.count(b'\r\n\r\n'), 0)
        self.assertEqual(req.as_bytes(skip_body=337), req.as_bytes())
        body = req.as_bytes(337-1).split(b'\r\n\r\n', 1)[1]
        self.assertEqual(body, b'<body skipped (len=337)>')


class TestBaseRequest(unittest.TestCase):
    # tests of methods of a base request which are encoding-specific
    def _getTargetClass(self):
        from webob.request import BaseRequest
        return BaseRequest

    def _makeOne(self, *arg, **kw):
        cls = self._getTargetClass()
        return cls(*arg, **kw)

    def _blankOne(self, *arg, **kw):
        cls = self._getTargetClass()
        return cls.blank(*arg, **kw)

    def test_method(self):
        environ = {'REQUEST_METHOD': 'OPTIONS',
                  }
        req = self._makeOne(environ)
        result = req.method
        self.assertEqual(result.__class__, str)
        self.assertEqual(result, 'OPTIONS')

    def test_http_version(self):
        environ = {'SERVER_PROTOCOL': '1.1',
                  }
        req = self._makeOne(environ)
        result = req.http_version
        self.assertEqual(result, '1.1')

    def test_script_name(self):
        environ = {'SCRIPT_NAME': '/script',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.script_name, '/script')

    def test_path_info(self):
        environ = {'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.path_info, '/path/info')

    def test_content_length_getter(self):
        environ = {'CONTENT_LENGTH': '1234',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.content_length, 1234)

    def test_content_length_setter_w_str(self):
        environ = {'CONTENT_LENGTH': '1234',
                  }
        req = self._makeOne(environ)
        req.content_length = '3456'
        self.assertEqual(req.content_length, 3456)

    def test_remote_user(self):
        environ = {'REMOTE_USER': 'phred',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.remote_user, 'phred')

    def test_remote_addr(self):
        environ = {'REMOTE_ADDR': '1.2.3.4',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.remote_addr, '1.2.3.4')

    def test_query_string(self):
        environ = {'QUERY_STRING': 'foo=bar&baz=bam',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.query_string, 'foo=bar&baz=bam')

    def test_server_name(self):
        environ = {'SERVER_NAME': 'somehost.tld',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.server_name, 'somehost.tld')

    def test_server_port_getter(self):
        environ = {'SERVER_PORT': '6666',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.server_port, 6666)

    def test_server_port_setter_with_string(self):
        environ = {'SERVER_PORT': '6666',
                  }
        req = self._makeOne(environ)
        req.server_port = '6667'
        self.assertEqual(req.server_port, 6667)

    def test_uscript_name(self):
        environ = {'SCRIPT_NAME': '/script',
                  }
        req = self._makeOne(environ)
        self.assertTrue(isinstance(req.uscript_name, text_type))
        self.assertEqual(req.uscript_name, '/script')

    def test_upath_info(self):
        environ = {'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        self.assertTrue(isinstance(req.upath_info, text_type))
        self.assertEqual(req.upath_info, '/path/info')

    def test_upath_info_set_unicode(self):
        environ = {'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        req.upath_info = text_('/another')
        self.assertTrue(isinstance(req.upath_info, text_type))
        self.assertEqual(req.upath_info, '/another')

    def test_content_type_getter_no_parameters(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.content_type, 'application/xml+foobar')

    def test_content_type_getter_w_parameters(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar;charset="utf8"',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.content_type, 'application/xml+foobar')

    def test_content_type_setter_w_None(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar;charset="utf8"',
                  }
        req = self._makeOne(environ)
        req.content_type = None
        self.assertEqual(req.content_type, '')
        self.assertTrue('CONTENT_TYPE' not in environ)

    def test_content_type_setter_existing_paramter_no_new_paramter(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar;charset="utf8"',
                  }
        req = self._makeOne(environ)
        req.content_type = 'text/xml'
        self.assertEqual(req.content_type, 'text/xml')
        self.assertEqual(environ['CONTENT_TYPE'], 'text/xml;charset="utf8"')

    def test_content_type_deleter_clears_environ_value(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar;charset="utf8"',
                  }
        req = self._makeOne(environ)
        del req.content_type
        self.assertEqual(req.content_type, '')
        self.assertTrue('CONTENT_TYPE' not in environ)

    def test_content_type_deleter_no_environ_value(self):
        environ = {}
        req = self._makeOne(environ)
        del req.content_type
        self.assertEqual(req.content_type, '')
        self.assertTrue('CONTENT_TYPE' not in environ)

    def test_headers_getter(self):
        CONTENT_TYPE = 'application/xml+foobar;charset="utf8"'
        environ = {'CONTENT_TYPE': CONTENT_TYPE,
                   'CONTENT_LENGTH': '123',
                  }
        req = self._makeOne(environ)
        headers = req.headers
        self.assertEqual(headers,
                        {'Content-Type': CONTENT_TYPE,
                         'Content-Length': '123'})

    def test_headers_setter(self):
        CONTENT_TYPE = 'application/xml+foobar;charset="utf8"'
        environ = {'CONTENT_TYPE': CONTENT_TYPE,
                   'CONTENT_LENGTH': '123',
                  }
        req = self._makeOne(environ)
        req.headers = {'Qux': 'Spam'}
        self.assertEqual(req.headers,
                        {'Qux': 'Spam'})
        self.assertEqual(environ, {'HTTP_QUX': 'Spam'})

    def test_no_headers_deleter(self):
        CONTENT_TYPE = 'application/xml+foobar;charset="utf8"'
        environ = {'CONTENT_TYPE': CONTENT_TYPE,
                   'CONTENT_LENGTH': '123',
                  }
        req = self._makeOne(environ)
        def _test():
            del req.headers
        self.assertRaises(AttributeError, _test)

    def test_client_addr_xff_singleval(self):
        environ = {
                   'HTTP_X_FORWARDED_FOR': '192.168.1.1',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, '192.168.1.1')

    def test_client_addr_xff_multival(self):
        environ = {
                   'HTTP_X_FORWARDED_FOR': '192.168.1.1, 192.168.1.2',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, '192.168.1.1')

    def test_client_addr_prefers_xff(self):
        environ = {'REMOTE_ADDR': '192.168.1.2',
                   'HTTP_X_FORWARDED_FOR': '192.168.1.1',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, '192.168.1.1')

    def test_client_addr_no_xff(self):
        environ = {'REMOTE_ADDR': '192.168.1.2',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, '192.168.1.2')

    def test_client_addr_no_xff_no_remote_addr(self):
        environ = {}
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, None)

    def test_host_port_w_http_host_and_no_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '80')

    def test_host_port_w_http_host_and_standard_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com:80',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '80')

    def test_host_port_w_http_host_and_oddball_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com:8888',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '8888')

    def test_host_port_w_http_host_https_and_no_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '443')

    def test_host_port_w_http_host_https_and_standard_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com:443',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '443')

    def test_host_port_w_http_host_https_and_oddball_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com:8888',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '8888')

    def test_host_port_wo_http_host(self):
        environ = {'wsgi.url_scheme': 'https',
                   'SERVER_PORT': '4333',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '4333')

    def test_host_url_w_http_host_and_no_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'http://example.com')

    def test_host_url_w_http_host_and_standard_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com:80',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'http://example.com')

    def test_host_url_w_http_host_and_oddball_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com:8888',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'http://example.com:8888')

    def test_host_url_w_http_host_https_and_no_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'https://example.com')

    def test_host_url_w_http_host_https_and_standard_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com:443',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'https://example.com')

    def test_host_url_w_http_host_https_and_oddball_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com:4333',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'https://example.com:4333')

    def test_host_url_wo_http_host(self):
        environ = {'wsgi.url_scheme': 'https',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '4333',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'https://example.com:4333')

    def test_application_url(self):
        inst = self._blankOne('/%C3%AB')
        inst.script_name = text_(b'/\xc3\xab', 'utf-8')
        app_url = inst.application_url
        self.assertEqual(app_url.__class__, str)
        self.assertEqual(app_url, 'http://localhost/%C3%AB')

    def test_path_url(self):
        inst = self._blankOne('/%C3%AB')
        inst.script_name = text_(b'/\xc3\xab', 'utf-8')
        app_url = inst.path_url
        self.assertEqual(app_url.__class__, str)
        self.assertEqual(app_url, 'http://localhost/%C3%AB/%C3%AB')

    def test_path(self):
        inst = self._blankOne('/%C3%AB')
        inst.script_name = text_(b'/\xc3\xab', 'utf-8')
        app_url = inst.path
        self.assertEqual(app_url.__class__, str)
        self.assertEqual(app_url, '/%C3%AB/%C3%AB')

    def test_path_qs_no_qs(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.path_qs, '/script/path/info')

    def test_path_qs_w_qs(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.path_qs, '/script/path/info?foo=bar&baz=bam')

    def test_url_no_qs(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.url, 'http://example.com/script/path/info')

    def test_url_w_qs(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.url,
                         'http://example.com/script/path/info?foo=bar&baz=bam')

    def test_relative_url_to_app_true_wo_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.relative_url('other/page', True),
                         'http://example.com/script/other/page')

    def test_relative_url_to_app_true_w_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.relative_url('/other/page', True),
                         'http://example.com/other/page')

    def test_relative_url_to_app_false_other_w_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.relative_url('/other/page', False),
                         'http://example.com/other/page')

    def test_relative_url_to_app_false_other_wo_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.relative_url('other/page', False),
                         'http://example.com/script/path/other/page')

    def test_path_info_pop_empty(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop()
        self.assertEqual(popped, None)
        self.assertEqual(environ['SCRIPT_NAME'], '/script')

    def test_path_info_pop_just_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop()
        self.assertEqual(popped, '')
        self.assertEqual(environ['SCRIPT_NAME'], '/script/')
        self.assertEqual(environ['PATH_INFO'], '')

    def test_path_info_pop_non_empty_no_pattern(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop()
        self.assertEqual(popped, 'path')
        self.assertEqual(environ['SCRIPT_NAME'], '/script/path')
        self.assertEqual(environ['PATH_INFO'], '/info')

    def test_path_info_pop_non_empty_w_pattern_miss(self):
        import re
        PATTERN = re.compile('miss')
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop(PATTERN)
        self.assertEqual(popped, None)
        self.assertEqual(environ['SCRIPT_NAME'], '/script')
        self.assertEqual(environ['PATH_INFO'], '/path/info')

    def test_path_info_pop_non_empty_w_pattern_hit(self):
        import re
        PATTERN = re.compile('path')
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop(PATTERN)
        self.assertEqual(popped, 'path')
        self.assertEqual(environ['SCRIPT_NAME'], '/script/path')
        self.assertEqual(environ['PATH_INFO'], '/info')

    def test_path_info_pop_skips_empty_elements(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '//path/info',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop()
        self.assertEqual(popped, 'path')
        self.assertEqual(environ['SCRIPT_NAME'], '/script//path')
        self.assertEqual(environ['PATH_INFO'], '/info')

    def test_path_info_peek_empty(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '',
                  }
        req = self._makeOne(environ)
        peeked = req.path_info_peek()
        self.assertEqual(peeked, None)
        self.assertEqual(environ['SCRIPT_NAME'], '/script')
        self.assertEqual(environ['PATH_INFO'], '')

    def test_path_info_peek_just_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/',
                  }
        req = self._makeOne(environ)
        peeked = req.path_info_peek()
        self.assertEqual(peeked, '')
        self.assertEqual(environ['SCRIPT_NAME'], '/script')
        self.assertEqual(environ['PATH_INFO'], '/')

    def test_path_info_peek_non_empty(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path',
                  }
        req = self._makeOne(environ)
        peeked = req.path_info_peek()
        self.assertEqual(peeked, 'path')
        self.assertEqual(environ['SCRIPT_NAME'], '/script')
        self.assertEqual(environ['PATH_INFO'], '/path')

    def test_is_xhr_no_header(self):
        req = self._makeOne({})
        self.assertTrue(not req.is_xhr)

    def test_is_xhr_header_miss(self):
        environ = {'HTTP_X_REQUESTED_WITH': 'notAnXMLHTTPRequest'}
        req = self._makeOne(environ)
        self.assertTrue(not req.is_xhr)

    def test_is_xhr_header_hit(self):
        environ = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
        req = self._makeOne(environ)
        self.assertTrue(req.is_xhr)

    # host
    def test_host_getter_w_HTTP_HOST(self):
        environ = {'HTTP_HOST': 'example.com:8888'}
        req = self._makeOne(environ)
        self.assertEqual(req.host, 'example.com:8888')

    def test_host_getter_wo_HTTP_HOST(self):
        environ = {'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '8888'}
        req = self._makeOne(environ)
        self.assertEqual(req.host, 'example.com:8888')

    def test_host_setter(self):
        environ = {}
        req = self._makeOne(environ)
        req.host = 'example.com:8888'
        self.assertEqual(environ['HTTP_HOST'], 'example.com:8888')

    def test_host_deleter_hit(self):
        environ = {'HTTP_HOST': 'example.com:8888'}
        req = self._makeOne(environ)
        del req.host
        self.assertTrue('HTTP_HOST' not in environ)

    def test_host_deleter_miss(self):
        environ = {}
        req = self._makeOne(environ)
        del req.host # doesn't raise

    def test_domain_nocolon(self):
        environ = {'HTTP_HOST':'example.com'}
        req = self._makeOne(environ)
        self.assertEqual(req.domain, 'example.com')

    def test_domain_withcolon(self):
        environ = {'HTTP_HOST':'example.com:8888'}
        req = self._makeOne(environ)
        self.assertEqual(req.domain, 'example.com')

    def test_encget_raises_without_default(self):
        inst = self._makeOne({})
        self.assertRaises(KeyError, inst.encget, 'a')

    def test_encget_doesnt_raises_with_default(self):
        inst = self._makeOne({})
        self.assertEqual(inst.encget('a', None), None)

    def test_encget_with_encattr(self):
        if PY3:
            val = b'\xc3\xab'.decode('latin-1')
        else:
            val = b'\xc3\xab'
        inst = self._makeOne({'a':val})
        self.assertEqual(inst.encget('a', encattr='url_encoding'),
                         text_(b'\xc3\xab', 'utf-8'))

    def test_encget_with_encattr_latin_1(self):
        if PY3:
            val = b'\xc3\xab'.decode('latin-1')
        else:
            val = b'\xc3\xab'
        inst = self._makeOne({'a':val})
        inst.my_encoding = 'latin-1'
        self.assertEqual(inst.encget('a', encattr='my_encoding'),
                         text_(b'\xc3\xab', 'latin-1'))

    def test_encget_no_encattr(self):
        if PY3:
            val = b'\xc3\xab'.decode('latin-1')
        else:
            val = b'\xc3\xab'
        inst = self._makeOne({'a':val})
        self.assertEqual(inst.encget('a'), val)

    def test_relative_url(self):
        inst = self._blankOne('/%C3%AB/c')
        result = inst.relative_url('a')
        self.assertEqual(result.__class__, str)
        self.assertEqual(result, 'http://localhost/%C3%AB/a')

    def test_header_getter(self):
        if PY3:
            val = b'abc'.decode('latin-1')
        else:
            val = b'abc'
        inst = self._makeOne({'HTTP_FLUB':val})
        result = inst.headers['Flub']
        self.assertEqual(result.__class__, str)
        self.assertEqual(result, 'abc')

    def test_json_body(self):
        inst = self._makeOne({})
        inst.body = b'{"a":"1"}'
        self.assertEqual(inst.json_body, {'a':'1'})
        inst.json_body = {'a': '2'}
        self.assertEqual(inst.body, b'{"a":"2"}')

    def test_host_get(self):
        inst = self._makeOne({'HTTP_HOST':'example.com'})
        result = inst.host
        self.assertEqual(result.__class__, str)
        self.assertEqual(result, 'example.com')

    def test_host_get_w_no_http_host(self):
        inst = self._makeOne({'SERVER_NAME':'example.com', 'SERVER_PORT':'80'})
        result = inst.host
        self.assertEqual(result.__class__, str)
        self.assertEqual(result, 'example.com:80')

class TestLegacyRequest(unittest.TestCase):
    # tests of methods of a bytesrequest which deal with http environment vars
    def _getTargetClass(self):
        from webob.request import LegacyRequest
        return LegacyRequest

    def _makeOne(self, *arg, **kw):
        cls = self._getTargetClass()
        return cls(*arg, **kw)

    def _blankOne(self, *arg, **kw):
        cls = self._getTargetClass()
        return cls.blank(*arg, **kw)

    def test_method(self):
        environ = {'REQUEST_METHOD': 'OPTIONS',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.method, 'OPTIONS')

    def test_http_version(self):
        environ = {'SERVER_PROTOCOL': '1.1',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.http_version, '1.1')

    def test_script_name(self):
        environ = {'SCRIPT_NAME': '/script',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.script_name, '/script')

    def test_path_info(self):
        environ = {'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.path_info, '/path/info')

    def test_content_length_getter(self):
        environ = {'CONTENT_LENGTH': '1234',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.content_length, 1234)

    def test_content_length_setter_w_str(self):
        environ = {'CONTENT_LENGTH': '1234',
                  }
        req = self._makeOne(environ)
        req.content_length = '3456'
        self.assertEqual(req.content_length, 3456)

    def test_remote_user(self):
        environ = {'REMOTE_USER': 'phred',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.remote_user, 'phred')

    def test_remote_addr(self):
        environ = {'REMOTE_ADDR': '1.2.3.4',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.remote_addr, '1.2.3.4')

    def test_query_string(self):
        environ = {'QUERY_STRING': 'foo=bar&baz=bam',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.query_string, 'foo=bar&baz=bam')

    def test_server_name(self):
        environ = {'SERVER_NAME': 'somehost.tld',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.server_name, 'somehost.tld')

    def test_server_port_getter(self):
        environ = {'SERVER_PORT': '6666',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.server_port, 6666)

    def test_server_port_setter_with_string(self):
        environ = {'SERVER_PORT': '6666',
                  }
        req = self._makeOne(environ)
        req.server_port = '6667'
        self.assertEqual(req.server_port, 6667)

    def test_uscript_name(self):
        environ = {'SCRIPT_NAME': '/script',
                  }
        req = self._makeOne(environ)
        self.assertTrue(isinstance(req.uscript_name, text_type))
        result = req.uscript_name
        self.assertEqual(result.__class__, text_type)
        self.assertEqual(result, '/script')

    def test_upath_info(self):
        environ = {'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        result = req.upath_info
        self.assertTrue(isinstance(result, text_type))
        self.assertEqual(result, '/path/info')

    def test_upath_info_set_unicode(self):
        environ = {'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        req.upath_info = text_('/another')
        result = req.upath_info
        self.assertTrue(isinstance(result, text_type))
        self.assertEqual(result, '/another')

    def test_content_type_getter_no_parameters(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.content_type, 'application/xml+foobar')

    def test_content_type_getter_w_parameters(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar;charset="utf8"',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.content_type, 'application/xml+foobar')

    def test_content_type_setter_w_None(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar;charset="utf8"',
                  }
        req = self._makeOne(environ)
        req.content_type = None
        self.assertEqual(req.content_type, '')
        self.assertTrue('CONTENT_TYPE' not in environ)

    def test_content_type_setter_existing_paramter_no_new_paramter(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar;charset="utf8"',
                  }
        req = self._makeOne(environ)
        req.content_type = 'text/xml'
        self.assertEqual(req.content_type, 'text/xml')
        self.assertEqual(environ['CONTENT_TYPE'], 'text/xml;charset="utf8"')

    def test_content_type_deleter_clears_environ_value(self):
        environ = {'CONTENT_TYPE': 'application/xml+foobar;charset="utf8"',
                  }
        req = self._makeOne(environ)
        del req.content_type
        self.assertEqual(req.content_type, '')
        self.assertTrue('CONTENT_TYPE' not in environ)

    def test_content_type_deleter_no_environ_value(self):
        environ = {}
        req = self._makeOne(environ)
        del req.content_type
        self.assertEqual(req.content_type, '')
        self.assertTrue('CONTENT_TYPE' not in environ)

    def test_headers_getter(self):
        CONTENT_TYPE = 'application/xml+foobar;charset="utf8"'
        environ = {'CONTENT_TYPE': CONTENT_TYPE,
                   'CONTENT_LENGTH': '123',
                  }
        req = self._makeOne(environ)
        headers = req.headers
        self.assertEqual(headers,
                        {'Content-Type':CONTENT_TYPE,
                         'Content-Length': '123'})

    def test_headers_setter(self):
        CONTENT_TYPE = 'application/xml+foobar;charset="utf8"'
        environ = {'CONTENT_TYPE': CONTENT_TYPE,
                   'CONTENT_LENGTH': '123',
                  }
        req = self._makeOne(environ)
        req.headers = {'Qux': 'Spam'}
        self.assertEqual(req.headers,
                        {'Qux': 'Spam'})
        self.assertEqual(environ['HTTP_QUX'], native_('Spam'))
        self.assertEqual(environ, {'HTTP_QUX': 'Spam'})

    def test_no_headers_deleter(self):
        CONTENT_TYPE = 'application/xml+foobar;charset="utf8"'
        environ = {'CONTENT_TYPE': CONTENT_TYPE,
                   'CONTENT_LENGTH': '123',
                  }
        req = self._makeOne(environ)
        def _test():
            del req.headers
        self.assertRaises(AttributeError, _test)

    def test_client_addr_xff_singleval(self):
        environ = {
                   'HTTP_X_FORWARDED_FOR': '192.168.1.1',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, '192.168.1.1')

    def test_client_addr_xff_multival(self):
        environ = {
                   'HTTP_X_FORWARDED_FOR': '192.168.1.1, 192.168.1.2',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, '192.168.1.1')

    def test_client_addr_prefers_xff(self):
        environ = {'REMOTE_ADDR': '192.168.1.2',
                   'HTTP_X_FORWARDED_FOR': '192.168.1.1',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, '192.168.1.1')

    def test_client_addr_no_xff(self):
        environ = {'REMOTE_ADDR': '192.168.1.2',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, '192.168.1.2')

    def test_client_addr_no_xff_no_remote_addr(self):
        environ = {}
        req = self._makeOne(environ)
        self.assertEqual(req.client_addr, None)

    def test_host_port_w_http_host_and_no_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '80')

    def test_host_port_w_http_host_and_standard_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com:80',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '80')

    def test_host_port_w_http_host_and_oddball_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com:8888',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '8888')

    def test_host_port_w_http_host_https_and_no_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '443')

    def test_host_port_w_http_host_https_and_standard_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com:443',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '443')

    def test_host_port_w_http_host_https_and_oddball_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com:8888',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '8888')

    def test_host_port_wo_http_host(self):
        environ = {'wsgi.url_scheme': 'https',
                   'SERVER_PORT': '4333',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_port, '4333')

    def test_host_url_w_http_host_and_no_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'http://example.com')

    def test_host_url_w_http_host_and_standard_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com:80',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'http://example.com')

    def test_host_url_w_http_host_and_oddball_port(self):
        environ = {'wsgi.url_scheme': 'http',
                   'HTTP_HOST': 'example.com:8888',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'http://example.com:8888')

    def test_host_url_w_http_host_https_and_no_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'https://example.com')

    def test_host_url_w_http_host_https_and_standard_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com:443',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'https://example.com')

    def test_host_url_w_http_host_https_and_oddball_port(self):
        environ = {'wsgi.url_scheme': 'https',
                   'HTTP_HOST': 'example.com:4333',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'https://example.com:4333')

    def test_host_url_wo_http_host(self):
        environ = {'wsgi.url_scheme': 'https',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '4333',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.host_url, 'https://example.com:4333')

    def test_application_url(self):
        inst = self._blankOne('/%C3%AB')
        inst.script_name = b'/\xc3\xab'
        app_url = inst.application_url
        if PY3: # pragma: no cover
            # this result is why you should not use legacyrequest under py 3
            self.assertEqual(app_url, 'http://localhost/%C3%83%C2%AB')
        else:
            self.assertEqual(app_url, 'http://localhost/%C3%AB')

    def test_path_url(self):
        inst = self._blankOne('/%C3%AB')
        inst.script_name = b'/\xc3\xab'
        result = inst.path_url
        if PY3: # pragma: no cover
            # this result is why you should not use legacyrequest under py 3
            self.assertEqual(result,
                             'http://localhost/%C3%83%C2%AB/%C3%83%C2%AB')
        else:
            self.assertEqual(result, 'http://localhost/%C3%AB/%C3%AB')

    def test_path(self):
        inst = self._blankOne('/%C3%AB')
        inst.script_name = b'/\xc3\xab'
        result = inst.path
        if PY3: # pragma: no cover
            # this result is why you should not use legacyrequest under py 3
            self.assertEqual(result, '/%C3%83%C2%AB/%C3%83%C2%AB')
        else:
            self.assertEqual(result, '/%C3%AB/%C3%AB')

    def test_path_qs_no_qs(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.path_qs, '/script/path/info')

    def test_path_qs_w_qs(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.path_qs, '/script/path/info?foo=bar&baz=bam')

    def test_url_no_qs(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.url, 'http://example.com/script/path/info')

    def test_url_w_qs(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.url,
                         'http://example.com/script/path/info?foo=bar&baz=bam')

    def test_relative_url_to_app_true_wo_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.relative_url('other/page', True),
                         'http://example.com/script/other/page')

    def test_relative_url_to_app_true_w_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.relative_url('/other/page', True),
                         'http://example.com/other/page')

    def test_relative_url_to_app_false_other_w_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.relative_url('/other/page', False),
                         'http://example.com/other/page')

    def test_relative_url_to_app_false_other_wo_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                   'QUERY_STRING': 'foo=bar&baz=bam'
                  }
        req = self._makeOne(environ)
        self.assertEqual(req.relative_url('other/page', False),
                         'http://example.com/script/path/other/page')

    def test_path_info_pop_empty(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop()
        self.assertEqual(popped, None)
        self.assertEqual(environ['SCRIPT_NAME'], '/script')

    def test_path_info_pop_just_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop()
        self.assertEqual(popped, '')
        self.assertEqual(environ['SCRIPT_NAME'], '/script/')
        self.assertEqual(environ['PATH_INFO'], '')

    def test_path_info_pop_non_empty_no_pattern(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop()
        self.assertEqual(popped, 'path')
        self.assertEqual(environ['SCRIPT_NAME'], '/script/path')
        self.assertEqual(environ['PATH_INFO'], '/info')

    def test_path_info_pop_non_empty_w_pattern_miss(self):
        import re
        PATTERN = re.compile('miss')
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop(PATTERN)
        self.assertEqual(popped, None)
        self.assertEqual(environ['SCRIPT_NAME'], '/script')
        self.assertEqual(environ['PATH_INFO'], '/path/info')

    def test_path_info_pop_non_empty_w_pattern_hit(self):
        import re
        PATTERN = re.compile('path')
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path/info',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop(PATTERN)
        self.assertEqual(popped, 'path')
        self.assertEqual(environ['SCRIPT_NAME'], '/script/path')
        self.assertEqual(environ['PATH_INFO'], '/info')

    def test_path_info_pop_skips_empty_elements(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '//path/info',
                  }
        req = self._makeOne(environ)
        popped = req.path_info_pop()
        self.assertEqual(popped, 'path')
        self.assertEqual(environ['SCRIPT_NAME'], '/script//path')
        self.assertEqual(environ['PATH_INFO'], '/info')

    def test_path_info_peek_empty(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '',
                  }
        req = self._makeOne(environ)
        peeked = req.path_info_peek()
        self.assertEqual(peeked, None)
        self.assertEqual(environ['SCRIPT_NAME'], '/script')
        self.assertEqual(environ['PATH_INFO'], '')

    def test_path_info_peek_just_leading_slash(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/',
                  }
        req = self._makeOne(environ)
        peeked = req.path_info_peek()
        self.assertEqual(peeked, '')
        self.assertEqual(environ['SCRIPT_NAME'], '/script')
        self.assertEqual(environ['PATH_INFO'], '/')

    def test_path_info_peek_non_empty(self):
        environ = {'wsgi.url_scheme': 'http',
                   'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '80',
                   'SCRIPT_NAME': '/script',
                   'PATH_INFO': '/path',
                  }
        req = self._makeOne(environ)
        peeked = req.path_info_peek()
        self.assertEqual(peeked, 'path')
        self.assertEqual(environ['SCRIPT_NAME'], '/script')
        self.assertEqual(environ['PATH_INFO'], '/path')

    def test_is_xhr_no_header(self):
        req = self._makeOne({})
        self.assertTrue(not req.is_xhr)

    def test_is_xhr_header_miss(self):
        environ = {'HTTP_X_REQUESTED_WITH': 'notAnXMLHTTPRequest'}
        req = self._makeOne(environ)
        self.assertTrue(not req.is_xhr)

    def test_is_xhr_header_hit(self):
        environ = {'HTTP_X_REQUESTED_WITH': 'XMLHttpRequest'}
        req = self._makeOne(environ)
        self.assertTrue(req.is_xhr)

    # host
    def test_host_getter_w_HTTP_HOST(self):
        environ = {'HTTP_HOST': 'example.com:8888'}
        req = self._makeOne(environ)
        self.assertEqual(req.host, 'example.com:8888')

    def test_host_getter_wo_HTTP_HOST(self):
        environ = {'SERVER_NAME': 'example.com',
                   'SERVER_PORT': '8888'}
        req = self._makeOne(environ)
        self.assertEqual(req.host, 'example.com:8888')

    def test_host_setter(self):
        environ = {}
        req = self._makeOne(environ)
        req.host = 'example.com:8888'
        self.assertEqual(environ['HTTP_HOST'], 'example.com:8888')

    def test_host_deleter_hit(self):
        environ = {'HTTP_HOST': 'example.com:8888'}
        req = self._makeOne(environ)
        del req.host
        self.assertTrue('HTTP_HOST' not in environ)

    def test_host_deleter_miss(self):
        environ = {}
        req = self._makeOne(environ)
        del req.host # doesn't raise

    def test_encget_raises_without_default(self):
        inst = self._makeOne({})
        self.assertRaises(KeyError, inst.encget, 'a')

    def test_encget_doesnt_raises_with_default(self):
        inst = self._makeOne({})
        self.assertEqual(inst.encget('a', None), None)

    def test_encget_with_encattr(self):
        if PY3:
            val = b'\xc3\xab'.decode('latin-1')
        else:
            val = b'\xc3\xab'
        inst = self._makeOne({'a':val})
        self.assertEqual(inst.encget('a', encattr='url_encoding'),
                         native_(b'\xc3\xab', 'latin-1'))

    def test_encget_no_encattr(self):
        if PY3:
            val = b'\xc3\xab'.decode('latin-1')
        else:
            val = b'\xc3\xab'
        inst = self._makeOne({'a':val})
        self.assertEqual(inst.encget('a'), native_(b'\xc3\xab', 'latin-1'))

    def test_relative_url(self):
        inst = self._blankOne('/%C3%AB/c')
        result = inst.relative_url('a')
        if PY3: # pragma: no cover
            # this result is why you should not use legacyrequest under py 3
            self.assertEqual(result, 'http://localhost/%C3%83%C2%AB/a')
        else:
            self.assertEqual(result, 'http://localhost/%C3%AB/a')

    def test_header_getter(self):
        if PY3:
            val = b'abc'.decode('latin-1')
        else:
            val = b'abc'
        inst = self._makeOne({'HTTP_FLUB':val})
        result = inst.headers['Flub']
        self.assertEqual(result, 'abc')

    def test_json_body(self):
        inst = self._makeOne({})
        inst.body = b'{"a":"1"}'
        self.assertEqual(inst.json_body, {'a':'1'})

    def test_host_get_w_http_host(self):
        inst = self._makeOne({'HTTP_HOST':'example.com'})
        result = inst.host
        self.assertEqual(result, 'example.com')

    def test_host_get_w_no_http_host(self):
        inst = self._makeOne({'SERVER_NAME':'example.com', 'SERVER_PORT':'80'})
        result = inst.host
        self.assertEqual(result, 'example.com:80')

class TestRequestConstructorWarnings(unittest.TestCase):
    def _getTargetClass(self):
        from webob.request import Request
        return Request

    def _makeOne(self, *arg, **kw):
        cls = self._getTargetClass()
        return cls(*arg, **kw)

    def test_ctor_w_unicode_errors(self):
        with warnings.catch_warnings(record=True) as w:
            # still emit if warning was printed previously
            warnings.simplefilter('always')
            self._makeOne({}, unicode_errors=True)
        self.assertEqual(len(w), 1)

    def test_ctor_w_decode_param_names(self):
        with warnings.catch_warnings(record=True) as w:
            # still emit if warning was printed previously
            warnings.simplefilter('always')
            self._makeOne({}, decode_param_names=True)
        self.assertEqual(len(w), 1)

class TestRequestWithAdhocAttr(unittest.TestCase):
    def _blankOne(self, *arg, **kw):
        from webob.request import Request
        return Request.blank(*arg, **kw)

    def test_adhoc_attrs_set(self):
        req = self._blankOne('/')
        req.foo = 1
        self.assertEqual(req.environ['webob.adhoc_attrs'], {'foo': 1})

    def test_adhoc_attrs_set_nonadhoc(self):
        req = self._blankOne('/', environ={'webob.adhoc_attrs':{}})
        req.request_body_tempfile_limit = 1
        self.assertEqual(req.environ['webob.adhoc_attrs'], {})

    def test_adhoc_attrs_get(self):
        req = self._blankOne('/', environ={'webob.adhoc_attrs': {'foo': 1}})
        self.assertEqual(req.foo, 1)

    def test_adhoc_attrs_get_missing(self):
        req = self._blankOne('/')
        self.assertRaises(AttributeError, getattr, req, 'some_attr')

    def test_adhoc_attrs_del(self):
        req = self._blankOne('/', environ={'webob.adhoc_attrs': {'foo': 1}})
        del req.foo
        self.assertEqual(req.environ['webob.adhoc_attrs'], {})

    def test_adhoc_attrs_del_missing(self):
        req = self._blankOne('/')
        self.assertRaises(AttributeError, delattr, req, 'some_attr')

class TestRequest_functional(unittest.TestCase):
    # functional tests of request
    def _getTargetClass(self):
        from webob.request import Request
        return Request

    def _makeOne(self, *arg, **kw):
        cls = self._getTargetClass()
        return cls(*arg, **kw)

    def _blankOne(self, *arg, **kw):
        cls = self._getTargetClass()
        return cls.blank(*arg, **kw)

    def test_gets(self):
        request = self._blankOne('/')
        status, headerlist, app_iter = request.call_application(simpleapp)
        self.assertEqual(status, '200 OK')
        res = b''.join(app_iter)
        self.assertTrue(b'Hello' in res)
        self.assertTrue(b"MultiDict([])" in res)
        self.assertTrue(b"post is <NoVars: Not a form request>" in res)

    def test_gets_with_query_string(self):
        request = self._blankOne('/?name=george')
        status, headerlist, app_iter = request.call_application(simpleapp)
        res = b''.join(app_iter)
        self.assertTrue(b"MultiDict" in res)
        self.assertTrue(b"'name'" in res)
        self.assertTrue(b"'george'" in res)
        self.assertTrue(b"Val is " in res)

    def test_language_parsing1(self):
        request = self._blankOne('/')
        status, headerlist, app_iter = request.call_application(simpleapp)
        res = b''.join(app_iter)
        self.assertTrue(b"The languages are: []" in res)

    def test_language_parsing2(self):
        request = self._blankOne(
            '/', headers={'Accept-Language': 'da, en-gb;q=0.8'})
        status, headerlist, app_iter = request.call_application(simpleapp)
        res = b''.join(app_iter)
        self.assertTrue(b"languages are: ['da', 'en-gb']" in res)

    def test_language_parsing3(self):
        request = self._blankOne(
            '/',
            headers={'Accept-Language': 'en-gb;q=0.8, da'})
        status, headerlist, app_iter = request.call_application(simpleapp)
        res = b''.join(app_iter)
        self.assertTrue(b"languages are: ['da', 'en-gb']" in res)

    def test_mime_parsing1(self):
        request = self._blankOne(
            '/',
            headers={'Accept':'text/html'})
        status, headerlist, app_iter = request.call_application(simpleapp)
        res = b''.join(app_iter)
        self.assertTrue(b"accepttypes is: text/html" in res)

    def test_mime_parsing2(self):
        request = self._blankOne(
            '/',
            headers={'Accept':'application/xml'})
        status, headerlist, app_iter = request.call_application(simpleapp)
        res = b''.join(app_iter)
        self.assertTrue(b"accepttypes is: application/xml" in res)

    def test_mime_parsing3(self):
        request = self._blankOne(
            '/',
            headers={'Accept':'application/xml,*/*'})
        status, headerlist, app_iter = request.call_application(simpleapp)
        res = b''.join(app_iter)
        self.assertTrue(b"accepttypes is: application/xml" in res)

    def test_accept_best_match(self):
        accept = self._blankOne('/').accept
        self.assertTrue(not accept)
        self.assertTrue(not self._blankOne('/', headers={'Accept': ''}).accept)
        req = self._blankOne('/', headers={'Accept':'text/plain'})
        self.assertTrue(req.accept)
        req = self._blankOne('/', accept=['*/*','text/*'])
        self.assertEqual(
            req.accept.best_match(['application/x-foo', 'text/plain']),
            'text/plain')
        self.assertEqual(
            req.accept.best_match(['text/plain', 'application/x-foo']),
            'text/plain')
        req = self._blankOne('/', accept=['text/plain', 'message/*'])
        self.assertEqual(
            req.accept.best_match(['message/x-foo', 'text/plain']),
            'text/plain')
        self.assertEqual(
            req.accept.best_match(['text/plain', 'message/x-foo']),
            'text/plain')

    def test_from_mimeparse(self):
        # http://mimeparse.googlecode.com/svn/trunk/mimeparse.py
        supported = ['application/xbel+xml', 'application/xml']
        tests = [('application/xbel+xml', 'application/xbel+xml'),
                ('application/xbel+xml; q=1', 'application/xbel+xml'),
                ('application/xml; q=1', 'application/xml'),
                ('application/*; q=1', 'application/xbel+xml'),
                ('*/*', 'application/xbel+xml')]

        for accept, get in tests:
            req = self._blankOne('/', headers={'Accept':accept})
            self.assertEqual(req.accept.best_match(supported), get)

        supported = ['application/xbel+xml', 'text/xml']
        tests = [('text/*;q=0.5,*/*; q=0.1', 'text/xml'),
                ('text/html,application/atom+xml; q=0.9', None)]

        for accept, get in tests:
            req = self._blankOne('/', headers={'Accept':accept})
            self.assertEqual(req.accept.best_match(supported), get)

        supported = ['application/json', 'text/html']
        tests = [
            ('application/json, text/javascript, */*', 'application/json'),
            ('application/json, text/html;q=0.9', 'application/json'),
        ]

        for accept, get in tests:
            req = self._blankOne('/', headers={'Accept':accept})
            self.assertEqual(req.accept.best_match(supported), get)

        offered = ['image/png', 'application/xml']
        tests = [
            ('image/png', 'image/png'),
            ('image/*', 'image/png'),
            ('image/*, application/xml', 'application/xml'),
        ]

        for accept, get in tests:
            req = self._blankOne('/', accept=accept)
            self.assertEqual(req.accept.best_match(offered), get)

    def test_headers(self):
        headers = {
            'If-Modified-Since': 'Sat, 29 Oct 1994 19:43:31 GMT',
            'Cookie': 'var1=value1',
            'User-Agent': 'Mozilla 4.0 (compatible; MSIE)',
            'If-None-Match': '"etag001", "etag002"',
            'X-Requested-With': 'XMLHttpRequest',
            }
        request = self._blankOne('/?foo=bar&baz', headers=headers)
        status, headerlist, app_iter = request.call_application(simpleapp)
        res = b''.join(app_iter)
        for thing in (
            'if_modified_since: ' +
                'datetime.datetime(1994, 10, 29, 19, 43, 31, tzinfo=UTC)',
            "user_agent: 'Mozilla",
            'is_xhr: True',
            "cookies is <RequestCookies",
            'var1',
            'value1',
            'params is NestedMultiDict',
            'foo',
            'bar',
            'baz',
            'if_none_match: <ETag etag001 or etag002>',
            ):
            self.assertTrue(bytes_(thing) in res)

    def test_bad_cookie(self):
        req = self._blankOne('/')
        req.headers['Cookie'] = '070-it-:><?0'
        self.assertEqual(req.cookies, {})
        req.headers['Cookie'] = 'foo=bar'
        self.assertEqual(req.cookies, {'foo': 'bar'})
        req.headers['Cookie'] = '...'
        self.assertEqual(req.cookies, {})
        req.headers['Cookie'] = '=foo'
        self.assertEqual(req.cookies, {})
        req.headers['Cookie'] = ('dismiss-top=6; CP=null*; '
            'PHPSESSID=0a539d42abc001cdc762809248d4beed; a=42')
        self.assertEqual(req.cookies, {
            'CP':           'null*',
            'PHPSESSID':    '0a539d42abc001cdc762809248d4beed',
            'a':            '42',
            'dismiss-top':  '6'
        })
        req.headers['Cookie'] = 'fo234{=bar blub=Blah'
        self.assertEqual(req.cookies, {'blub': 'Blah'})

    def test_cookie_quoting(self):
        req = self._blankOne('/')
        req.headers['Cookie'] = 'foo="?foo"; Path=/'
        self.assertEqual(req.cookies, {'foo': '?foo'})

    def test_path_quoting(self):
        path = '/:@&+$,/bar'
        req = self._blankOne(path)
        self.assertEqual(req.path, path)
        self.assertTrue(req.url.endswith(path))

    def test_params(self):
        req = self._blankOne('/?a=1&b=2')
        req.method = 'POST'
        req.body = b'b=3'
        self.assertEqual(list(req.params.items()),
                         [('a', '1'), ('b', '2'), ('b', '3')])
        new_params = req.params.copy()
        self.assertEqual(list(new_params.items()),
                         [('a', '1'), ('b', '2'), ('b', '3')])
        new_params['b'] = '4'
        self.assertEqual(list(new_params.items()), [('a', '1'), ('b', '4')])
        # The key name is \u1000:
        req = self._blankOne('/?%E1%80%80=x')
        val = text_type(b'\u1000', 'unicode_escape')
        self.assertTrue(val in list(req.GET.keys()))
        self.assertEqual(req.GET[val], 'x')

    def test_copy_body(self):
        req = self._blankOne('/', method='POST', body=b'some text',
                            request_body_tempfile_limit=1)
        old_body_file = req.body_file_raw
        req.copy_body()
        self.assertTrue(req.body_file_raw is not old_body_file)
        req = self._blankOne('/', method='POST',
                body_file=UnseekableInput(b'0123456789'), content_length=10)
        self.assertTrue(not hasattr(req.body_file_raw, 'seek'))
        old_body_file = req.body_file_raw
        req.make_body_seekable()
        self.assertTrue(req.body_file_raw is not old_body_file)
        self.assertEqual(req.body, b'0123456789')
        old_body_file = req.body_file
        req.make_body_seekable()
        self.assertTrue(req.body_file_raw is old_body_file)
        self.assertTrue(req.body_file is old_body_file)

    def test_already_consumed_stream(self):
        from webob.request import Request
        body = 'something'.encode('latin-1')
        content_type = 'application/x-www-form-urlencoded; charset=latin-1'
        environ = {
            'wsgi.input': BytesIO(body),
            'CONTENT_TYPE': content_type,
            'CONTENT_LENGTH': len(body),
            'REQUEST_METHOD': 'POST'
        }
        req = Request(environ)
        req = req.decode('latin-1')
        req2 = Request(environ)
        req2 = req2.decode('latin-1')
        self.assertEqual(body, req2.body)

    def test_broken_seek(self):
        # copy() should work even when the input has a broken seek method
        req = self._blankOne('/', method='POST',
                body_file=UnseekableInputWithSeek(b'0123456789'),
                content_length=10)
        self.assertTrue(hasattr(req.body_file_raw, 'seek'))
        self.assertRaises(IOError, req.body_file_raw.seek, 0)
        old_body_file = req.body_file
        req2 = req.copy()
        self.assertTrue(req2.body_file_raw is req2.body_file is not
                        old_body_file)
        self.assertEqual(req2.body, b'0123456789')

    def test_set_body(self):
        req = self._blankOne('/', method='PUT', body=b'foo')
        self.assertTrue(req.is_body_seekable)
        self.assertEqual(req.body, b'foo')
        self.assertEqual(req.content_length, 3)
        del req.body
        self.assertEqual(req.body, b'')
        self.assertEqual(req.content_length, 0)

    def test_broken_clen_header(self):
        # if the UA sends "content_length: ..' header (the name is wrong)
        # it should not break the req.headers.items()
        req = self._blankOne('/')
        req.environ['HTTP_CONTENT_LENGTH'] = '0'
        req.headers.items()

    def test_nonstr_keys(self):
        # non-string env keys shouldn't break req.headers
        req = self._blankOne('/')
        req.environ[1] = 1
        req.headers.items()

    def test_authorization(self):
        req = self._blankOne('/')
        req.authorization = 'Digest uri="/?a=b"'
        self.assertEqual(req.authorization, ('Digest', {'uri': '/?a=b'}))

    def test_as_bytes(self):
        req = self._blankOne('http://example.com:8000/test.html?params')
        inp = BytesIO(req.as_bytes())
        self.equal_req(req, inp)

        req = self._blankOne('http://example.com/test2')
        req.method = 'POST'
        req.body = b'test=example'
        inp = BytesIO(req.as_bytes())
        self.equal_req(req, inp)

    def test_as_text(self):
        req = self._blankOne('http://example.com:8000/test.html?params')
        inp = StringIO(req.as_text())
        self.equal_req(req, inp)

        req = self._blankOne('http://example.com/test2')
        req.method = 'POST'
        req.body = b'test=example'
        inp = StringIO(req.as_text())
        self.equal_req(req, inp)

    def test_req_kw_none_val(self):
        request = self._makeOne({}, content_length=None)
        self.assertTrue('content-length' not in request.headers)
        self.assertTrue('content-type' not in request.headers)

    def test_env_keys(self):
        req = self._blankOne('/')
        # SCRIPT_NAME can be missing
        del req.environ['SCRIPT_NAME']
        self.assertEqual(req.script_name, '')
        self.assertEqual(req.uscript_name, '')

    def test_repr_nodefault(self):
        from webob.request import NoDefault
        nd = NoDefault
        self.assertEqual(repr(nd), '(No Default)')

    def test_request_noenviron_param(self):
        # Environ is a a mandatory not null param in Request.
        self.assertRaises(TypeError, self._makeOne, environ=None)

    def test_unexpected_kw(self):
        # Passed an attr in kw that does not exist in the class, should
        # raise an error
        # Passed an attr in kw that does exist in the class, should be ok
        self.assertRaises(TypeError,
                          self._makeOne, {'a':1}, this_does_not_exist=1)
        r = self._makeOne({'a':1}, server_name='127.0.0.1')
        self.assertEqual(getattr(r, 'server_name', None), '127.0.0.1')

    def test_conttype_set_del(self):
        # Deleting content_type attr from a request should update the
        # environ dict
        # Assigning content_type should replace first option of the environ
        # dict
        r = self._makeOne({'a':1}, **{'content_type':'text/html'})
        self.assertTrue('CONTENT_TYPE' in r.environ)
        self.assertTrue(hasattr(r, 'content_type'))
        del r.content_type
        self.assertTrue('CONTENT_TYPE' not in r.environ)
        a = self._makeOne({'a':1},
                content_type='charset=utf-8;application/atom+xml;type=entry')
        self.assertTrue(a.environ['CONTENT_TYPE']==
                'charset=utf-8;application/atom+xml;type=entry')
        a.content_type = 'charset=utf-8'
        self.assertTrue(a.environ['CONTENT_TYPE']==
                'charset=utf-8;application/atom+xml;type=entry')

    def test_headers2(self):
        # Setting headers in init and later with a property, should update
        # the info
        headers = {'Host': 'www.example.com',
                'Accept-Language': 'en-us,en;q=0.5',
                'Accept-Encoding': 'gzip,deflate',
                'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
                'Keep-Alive': '115',
                'Connection': 'keep-alive',
                'Cache-Control': 'max-age=0'}
        r = self._makeOne({'a':1}, headers=headers)
        for i in headers.keys():
            self.assertTrue(i in r.headers and
                'HTTP_'+i.upper().replace('-', '_') in r.environ)
        r.headers = {'Server':'Apache'}
        self.assertEqual(set(r.environ.keys()), set(['a',  'HTTP_SERVER']))

    def test_host_url(self):
        # Request has a read only property host_url that combines several
        # keys to create a host_url
        a = self._makeOne(
            {'wsgi.url_scheme':'http'}, **{'host':'www.example.com'})
        self.assertEqual(a.host_url, 'http://www.example.com')
        a = self._makeOne(
            {'wsgi.url_scheme':'http'}, **{'server_name':'localhost',
                                                'server_port':5000})
        self.assertEqual(a.host_url, 'http://localhost:5000')
        a = self._makeOne(
            {'wsgi.url_scheme':'https'}, **{'server_name':'localhost',
                                            'server_port':443})
        self.assertEqual(a.host_url, 'https://localhost')

    def test_path_info_p(self):
        # Peek path_info to see what's coming
        # Pop path_info until there's nothing remaining
        a = self._makeOne({'a':1}, **{'path_info':'/foo/bar','script_name':''})
        self.assertEqual(a.path_info_peek(), 'foo')
        self.assertEqual(a.path_info_pop(), 'foo')
        self.assertEqual(a.path_info_peek(), 'bar')
        self.assertEqual(a.path_info_pop(), 'bar')
        self.assertEqual(a.path_info_peek(), None)
        self.assertEqual(a.path_info_pop(), None)

    def test_urlvars_property(self):
        # Testing urlvars setter/getter/deleter
        a = self._makeOne({'wsgiorg.routing_args':((),{'x':'y'}),
                           'paste.urlvars':{'test':'value'}})
        a.urlvars = {'hello':'world'}
        self.assertTrue('paste.urlvars' not in a.environ)
        self.assertEqual(a.environ['wsgiorg.routing_args'],
                         ((), {'hello':'world'}))
        del a.urlvars
        self.assertTrue('wsgiorg.routing_args' not in a.environ)
        a = self._makeOne({'paste.urlvars':{'test':'value'}})
        self.assertEqual(a.urlvars, {'test':'value'})
        a.urlvars = {'hello':'world'}
        self.assertEqual(a.environ['paste.urlvars'], {'hello':'world'})
        del a.urlvars
        self.assertTrue('paste.urlvars' not in a.environ)

    def test_urlargs_property(self):
        # Testing urlargs setter/getter/deleter
        a = self._makeOne({'paste.urlvars':{'test':'value'}})
        self.assertEqual(a.urlargs, ())
        a.urlargs = {'hello':'world'}
        self.assertEqual(a.environ['wsgiorg.routing_args'],
                         ({'hello':'world'}, {'test':'value'}))
        a = self._makeOne({'a':1})
        a.urlargs = {'hello':'world'}
        self.assertEqual(a.environ['wsgiorg.routing_args'],
                         ({'hello':'world'}, {}))
        del a.urlargs
        self.assertTrue('wsgiorg.routing_args' not in a.environ)

    def test_host_property(self):
        # Testing host setter/getter/deleter
        a = self._makeOne({'wsgi.url_scheme':'http'}, server_name='localhost',
                          server_port=5000)
        self.assertEqual(a.host, "localhost:5000")
        a.host = "localhost:5000"
        self.assertTrue('HTTP_HOST' in a.environ)
        del a.host
        self.assertTrue('HTTP_HOST' not in a.environ)

    def test_body_property(self):
        # Testing body setter/getter/deleter plus making sure body has a
        # seek method
        #a = Request({'a':1}, **{'CONTENT_LENGTH':'?'})
        # I cannot think of a case where somebody would put anything else
        # than a # numerical value in CONTENT_LENGTH, Google didn't help
        # either
        #self.assertEqual(a.body, '')
        # I need to implement a not seekable stringio like object.

        import string
        class DummyIO(object):
            def __init__(self, txt):
                self.txt = txt
            def read(self, n=-1):
                return self.txt[0:n]
        cls = self._getTargetClass()
        limit = cls.request_body_tempfile_limit
        len_strl = limit // len(string.ascii_letters) + 1
        r = self._makeOne(
            {'a':1, 'REQUEST_METHOD': 'POST'},
            body_file=DummyIO(bytes_(string.ascii_letters) * len_strl))
        self.assertEqual(len(r.body), len(string.ascii_letters*len_strl)-1)
        self.assertRaises(TypeError,
                          setattr, r, 'body', text_('hello world'))
        r.body = None
        self.assertEqual(r.body, b'')
        r = self._makeOne({'a':1}, method='PUT', body_file=DummyIO(
            bytes_(string.ascii_letters)))
        self.assertTrue(not hasattr(r.body_file_raw, 'seek'))
        r.make_body_seekable()
        self.assertTrue(hasattr(r.body_file_raw, 'seek'))
        r = self._makeOne({'a':1}, method='PUT',
                          body_file=BytesIO(bytes_(string.ascii_letters)))
        self.assertTrue(hasattr(r.body_file_raw, 'seek'))
        r.make_body_seekable()
        self.assertTrue(hasattr(r.body_file_raw, 'seek'))

    def test_repr_invalid(self):
        # If we have an invalid WSGI environ, the repr should tell us.
        req = self._makeOne({'CONTENT_LENGTH':'0', 'body':''})
        self.assertTrue(repr(req).endswith('(invalid WSGI environ)>'))

    def test_from_garbage_file(self):
        # If we pass a file with garbage to from_file method it should
        # raise an error plus missing bits in from_file method
        io = BytesIO(b'hello world')

        cls = self._getTargetClass()
        self.assertRaises(ValueError, cls.from_file, io)
        val_file = BytesIO(
            b"GET /webob/ HTTP/1.1\n"
            b"Host: pythonpaste.org\n"
            b"User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13)"
            b"Gecko/20101206 Ubuntu/10.04 (lucid) Firefox/3.6.13\n"
            b"Accept: "
            b"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;"
            b"q=0.8\n"
            b"Accept-Language: en-us,en;q=0.5\n"
            b"Accept-Encoding: gzip,deflate\n"
            b"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n"
            # duplicate on purpose
            b"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\n"
            b"Keep-Alive: 115\n"
            b"Connection: keep-alive\n"
        )
        req = cls.from_file(val_file)
        self.assertTrue(isinstance(req, cls))
        self.assertTrue(not repr(req).endswith('(invalid WSGI environ)>'))
        val_file = BytesIO(
            b"GET /webob/ HTTP/1.1\n"
            b"Host pythonpaste.org\n"
        )
        self.assertRaises(ValueError, cls.from_file, val_file)

    def test_from_file_patch(self):
        cls = self._getTargetClass()
        req = cls.from_bytes(_test_req_patch)
        self.assertEqual("PATCH", req.method)
        self.assertTrue(len(req.body))
        self.assertTrue(req.body in _test_req_patch)
        self.assertEqual(_test_req_patch, req.as_bytes())

    def test_from_bytes(self):
        # A valid request without a Content-Length header should still read
        # the full body.
        # Also test parity between as_string and from_bytes / from_file.
        import cgi
        cls = self._getTargetClass()
        req = cls.from_bytes(_test_req)
        self.assertTrue(isinstance(req, cls))
        self.assertTrue(not repr(req).endswith('(invalid WSGI environ)>'))
        self.assertTrue('\n' not in req.http_version or '\r' in
                        req.http_version)
        self.assertTrue(',' not in req.host)
        self.assertTrue(req.content_length is not None)
        self.assertEqual(req.content_length, 337)
        self.assertTrue(b'foo' in req.body)
        bar_contents = b"these are the contents of the file 'bar.txt'\r\n"
        self.assertTrue(bar_contents in req.body)
        self.assertEqual(req.params['foo'], 'foo')
        bar = req.params['bar']
        self.assertTrue(isinstance(bar, cgi.FieldStorage))
        self.assertEqual(bar.type, 'application/octet-stream')
        bar.file.seek(0)
        self.assertEqual(bar.file.read(), bar_contents)
        # out should equal contents, except for the Content-Length header,
        # so insert that.
        _test_req_copy = _test_req.replace(
            b'Content-Type',
            b'Content-Length: 337\r\nContent-Type'
            )
        self.assertEqual(req.as_bytes(), _test_req_copy)

        req2 = cls.from_bytes(_test_req2)
        self.assertTrue('host' not in req2.headers)
        self.assertEqual(req2.as_bytes(), _test_req2.rstrip())
        self.assertRaises(ValueError, cls.from_bytes, _test_req2 + b'xx')

    def test_from_text(self):
        import cgi
        cls = self._getTargetClass()
        req = cls.from_text(text_(_test_req, 'utf-8'))
        self.assertTrue(isinstance(req, cls))
        self.assertTrue(not repr(req).endswith('(invalid WSGI environ)>'))
        self.assertTrue('\n' not in req.http_version or '\r' in
                        req.http_version)
        self.assertTrue(',' not in req.host)
        self.assertTrue(req.content_length is not None)
        self.assertEqual(req.content_length, 337)
        self.assertTrue(b'foo' in req.body)
        bar_contents = b"these are the contents of the file 'bar.txt'\r\n"
        self.assertTrue(bar_contents in req.body)
        self.assertEqual(req.params['foo'], 'foo')
        bar = req.params['bar']
        self.assertTrue(isinstance(bar, cgi.FieldStorage))
        self.assertEqual(bar.type, 'application/octet-stream')
        bar.file.seek(0)
        self.assertEqual(bar.file.read(), bar_contents)
        # out should equal contents, except for the Content-Length header,
        # so insert that.
        _test_req_copy = _test_req.replace(
            b'Content-Type',
            b'Content-Length: 337\r\nContent-Type'
            )
        self.assertEqual(req.as_bytes(), _test_req_copy)

        req2 = cls.from_bytes(_test_req2)
        self.assertTrue('host' not in req2.headers)
        self.assertEqual(req2.as_bytes(), _test_req2.rstrip())
        self.assertRaises(ValueError, cls.from_bytes, _test_req2 + b'xx')

    def test_blank(self):
        # BaseRequest.blank class method
        self.assertRaises(ValueError, self._blankOne,
                    'www.example.com/foo?hello=world', None,
                    'www.example.com/foo?hello=world')
        self.assertRaises(ValueError, self._blankOne,
                    'gopher.example.com/foo?hello=world', None,
                    'gopher://gopher.example.com')
        req = self._blankOne('www.example.com/foo?hello=world', None,
                             'http://www.example.com')
        self.assertEqual(req.environ.get('HTTP_HOST', None),
                         'www.example.com:80')
        self.assertEqual(req.environ.get('PATH_INFO', None),
                         'www.example.com/foo')
        self.assertEqual(req.environ.get('QUERY_STRING', None),
                         'hello=world')
        self.assertEqual(req.environ.get('REQUEST_METHOD', None), 'GET')
        req = self._blankOne('www.example.com/secure?hello=world', None,
                             'https://www.example.com/secure')
        self.assertEqual(req.environ.get('HTTP_HOST', None),
                         'www.example.com:443')
        self.assertEqual(req.environ.get('PATH_INFO', None),
                         'www.example.com/secure')
        self.assertEqual(req.environ.get('QUERY_STRING', None), 'hello=world')
        self.assertEqual(req.environ.get('REQUEST_METHOD', None), 'GET')
        self.assertEqual(req.environ.get('SCRIPT_NAME', None), '/secure')
        self.assertEqual(req.environ.get('SERVER_NAME', None),
                         'www.example.com')
        self.assertEqual(req.environ.get('SERVER_PORT', None), '443')


    def test_post_does_not_reparse(self):
        # test that there's no repetitive parsing is happening on every
        # req.POST access
        req = self._blankOne('/',
            content_type='multipart/form-data; boundary=boundary',
            POST=_cgi_escaping_body
        )
        post1 = req.POST
        self.assertTrue('webob._parsed_post_vars' in req.environ)
        post2 = req.POST
        self.assertTrue(post1 is post2)


    def test_middleware_body(self):
        def app(env, sr):
            sr('200 OK', [])
            return [env['wsgi.input'].read()]

        def mw(env, sr):
            req = self._makeOne(env)
            data = req.body_file.read()
            resp = req.get_response(app)
            resp.headers['x-data'] = data
            return resp(env, sr)

        req = self._blankOne('/', method='PUT', body=b'abc')
        resp = req.get_response(mw)
        self.assertEqual(resp.body, b'abc')
        self.assertEqual(resp.headers['x-data'], b'abc')

    def test_body_file_noseek(self):
        req = self._blankOne('/', method='PUT', body=b'abc')
        lst = [req.body_file.read(1) for i in range(3)]
        self.assertEqual(lst, [b'a', b'b', b'c'])

    def test_cgi_escaping_fix(self):
        req = self._blankOne('/',
            content_type='multipart/form-data; boundary=boundary',
            POST=_cgi_escaping_body
        )
        self.assertEqual(list(req.POST.keys()), ['%20%22"'])
        req.body_file.read()
        self.assertEqual(list(req.POST.keys()), ['%20%22"'])

    def test_content_type_none(self):
        r = self._blankOne('/', content_type='text/html')
        self.assertEqual(r.content_type, 'text/html')
        r.content_type = None

    def test_body_file_seekable(self):
        r = self._blankOne('/', method='POST')
        r.body_file = BytesIO(b'body')
        self.assertEqual(r.body_file_seekable.read(), b'body')

    def test_request_init(self):
        # port from doctest (docs/reference.txt)
        req = self._blankOne('/article?id=1')
        self.assertEqual(req.environ['HTTP_HOST'], 'localhost:80')
        self.assertEqual(req.environ['PATH_INFO'], '/article')
        self.assertEqual(req.environ['QUERY_STRING'], 'id=1')
        self.assertEqual(req.environ['REQUEST_METHOD'], 'GET')
        self.assertEqual(req.environ['SCRIPT_NAME'], '')
        self.assertEqual(req.environ['SERVER_NAME'], 'localhost')
        self.assertEqual(req.environ['SERVER_PORT'], '80')
        self.assertEqual(req.environ['SERVER_PROTOCOL'], 'HTTP/1.0')
        self.assertTrue(hasattr(req.environ['wsgi.errors'], 'write') and
                     hasattr(req.environ['wsgi.errors'], 'flush'))
        self.assertTrue(hasattr(req.environ['wsgi.input'], 'next') or
                     hasattr(req.environ['wsgi.input'], '__next__'))
        self.assertEqual(req.environ['wsgi.multiprocess'], False)
        self.assertEqual(req.environ['wsgi.multithread'], False)
        self.assertEqual(req.environ['wsgi.run_once'], False)
        self.assertEqual(req.environ['wsgi.url_scheme'], 'http')
        self.assertEqual(req.environ['wsgi.version'], (1, 0))

        # Test body
        self.assertTrue(hasattr(req.body_file, 'read'))
        self.assertEqual(req.body, b'')
        req.method = 'PUT'
        req.body = b'test'
        self.assertTrue(hasattr(req.body_file, 'read'))
        self.assertEqual(req.body, b'test')

        # Test method & URL
        self.assertEqual(req.method, 'PUT')
        self.assertEqual(req.scheme, 'http')
        self.assertEqual(req.script_name, '') # The base of the URL
        req.script_name = '/blog'  # make it more interesting
        self.assertEqual(req.path_info, '/article')
        # Content-Type of the request body
        self.assertEqual(req.content_type, '')
        # The auth'ed user (there is none set)
        self.assertTrue(req.remote_user is None)
        self.assertTrue(req.remote_addr is None)
        self.assertEqual(req.host, 'localhost:80')
        self.assertEqual(req.host_url, 'http://localhost')
        self.assertEqual(req.application_url, 'http://localhost/blog')
        self.assertEqual(req.path_url, 'http://localhost/blog/article')
        self.assertEqual(req.url, 'http://localhost/blog/article?id=1')
        self.assertEqual(req.path, '/blog/article')
        self.assertEqual(req.path_qs, '/blog/article?id=1')
        self.assertEqual(req.query_string, 'id=1')
        self.assertEqual(req.relative_url('archive'),
                         'http://localhost/blog/archive')

        # Doesn't change request
        self.assertEqual(req.path_info_peek(), 'article')
        # Does change request!
        self.assertEqual(req.path_info_pop(), 'article')
        self.assertEqual(req.script_name, '/blog/article')
        self.assertEqual(req.path_info, '')

        # Headers
        req.headers['Content-Type'] = 'application/x-www-urlencoded'
        self.assertEqual(sorted(req.headers.items()),
                         [('Content-Length', '4'),
                          ('Content-Type', 'application/x-www-urlencoded'),
                          ('Host', 'localhost:80')])
        self.assertEqual(req.environ['CONTENT_TYPE'],
                         'application/x-www-urlencoded')

    def test_request_query_and_POST_vars(self):
        # port from doctest (docs/reference.txt)

        # Query & POST variables
        from webob.multidict import MultiDict
        from webob.multidict import NestedMultiDict
        from webob.multidict import NoVars
        from webob.multidict import GetDict
        req = self._blankOne('/test?check=a&check=b&name=Bob')
        GET = GetDict([('check', 'a'),
                      ('check', 'b'),
                      ('name', 'Bob')], {})
        self.assertEqual(req.GET, GET)
        self.assertEqual(req.GET['check'], 'b')
        self.assertEqual(req.GET.getall('check'), ['a', 'b'])
        self.assertEqual(list(req.GET.items()),
                         [('check', 'a'), ('check', 'b'), ('name', 'Bob')])

        self.assertTrue(isinstance(req.POST, NoVars))
        # NoVars can be read like a dict, but not written
        self.assertEqual(list(req.POST.items()), [])
        req.method = 'POST'
        req.body = b'name=Joe&email=joe@example.com'
        self.assertEqual(req.POST,
                         MultiDict([('name', 'Joe'),
                                    ('email', 'joe@example.com')]))
        self.assertEqual(req.POST['name'], 'Joe')

        self.assertTrue(isinstance(req.params, NestedMultiDict))
        self.assertEqual(list(req.params.items()),
                         [('check', 'a'),
                          ('check', 'b'),
                          ('name', 'Bob'),
                          ('name', 'Joe'),
                          ('email', 'joe@example.com')])
        self.assertEqual(req.params['name'], 'Bob')
        self.assertEqual(req.params.getall('name'), ['Bob', 'Joe'])

    def test_request_put(self):
        from datetime import datetime
        from webob import Response
        from webob import UTC
        from webob.acceptparse import MIMEAccept
        from webob.byterange import Range
        from webob.etag import ETagMatcher
        from webob.multidict import MultiDict
        from webob.multidict import GetDict
        req = self._blankOne('/test?check=a&check=b&name=Bob')
        req.method = 'PUT'
        req.body = b'var1=value1&var2=value2&rep=1&rep=2'
        req.environ['CONTENT_LENGTH'] = str(len(req.body))
        req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        GET = GetDict([('check', 'a'),
                      ('check', 'b'),
                      ('name', 'Bob')], {})
        self.assertEqual(req.GET, GET)
        self.assertEqual(req.POST, MultiDict(
                                [('var1', 'value1'),
                                 ('var2', 'value2'),
                                 ('rep', '1'),
                                 ('rep', '2')]))
        self.assertEqual(
            list(req.GET.items()),
            [('check', 'a'), ('check', 'b'), ('name', 'Bob')])

        # Unicode
        req.charset = 'utf8'
        self.assertEqual(list(req.GET.items()),
                         [('check', 'a'), ('check', 'b'), ('name', 'Bob')])

        # Cookies
        req.headers['Cookie'] = 'test=value'
        self.assertTrue(isinstance(req.cookies, collections.MutableMapping))
        self.assertEqual(list(req.cookies.items()), [('test', 'value')])
        req.charset = None
        self.assertEqual(req.cookies, {'test': 'value'})

        # Accept-* headers
        self.assertTrue('text/html' in req.accept)
        req.accept = 'text/html;q=0.5, application/xhtml+xml;q=1'
        self.assertTrue(isinstance(req.accept, MIMEAccept))
        self.assertTrue('text/html' in req.accept)

        self.assertEqual(req.accept.best_match(['text/html',
                                                'application/xhtml+xml']),
                         'application/xhtml+xml')

        req.accept_language = 'es, pt-BR'
        self.assertEqual(req.accept_language.best_match(['es']), 'es')

        # Conditional Requests
        server_token = 'opaque-token'
        # shouldn't return 304
        self.assertTrue(not server_token in req.if_none_match)
        req.if_none_match = server_token
        self.assertTrue(isinstance(req.if_none_match, ETagMatcher))
        # You *should* return 304
        self.assertTrue(server_token in req.if_none_match)
        # if_none_match should use weak matching
        weak_token = 'W/"%s"' % server_token
        req.if_none_match = weak_token
        assert req.headers['if-none-match'] == weak_token
        self.assertTrue(server_token in req.if_none_match)


        req.if_modified_since = datetime(2006, 1, 1, 12, 0, tzinfo=UTC)
        self.assertEqual(req.headers['If-Modified-Since'],
                         'Sun, 01 Jan 2006 12:00:00 GMT')
        server_modified = datetime(2005, 1, 1, 12, 0, tzinfo=UTC)
        self.assertTrue(req.if_modified_since)
        self.assertTrue(req.if_modified_since >= server_modified)

        self.assertTrue(not req.if_range)
        self.assertTrue(Response(etag='some-etag',
                              last_modified=datetime(2005, 1, 1, 12, 0))
            in req.if_range)
        req.if_range = 'opaque-etag'
        self.assertTrue(Response(etag='other-etag') not in req.if_range)
        self.assertTrue(Response(etag='opaque-etag') in req.if_range)

        res = Response(etag='opaque-etag')
        self.assertTrue(res in req.if_range)

        req.range = 'bytes=0-100'
        self.assertTrue(isinstance(req.range, Range))
        self.assertEqual(tuple(req.range), (0, 101))
        cr = req.range.content_range(length=1000)
        self.assertEqual(tuple(cr), (0, 101, 1000))

        self.assertTrue(server_token in req.if_match)
        # No If-Match means everything is ok
        req.if_match = server_token
        self.assertTrue(server_token in req.if_match)
        # Still OK
        req.if_match = 'other-token'
        # Not OK, should return 412 Precondition Failed:
        self.assertTrue(not server_token in req.if_match)

    def test_request_patch(self):
        from webob.multidict import MultiDict
        from webob.multidict import GetDict
        req = self._blankOne('/test?check=a&check=b&name=Bob')
        req.method = 'PATCH'
        req.body = b'var1=value1&var2=value2&rep=1&rep=2'
        req.environ['CONTENT_LENGTH'] = str(len(req.body))
        req.environ['CONTENT_TYPE'] = 'application/x-www-form-urlencoded'
        GET = GetDict([('check', 'a'),
                      ('check', 'b'),
                      ('name', 'Bob')], {})
        self.assertEqual(req.GET, GET)
        self.assertEqual(req.POST, MultiDict(
                                [('var1', 'value1'),
                                 ('var2', 'value2'),
                                 ('rep', '1'),
                                 ('rep', '2')]))

    def test_call_WSGI_app(self):
        req = self._blankOne('/')
        def wsgi_app(environ, start_response):
            start_response('200 OK', [('Content-type', 'text/plain')])
            return [b'Hi!']
        self.assertEqual(req.call_application(wsgi_app),
                         ('200 OK', [('Content-type', 'text/plain')],
                          [b'Hi!']))

        res = req.get_response(wsgi_app)
        from webob.response import Response
        self.assertTrue(isinstance(res, Response))
        self.assertEqual(res.status, '200 OK')
        from webob.headers import ResponseHeaders
        self.assertTrue(isinstance(res.headers, ResponseHeaders))
        self.assertEqual(list(res.headers.items()),
                         [('Content-type', 'text/plain')])
        self.assertEqual(res.body, b'Hi!')

    def test_get_response_catch_exc_info_true(self):
        req = self._blankOne('/')
        def wsgi_app(environ, start_response):
            start_response('200 OK', [('Content-type', 'text/plain')])
            return [b'Hi!']
        res = req.get_response(wsgi_app, catch_exc_info=True)
        from webob.response import Response
        self.assertTrue(isinstance(res, Response))
        self.assertEqual(res.status, '200 OK')
        from webob.headers import ResponseHeaders
        self.assertTrue(isinstance(res.headers, ResponseHeaders))
        self.assertEqual(list(res.headers.items()),
                         [('Content-type', 'text/plain')])
        self.assertEqual(res.body, b'Hi!')

    def equal_req(self, req, inp):
        cls = self._getTargetClass()
        req2 = cls.from_file(inp)
        self.assertEqual(req.url, req2.url)
        headers1 = dict(req.headers)
        headers2 = dict(req2.headers)
        self.assertEqual(int(headers1.get('Content-Length', '0')),
            int(headers2.get('Content-Length', '0')))
        if 'Content-Length' in headers1:
            del headers1['Content-Length']
        if 'Content-Length' in headers2:
            del headers2['Content-Length']
        self.assertEqual(headers1, headers2)
        req_body = req.body
        req2_body = req2.body
        self.assertEqual(req_body, req2_body)

class FakeCGIBodyTests(unittest.TestCase):
    def test_encode_multipart_value_type_options(self):
        from cgi import FieldStorage
        from webob.request import BaseRequest, FakeCGIBody
        from webob.multidict import MultiDict
        multipart_type = 'multipart/form-data; boundary=foobar'
        from io import BytesIO
        body = (
            b'--foobar\r\n'
            b'Content-Disposition: form-data; name="bananas"; '
                    b'filename="bananas.txt"\r\n'
            b'Content-type: text/plain; charset="utf-7"\r\n'
            b'\r\n'
            b"these are the contents of the file 'bananas.txt'\r\n"
            b'\r\n'
            b'--foobar--')
        multipart_body = BytesIO(body)
        environ = BaseRequest.blank('/').environ
        environ.update(CONTENT_TYPE=multipart_type)
        environ.update(REQUEST_METHOD='POST')
        environ.update(CONTENT_LENGTH=len(body))
        fs = FieldStorage(multipart_body, environ=environ)
        vars = MultiDict.from_fieldstorage(fs)
        self.assertEqual(vars['bananas'].__class__, FieldStorage)
        fake_body = FakeCGIBody(vars, multipart_type)
        self.assertEqual(fake_body.read(), body)

    def test_encode_multipart_no_boundary(self):
        from webob.request import FakeCGIBody
        self.assertRaises(ValueError, FakeCGIBody, {}, 'multipart/form-data')

    def test_repr(self):
        from webob.request import FakeCGIBody
        body = FakeCGIBody({'bananas': 'bananas'},
                           'multipart/form-data; boundary=foobar')
        body.read(1)
        import re
        self.assertEqual(
            re.sub(r'\b0x[0-9a-f]+\b', '<whereitsat>', repr(body)),
            "<FakeCGIBody at <whereitsat> viewing {'bananas': 'ba...nas'}>",
        )

    def test_fileno(self):
        from webob.request import FakeCGIBody
        body = FakeCGIBody({'bananas': 'bananas'},
                           'multipart/form-data; boundary=foobar')
        self.assertEqual(body.fileno(), None)

    def test_iter(self):
        from webob.request import FakeCGIBody
        body = FakeCGIBody({'bananas': 'bananas'},
                           'multipart/form-data; boundary=foobar')
        self.assertEqual(list(body), [
            b'--foobar\r\n',
            b'Content-Disposition: form-data; name="bananas"\r\n',
            b'\r\n',
            b'bananas\r\n',
            b'--foobar--',
         ])

    def test_readline(self):
        from webob.request import FakeCGIBody
        body = FakeCGIBody({'bananas': 'bananas'},
                           'multipart/form-data; boundary=foobar')
        self.assertEqual(body.readline(), b'--foobar\r\n')
        self.assertEqual(
            body.readline(),
            b'Content-Disposition: form-data; name="bananas"\r\n')
        self.assertEqual(body.readline(), b'\r\n')
        self.assertEqual(body.readline(), b'bananas\r\n')
        self.assertEqual(body.readline(), b'--foobar--')
        # subsequent calls to readline will return ''

    def test_read_bad_content_type(self):
        from webob.request import FakeCGIBody
        body = FakeCGIBody({'bananas': 'bananas'}, 'application/jibberjabber')
        self.assertRaises(AssertionError, body.read)

    def test_read_urlencoded(self):
        from webob.request import FakeCGIBody
        body = FakeCGIBody({'bananas': 'bananas'},
                           'application/x-www-form-urlencoded')
        self.assertEqual(body.read(), b'bananas=bananas')

    def test_readable(self):
        from webob.request import FakeCGIBody
        body = FakeCGIBody({'bananas': 'bananas'}, 'application/something')
        self.assertTrue(body.readable())


class Test_cgi_FieldStorage__repr__patch(unittest.TestCase):
    def _callFUT(self, fake):
        from webob.request import _cgi_FieldStorage__repr__patch
        return _cgi_FieldStorage__repr__patch(fake)

    def test_with_file(self):
        class Fake(object):
            name = 'name'
            file = 'file'
            filename = 'filename'
            value = 'value'
        fake = Fake()
        result = self._callFUT(fake)
        self.assertEqual(result, "FieldStorage('name', 'filename')")

    def test_without_file(self):
        class Fake(object):
            name = 'name'
            file = None
            filename = 'filename'
            value = 'value'
        fake = Fake()
        result = self._callFUT(fake)
        self.assertEqual(result, "FieldStorage('name', 'filename', 'value')")


class TestLimitedLengthFile(unittest.TestCase):
    def _makeOne(self, file, maxlen):
        from webob.request import LimitedLengthFile
        return LimitedLengthFile(file, maxlen)

    def test_fileno(self):
        class DummyFile(object):
            def fileno(self):
                return 1
        dummyfile = DummyFile()
        inst = self._makeOne(dummyfile, 0)
        self.assertEqual(inst.fileno(), 1)


class Test_environ_from_url(unittest.TestCase):
    def _callFUT(self, *arg, **kw):
        from webob.request import environ_from_url
        return environ_from_url(*arg, **kw)

    def test_environ_from_url(self):
        # Generating an environ just from an url plus testing environ_add_POST
        self.assertRaises(TypeError, self._callFUT,
                    'http://www.example.com/foo?bar=baz#qux')
        self.assertRaises(TypeError, self._callFUT,
                    'gopher://gopher.example.com')
        req = self._callFUT('http://www.example.com/foo?bar=baz')
        self.assertEqual(req.get('HTTP_HOST', None), 'www.example.com:80')
        self.assertEqual(req.get('PATH_INFO', None), '/foo')
        self.assertEqual(req.get('QUERY_STRING', None), 'bar=baz')
        self.assertEqual(req.get('REQUEST_METHOD', None), 'GET')
        self.assertEqual(req.get('SCRIPT_NAME', None), '')
        self.assertEqual(req.get('SERVER_NAME', None), 'www.example.com')
        self.assertEqual(req.get('SERVER_PORT', None), '80')
        req = self._callFUT('https://www.example.com/foo?bar=baz')
        self.assertEqual(req.get('HTTP_HOST', None), 'www.example.com:443')
        self.assertEqual(req.get('PATH_INFO', None), '/foo')
        self.assertEqual(req.get('QUERY_STRING', None), 'bar=baz')
        self.assertEqual(req.get('REQUEST_METHOD', None), 'GET')
        self.assertEqual(req.get('SCRIPT_NAME', None), '')
        self.assertEqual(req.get('SERVER_NAME', None), 'www.example.com')
        self.assertEqual(req.get('SERVER_PORT', None), '443')


        from webob.request import environ_add_POST

        environ_add_POST(req, None)
        self.assertTrue('CONTENT_TYPE' not in req)
        self.assertTrue('CONTENT_LENGTH' not in req)
        environ_add_POST(req, {'hello':'world'})
        self.assertTrue(req.get('HTTP_HOST', None), 'www.example.com:443')
        self.assertEqual(req.get('PATH_INFO', None), '/foo')
        self.assertEqual(req.get('QUERY_STRING', None), 'bar=baz')
        self.assertEqual(req.get('REQUEST_METHOD', None), 'POST')
        self.assertEqual(req.get('SCRIPT_NAME', None), '')
        self.assertEqual(req.get('SERVER_NAME', None), 'www.example.com')
        self.assertEqual(req.get('SERVER_PORT', None), '443')
        self.assertEqual(req.get('CONTENT_LENGTH', None),'11')
        self.assertEqual(req.get('CONTENT_TYPE', None),
                         'application/x-www-form-urlencoded')
        self.assertEqual(req['wsgi.input'].read(), b'hello=world')

    def test_environ_from_url_highorder_path_info(self):
        from webob.request import Request
        env = self._callFUT('/%E6%B5%81')
        self.assertEqual(env['PATH_INFO'], '/\xe6\xb5\x81')
        request = Request(env)
        expected = text_(b'/\xe6\xb5\x81', 'utf-8') # u'/\u6d41'
        self.assertEqual(request.path_info, expected)
        self.assertEqual(request.upath_info, expected)

    def test_fileupload_mime_type_detection(self):
        from webob.request import Request
        # sometimes on win the detected mime type for .jpg will be
        # image/pjpeg for ex. so use a non-standard extesion to avoid that
        import mimetypes
        mimetypes.add_type('application/x-foo', '.foo')
        request = Request.blank("/", POST=dict(file1=("foo.foo", "xxx"),
                                               file2=("bar.mp3", "xxx")))
        self.assertTrue("audio/mpeg" in request.body.decode('ascii'),
                        str(request))
        self.assertTrue('application/x-foo' in request.body.decode('ascii'),
                        str(request))

class TestRequestMultipart(unittest.TestCase):
    def test_multipart_with_charset(self):
        from webob.request import Request
        req = Request.from_bytes(_test_req_multipart_charset)
        self.assertEqual(req.POST['title'].encode('utf8'),
                         text_('こんにちは', 'utf-8').encode('utf8'))

def simpleapp(environ, start_response):
    from webob.request import Request
    status = '200 OK'
    response_headers = [('Content-type','text/plain')]
    start_response(status, response_headers)
    request = Request(environ)
    request.remote_user = 'bob'
    return [ bytes_(x) for x in [
        'Hello world!\n',
        'The get is %r' % request.GET,
        ' and Val is %s\n' % repr(request.GET.get('name')),
        'The languages are: %s\n' % list(request.accept_language),
        'The accepttypes is: %s\n' %
            request.accept.best_match(['application/xml', 'text/html']),
        'post is %r\n' % request.POST,
        'params is %r\n' % request.params,
        'cookies is %r\n' % request.cookies,
        'body: %r\n' % request.body,
        'method: %s\n' % request.method,
        'remote_user: %r\n' % request.environ['REMOTE_USER'],
        'host_url: %r; application_url: %r; path_url: %r; url: %r\n' %
            (request.host_url,
             request.application_url,
             request.path_url,
             request.url),
        'urlvars: %r\n' % request.urlvars,
        'urlargs: %r\n' % (request.urlargs, ),
        'is_xhr: %r\n' % request.is_xhr,
        'if_modified_since: %r\n' % request.if_modified_since,
        'user_agent: %r\n' % request.user_agent,
        'if_none_match: %r\n' % request.if_none_match,
        ]]

_cgi_escaping_body = '''--boundary
Content-Disposition: form-data; name="%20%22""


--boundary--'''

def _norm_req(s):
    return b'\r\n'.join(s.strip().replace(b'\r', b'').split(b'\n'))

_test_req = b"""
POST /webob/ HTTP/1.0
Accept: */*
Cache-Control: max-age=0
Content-Type: multipart/form-data; boundary=----------------------------deb95b63e42a
Host: pythonpaste.org
User-Agent: UserAgent/1.0 (identifier-version) library/7.0 otherlibrary/0.8

------------------------------deb95b63e42a
Content-Disposition: form-data; name="foo"

foo
------------------------------deb95b63e42a
Content-Disposition: form-data; name="bar"; filename="bar.txt"
Content-type: application/octet-stream

these are the contents of the file 'bar.txt'

------------------------------deb95b63e42a--
"""

_test_req_patch = b"""
PATCH /webob/ HTTP/1.1
Content-Length: 14
Content-Type: application/json

{"foo": "bar"}
"""

_test_req2 = b"""
POST / HTTP/1.0
Content-Length: 0

"""

_test_req_multipart_charset = b"""
POST /upload/ HTTP/1.1
Host: foo.com
User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.13) Gecko/20101206 Ubuntu/10.04 (lucid) Firefox/3.6.13
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.8,ja;q=0.6
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Content-Type: multipart/form-data; boundary=000e0ce0b196b4ee6804c6c8af94
Content-Length: 926

--000e0ce0b196b4ee6804c6c8af94
Content-Type: text/plain; charset=ISO-2022-JP
Content-Disposition: form-data; name=title
Content-Transfer-Encoding: 7bit

\x1b$B$3$s$K$A$O\x1b(B
--000e0ce0b196b4ee6804c6c8af94
Content-Type: text/plain; charset=ISO-8859-1
Content-Disposition: form-data; name=submit

Submit
--000e0ce0b196b4ee6804c6c8af94
Content-Type: message/external-body; charset=ISO-8859-1; blob-key=AMIfv94TgpPBtKTL3a0U9Qh1QCX7OWSsmdkIoD2ws45kP9zQAGTOfGNz4U18j7CVXzODk85WtiL5gZUFklTGY3y4G0Jz3KTPtJBOFDvQHQew7YUymRIpgUXgENS_fSEmInAIQdpSc2E78MRBVEZY392uhph3r-In96t8Z58WIRc-Yikx1bnarWo
Content-Disposition: form-data; name=file; filename="photo.jpg"

Content-Type: image/jpeg
Content-Length: 38491
X-AppEngine-Upload-Creation: 2012-08-08 15:32:29.035959
Content-MD5: ZjRmNGRhYmNhZTkyNzcyOWQ5ZGUwNDgzOWFkNDAxN2Y=
Content-Disposition: form-data; name=file; filename="photo.jpg"


--000e0ce0b196b4ee6804c6c8af94--"""


_test_req = _norm_req(_test_req)
_test_req_patch = _norm_req(_test_req_patch)
_test_req2 = _norm_req(_test_req2) + b'\r\n'
_test_req_multipart_charset = _norm_req(_test_req_multipart_charset)

class UnseekableInput(object):
    def __init__(self, data):
        self.data = data
        self.pos = 0
    def read(self, size=-1):
        if size == -1:
            t = self.data[self.pos:]
            self.pos = len(self.data)
            return t
        else:
            assert(self.pos + size <= len(self.data))
            t = self.data[self.pos:self.pos+size]
            self.pos += size
            return t

class UnseekableInputWithSeek(UnseekableInput):
    def seek(self, pos, rel=0):
        raise IOError("Invalid seek!")