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
|
#
# Copyright (C) 2000, 2001, 2013 Gregory Trubetskoy
# Copyright (C) 2002, 2003, 2004, 2005, 2006, 2007 Apache Software Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You
# may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.
#
#
"""
Writing Tests
Writing mod_python tests can be a tricky task. This module
attempts to lay out a framework for making the testing process
consistent and quick to implement.
All tests are based on Python Unit Test framework, it's a good
idea to study the docs for the unittest module before going any
further.
To write a test, first decide in which of the 3 following categories
it falls:
o Simple tests that do not require any special server configuration
and can be conducted along with other similar tests all in one
request.
o Per-Request tests. These tests require a whole separate request
(or several requests) for a complete test.
o Per-Instance tests. These require restarting the instance of
http and running it in a particular way, perhaps with a special
config to complete the test. An example might be load testing, or
checking for memory leaks.
There are two modules involved in testing - the one you're looking at
now (test.py), which is responsible for setting up the http config
running it and initiating requests, AND htdocs/tests.py (sorry for
boring names), which is where all mod_python handlers reside.
To write a Simple test:
o Look at tests.SimpleTestCase class and the test methods in it,
then write your own following the example.
o Look at the tests.make_suite function, and make sure your test
is added to the suite in there.
o Keep in mind that the only way for Simple tests to communicate
with the outside world is via the error log, do not be shy about
writing to it.
To write a Per-Request test:
Most, if not all per-request tests require special server configuration
as part of the fixture. To avoid having to restart the server with a
different config (which would, btw, effectively turn this into a per-
instance test), we separate configs by placing them in separate virtual
hosts. This will become clearer if you follow the code.
o Look at test.PerRequestCase class.
o Note that for every test there are two methods defined: the test
method itself, plus a method with the same name ending with
"_conf". The _conf methods are supposed to return the virtual
host config necessary for this test. As tests are instantiated,
the configs are appended to a class variable (meaning its shared
across all instances) appendConfig, then before the suite is run,
the httpd config is built and httpd started. Each test will
know to query its own virtual host. This way all tests can be
conducted using a single instance of httpd.
o Note how the _config methods generate the config - they use the
httpdconf module to generate an object whose string representation
is the config part, simlar to the way HTMLgen produces html. You
do not have to do it this way, but it makes for cleaner code.
o Every Per-Request test must also have a corresponding handler in
the tests module. The convention is name everything based on the
subject of the test, e.g. the test of req.document_root() will have
a test method in PerRequestCase class called test_req_documet_root,
a config method PerRequestCase.test_req_document_root_conf, the
VirtualHost name will be test_req_document_root, and the handler
in tests.py will be called req_document_root.
o Note that you cannot use urllib if you have to specify a custom
host: header, which is required for this whole thing to work.
There is a convenience method, vhost_get, which takes the host
name as the first argument, and optionally path as the second
(though that is almost never needed). If vhost_get does not
suffice, use httplib. Note the very useful skip_host=1 argument.
o Remember to have your test added to the suite in
PerInstanceTestCase.testPerRequestTests
To write a Per-Instance test:
o Look at test.PerInstanceTestCase class.
o You have to start httpd in your test, but no need to stop it,
it will be stopped for you in tearDown()
o Add the test to the suite in test.suite() method
"""
from __future__ import print_function
import sys
import os
PY2 = sys.version[0] == '2'
try:
import mod_python.version
except:
print (
"Cannot import mod_python.version. Either you didn't "
"run the ./configure script, or you're running this script "
"in a Win32 environment, in which case you have to make it by hand."
)
sys.exit()
else:
def testpath(variable,isfile):
value = getattr(mod_python.version,variable,'<undefined>')
if isfile:
if os.path.isfile(value):
return True
else:
if os.path.isdir(value):
return True
print('Bad value for mod_python.version.%s : %s'%(
variable,
value
))
return False
good = testpath('HTTPD',True)
good = testpath('TESTHOME',False) and good
good = testpath('LIBEXECDIR',False) and good
good = testpath('TEST_MOD_PYTHON_SO',True) and good
if not good:
print("Please check your mod_python/version.py file")
sys.exit()
del testpath
del good
from mod_python.httpdconf import *
import unittest
if PY2:
from commands import getoutput
import urllib2
import httplib
from httplib import UNAUTHORIZED
import md5
from cStringIO import StringIO
from urllib2 import urlopen
from urllib import urlencode
else:
from subprocess import getoutput
import urllib.request, urllib.error
import http.client
from http.client import UNAUTHORIZED
from hashlib import md5
from io import StringIO, BytesIO, TextIOWrapper
from urllib.request import urlopen
from urllib.parse import urlencode
import shutil
import time
import socket
import tempfile
import base64
import random
try:
import threading
THREADS = True
except:
THREADS = False
HTTPD = mod_python.version.HTTPD
TESTHOME = mod_python.version.TESTHOME
MOD_PYTHON_SO = mod_python.version.TEST_MOD_PYTHON_SO
LIBEXECDIR = mod_python.version.LIBEXECDIR
SERVER_ROOT = TESTHOME
CONFIG = os.path.join(TESTHOME, "conf", "test.conf")
DOCUMENT_ROOT = os.path.join(TESTHOME, "htdocs")
TMP_DIR = os.path.join(TESTHOME, "tmp")
PORT = 0 # this is set in fundUnusedPort()
# readBlockSize is required for the test_fileupload_* tests.
# We can't import mod_python.util.readBlockSize from a cmd line
# interpreter, so we'll hard code it here.
# If util.readBlockSize changes, it MUST be changed here as well.
# Maybe we should set up a separate test to query the server to
# get the correct readBlockSize?
#
readBlockSize = 65368
def findUnusedPort():
# bind to port 0 which makes the OS find the next
# unused port.
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
return port
def http_connection(conn_str):
if PY2:
return httplib.HTTPConnection(conn_str)
else:
return http.client.HTTPConnection(conn_str)
def md5_hash(s):
if PY2:
return md5.new(s).hexdigest()
else:
if isinstance(s, str):
s = s.encode('latin1')
return md5(s).hexdigest().encode('latin1')
def get_ab_path():
""" Find the location of the ab (apache benchmark) program """
for name in ['ab', 'ab2', 'ab.exe', 'ab2.exe']:
path = os.path.join(os.path.split(HTTPD)[0], name)
if os.path.exists(path):
return quote_if_space(path)
return None
def get_apache_version():
print("Checking Apache version....")
httpd = quote_if_space(HTTPD)
stdout = getoutput('%s -v' % (httpd))
version_str = None
for line in stdout.splitlines():
if line.startswith('Server version'):
version_str = line.strip()
break
if version_str:
version_str = version_str.split('/')[1]
major,minor,patch = version_str.split('.',3)
version = '%s.%s' % (major,minor)
else:
print("Can't determine Apache version. Assuming 2.0")
version = '2.0'
print(version)
return version
APACHE_VERSION = get_apache_version()
if not mod_python.version.HTTPD_VERSION.startswith(APACHE_VERSION):
print("ERROR: Build version %s does not match version reported by %s: %s, re-run ./configure?" % \
(mod_python.version.HTTPD_VERSION, HTTPD, APACHE_VERSION))
sys.exit()
class HttpdCtrl:
# a mixin providing ways to control httpd
def checkFiles(self):
modules = os.path.join(SERVER_ROOT, "modules")
if not os.path.exists(modules):
os.mkdir(modules)
logs = os.path.join(SERVER_ROOT, "logs")
if os.path.exists(logs):
shutil.rmtree(logs)
os.mkdir(logs)
# place
if os.path.exists(TMP_DIR):
shutil.rmtree(TMP_DIR)
os.mkdir(TMP_DIR)
def makeConfig(self, append=Container()):
# create config files, etc
print(" Creating config....")
self.checkFiles()
global PORT
PORT = findUnusedPort()
print(" listen port:", PORT)
# where other modules might be
modpath = LIBEXECDIR
s = Container(
IfModule("!prefork.c",
IfModule("!worker.c",
IfModule("!perchild.c",
IfModule("!mpm_winnt.c",
LoadModule("mpm_prefork_module modules/mod_mpm_prefork.so"),
)))),
IfModule("prefork.c",
StartServers("3"),
MaxSpareServers("1")),
IfModule("worker.c",
StartServers("2"),
MaxClients("6"),
MinSpareThreads("1"),
MaxSpareThreads("1"),
ThreadsPerChild("3"),
MaxRequestsPerChild("0")),
IfModule("perchild.c",
NumServers("2"),
StartThreads("2"),
MaxSpareThreads("1"),
MaxThreadsPerChild("2")),
IfModule("mpm_winnt.c",
ThreadsPerChild("5"),
MaxRequestsPerChild("0")),
IfModule("!mod_mime.c",
LoadModule("mime_module %s" %
quote_if_space(os.path.join(modpath, "mod_mime.so")))),
IfModule("!mod_log_config.c",
LoadModule("log_config_module %s" %
quote_if_space(os.path.join(modpath, "mod_log_config.so")))),
IfModule("!mod_dir.c",
LoadModule("dir_module %s" %
quote_if_space(os.path.join(modpath, "mod_dir.so")))),
IfModule("!mod_include.c",
LoadModule("include_module %s" %
quote_if_space(os.path.join(modpath, "mod_include.so")))),
ServerRoot(SERVER_ROOT),
ErrorLog("logs/error_log"),
LogLevel("debug"),
LogFormat(r'"%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined'),
CustomLog("logs/access_log combined"),
TypesConfig("conf/mime.types"),
PidFile("logs/httpd.pid"),
ServerName("127.0.0.1"),
Listen(PORT),
Timeout(60),
PythonOption('mod_python.mutex_directory %s' % TMP_DIR),
PythonOption('PythonOptionTest sample_value'),
DocumentRoot(DOCUMENT_ROOT),
LoadModule("python_module %s" % quote_if_space(MOD_PYTHON_SO)))
if APACHE_VERSION == '2.4':
s.append(Mutex("file:logs"))
else:
s.append(LockFile("logs/accept.lock"))
if APACHE_VERSION == '2.4':
s.append(IfModule("!mod_unixd.c",
LoadModule("unixd_module %s" %
quote_if_space(os.path.join(modpath, "mod_unixd.so")))))
s.append(IfModule("!mod_authn_core.c",
LoadModule("authn_core_module %s" %
quote_if_space(os.path.join(modpath, "mod_authn_core.so")))))
s.append(IfModule("!mod_authz_core.c",
LoadModule("authz_core_module %s" %
quote_if_space(os.path.join(modpath, "mod_authz_core.so")))))
s.append(IfModule("!mod_authn_file.c",
LoadModule("authn_file_module %s" %
quote_if_space(os.path.join(modpath, "mod_authn_file.so")))))
s.append(IfModule("!mod_authz_user.c",
LoadModule("authz_user_module %s" %
quote_if_space(os.path.join(modpath, "mod_authz_user.so")))))
if APACHE_VERSION in ['2.2', '2.4']:
# mod_auth has been split into mod_auth_basic and some other modules
s.append(IfModule("!mod_auth_basic.c",
LoadModule("auth_basic_module %s" %
quote_if_space(os.path.join(modpath, "mod_auth_basic.so")))))
# Default KeepAliveTimeout is 5 for apache 2.2, but 15 in apache 2.0
# Explicitly set the value so it's the same as 2.0
s.append(KeepAliveTimeout("15"))
else:
s.append(IfModule("!mod_auth.c",
LoadModule("auth_module %s" %
quote_if_space(os.path.join(modpath, "mod_auth.so")))))
s.append(Comment(" --APPENDED--"))
s.append(append)
f = open(CONFIG, "w")
f.write(str(s))
f.close()
def startHttpd(self,extra=''):
print(" Starting Apache....")
httpd = quote_if_space(HTTPD)
config = quote_if_space(CONFIG)
cmd = '%s %s -k start -f %s' % (httpd, extra, config)
print(" ", cmd)
os.system(cmd)
time.sleep(1)
self.httpd_running = 1
def stopHttpd(self):
print(" Stopping Apache...")
httpd = quote_if_space(HTTPD)
config = quote_if_space(CONFIG)
cmd = '%s -k stop -f %s' % (httpd, config)
print(" ", cmd)
os.system(cmd)
time.sleep(1)
# Wait for apache to stop by checking for the existence of pid the
# file. If pid file still exists after 20 seconds raise an error.
# This check is here to facilitate testing on the qemu emulator.
# Qemu will run about 1/10 the native speed, so 1 second may
# not be long enough for apache to shut down.
count = 0
pid_file = os.path.join(os.getcwd(), 'logs/httpd.pid')
while os.path.exists(pid_file):
time.sleep(1)
count += 1
if count > 20:
# give up - apache refuses to die - or died a horrible
# death and never removed the pid_file.
raise RuntimeError(" Trouble stopping apache")
self.httpd_running = 0
class PerRequestTestCase(unittest.TestCase):
appendConfig = APACHE_VERSION < '2.4' and Container(NameVirtualHost('*')) or Container()
def __init__(self, methodName="runTest"):
unittest.TestCase.__init__(self, methodName)
# add to config
try:
confMeth = getattr(self, methodName+"_conf")
self.__class__.appendConfig.append(confMeth())
except AttributeError:
pass
def vhost_get(self, vhost, path="/tests.py"):
# this is so that tests could easily be staged with curl
curl = "curl --verbose --header 'Host: %s' http://127.0.0.1:%s%s" % (vhost, PORT, path)
print(" $ %s" % curl)
# allows to specify a custom host: header
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", path, skip_host=1)
conn.putheader("Host", "%s:%s" % (vhost, PORT))
conn.endheaders()
response = conn.getresponse()
if PY2:
rsp = response.read()
else:
rsp = response.read().decode('latin1')
conn.close()
return rsp
def vhost_post_multipart_form_data(self, vhost, path="/tests.py",variables={}, files={}):
# variables is a { name : value } dict
# files is a { name : (filename, content) } dict
# build the POST entity
if PY2:
entity = StringIO()
boundary = "============="+''.join( [ random.choice('0123456789') for x in range(10) ] )+'=='
else:
bio = BytesIO()
entity = TextIOWrapper(bio, encoding='latin1')
boundary = "============="+''.join( [ random.choice('0123456789') for x in range(10) ] )+'=='
# A part for each variable
for name, value in variables.items():
entity.write('--')
entity.write(boundary)
entity.write('\r\n')
entity.write('Content-Type: text/plain\r\n')
entity.write('Content-Disposition: form-data;\r\n name="%s"\r\n' % name)
entity.write('\r\n')
entity.write(str(value))
entity.write('\r\n')
# A part for each file
for name, filespec in files.items():
filename, content = filespec
# if content is readable, read it
try:
content = content.read()
except:
pass
if not isinstance(content, str): # always false on 2.x
content = content.decode('latin1')
entity.write('--')
entity.write(boundary)
entity.write('\r\n')
entity.write('Content-Type: application/octet-stream\r\n')
entity.write('Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (name, filename))
entity.write('\r\n')
entity.write(content)
entity.write('\r\n')
# The final boundary
entity.write('--')
entity.write(boundary)
entity.write('--\r\n')
entity.flush()
if PY2:
entity = entity.getvalue()
else:
entity = bio.getvalue()
conn = http_connection("127.0.0.1:%s" % PORT)
#conn.set_debuglevel(1000)
conn.putrequest("POST", path, skip_host=1)
conn.putheader("Host", "%s:%s" % (vhost, PORT))
conn.putheader("Content-Type", 'multipart/form-data; boundary="%s"' % boundary)
conn.putheader("Content-Length", '%s'%(len(entity)))
conn.endheaders()
start = time.time()
conn.send(entity)
response = conn.getresponse()
rsp = response.read()
conn.close()
print(' --> Send + process + receive took %.3f s'%(time.time()-start))
return rsp
### Tests begin here
def test_req_document_root_conf(self):
c = VirtualHost("*",
ServerName("test_req_document_root"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_document_root"),
PythonDebug("On")))
return c
def test_req_document_root(self):
print("\n * Testing req.document_root()")
rsp = self.vhost_get("test_req_document_root")
if rsp.upper() != DOCUMENT_ROOT.replace("\\", "/").upper():
self.fail(repr(rsp))
def test_req_add_handler_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_handler"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_add_handler"),
PythonDebug("On")))
return c
def test_req_add_handler(self):
print("\n * Testing req.add_handler()")
rsp = self.vhost_get("test_req_add_handler")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_req_add_bad_handler_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_bad_handler"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_add_bad_handler"),
PythonDebug("On")))
return c
def test_req_add_bad_handler(self):
# adding a non-existent handler with req.add_handler should raise
# an exception.
print("""\n * Testing req.add_handler("PythonHandler", "bad_handler")""")
rsp = self.vhost_get("test_req_add_bad_handler")
# look for evidence of the exception in the error log
time.sleep(1)
f = open(os.path.join(SERVER_ROOT, "logs/error_log"))
log = f.read()
f.close()
if log.find("contains no 'bad_handler'") == -1:
self.fail("""Could not find "contains no 'bad_handler'" in error_log""")
def test_req_add_empty_handler_string_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_empty_handler_string"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_add_empty_handler_string"),
PythonDebug("On")))
return c
def test_req_add_empty_handler_string(self):
# Adding an empty string as the handler in req.add_handler
# should raise an exception
print("""\n * Testing req.add_handler("PythonHandler","")""")
rsp = self.vhost_get("test_req_add_empty_handler_string")
if (rsp == "no exception"):
self.fail("Expected an exception")
def test_req_add_handler_empty_phase_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_handler_empty_phase"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonInterpPerDirective("On"),
PythonFixupHandler("tests::req_add_handler_empty_phase"),
PythonDebug("On")))
return c
def test_req_add_handler_empty_phase(self):
# Adding handler to content phase when no handler already
# exists for that phase.
print("""\n * Testing req.add_handler() for empty phase""")
rsp = self.vhost_get("test_req_add_handler_empty_phase")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_req_add_handler_directory_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_handler_directory"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonInterpPerDirective("On"),
PythonFixupHandler("tests::test_req_add_handler_directory"),
PythonDebug("On")))
return c
def test_req_add_handler_directory(self):
# Checking that directory is canonicalized and trailing
# slash is added.
print("""\n * Testing req.add_handler() directory""")
rsp = self.vhost_get("test_req_add_handler_directory")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_accesshandler_add_handler_to_empty_hl_conf(self):
# Note that there is no PythonHandler specified in the the VirtualHost
# config. We want to see if req.add_handler will work when the
# handler list is empty.
#PythonHandler("tests::req_add_empty_handler_string"),
c = VirtualHost("*",
ServerName("test_accesshandler_add_handler_to_empty_hl"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonAccessHandler("tests::accesshandler_add_handler_to_empty_hl"),
PythonDebug("On")))
return c
def test_accesshandler_add_handler_to_empty_hl(self):
print("""\n * Testing req.add_handler() when handler list is empty""")
rsp = self.vhost_get("test_accesshandler_add_handler_to_empty_hl")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_req_allow_methods_conf(self):
c = VirtualHost("*",
ServerName("test_req_allow_methods"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_allow_methods"),
PythonDebug("On")))
return c
def test_req_allow_methods(self):
print("\n * Testing req.allow_methods()")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_allow_methods", PORT))
conn.endheaders()
response = conn.getresponse()
server_hdr = response.getheader("Allow", "")
conn.close()
self.failUnless(server_hdr.find("PYTHONIZE") > -1, "req.allow_methods() didn't work")
def test_req_unauthorized_conf(self):
if APACHE_VERSION == '2.4':
c = VirtualHost("*",
ServerName("test_req_unauthorized"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("basic"),
Require("all granted"),
PythonHandler("tests::req_unauthorized"),
PythonDebug("On")))
else:
c = VirtualHost("*",
ServerName("test_req_unauthorized"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("basic"),
PythonHandler("tests::req_unauthorized"),
PythonDebug("On")))
return c
def test_req_unauthorized(self):
print("\n * Testing whether returning HTTP_UNAUTHORIZED works")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_unauthorized", PORT))
auth = base64.encodestring(b"spam:eggs").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_unauthorized", PORT))
auth = base64.encodestring(b"spam:BAD PASSWD").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if response.status != UNAUTHORIZED:
self.fail("req.status is not httplib.UNAUTHORIZED, but: %s" % repr(response.status))
if rsp == b"test ok":
self.fail("We were supposed to get HTTP_UNAUTHORIZED")
def test_req_get_basic_auth_pw_conf(self):
if APACHE_VERSION == '2.4':
c = VirtualHost("*",
ServerName("test_req_get_basic_auth_pw"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("basic"),
Require("all granted"),
PythonHandler("tests::req_get_basic_auth_pw"),
PythonDebug("On")))
else:
c = VirtualHost("*",
ServerName("test_req_get_basic_auth_pw"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("basic"),
PythonHandler("tests::req_get_basic_auth_pw"),
PythonDebug("On")))
return c
def test_req_get_basic_auth_pw(self):
print("\n * Testing req.get_basic_auth_pw()")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_get_basic_auth_pw", PORT))
auth = base64.encodestring(b"spam:eggs").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_get_basic_auth_pw_latin1_conf(self):
return self.test_req_get_basic_auth_pw_conf()
def test_req_get_basic_auth_pw_latin1(self):
print("\n * Testing req.get_basic_auth_pw_latin1()")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_get_basic_auth_pw", PORT))
auth = base64.encodestring(b'sp\xe1m:\xe9ggs').strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_auth_type_conf(self):
c = VirtualHost("*",
ServerName("test_req_auth_type"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("dummy"),
Require("valid-user"),
PythonAuthenHandler("tests::req_auth_type"),
PythonAuthzHandler("tests::req_auth_type"),
PythonHandler("tests::req_auth_type"),
PythonDebug("On")))
return c
def test_req_auth_type(self):
print("\n * Testing req.auth_type()")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_auth_type", PORT))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_requires_conf(self):
c = VirtualHost("*",
ServerName("test_req_requires"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthName("blah"),
AuthType("dummy"),
Require("valid-user"),
PythonAuthenHandler("tests::req_requires"),
PythonDebug("On")))
return c
def test_req_requires(self):
print("\n * Testing req.requires()")
rsp = self.vhost_get("test_req_requires")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_requires", PORT))
auth = base64.encodestring(b"spam:eggs").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_internal_redirect_conf(self):
c = VirtualHost("*",
ServerName("test_req_internal_redirect"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_internal_redirect | .py"),
PythonHandler("tests::req_internal_redirect_int | .int"),
PythonDebug("On")))
return c
def test_req_internal_redirect(self):
print("\n * Testing req.internal_redirect()")
rsp = self.vhost_get("test_req_internal_redirect")
if rsp != "test ok":
self.fail("internal_redirect")
def test_req_construct_url_conf(self):
c = VirtualHost("*",
ServerName("test_req_construct_url"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_construct_url"),
PythonDebug("On")))
return c
def test_req_construct_url(self):
print("\n * Testing req.construct_url()")
rsp = self.vhost_get("test_req_construct_url")
if rsp != "test ok":
self.fail("construct_url")
def test_req_read_conf(self):
c = Container(Timeout("5"),
VirtualHost("*",
ServerName("test_req_read"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_read"),
PythonDebug("On"))))
return c
def test_req_read(self):
print("\n * Testing req.read()")
params = b'1234567890'*10000
print(" writing %d bytes..." % len(params))
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("POST", "/tests.py", skip_host=1)
conn.putheader("Host", "test_req_read:%s" % PORT)
conn.putheader("Content-Length", str(len(params)))
conn.endheaders()
conn.send(params)
response = conn.getresponse()
rsp = response.read()
conn.close()
print(" response size: %d\n" % len(rsp))
if (rsp != params):
self.fail(repr(rsp))
print(" read/write ok, now lets try causing a timeout (should be 5 secs)")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("POST", "/tests.py", skip_host=1)
conn.putheader("Host", "test_req_read:%s" % PORT)
conn.putheader("Content-Length", str(10))
conn.endheaders()
conn.send(b"123456789")
response = conn.getresponse()
rsp = response.read()
conn.close()
if rsp.find(b"IOError") < 0 and rsp.find(b"OSError") < 0:
self.fail("timeout test failed")
def test_req_readline_conf(self):
c = VirtualHost("*",
ServerName("test_req_readline"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_readline"),
PythonDebug("On")))
return c
def test_req_readline(self):
print("\n * Testing req.readline()")
params = (b'1234567890'*3000+b'\n')*4
print(" writing %d bytes..." % len(params))
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("POST", "/tests.py", skip_host=1)
conn.putheader("Host", "test_req_readline:%s" % PORT)
conn.putheader("Content-Length", str(len(params)))
conn.endheaders()
conn.send(params)
response = conn.getresponse()
rsp = response.read()
conn.close()
print(" response size: %d\n" % len(rsp))
if (rsp != params):
self.fail(repr(rsp))
def test_req_readlines_conf(self):
c = VirtualHost("*",
ServerName("test_req_readlines"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_readlines"),
PythonDebug("On")))
return c
def test_req_readlines(self):
print("\n * Testing req.readlines()")
params = (b'1234567890'*3000+b'\n')*4
print(" writing %d bytes..." % len(params))
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("POST", "/tests.py", skip_host=1)
conn.putheader("Host", "test_req_readlines:%s" % PORT)
conn.putheader("Content-Length", str(len(params)))
conn.endheaders()
conn.send(params)
response = conn.getresponse()
rsp = response.read()
conn.close()
print(" response size: %d\n" % len(rsp))
if (rsp != params):
self.fail(repr(rsp))
print("\n * Testing req.readlines(size_hint=30000)")
params = (b'1234567890'*3000+b'\n')*4
print(" writing %d bytes..." % len(params))
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("POST", "/tests.py", skip_host=1)
conn.putheader("Host", "test_req_readlines:%s" % PORT)
conn.putheader("Content-Length", str(len(params)))
conn.putheader("SizeHint", str(30000))
conn.endheaders()
conn.send(params)
response = conn.getresponse()
rsp = response.read()
conn.close()
print(" response size: %d\n" % len(rsp))
if (rsp != (b'1234567890'*3000+b'\n')):
self.fail(repr(rsp))
print("\n * Testing req.readlines(size_hint=32000)")
params = (b'1234567890'*3000+b'\n')*4
print(" writing %d bytes..." % len(params))
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("POST", "/tests.py", skip_host=1)
conn.putheader("Host", "test_req_readlines:%s" % PORT)
conn.putheader("Content-Length", str(len(params)))
conn.putheader("SizeHint", str(32000))
conn.endheaders()
conn.send(params)
response = conn.getresponse()
rsp = response.read()
conn.close()
print(" response size: %d\n" % len(rsp))
if (rsp != ((b'1234567890'*3000+b'\n')*2)):
self.fail(repr(rsp))
def test_req_discard_request_body_conf(self):
c = Container(Timeout("5"),
VirtualHost("*",
ServerName("test_req_discard_request_body"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_discard_request_body"),
PythonDebug("On"))))
return c
def test_req_discard_request_body(self):
print("\n * Testing req.discard_request_body()")
params = b'1234567890'*2
print(" writing %d bytes..." % len(params))
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "test_req_discard_request_body:%s" % PORT)
conn.putheader("Content-Length", str(len(params)))
conn.endheaders()
conn.send(params)
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_register_cleanup_conf(self):
c = VirtualHost("*",
ServerName("test_req_register_cleanup"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_register_cleanup"),
PythonDebug("On")))
return c
def test_req_register_cleanup(self):
print("\n * Testing req.register_cleanup()")
rsp = self.vhost_get("test_req_register_cleanup")
# see what's in the log now
time.sleep(1)
f = open(os.path.join(SERVER_ROOT, "logs/error_log"))
log = f.read()
f.close()
if log.find("req_register_cleanup test ok") == -1:
self.fail("Could not find test message in error_log")
def test_req_headers_out_conf(self):
c = VirtualHost("*",
ServerName("test_req_headers_out"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_headers_out"),
PythonDebug("On")))
return c
def test_req_headers_out(self):
print("\n * Testing req.headers_out")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/test.py", skip_host=1)
conn.putheader("Host", "test_req_headers_out:%s" % PORT)
conn.endheaders()
response = conn.getresponse()
h = response.getheader("x-test-header", None)
response.read()
conn.close()
if h is None:
self.fail("Could not find x-test-header")
if h != "test ok":
self.fail("x-test-header is there, but does not contain 'test ok'")
def test_req_sendfile_conf(self):
c = VirtualHost("*",
ServerName("test_req_sendfile"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_sendfile"),
PythonDebug("On")))
return c
def test_req_sendfile(self):
print("\n * Testing req.sendfile() with offset and length")
rsp = self.vhost_get("test_req_sendfile")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_req_sendfile2_conf(self):
c = VirtualHost("*",
ServerName("test_req_sendfile2"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_sendfile2"),
PythonDebug("On")))
return c
def test_req_sendfile2(self):
print("\n * Testing req.sendfile() without offset and length")
rsp = self.vhost_get("test_req_sendfile2")
if (rsp != "0123456789"*100):
self.fail(repr(rsp))
def test_req_sendfile3_conf(self):
c = VirtualHost("*",
ServerName("test_req_sendfile3"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_sendfile3"),
PythonDebug("On")))
return c
def test_req_sendfile3(self):
if os.name == 'posix':
print("\n * Testing req.sendfile() for a file which is a symbolic link")
rsp = self.vhost_get("test_req_sendfile3")
if (rsp != "0123456789"*100):
self.fail(repr(rsp))
else:
print("\n * Skipping req.sendfile() for a file which is a symbolic link")
def test_req_handler_conf(self):
c = VirtualHost("*",
ServerName("test_req_handler"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
PythonFixupHandler("tests::req_handler"),
PythonDebug("On")))
return c
def test_req_handler(self):
print("\n * Testing req.handler")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_handler", PORT))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_no_cache_conf(self):
c = VirtualHost("*",
ServerName("test_req_no_cache"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_no_cache"),
PythonDebug("On")))
return c
def test_req_no_cache(self):
print("\n * Testing req.no_cache")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_no_cache", PORT))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if response.getheader("expires", None) is None:
self.fail(repr(response.getheader("expires", None)))
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_req_update_mtime_conf(self):
c = VirtualHost("*",
ServerName("test_req_update_mtime"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_update_mtime"),
PythonDebug("On")))
return c
def test_req_update_mtime(self):
print("\n * Testing req.update_mtime")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_req_update_mtime", PORT))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if response.getheader("etag", None) is None:
self.fail(repr(response.getheader("etag", None)))
if response.getheader("last-modified", None) is None:
self.fail(repr(response.getheader("last-modified", None)))
if (rsp != b"test ok"):
self.fail(repr(rsp))
def test_util_redirect_conf(self):
c = VirtualHost("*",
ServerName("test_util_redirect"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
PythonFixupHandler("tests::util_redirect"),
PythonHandler("tests::util_redirect"),
PythonDebug("On")))
return c
def test_util_redirect(self):
print("\n * Testing util.redirect()")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_util_redirect", PORT))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if response.status != 302:
self.fail('did not receive 302 status response: %s' % repr(response.status))
if response.getheader("location", None) != "/dummy":
self.fail('did not receive correct location for redirection')
if rsp != b"test ok":
self.fail(repr(rsp))
def test_req_server_get_config_conf(self):
c = VirtualHost("*",
ServerName("test_req_server_get_config"),
DocumentRoot(DOCUMENT_ROOT),
PythonDebug("On"),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_server_get_config"),
PythonDebug("Off")))
return c
def test_req_server_get_config(self):
print("\n * Testing req.server.get_config()")
rsp = self.vhost_get("test_req_server_get_config")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_req_server_get_options_conf(self):
c = VirtualHost("*",
ServerName("test_req_server_get_options"),
DocumentRoot(DOCUMENT_ROOT),
PythonDebug("Off"),
PythonOption("global 1"),
PythonOption("override 1"),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::req_server_get_options"),
PythonOption("local 1"),
PythonOption("override 2"),
PythonDebug("On")))
return c
def test_req_server_get_options(self):
print("\n * Testing req.server.get_options()")
rsp = self.vhost_get("test_req_server_get_options")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_fileupload_conf(self):
c = VirtualHost("*",
ServerName("test_fileupload"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::fileupload"),
PythonDebug("On")))
return c
def test_fileupload(self):
print("\n * Testing 1 MB file upload support")
content = ''.join( [ chr(random.randrange(256)) for x in range(1024*1024) ] )
digest = md5_hash(content)
rsp = self.vhost_post_multipart_form_data(
"test_fileupload",
variables={'test':'abcd'},
files={'testfile':('test.txt',content)},
)
if (rsp != digest):
self.fail('1 MB file upload failed, its contents were corrupted. Expected (%s), got (%s)' % (repr(digest), repr(rsp)))
def test_fileupload_embedded_cr_conf(self):
c = VirtualHost("*",
ServerName("test_fileupload"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::fileupload"),
PythonDebug("On")))
return c
def test_fileupload_embedded_cr(self):
# Strange things can happen if there is a '\r' character at position
# readBlockSize of a line being read by FieldStorage.read_to_boundary
# where the line length is > readBlockSize.
# This test will expose this problem.
print("\n * Testing file upload with \\r char in a line at position == readBlockSize")
content = (
'a'*100 + '\r\n'
+ 'b'*(readBlockSize-1) + '\r' # trick !
+ 'ccc' + 'd'*100 + '\r\n'
)
digest = md5_hash(content)
rsp = self.vhost_post_multipart_form_data(
"test_fileupload",
variables={'test':'abcd'},
files={'testfile':('test.txt',content)},
)
if (rsp != digest):
self.fail('file upload embedded \\r test failed, its contents were corrupted (%s)'%rsp)
# The UNIX-HATERS handbook illustrates this problem. Once we've done some additional
# investigation to make sure that our synthetic file used above is correct,
# we can likely remove this conditional test. Also, there is no way to be sure
# that ugh.pdf will always be the same in the future so the test may not be valid
# over the long term.
try:
ugh = open('ugh.pdf','rb')
content = ugh.read()
ugh.close()
except:
print(" * Skipping the test for The UNIX-HATERS handbook file upload.")
print(" To make this test, you need to download ugh.pdf from")
print(" http://web.mit.edu/~simsong/www/ugh.pdf")
print(" into this script's directory.")
else:
print(" * Testing The UNIX-HATERS handbook file upload support")
digest = md5_hash(content)
rsp = self.vhost_post_multipart_form_data(
"test_fileupload",
variables={'test':'abcd'},
files={'testfile':('ugh.pdf',content)},
)
if (rsp != digest):
self.fail('The UNIX-HATERS handbook file upload failed, its contents was corrupted (%s)'%rsp)
def test_fileupload_split_boundary_conf(self):
c = VirtualHost("*",
ServerName("test_fileupload"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::fileupload"),
PythonDebug("On")))
return c
def test_fileupload_split_boundary(self):
# This test is similar to test_fileupload_embedded_cr, but it is possible to
# write an implementation of FieldStorage.read_to_boundary that will pass
# that test but fail this one.
#
# Strange things can happen if the last line in the file being uploaded
# has length == readBlockSize -1. The boundary string marking the end of the
# file (eg. '\r\n--myboundary') will be split between the leading '\r' and the
# '\n'. Some implementations of read_to_boundary we've tried assume that this
# '\r' character is part of the file, instead of the boundary string. The '\r'
# will be appended to the uploaded file, leading to a corrupted file.
print("\n * Testing file upload where length of last line == readBlockSize - 1")
content = (
'a'*100 + '\r\n'
+ 'b'*(readBlockSize-1) # trick !
)
digest = md5_hash(content)
rsp = self.vhost_post_multipart_form_data(
"test_fileupload",
variables={'test':'abcd'},
files={'testfile':('test.txt',content)},
)
if (rsp != digest):
self.fail('file upload long line test failed, its contents were corrupted (%s)'%rsp)
print(" * Testing file upload where length of last line == readBlockSize - 1 with an extra \\r")
content = (
'a'*100 + '\r\n'
+ 'b'*(readBlockSize-1)
+ '\r' # second trick !
)
digest = md5_hash(content)
rsp = self.vhost_post_multipart_form_data(
"test_fileupload",
variables={'test':'abcd'},
files={'testfile':('test.txt',content)},
)
if (rsp != digest):
self.fail('file upload long line test failed, its contents were corrupted (%s)'%rsp)
def test_sys_argv_conf(self):
c = VirtualHost("*",
ServerName("test_sys_argv"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::test_sys_argv"),
PythonDebug("On")))
return c
def test_sys_argv(self):
print("\n * Testing sys.argv definition")
rsp = self.vhost_get("test_sys_argv")
if (rsp != "['mod_python']"):
self.fail(repr(rsp))
def test_PythonOption_conf(self):
c = VirtualHost("*",
ServerName("test_PythonOption"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::PythonOption_items"),
PythonDebug("On")))
return c
def test_PythonOption(self):
print("\n * Testing PythonOption")
rsp = self.vhost_get("test_PythonOption")
if (rsp != "[('PythonOptionTest', 'sample_value')]"):
self.fail(repr(rsp))
def test_PythonOption_override_conf(self):
c = VirtualHost("*",
ServerName("test_PythonOption_override"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::PythonOption_items"),
PythonOption('PythonOptionTest "new_value"'),
PythonOption('PythonOptionTest2 "new_value2"'),
PythonDebug("On")))
return c
def test_PythonOption_override(self):
print("\n * Testing PythonOption override")
rsp = self.vhost_get("test_PythonOption_override")
if (rsp != "[('PythonOptionTest', 'new_value'), ('PythonOptionTest2', 'new_value2')]"):
self.fail(repr(rsp))
def test_PythonOption_remove_conf(self):
c = VirtualHost("*",
ServerName("test_PythonOption_remove"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::PythonOption_items"),
PythonOption('PythonOptionTest ""'),
PythonOption('PythonOptionTest2 "new_value2"'),
PythonDebug("On")))
return c
def test_PythonOption_remove(self):
print("\n * Testing PythonOption remove")
rsp = self.vhost_get("test_PythonOption_remove")
if (rsp != "[('PythonOptionTest2', 'new_value2')]"):
self.fail(repr(rsp))
def test_PythonOption_remove2_conf(self):
c = VirtualHost("*",
ServerName("test_PythonOption_remove2"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::PythonOption_items"),
PythonOption('PythonOptionTest'),
PythonOption('PythonOptionTest2 "new_value2"'),
PythonOption('PythonOptionTest3 new_value3'),
PythonDebug("On")))
return c
def test_PythonOption_remove2(self):
print("\n * Testing PythonOption remove2")
rsp = self.vhost_get("test_PythonOption_remove2")
if (rsp != "[('PythonOptionTest2', 'new_value2'), ('PythonOptionTest3', 'new_value3')]"):
self.fail(repr(rsp))
def test_interpreter_per_directive_conf(self):
c = VirtualHost("*",
ServerName("test_interpreter_per_directive"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
PythonInterpPerDirective('On'),
SetHandler("mod_python"),
PythonHandler("tests::interpreter"),
PythonDebug("On")))
return c
def test_interpreter_per_directive(self):
print("\n * Testing interpreter per directive")
interpreter_name = (DOCUMENT_ROOT.replace('\\', '/')+'/').upper()
rsp = self.vhost_get("test_interpreter_per_directive").upper()
if (rsp != interpreter_name):
self.fail(repr(rsp))
rsp = self.vhost_get("test_interpreter_per_directive", '/subdir/foo.py').upper()
if (rsp != interpreter_name):
self.fail(repr(rsp))
rsp = self.vhost_get("test_interpreter_per_directive", '/subdir/').upper()
if (rsp != interpreter_name):
self.fail(repr(rsp))
def test_interpreter_per_directory_conf(self):
c = VirtualHost("*",
ServerName("test_interpreter_per_directory"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
PythonInterpPerDirectory('On'),
SetHandler("mod_python"),
PythonFixupHandler("tests::interpreter"),
PythonDebug("On")),
)
return c
def test_interpreter_per_directory(self):
print("\n * Testing interpreter per directory")
interpreter_name = (DOCUMENT_ROOT.replace('\\', '/')+'/').upper()
rsp = self.vhost_get("test_interpreter_per_directory").upper()
if (rsp != interpreter_name):
self.fail(repr(rsp))
rsp = self.vhost_get("test_interpreter_per_directory", '/subdir/foo.py').upper()
if (rsp != interpreter_name+'SUBDIR/'):
self.fail(repr(rsp))
rsp = self.vhost_get("test_interpreter_per_directory", '/subdir/').upper()
if (rsp != interpreter_name+'SUBDIR/'):
self.fail(repr(rsp))
rsp = self.vhost_get("test_interpreter_per_directory", '/subdir').upper()
if (rsp != interpreter_name+'SUBDIR/'):
self.fail(repr(rsp))
def test_util_fieldstorage_conf(self):
c = VirtualHost("*",
ServerName("test_util_fieldstorage"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::util_fieldstorage"),
PythonDebug("On")))
return c
def test_util_fieldstorage(self):
print("\n * Testing util_fieldstorage()")
params = urlencode([('spam', 1), ('spam', 2), ('eggs', 3), ('bacon', 4)])
headers = {"Host": "test_util_fieldstorage",
"Content-type": "application/x-www-form-urlencoded",
"Accept": "text/plain"}
conn = http_connection("127.0.0.1:%s" % PORT)
conn.request("POST", "/tests.py", params, headers)
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != "[Field('spam', '1'), Field('spam', '2'), Field('eggs', '3'), Field('bacon', '4')]" and
rsp != b"[Field(b'spam', b'1'), Field(b'spam', b'2'), Field(b'eggs', b'3'), Field(b'bacon', b'4')]"):
self.fail(repr(rsp))
def test_postreadrequest_conf(self):
c = VirtualHost("*",
ServerName("test_postreadrequest"),
DocumentRoot(DOCUMENT_ROOT),
SetHandler("mod_python"),
PythonPath("[r'%s']+sys.path" % DOCUMENT_ROOT),
PythonPostReadRequestHandler("tests::postreadrequest"),
PythonDebug("On"))
return c
def test_postreadrequest(self):
print("\n * Testing PostReadRequestHandler")
rsp = self.vhost_get("test_postreadrequest")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_trans_conf(self):
c = VirtualHost("*",
ServerName("test_trans"),
DocumentRoot(DOCUMENT_ROOT),
SetHandler("mod_python"),
PythonPath("[r'%s']+sys.path" % DOCUMENT_ROOT),
PythonTransHandler("tests::trans"),
PythonDebug("On"))
return c
def test_trans(self):
print("\n * Testing TransHandler")
rsp = self.vhost_get("test_trans")
if (rsp[0:2] != " #"): # first line in tests.py
self.fail(repr(rsp))
def test_import_conf(self):
# configure apache to import it at startup
c = Container(PythonPath("[r'%s']+sys.path" % DOCUMENT_ROOT),
PythonImport("dummymodule test_import"),
PythonImport("dummymodule::function test_import"),
VirtualHost("*",
ServerName("test_import"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::import_test"),
PythonDebug("On"))))
return c
def test_import(self):
print("\n * Testing PythonImport")
rsp = self.vhost_get("test_import")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_outputfilter_conf(self):
c = VirtualHost("*",
ServerName("test_outputfilter"),
DocumentRoot(DOCUMENT_ROOT),
SetHandler("mod_python"),
PythonPath("[r'%s']+sys.path" % DOCUMENT_ROOT),
PythonHandler("tests::simplehandler"),
PythonOutputFilter("tests::outputfilter MP_TEST_FILTER"),
PythonDebug("On"),
AddOutputFilter("MP_TEST_FILTER .py"))
return c
def test_outputfilter(self):
print("\n * Testing PythonOutputFilter")
rsp = self.vhost_get("test_outputfilter")
if (rsp != "TEST OK"):
self.fail(repr(rsp))
def test_req_add_output_filter_conf(self):
c = VirtualHost("*",
ServerName("test_req_add_output_filter"),
DocumentRoot(DOCUMENT_ROOT),
SetHandler("mod_python"),
PythonPath("[r'%s']+sys.path" % DOCUMENT_ROOT),
PythonHandler("tests::req_add_output_filter"),
PythonOutputFilter("tests::outputfilter MP_TEST_FILTER"),
PythonDebug("On"))
return c
def test_req_add_output_filter(self):
print("\n * Testing req.add_output_filter")
rsp = self.vhost_get("test_req_add_output_filter")
if (rsp != "TEST OK"):
self.fail(repr(rsp))
def test_req_register_output_filter_conf(self):
c = VirtualHost("*",
ServerName("test_req_register_output_filter"),
DocumentRoot(DOCUMENT_ROOT),
SetHandler("mod_python"),
PythonPath("[r'%s']+sys.path" % DOCUMENT_ROOT),
PythonHandler("tests::req_register_output_filter"),
PythonDebug("On"))
return c
def test_req_register_output_filter(self):
print("\n * Testing req.register_output_filter")
rsp = self.vhost_get("test_req_register_output_filter")
if (rsp != "TEST OK"):
self.fail(repr(rsp))
def test_connectionhandler_conf(self):
try:
localip = socket.gethostbyname("localhost")
except:
localip = "127.0.0.1"
self.conport = findUnusedPort()
c = Container(Listen("%d" % self.conport),
VirtualHost("%s:%d" % (localip, self.conport),
SetHandler("mod_python"),
PythonPath("[r'%s']+sys.path" % DOCUMENT_ROOT),
PythonConnectionHandler("tests::connectionhandler")))
return c
def test_connectionhandler(self):
print("\n * Testing PythonConnectionHandler on port %d" % self.conport)
url = "http://127.0.0.1:%s/tests.py" % self.conport
f = urlopen(url)
if PY2:
rsp = f.read()
else:
rsp = f.read().decode('latin1')
f.close()
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_internal_conf(self):
c = VirtualHost("*",
ServerName("test_internal"),
ServerAdmin("serveradmin@somewhere.com"),
ErrorLog("logs/error_log"),
ServerPath("some/path"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests"),
PythonOption('PythonOptionTest ""'),
PythonOption('mod_python.mutex_directory ""'),
PythonOption("testing 123"),
PythonDebug("On")))
return c
def test_internal(self):
print("\n * Testing internally (status messages go to error_log)")
rsp = self.vhost_get("test_internal")
if (rsp[-7:] != "test ok"):
self.fail("Some tests failed, see error_log")
def test_pipe_ext_conf(self):
c = VirtualHost("*",
ServerName("test_pipe_ext"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher | .py"),
PythonHandler("tests::simplehandler"),
PythonDebug("On")))
return c
def test_pipe_ext(self):
print("\n * Testing | .ext syntax")
rsp = self.vhost_get("test_pipe_ext", path="/tests.py/pipe_ext")
if (rsp[-8:] != "pipe ext"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_pipe_ext", path="/tests/anything")
if (rsp[-7:] != "test ok"):
self.fail(repr(rsp))
def test_wsgihandler_conf(self):
c = VirtualHost("*",
ServerName("test_wsgihandler"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.wsgi"),
PythonOption("mod_python.wsgi.application wsgitest"),
PythonDebug("On")))
return c
def test_wsgihandler(self):
print("\n * Testing mod_python.wsgi")
rsp = self.vhost_get("test_wsgihandler")
if (rsp[-8:] != "test ok\n"):
self.fail(repr(rsp))
# see what's in the log now
time.sleep(0.1)
log = open(os.path.join(SERVER_ROOT, "logs/error_log")).read()
if "written_from_wsgi_test" not in log:
self.fail("string 'written_from_wsgi_test' not found in error log.")
def test_wsgihandler_location_conf(self):
c = VirtualHost("*",
ServerName("test_wsgihandler_location"),
DocumentRoot(DOCUMENT_ROOT),
Location("/foo",
SetHandler("mod_python"),
PythonHandler("mod_python.wsgi"),
PythonPath("[r'%s']+sys.path" % DOCUMENT_ROOT),
PythonOption("mod_python.wsgi.application wsgitest::base_uri"),
PythonDebug("On")))
return c
def test_wsgihandler_location(self):
print("\n * Testing mod_python.wsgi")
rsp = self.vhost_get("test_wsgihandler_location", "/foo/bar")
if (rsp[-8:] != "test ok\n"):
self.fail(repr(rsp))
def test_cgihandler_conf(self):
c = VirtualHost("*",
ServerName("test_cgihandler"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.cgihandler"),
PythonDebug("On")))
return c
def test_cgihandler(self):
print("\n * Testing mod_python.cgihandler")
rsp = self.vhost_get("test_cgihandler", path="/cgitest.py")
if (rsp[-8:] != "test ok\n"):
self.fail(repr(rsp))
def test_psphandler_conf(self):
c = VirtualHost("*",
ServerName("test_psphandler"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.psp"),
PythonDebug("On")))
return c
def test_psphandler(self):
print("\n * Testing mod_python.psp")
rsp = self.vhost_get("test_psphandler", path="/psptest.psp")
if (rsp[-8:] != "test ok\n"):
self.fail(repr(rsp))
def test_psp_parser_conf(self):
c = VirtualHost("*",
ServerName("test_psp_parser"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.psp"),
PythonDebug("On")))
return c
def test_psp_parser(self):
print("\n * Testing mod_python.psp parser")
# lines in psp_parser.psp should look like:
# test:<char>:<test_string>$
#
# For example:
# test:n:\n$
# test:t:\t$
rsp = self.vhost_get("test_psp_parser", path="/psp_parser.psp")
lines = [ line.strip() for line in rsp.split('$') if line ]
failures = []
for line in lines:
parts = line.split(':', 2)
if len(parts) < 3:
continue
t, test_case, test_string = parts[0:3]
if not t.strip().startswith('test'):
continue
expected_result = test_case
# do the substitutions in expected_result
for ss, rs in [('-', '\\'),('CR', '\r'), ('LF', '\n'), ('TB', '\t')]:
expected_result = expected_result.replace(ss, rs)
if expected_result != test_string:
failures.append(test_case)
#print 'expect{%s} got{%s}' % (expected_result, test_string)
if failures:
msg = 'psp_parser parse errors for: %s' % (', '.join(failures))
self.fail(msg)
def test_psp_error_conf(self):
c = VirtualHost("*",
ServerName("test_psp_error"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.psp"),
PythonOption('mod_python.session.database_directory "%s"' % TMP_DIR),
PythonDebug("On")))
return c
def test_psp_error(self):
print("\n * Testing mod_python.psp error page")
rsp = self.vhost_get("test_psp_error", path="/psptest_main.psp")
if (rsp.strip().split() != ["okay","fail"]):
self.fail(repr(rsp))
def test_Cookie_Cookie_conf(self):
c = VirtualHost("*",
ServerName("test_Cookie_Cookie"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::Cookie_Cookie"),
PythonDebug("On")))
return c
def test_Cookie_Cookie(self):
print("\n * Testing Cookie.Cookie")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/testz.py", skip_host=1)
# this is three cookies, nastily formatted
conn.putheader("Host", "test_Cookie_Cookie:%s" % PORT)
conn.putheader("Cookie", "spam=foo; path=blah;;eggs=bar;")
conn.putheader("Cookie", "bar=foo")
conn.endheaders()
response = conn.getresponse()
setcookie = response.getheader("set-cookie", None)
rsp = response.read()
conn.close()
if rsp != b"test ok" or ('path=blah' not in setcookie or
'eggs=bar' not in setcookie or
'bar=foo' not in setcookie or
'spam=foo' not in setcookie):
print(repr(rsp))
print(repr(setcookie))
self.fail("cookie parsing failed")
def test_Cookie_MarshalCookie_conf(self):
c = VirtualHost("*",
ServerName("test_Cookie_MarshalCookie"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::Cookie_Cookie"),
PythonDebug("On")))
return c
def test_Cookie_MarshalCookie(self):
print("\n * Testing Cookie.MarshalCookie")
mc = "eggs=d049b2b61adb6a1d895646719a3dc30bcwQAAABzcGFt"
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/testz.py", skip_host=1)
conn.putheader("Host", "test_Cookie_MarshalCookie:%s" % PORT)
conn.putheader("Cookie", mc)
conn.endheaders()
response = conn.getresponse()
setcookie = response.getheader("set-cookie", None)
rsp = response.read()
conn.close()
if rsp != b"test ok" or setcookie != mc:
print(repr(rsp))
self.fail("marshalled cookie parsing failed")
# and now a long MarshalledCookie test !
mc = ('test=859690207856ec75fc641a7566894e40c1QAAAB0'
'aGlzIGlzIGEgdmVyeSBsb25nIHZhbHVlLCBsb25nIGxvb'
'mcgbG9uZyBsb25nIGxvbmcgc28gbG9uZyBidXQgd2UnbG'
'wgZmluaXNoIGl0IHNvb24=')
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/testz.py", skip_host=1)
conn.putheader("Host", "test_Cookie_MarshalCookie:%s" % PORT)
conn.putheader("Cookie", mc)
conn.endheaders()
response = conn.getresponse()
setcookie = response.getheader("set-cookie", None)
rsp = response.read()
conn.close()
if rsp != b"test ok" or setcookie != mc:
print(repr(rsp))
self.fail("long marshalled cookie parsing failed")
def test_Session_Session_conf(self):
c = VirtualHost("*",
ServerName("test_Session_Session"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::Session_Session"),
PythonOption('mod_python.session.database_directory "%s"' % TMP_DIR),
PythonOption('mod_python.session.application_path "/path"'),
PythonOption('mod_python.session.application_domain "test_Session_Session"'),
PythonDebug("On")))
return c
def test_Session_Session(self):
print("\n * Testing Session.Session")
conn = http_connection("127.0.0.1:%s" % PORT)
#conn.set_debuglevel(1000)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "test_Session_Session:%s" % PORT)
conn.endheaders()
response = conn.getresponse()
setcookie = response.getheader("set-cookie", None)
rsp = response.read()
conn.close()
if rsp != b"test ok" or setcookie == None:
self.fail("session did not set a cookie")
parts = setcookie.split('; ')
fields = {}
for part in parts:
key, value = part.split('=')
fields[key] = value
if 'path' not in fields or fields['path'] != '/path':
self.fail("session did not contain expected 'path'")
if 'domain' not in fields or fields['domain'] != 'test_Session_Session':
self.fail("session did not contain expected 'domain'")
conn = http_connection("127.0.0.1:%s" % PORT)
#conn.set_debuglevel(1000)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "test_Session_Session:%s" % PORT)
conn.putheader("Cookie", setcookie)
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if rsp != b"test ok":
self.fail("session did not accept our cookie: %s" % repr(rsp))
def test_Session_illegal_sid_conf(self):
c = VirtualHost("*",
ServerName("test_Session_Session"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::Session_Session"),
PythonOption('mod_python.session.database_directory "%s"' % TMP_DIR),
PythonDebug("On")))
return c
def test_Session_illegal_sid(self):
print("\n * Testing Session with illegal session id value")
bad_cookie = 'pysid=/path/traversal/attack/bad; path=/'
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "test_Session_Session:%s" % PORT)
conn.putheader("Cookie", bad_cookie)
conn.endheaders()
response = conn.getresponse()
setcookie = response.getheader("set-cookie", None)
status = response.status
conn.close()
if status != 200 or not setcookie:
self.fail("session id with illegal characters not replaced")
bad_cookie = 'pysid=%s; path=/' % ('abcdef'*64)
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "test_Session_Session:%s" % PORT)
conn.putheader("Cookie", bad_cookie)
conn.endheaders()
response = conn.getresponse()
setcookie = response.getheader("set-cookie", None)
status = response.status
conn.close()
if status != 200 or not setcookie:
self.fail("session id which is too long not replaced")
def test_files_directive_conf(self):
c = VirtualHost("*",
ServerName("test_files_directive"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
Files("*.py",
SetHandler("mod_python"),
PythonHandler("tests::files_directive"),
PythonDebug("On"))))
return c
def test_files_directive(self):
directory = (DOCUMENT_ROOT.replace('\\', '/')+'/').upper()
print("\n * Testing Files directive")
rsp = self.vhost_get("test_files_directive", path="/tests.py").upper()
if rsp != directory:
self.fail(repr(rsp))
def test_none_handler_conf(self):
c = VirtualHost("*",
ServerName("test_none_handler"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::none_handler"),
PythonDebug("On")))
return c
def test_none_handler(self):
print("\n * Testing None handler")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py", skip_host=1)
conn.putheader("Host", "test_none_handler:%s" % PORT)
conn.endheaders()
response = conn.getresponse()
status = response.status
rsp = response.read()
conn.close()
if status != 500:
print(status, rsp)
self.fail("none handler should generate error")
def test_server_return_conf(self):
c = VirtualHost("*",
ServerName("test_server_return"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::server_return_1"),
PythonHandler("tests::server_return_2"),
PythonDebug("On")))
return c
def test_server_return(self):
print("\n * Testing SERVER_RETURN")
rsp = self.vhost_get("test_server_return")
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_phase_status_conf(self):
c = VirtualHost("*",
ServerName("test_phase_status"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
AuthType("bogus"),
AuthName("bogus"),
Require("valid-user"),
PythonAuthenHandler("tests::phase_status_1"),
PythonAuthenHandler("tests::phase_status_2"),
PythonAuthenHandler("tests::phase_status_3"),
PythonAuthzHandler("tests::phase_status_4"),
PythonFixupHandler("tests::phase_status_5"),
PythonFixupHandler("tests::phase_status_6"),
PythonFixupHandler("tests::phase_status_7"),
PythonHandler("tests::phase_status_8"),
PythonCleanupHandler("tests::phase_status_cleanup"),
PythonDebug("On")))
return c
def test_phase_status(self):
print("\n * Testing phase status")
rsp = self.vhost_get("test_phase_status")
if (rsp != "test ok"):
self.fail(repr(rsp))
# see what's in the log now
time.sleep(0.1)
log = open(os.path.join(SERVER_ROOT, "logs/error_log")).read()
if "phase_status_cleanup_log_entry" not in log:
self.fail("phase_status_cleanup_log_entry not found in logs, cleanup handler never ran?")
def test_publisher_conf(self):
c = VirtualHost("*",
ServerName("test_publisher"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher(self):
print("\n * Testing mod_python.publisher")
rsp = self.vhost_get("test_publisher", path="/tests.py")
if (rsp != "test ok, interpreter=test_publisher"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher", path="/tests.py/index")
if (rsp != "test ok, interpreter=test_publisher"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher", path="/tests.py/test_publisher")
if (rsp != "test ok, interpreter=test_publisher"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher", path="/")
if (rsp != "test 1 ok, interpreter=test_publisher"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher", path="/foobar")
if (rsp != "test 2 ok, interpreter=test_publisher"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher", path="/tests")
if (rsp != "test ok, interpreter=test_publisher"):
self.fail(repr(rsp))
def test_publisher_auth_nested_conf(self):
c = VirtualHost("*",
ServerName("test_publisher_auth_nested"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher_auth_nested(self):
print("\n * Testing mod_python.publisher auth nested")
conn = http_connection("127.0.0.1:%s" % PORT)
#conn.set_debuglevel(1000)
conn.putrequest("GET", "/tests.py/test_publisher_auth_nested", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_publisher_auth_nested", PORT))
auth = base64.encodestring(b"spam:eggs").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok, interpreter=test_publisher_auth_nested"):
self.fail(repr(rsp))
def test_publisher_auth_method_nested_conf(self):
c = VirtualHost("*",
ServerName("test_publisher_auth_method_nested"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher_auth_method_nested(self):
print("\n * Testing mod_python.publisher auth method nested")
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py/test_publisher_auth_method_nested/method", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_publisher_auth_method_nested", PORT))
auth = base64.encodestring(b"spam:eggs").strip()
if PY2:
conn.putheader("Authorization", "Basic %s" % auth)
else:
conn.putheader("Authorization", "Basic %s" % auth.decode("latin1"))
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok, interpreter=test_publisher_auth_method_nested"):
self.fail(repr(rsp))
def test_publisher_auth_digest_conf(self):
c = VirtualHost("*",
ServerName("test_publisher_auth_digest"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher_auth_digest(self):
print("\n * Testing mod_python.publisher auth digest compatability")
# The contents of the authorization header is not relevant,
# as long as it looks valid.
conn = http_connection("127.0.0.1:%s" % PORT)
conn.putrequest("GET", "/tests.py/test_publisher", skip_host=1)
conn.putheader("Host", "%s:%s" % ("test_publisher_auth_digest", PORT))
conn.putheader("Authorization", 'Digest username="Mufasa", realm="testrealm@host.com", nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", uri="/dir/index.html", qop=auth, nc=00000001, cnonce="0a4f113b", response="6629fae49393a05397450978507c4ef1", opaque="5ccc069c403ebaf9f0171e9517f40e41"')
conn.endheaders()
response = conn.getresponse()
rsp = response.read()
conn.close()
if (rsp != b"test ok, interpreter=test_publisher_auth_digest"):
self.fail(repr(rsp))
def test_publisher_security_conf(self):
c = VirtualHost("*",
ServerName("test_publisher"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher_security(self):
print("\n * Testing mod_python.publisher security")
def get_status(path):
conn = http_connection("127.0.0.1:%s" % PORT)
#conn.set_debuglevel(1000)
conn.putrequest("GET", path, skip_host=1)
conn.putheader("Host", "test_publisher:%s" % PORT)
conn.endheaders()
response = conn.getresponse()
status, response = response.status, response.read()
conn.close()
return status, response
status, response = get_status("/tests.py/_SECRET_PASSWORD")
if status != 403:
self.fail('Vulnerability : underscore prefixed attribute (%i)\n%s' % (status, response))
status, response = get_status("/tests.py/__ANSWER")
if status != 403:
self.fail('Vulnerability : underscore prefixed attribute (%i)\n%s' % (status, response))
status, response = get_status("/tests.py/re")
if status != 403:
self.fail('Vulnerability : module published (%i)\n%s' % (status, response))
status, response = get_status("/tests.py/OldStyleClassTest")
if status != 403:
self.fail('Vulnerability : old style class published (%i)\n%s' % (status, response))
status, response = get_status("/tests.py/InstanceTest")
if status != 403:
self.fail('Vulnerability : new style class published (%i)\n%s' % (status, response))
status, response = get_status("/tests.py/index/func_code")
if status != 403:
self.fail('Vulnerability : function traversal (%i)\n%s' % (status, response))
status, response = get_status("/tests.py/old_instance/traverse/func_code")
if status != 403:
self.fail('Vulnerability : old-style method traversal (%i)\n%s' % (status, response))
status, response = get_status("/tests.py/instance/traverse/func_code")
if status != 403:
self.fail('Vulnerability : new-style method traversal (%i)\n%s' % (status, response))
status, response = get_status("/tests.py/test_dict/keys")
if status != 403:
self.fail('Vulnerability : built-in type traversal (%i)\n%s' % (status, response))
status, response = get_status("/tests.py/test_dict_keys")
if status != 403:
self.fail('Vulnerability : built-in type publishing (%i)\n%s' % (status, response))
def test_publisher_iterator_conf(self):
c = VirtualHost("*",
ServerName("test_publisher"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher_iterator(self):
print("\n * Testing mod_python.publisher iterators")
rsp = self.vhost_get("test_publisher", path="/tests.py/test_dict_iteration")
if (rsp != "123"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher", path="/tests.py/test_generator")
if (rsp != "0123456789"):
self.fail(repr(rsp))
def test_publisher_hierarchy_conf(self):
c = VirtualHost("*",
ServerName("test_publisher_hierarchy"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher_hierarchy(self):
print("\n * Testing mod_python.publisher hierarchy")
rsp = self.vhost_get("test_publisher_hierarchy", path="/tests.py/hierarchy_root")
if (rsp != "Called root"):
self.fail(repr(rsp))
if PY2:
rsp = self.vhost_get("test_publisher_hierarchy", path="/tests.py/hierarchy_root_2")
if (rsp != "test ok, interpreter=test_publisher_hierarchy"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher_hierarchy", path="/tests.py/hierarchy_root/page1")
if (rsp != "Called page1"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher_hierarchy", path="/tests.py/hierarchy_root_2/page1")
if (rsp != "test ok, interpreter=test_publisher_hierarchy"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher_hierarchy", path="/tests.py/hierarchy_root/page1/subpage1")
if (rsp != "Called subpage1"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher_hierarchy", path="/tests.py/hierarchy_root/page2")
if (rsp != "Called page2"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher_hierarchy", path="/tests.py/hierarchy_root_2/page2")
if (rsp != "test ok, interpreter=test_publisher_hierarchy"):
self.fail(repr(rsp))
def test_publisher_old_style_instance_conf(self):
c = VirtualHost("*",
ServerName("test_publisher"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher_old_style_instance(self):
print("\n * Testing mod_python.publisher old-style instance publishing")
rsp = self.vhost_get("test_publisher", path="/tests.py/old_instance")
if (rsp != "test callable old-style instance ok"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher", path="/tests.py/old_instance/traverse")
if (rsp != "test traversable old-style instance ok"):
self.fail(repr(rsp))
def test_publisher_instance_conf(self):
c = VirtualHost("*",
ServerName("test_publisher"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher_instance(self):
print("\n * Testing mod_python.publisher instance publishing")
rsp = self.vhost_get("test_publisher", path="/tests.py/instance")
if (rsp != "test callable instance ok"):
self.fail(repr(rsp))
rsp = self.vhost_get("test_publisher", path="/tests.py/instance/traverse")
if (rsp != "test traversable instance ok"):
self.fail(repr(rsp))
def test_publisher_cache_conf(self):
c = VirtualHost("*",
ServerName("test_publisher"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("mod_python.publisher"),
PythonDebug("On")))
return c
def test_publisher_cache(self):
## It is not possible to get reliable results with this test
# for mpm-prefork and worker, and in fact it may not be possible
# to get consistent results.
# Therefore this test is currently disabled in the
# testPerRequestTests setup.
print("\n * Testing mod_python.publisher cache")
def write_published():
published = file('htdocs/temp.py','wb')
published.write('import time\n')
published.write('LOAD_TIME = time.time()\n')
published.write('def index(req):\n')
published.write(' return "OK %f"%LOAD_TIME\n')
published.close()
write_published()
try:
rsp = self.vhost_get("test_publisher", path="/temp.py")
if not rsp.startswith('OK '):
self.fail(repr(rsp))
rsp2 = self.vhost_get("test_publisher", path="/temp.py")
if rsp != rsp2:
self.fail(
"The publisher cache has reloaded a published module"
" even though it wasn't modified !"
)
# We wait three seconds to be sure we won't be annoyed
# by any lack of resolution of the stat().st_mtime member.
time.sleep(3)
write_published()
rsp2 = self.vhost_get("test_publisher", path="/temp.py")
if rsp == rsp2:
self.fail(
"The publisher cache has not reloaded a published module"
" even though it was modified !"
)
rsp = self.vhost_get("test_publisher", path="/temp.py")
if rsp != rsp2:
self.fail(
"The publisher cache has reloaded a published module"
" even though it wasn't modified !"
)
finally:
os.remove('htdocs/temp.py')
def test_server_side_include_conf(self):
c = VirtualHost("*",
ServerName("test_server_side_include"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
Options("+Includes"),
AddType("text/html .shtml"),
AddOutputFilter("INCLUDES .shtml"),
PythonFixupHandler("tests::server_side_include"),
PythonDebug("On")))
return c
def test_server_side_include(self):
print("\n * Testing server side include")
rsp = self.vhost_get("test_server_side_include", path="/ssi.shtml")
rsp = rsp.strip()
if (rsp != "test ok"):
self.fail(repr(rsp))
def test_memory_conf(self):
c = VirtualHost("*",
ServerName("test_memory"),
DocumentRoot(DOCUMENT_ROOT),
Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::memory"),
PythonDebug("On")))
return c
def test_memory(self):
# Note: This test will fail on Apache 2.2 because of a bug,
# but will pass on 2.4 where it is fixed (2.4 reuses the
# brigade on ap_rflush() rather than creating a new one each
# time). http://modpython.org/pipermail/mod_python/2007-July/023974.html
print("\n * Testing req.write() and req.flush() memory usage (100,000 iterations)")
rsp = self.vhost_get("test_memory")
before, after = list(map(int, rsp.split("|")[1:]))
if before != after:
self.fail("Memory before: %s, memory after: %s" % (before, after))
class PerInstanceTestCase(unittest.TestCase, HttpdCtrl):
# this is a test case which requires a complete
# restart of httpd (e.g. we're using a fancy config)
def tearDown(self):
if self.httpd_running:
self.stopHttpd()
def testLoadModule(self):
print("\n* Testing LoadModule")
self.makeConfig()
self.startHttpd()
f = urlopen("http://127.0.0.1:%s/tests.py" % PORT)
server_hdr = f.info()["Server"]
f.close()
self.failUnless(server_hdr.find("Python") > -1,
"%s does not appear to load, Server header does not contain Python"
% MOD_PYTHON_SO)
def testVersionCheck(self):
print("\n* Testing C/Py version mismatch warning")
c = Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::okay"),
PythonDebug("On"))
self.makeConfig(c)
self.startHttpd()
urlopen("http://127.0.0.1:%s/tests.py" % PORT)
self.stopHttpd()
# see what's in the log now
time.sleep(0.1)
log = open(os.path.join(SERVER_ROOT, "logs/error_log")).read()
if "mod_python version mismatch" in log:
self.fail("version mismatch found in logs, but versions should be same?")
from distutils.sysconfig import get_python_lib
version_path = os.path.join(get_python_lib(), "mod_python", "version.py")
# the rest of this test requires write perms to site-packages/mod_python
if os.access(version_path, os.W_OK):
# change the version to not match
v = open(version_path).read()
wrong_v = v + "\nversion = 'WRONG VERSION'\n"
open(version_path, "w").write(wrong_v)
try:
self.startHttpd()
urlopen("http://127.0.0.1:%s/tests.py" % PORT)
self.stopHttpd()
time.sleep(0.1)
log = open(os.path.join(SERVER_ROOT, "logs/error_log")).read()
if "mod_python version mismatch" not in log:
self.fail("version are different, no version mismatch found in logs")
finally:
# restore version.py
open(version_path, "w").write(v)
def test_global_lock(self):
print("\n * Testing _global_lock")
c = Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::global_lock"),
PythonDebug("On"))
self.makeConfig(c)
self.startHttpd()
f = urlopen("http://127.0.0.1:%s/tests.py" % PORT)
if PY2:
rsp = f.read()
else:
rsp = f.read().decode('latin1')
f.close()
if (rsp != "test ok"):
self.fail(repr(rsp))
# if the mutex works, this test will take at least 5 secs
ab = get_ab_path()
if not ab:
print(" Can't find ab. Skipping _global_lock test")
return
t1 = time.time()
print(" ", time.ctime())
if os.name == "nt":
cmd = '%s -c 5 -n 5 http://127.0.0.1:%s/tests.py > NUL:' \
% (ab, PORT)
else:
cmd = '%s -c 5 -n 5 http://127.0.0.1:%s/tests.py > /dev/null' \
% (ab, PORT)
print(" ", cmd)
os.system(cmd)
print(" ", time.ctime())
t2 = time.time()
if (t2 - t1) < 5:
self.fail("global_lock is broken (too quick): %f" % (t2 - t1))
def testPerRequestTests(self):
print("\n* Running the per-request test suite...")
perRequestSuite = unittest.TestSuite()
perRequestSuite.addTest(PerRequestTestCase("test_req_document_root"))
perRequestSuite.addTest(PerRequestTestCase("test_req_add_handler"))
perRequestSuite.addTest(PerRequestTestCase("test_req_add_bad_handler"))
perRequestSuite.addTest(PerRequestTestCase("test_req_add_empty_handler_string"))
perRequestSuite.addTest(PerRequestTestCase("test_req_add_handler_empty_phase"))
perRequestSuite.addTest(PerRequestTestCase("test_req_add_handler_directory"))
perRequestSuite.addTest(PerRequestTestCase("test_accesshandler_add_handler_to_empty_hl"))
perRequestSuite.addTest(PerRequestTestCase("test_req_allow_methods"))
perRequestSuite.addTest(PerRequestTestCase("test_req_unauthorized"))
perRequestSuite.addTest(PerRequestTestCase("test_req_get_basic_auth_pw"))
perRequestSuite.addTest(PerRequestTestCase("test_req_get_basic_auth_pw_latin1"))
perRequestSuite.addTest(PerRequestTestCase("test_req_auth_type"))
if APACHE_VERSION != '2.4':
perRequestSuite.addTest(PerRequestTestCase("test_req_requires"))
perRequestSuite.addTest(PerRequestTestCase("test_req_internal_redirect"))
perRequestSuite.addTest(PerRequestTestCase("test_req_construct_url"))
perRequestSuite.addTest(PerRequestTestCase("test_req_read"))
perRequestSuite.addTest(PerRequestTestCase("test_req_readline"))
perRequestSuite.addTest(PerRequestTestCase("test_req_readlines"))
perRequestSuite.addTest(PerRequestTestCase("test_req_discard_request_body"))
perRequestSuite.addTest(PerRequestTestCase("test_req_register_cleanup"))
perRequestSuite.addTest(PerRequestTestCase("test_req_headers_out"))
perRequestSuite.addTest(PerRequestTestCase("test_req_sendfile"))
perRequestSuite.addTest(PerRequestTestCase("test_req_sendfile2"))
perRequestSuite.addTest(PerRequestTestCase("test_req_sendfile3"))
perRequestSuite.addTest(PerRequestTestCase("test_req_handler"))
perRequestSuite.addTest(PerRequestTestCase("test_req_no_cache"))
perRequestSuite.addTest(PerRequestTestCase("test_req_update_mtime"))
perRequestSuite.addTest(PerRequestTestCase("test_util_redirect"))
perRequestSuite.addTest(PerRequestTestCase("test_req_server_get_config"))
perRequestSuite.addTest(PerRequestTestCase("test_req_server_get_options"))
perRequestSuite.addTest(PerRequestTestCase("test_fileupload"))
perRequestSuite.addTest(PerRequestTestCase("test_fileupload_embedded_cr"))
perRequestSuite.addTest(PerRequestTestCase("test_fileupload_split_boundary"))
perRequestSuite.addTest(PerRequestTestCase("test_sys_argv"))
perRequestSuite.addTest(PerRequestTestCase("test_PythonOption_override"))
perRequestSuite.addTest(PerRequestTestCase("test_PythonOption_remove"))
perRequestSuite.addTest(PerRequestTestCase("test_PythonOption_remove2"))
perRequestSuite.addTest(PerRequestTestCase("test_util_fieldstorage"))
perRequestSuite.addTest(PerRequestTestCase("test_postreadrequest"))
perRequestSuite.addTest(PerRequestTestCase("test_trans"))
perRequestSuite.addTest(PerRequestTestCase("test_outputfilter"))
perRequestSuite.addTest(PerRequestTestCase("test_req_add_output_filter"))
perRequestSuite.addTest(PerRequestTestCase("test_req_register_output_filter"))
perRequestSuite.addTest(PerRequestTestCase("test_connectionhandler"))
perRequestSuite.addTest(PerRequestTestCase("test_import"))
perRequestSuite.addTest(PerRequestTestCase("test_pipe_ext"))
perRequestSuite.addTest(PerRequestTestCase("test_cgihandler"))
perRequestSuite.addTest(PerRequestTestCase("test_psphandler"))
perRequestSuite.addTest(PerRequestTestCase("test_psp_parser"))
perRequestSuite.addTest(PerRequestTestCase("test_psp_error"))
perRequestSuite.addTest(PerRequestTestCase("test_Cookie_Cookie"))
perRequestSuite.addTest(PerRequestTestCase("test_Cookie_MarshalCookie"))
perRequestSuite.addTest(PerRequestTestCase("test_Session_Session"))
perRequestSuite.addTest(PerRequestTestCase("test_Session_illegal_sid"))
perRequestSuite.addTest(PerRequestTestCase("test_interpreter_per_directive"))
perRequestSuite.addTest(PerRequestTestCase("test_interpreter_per_directory"))
perRequestSuite.addTest(PerRequestTestCase("test_files_directive"))
perRequestSuite.addTest(PerRequestTestCase("test_none_handler"))
perRequestSuite.addTest(PerRequestTestCase("test_server_return"))
perRequestSuite.addTest(PerRequestTestCase("test_phase_status"))
perRequestSuite.addTest(PerRequestTestCase("test_publisher"))
perRequestSuite.addTest(PerRequestTestCase("test_publisher_auth_nested"))
perRequestSuite.addTest(PerRequestTestCase("test_publisher_auth_method_nested"))
perRequestSuite.addTest(PerRequestTestCase("test_publisher_auth_digest"))
perRequestSuite.addTest(PerRequestTestCase("test_publisher_old_style_instance"))
perRequestSuite.addTest(PerRequestTestCase("test_publisher_instance"))
perRequestSuite.addTest(PerRequestTestCase("test_publisher_security"))
# perRequestSuite.addTest(PerRequestTestCase("test_publisher_iterator"))
perRequestSuite.addTest(PerRequestTestCase("test_publisher_hierarchy"))
perRequestSuite.addTest(PerRequestTestCase("test_server_side_include"))
if APACHE_VERSION == '2.4' and sys.platform.startswith("linux") and THREADS:
perRequestSuite.addTest(PerRequestTestCase("test_memory"))
perRequestSuite.addTest(PerRequestTestCase("test_wsgihandler"))
perRequestSuite.addTest(PerRequestTestCase("test_wsgihandler_location"))
# test_publisher_cache does not work correctly for mpm-prefork/worker
# and it may not be possible to get a reliable test for all
# configurations, so disable it.
# perRequestSuite.addTest(PerRequestTestCase("test_publisher_cache"))
# this must be last so its error_log is not overwritten
perRequestSuite.addTest(PerRequestTestCase("test_internal"))
self.makeConfig(PerRequestTestCase.appendConfig)
self.startHttpd()
tr = unittest.TextTestRunner()
result = tr.run(perRequestSuite)
self.failUnless(result.wasSuccessful())
def test_srv_register_cleanup(self):
print("\n* Testing server.register_cleanup()...")
c = Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::srv_register_cleanup"),
PythonDebug("On"))
self.makeConfig(c)
self.startHttpd()
f = urlopen("http://127.0.0.1:%s/tests.py" % PORT)
f.read()
f.close()
time.sleep(2)
self.stopHttpd()
# see what's in the log now
time.sleep(2)
f = open(os.path.join(SERVER_ROOT, "logs/error_log"))
log = f.read()
f.close()
if log.find("srv_register_cleanup test ok") == -1:
self.fail("Could not find test message in error_log")
def test_apache_register_cleanup(self):
print("\n* Testing apache.register_cleanup()...")
c = Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::apache_register_cleanup"),
PythonDebug("On"))
self.makeConfig(c)
self.startHttpd()
f = urlopen("http://127.0.0.1:%s/tests.py" % PORT)
f.read()
f.close()
time.sleep(2)
self.stopHttpd()
# see what's in the log now
time.sleep(2)
f = open(os.path.join(SERVER_ROOT, "logs/error_log"))
log = f.read()
f.close()
if log.find("apache_register_cleanup test ok") == -1:
self.fail("Could not find test message in error_log")
def test_apache_exists_config_define(self):
print("\n* Testing apache.exists_config_define()...")
c = Directory(DOCUMENT_ROOT,
SetHandler("mod_python"),
PythonHandler("tests::apache_exists_config_define"),
PythonDebug("On"))
self.makeConfig(c)
self.startHttpd()
f = urlopen("http://127.0.0.1:%s/tests.py" % PORT)
if PY2:
rsp = f.read()
else:
rsp = f.read().decode('latin1')
f.close()
self.stopHttpd()
if rsp != 'NO_FOOBAR':
self.fail('Failure on apache.exists_config_define() : %s'%rsp)
self.startHttpd(extra="-DFOOBAR")
f = urlopen("http://127.0.0.1:%s/tests.py" % PORT)
if PY2:
rsp = f.read()
else:
rsp = f.read().decode('latin1')
f.close()
f.close()
self.stopHttpd()
if rsp != 'FOOBAR':
self.fail('Failure on apache.exists_config_define() : %s'%rsp)
def suite():
mpTestSuite = unittest.TestSuite()
mpTestSuite.addTest(PerInstanceTestCase("testLoadModule"))
mpTestSuite.addTest(PerInstanceTestCase("testVersionCheck"))
mpTestSuite.addTest(PerInstanceTestCase("test_srv_register_cleanup"))
mpTestSuite.addTest(PerInstanceTestCase("test_apache_register_cleanup"))
mpTestSuite.addTest(PerInstanceTestCase("test_apache_exists_config_define"))
mpTestSuite.addTest(PerInstanceTestCase("test_global_lock"))
mpTestSuite.addTest(PerInstanceTestCase("testPerRequestTests"))
return mpTestSuite
tr = unittest.TextTestRunner()
tr.run(suite())
|