summaryrefslogtreecommitdiffstats
path: root/library/ttk
stat options
Period:
Authors:

Commits per author per week (path 'library/ttk')

AuthorW26 2024W27 2024W28 2024W29 2024Total
Total00000
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409
#!/usr/bin/env python
"""
TestCmdTests.py:  Unit tests for the TestCmd.py module.

Copyright 2000-2010 Steven Knight
This module is free software, and you may redistribute it and/or modify
it under the same terms as Python itself, so long as this copyright message
and disclaimer are retained in their original form.

IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGE.

THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE.  THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
"""

__author__ = "Steven Knight <knight at baldmt dot com>"
__revision__ = "TestCmdTests.py 1.3.D001 2010/06/03 12:58:27 knight"

import os
import shutil
import signal
import stat
import StringIO
import sys
import tempfile
import time
import types
import unittest
import UserList

# Strip the current directory so we get the right TestCmd.py module.
sys.path = sys.path[1:]

import TestCmd

def _is_readable(path):
    # XXX this doesn't take into account UID, it assumes it's our file
    return os.stat(path)[stat.ST_MODE] & stat.S_IREAD

def _is_writable(path):
    # XXX this doesn't take into account UID, it assumes it's our file
    return os.stat(path)[stat.ST_MODE] & stat.S_IWRITE

def _is_executable(path):
    # XXX this doesn't take into account UID, it assumes it's our file
    return os.stat(path)[stat.ST_MODE] & stat.S_IEXEC

def _clear_dict(dict, *keys):
    for key in keys:
        try:
            dict[key] = ''  # del dict[key]
        except KeyError:
            pass

import subprocess

try:
    subprocess.Popen.terminate
except AttributeError:
    if sys.platform == 'win32':
        import win32process
        def terminate(self):
            win32process.TerminateProcess(self._handle, 1)
    else:
        def terminate(self):
            os.kill(self.pid, signal.SIGTERM)
    method = types.MethodType(terminate, None, subprocess.Popen)
    setattr(subprocess.Popen, 'terminate', method)

class ExitError(Exception):
    pass

class TestCmdTestCase(unittest.TestCase):
    """Base class for TestCmd test cases, with fixture and utility methods."""

    def setUp(self):
        self.orig_cwd = os.getcwd()

    def tearDown(self):
        os.chdir(self.orig_cwd)

    def setup_run_scripts(self):
        class T:
            pass

        t = T()

        t.script = 'script'
        t.scriptx = 'scriptx.bat'
        t.script1 = 'script_1.txt'
        t.scriptout = 'scriptout'
        t.scripterr = 'scripterr'
        fmt = "import os, sys; cwd = os.getcwd(); " + \
              "sys.stdout.write('%s:  STDOUT:  %%s:  %%s\\n' %% (cwd, sys.argv[1:])); " + \
              "sys.stderr.write('%s:  STDERR:  %%s:  %%s\\n' %% (cwd, sys.argv[1:]))"
        fmtout = "import os, sys; cwd = os.getcwd(); " + \
                 "sys.stdout.write('%s:  STDOUT:  %%s:  %%s\\n' %% (cwd, sys.argv[1:]))"
        fmterr = "import os, sys; cwd = os.getcwd(); " + \
                 "sys.stderr.write('%s:  STDERR:  %%s:  %%s\\n' %% (cwd, sys.argv[1:]))"
        text = fmt % (t.script, t.script)
        textx = fmt % (t.scriptx, t.scriptx)
        if sys.platform == 'win32':
            textx = textx.replace('%', '%%')
            textx = '@python -c "%s"' % textx + ' %1 %2 %3 %4 %5 %6 %7 %8 %9\n'
        else:
            textx = '#! /usr/bin/env python\n' + textx + '\n'
        text1 = 'A first line to be ignored!\n' + fmt % (t.script1, t.script1)
        textout = fmtout % (t.scriptout)
        texterr = fmterr % (t.scripterr)

        run_env = TestCmd.TestCmd(workdir = '')
        run_env.subdir('sub dir')
        t.run_env = run_env

        t.sub_dir = run_env.workpath('sub dir')
        t.script_path = run_env.workpath('sub dir', t.script)
        t.scriptx_path = run_env.workpath('sub dir', t.scriptx)
        t.script1_path = run_env.workpath('sub dir', t.script1)
        t.scriptout_path = run_env.workpath('sub dir', t.scriptout)
        t.scripterr_path = run_env.workpath('sub dir', t.scripterr)

        run_env.write(t.script_path, text)
        run_env.write(t.scriptx_path, textx)
        run_env.write(t.script1_path, text1)
        run_env.write(t.scriptout_path, textout)
        run_env.write(t.scripterr_path, texterr)

        os.chmod(t.script_path, 0644)  # XXX UNIX-specific
        os.chmod(t.scriptx_path, 0755)  # XXX UNIX-specific
        os.chmod(t.script1_path, 0644)  # XXX UNIX-specific
        os.chmod(t.scriptout_path, 0644)  # XXX UNIX-specific
        os.chmod(t.scripterr_path, 0644)  # XXX UNIX-specific

        t.orig_cwd = os.getcwd()

        t.workdir = run_env.workpath('sub dir')
        os.chdir(t.workdir)

        return t

    def translate_newlines(self, data):
        data = data.replace("\r\n", "\n")
        return data

    def call_python(self, input, python=None):
        if python is None:
            python = sys.executable
        p = subprocess.Popen(python,
                             stdin=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdout=subprocess.PIPE)
        stdout, stderr = p.communicate(input)
        stdout = self.translate_newlines(stdout)
        stderr = self.translate_newlines(stderr)
        return stdout, stderr, p.returncode

    def popen_python(self, input, status=0, stdout="", stderr="", python=None):
        if python is None:
            python = sys.executable
        _stdout, _stderr, _status = self.call_python(input, python)
        _stdout = self.translate_newlines(_stdout)
        _stderr = self.translate_newlines(_stderr)
        assert _status == status, \
                "status = %s, expected %s\n" % (str(_status), str(status)) + \
                "STDOUT ===================\n" + _stdout + \
                "STDERR ===================\n" + _stderr
        assert _stdout == stdout, \
                "Expected STDOUT ==========\n" + stdout + \
                "Actual STDOUT ============\n" + _stdout + \
                "STDERR ===================\n" + _stderr
        assert _stderr == stderr, \
                "Expected STDERR ==========\n" + stderr + \
                "Actual STDERR ============\n" + _stderr

    def run_match(self, content, *args):
        expect = "%s:  %s:  %s:  %s\n" % args
        content = self.translate_newlines(content)
        assert content == expect, \
                "Expected %s ==========\n" % args[1] + expect + \
                "Actual %s ============\n" % args[1] + content



class __init__TestCase(TestCmdTestCase):
    def test_init(self):
        """Test init()"""
        test = TestCmd.TestCmd()
        test = TestCmd.TestCmd(description = 'test')
        test = TestCmd.TestCmd(description = 'test', program = 'foo')
        test = TestCmd.TestCmd(description = 'test',
                               program = 'foo',
                               universal_newlines=None)



class basename_TestCase(TestCmdTestCase):
    def test_basename(self):
        """Test basename() [XXX TO BE WRITTEN]"""
        assert 1 == 1



class cleanup_TestCase(TestCmdTestCase):
    def test_cleanup(self):
        """Test cleanup()"""
        test = TestCmd.TestCmd(workdir = '')
        wdir = test.workdir
        test.write('file1', "Test file #1\n")
        test.cleanup()
        assert not os.path.exists(wdir)

    def test_writable(self):
        """Test cleanup() when the directory isn't writable"""
        test = TestCmd.TestCmd(workdir = '')
        wdir = test.workdir
        test.write('file2', "Test file #2\n")
        os.chmod(test.workpath('file2'), 0400)
        os.chmod(wdir, 0500)
        test.cleanup()
        assert not os.path.exists(wdir)

    def test_shutil(self):
        """Test cleanup() when used with shutil"""
        test = TestCmd.TestCmd(workdir = '')
        wdir = test.workdir
        os.chdir(wdir)

        import shutil
        save_rmtree = shutil.rmtree
        def my_rmtree(dir, ignore_errors=0, wdir=wdir, _rmtree=save_rmtree):
            assert os.getcwd() != wdir
            return _rmtree(dir, ignore_errors=ignore_errors)
        try:
            shutil.rmtree = my_rmtree
            test.cleanup()
        finally:
            shutil.rmtree = save_rmtree

    def test_atexit(self):
        """Test cleanup() when atexit is used"""
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import atexit
def my_exitfunc():
    print "my_exitfunc()"
atexit.register(my_exitfunc)
import TestCmd
result = TestCmd.TestCmd(workdir = '')
sys.exit(0)
""" % self.orig_cwd, stdout='my_exitfunc()\n')

    def test_exitfunc(self):
        """Test cleanup() when sys.exitfunc is set"""
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
def my_exitfunc():
    print "my_exitfunc()"
sys.exitfunc = my_exitfunc
import TestCmd
result = TestCmd.TestCmd(workdir = '')
sys.exit(0)
""" % self.orig_cwd, stdout='my_exitfunc()\n')



class chmod_TestCase(TestCmdTestCase):
    def test_chmod(self):
        """Test chmod()"""
        test = TestCmd.TestCmd(workdir = '', subdir = 'sub')

        wdir_file1 = os.path.join(test.workdir, 'file1')
        wdir_sub_file2 = os.path.join(test.workdir, 'sub', 'file2')

        open(wdir_file1, 'w').write("")
        open(wdir_sub_file2, 'w').write("")

        if sys.platform == 'win32':

            test.chmod(wdir_file1, stat.S_IREAD)
            test.chmod(['sub', 'file2'], stat.S_IWRITE)

            file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
            assert file1_mode == 0444, '0%o' % file1_mode
            file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
            assert file2_mode == 0666, '0%o' % file2_mode

            test.chmod('file1', stat.S_IWRITE)
            test.chmod(wdir_sub_file2, stat.S_IREAD)

            file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
            assert file1_mode == 0666, '0%o' % file1_mode
            file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
            assert file2_mode == 0444, '0%o' % file2_mode

        else:

            test.chmod(wdir_file1, 0700)
            test.chmod(['sub', 'file2'], 0760)

            file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
            assert file1_mode == 0700, '0%o' % file1_mode
            file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
            assert file2_mode == 0760, '0%o' % file2_mode

            test.chmod('file1', 0765)
            test.chmod(wdir_sub_file2, 0567)

            file1_mode = stat.S_IMODE(os.stat(wdir_file1)[stat.ST_MODE])
            assert file1_mode == 0765, '0%o' % file1_mode
            file2_mode = stat.S_IMODE(os.stat(wdir_sub_file2)[stat.ST_MODE])
            assert file2_mode == 0567, '0%o' % file2_mode



class combine_TestCase(TestCmdTestCase):
    def test_combine(self):
        """Test combining stdout and stderr"""
        run_env = TestCmd.TestCmd(workdir = '')
        run_env.write('run1', """import sys
sys.stdout.write("run1 STDOUT %s\\n" % sys.argv[1:])
sys.stdout.write("run1 STDOUT second line\\n")
sys.stderr.write("run1 STDERR %s\\n" % sys.argv[1:])
sys.stderr.write("run1 STDERR second line\\n")
sys.stdout.write("run1 STDOUT third line\\n")
sys.stderr.write("run1 STDERR third line\\n")
""")
        run_env.write('run2', """import sys
sys.stdout.write("run2 STDOUT %s\\n" % sys.argv[1:])
sys.stdout.write("run2 STDOUT second line\\n")
sys.stderr.write("run2 STDERR %s\\n" % sys.argv[1:])
sys.stderr.write("run2 STDERR second line\\n")
sys.stdout.write("run2 STDOUT third line\\n")
sys.stderr.write("run2 STDERR third line\\n")
""")
        cwd = os.getcwd()
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:
            test = TestCmd.TestCmd(interpreter = 'python',
                                   workdir = '',
                                   combine = 1)
            try:
                output = test.stdout()
            except IndexError:
                pass
            else:
                raise IndexError("got unexpected output:\n\t`%s'\n" % output)

            # The underlying system subprocess implementations can combine
            # stdout and stderr in different orders, so we accomodate both.

            test.program_set('run1')
            test.run(arguments = 'foo bar')
            stdout_lines = """\
run1 STDOUT ['foo', 'bar']
run1 STDOUT second line
run1 STDOUT third line
"""
            stderr_lines = """\
run1 STDERR ['foo', 'bar']
run1 STDERR second line
run1 STDERR third line
"""
            foo_bar_expect = (stdout_lines + stderr_lines,
                              stderr_lines + stdout_lines)

            test.program_set('run2')
            test.run(arguments = 'snafu')
            stdout_lines = """\
run2 STDOUT ['snafu']
run2 STDOUT second line
run2 STDOUT third line
"""
            stderr_lines = """\
run2 STDERR ['snafu']
run2 STDERR second line
run2 STDERR third line
"""
            snafu_expect = (stdout_lines + stderr_lines,
                            stderr_lines + stdout_lines)

            # XXX SHOULD TEST ABSOLUTE NUMBER AS WELL
            output = test.stdout()
            output = self.translate_newlines(output)
            assert output in snafu_expect, output
            error = test.stderr()
            assert error == '', error

            output = test.stdout(run = -1)
            output = self.translate_newlines(output)
            assert output in foo_bar_expect, output
            error = test.stderr(-1)
            assert error == '', error
        finally:
            os.chdir(cwd)



class description_TestCase(TestCmdTestCase):
    def test_description(self):
        """Test description()"""
        test = TestCmd.TestCmd()
        assert test.description is None, 'initialized description?'
        test = TestCmd.TestCmd(description = 'test')
        assert test.description == 'test', 'uninitialized description'
        test.description_set('foo')
        assert test.description == 'foo', 'did not set description'



class diff_TestCase(TestCmdTestCase):
    def test_diff_re(self):
        """Test diff_re()"""
        result = TestCmd.diff_re(["abcde"], ["abcde"])
        assert result == [], result
        result = TestCmd.diff_re(["a.*e"], ["abcde"])
        assert result == [], result
        result = TestCmd.diff_re(["a.*e"], ["xxx"])
        assert result == ['1c1', "< 'a.*e'", '---', "> 'xxx'"], result

    def test_diff_custom_function(self):
        """Test diff() using a custom function"""
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def my_diff(a, b):
    return [
        '*****',
        a,
        '*****',
        b,
        '*****',
    ]
test = TestCmd.TestCmd(diff = my_diff)
test.diff("a\\nb1\\nc\\n", "a\\nb2\\nc\\n", "STDOUT")
sys.exit(0)
""" % self.orig_cwd,
                          stdout = """\
STDOUT==========================================================================
*****
['a', 'b1', 'c']
*****
['a', 'b2', 'c']
*****
""")

    def test_diff_string(self):
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff = 'diff_re')
test.diff("a\\nb1\\nc\\n", "a\\nb2\\nc\\n", 'STDOUT')
sys.exit(0)
""" % self.orig_cwd,
                          stdout = """\
STDOUT==========================================================================
2c2
< 'b1'
---
> 'b2'
""")

    def test_error(self):
        """Test handling a compilation error in TestCmd.diff_re()"""
        script_input = """import sys
sys.path = ['%s'] + sys.path
import TestCmd
assert TestCmd.diff_re(["a.*(e"], ["abcde"])
sys.exit(0)
""" % self.orig_cwd
        stdout, stderr, status = self.call_python(script_input)
        assert status == 1, status
        expect1 = "Regular expression error in '^a.*(e$': missing )\n"
        expect2 = "Regular expression error in '^a.*(e$': unbalanced parenthesis\n"
        assert (stderr.find(expect1) != -1 or
                stderr.find(expect2) != -1), repr(stderr)

    def test_simple_diff_static_method(self):
        """Test calling the TestCmd.TestCmd.simple_diff() static method"""
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
result = TestCmd.TestCmd.simple_diff(['a', 'b', 'c', 'e', 'f1'],
                                     ['a', 'c', 'd', 'e', 'f2'])
expect = ['2d1', '< b', '3a3', '> d', '5c5', '< f1', '---', '> f2']
assert result == expect, result
sys.exit(0)
""" % self.orig_cwd)

    def test_context_diff_static_method(self):
        """Test calling the TestCmd.TestCmd.context_diff() static method"""
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
result = TestCmd.TestCmd.context_diff(['a\\n', 'b\\n', 'c\\n', 'e\\n', 'f1\\n'],
                                      ['a\\n', 'c\\n', 'd\\n', 'e\\n', 'f2\\n'])
result = list(result)
expect = [
    '*** \\n',
    '--- \\n',
    '***************\\n',
    '*** 1,5 ****\\n',
    '  a\\n',
    '- b\\n',
    '  c\\n',
    '  e\\n',
    '! f1\\n',
    '--- 1,5 ----\\n',
    '  a\\n',
    '  c\\n',
    '+ d\\n',
    '  e\\n',
    '! f2\\n',
]
assert result == expect, result
sys.exit(0)
""" % self.orig_cwd)

    def test_unified_diff_static_method(self):
        """Test calling the TestCmd.TestCmd.unified_diff() static method"""
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
result = TestCmd.TestCmd.unified_diff(['a\\n', 'b\\n', 'c\\n', 'e\\n', 'f1\\n'],
                                      ['a\\n', 'c\\n', 'd\\n', 'e\\n', 'f2\\n'])
result = list(result)
expect = [
    '--- \\n',
    '+++ \\n',
    '@@ -1,5 +1,5 @@\\n',
    ' a\\n',
    '-b\\n',
    ' c\\n',
    '+d\\n',
    ' e\\n',
    '-f1\\n',
    '+f2\\n'
]
assert result == expect, result
sys.exit(0)
""" % self.orig_cwd)

    def test_diff_re_static_method(self):
        """Test calling the TestCmd.TestCmd.diff_re() static method"""
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
result = TestCmd.TestCmd.diff_re(['a', 'b', 'c', '.', 'f1'],
                                 ['a', 'c', 'd', 'e', 'f2'])
expect = [
    '2c2',
    "< 'b'",
    '---',
    "> 'c'",
    '3c3',
    "< 'c'",
    '---',
    "> 'd'",
    '5c5',
    "< 'f1'",
    '---',
    "> 'f2'"
]
assert result == expect, result
sys.exit(0)
""" % self.orig_cwd)



class diff_stderr_TestCase(TestCmdTestCase):
    def test_diff_stderr_default(self):
        """Test diff_stderr() default behavior"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd()
test.diff_stderr('a\nb1\nc\n', 'a\nb2\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
2c2
< b1
---
> b2
""")

    def test_diff_stderr_not_affecting_diff_stdout(self):
        """Test diff_stderr() not affecting diff_stdout() behavior"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stderr='diff_re')
print "diff_stderr:"
test.diff_stderr('a\nb.\nc\n', 'a\nbb\nc\n')
print "diff_stdout:"
test.diff_stdout('a\nb.\nc\n', 'a\nbb\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
diff_stderr:
diff_stdout:
2c2
< b.
---
> bb
""")

    def test_diff_stderr_custom_function(self):
        """Test diff_stderr() using a custom function"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def my_diff(a, b):
    return ["a:"] + a + ["b:"] + b
test = TestCmd.TestCmd(diff_stderr=my_diff)
test.diff_stderr('abc', 'def')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
a:
abc
b:
def
""")

    def test_diff_stderr_TestCmd_function(self):
        """Test diff_stderr() using a TestCmd function"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stderr = TestCmd.diff_re)
test.diff_stderr('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
1c1
< 'a'
---
> 'b'
""")

    def test_diff_stderr_static_method(self):
        """Test diff_stderr() using a static method"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stderr=TestCmd.TestCmd.diff_re)
test.diff_stderr('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
1c1
< 'a'
---
> 'b'
""")

    def test_diff_stderr_string(self):
        """Test diff_stderr() using a string to fetch the diff method"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stderr='diff_re')
test.diff_stderr('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
1c1
< 'a'
---
> 'b'
""")



class diff_stdout_TestCase(TestCmdTestCase):
    def test_diff_stdout_default(self):
        """Test diff_stdout() default behavior"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd()
test.diff_stdout('a\nb1\nc\n', 'a\nb2\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
2c2
< b1
---
> b2
""")

    def test_diff_stdout_not_affecting_diff_stderr(self):
        """Test diff_stdout() not affecting diff_stderr() behavior"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stdout='diff_re')
print "diff_stdout:"
test.diff_stdout('a\nb.\nc\n', 'a\nbb\nc\n')
print "diff_stderr:"
test.diff_stderr('a\nb.\nc\n', 'a\nbb\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
diff_stdout:
diff_stderr:
2c2
< b.
---
> bb
""")

    def test_diff_stdout_custom_function(self):
        """Test diff_stdout() using a custom function"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def my_diff(a, b):
    return ["a:"] + a + ["b:"] + b
test = TestCmd.TestCmd(diff_stdout=my_diff)
test.diff_stdout('abc', 'def')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
a:
abc
b:
def
""")

    def test_diff_stdout_TestCmd_function(self):
        """Test diff_stdout() using a TestCmd function"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stdout = TestCmd.diff_re)
test.diff_stdout('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
1c1
< 'a'
---
> 'b'
""")

    def test_diff_stdout_static_method(self):
        """Test diff_stdout() using a static method"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stdout=TestCmd.TestCmd.diff_re)
test.diff_stdout('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
1c1
< 'a'
---
> 'b'
""")

    def test_diff_stdout_string(self):
        """Test diff_stdout() using a string to fetch the diff method"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(diff_stdout='diff_re')
test.diff_stdout('a\n.\n', 'b\nc\n')
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
1c1
< 'a'
---
> 'b'
""")



class exit_TestCase(TestCmdTestCase):
    def test_exit(self):
        """Test exit()"""
        def _test_it(cwd, tempdir, condition, preserved):
            close_true = {'pass_test': 1, 'fail_test': 0, 'no_result': 0}
            exit_status = {'pass_test': 0, 'fail_test': 1, 'no_result': 2}
            result_string = {'pass_test': "PASSED\n",
                             'fail_test': "FAILED test at line 5 of <stdin>\n",
                             'no_result': "NO RESULT for test at line 5 of <stdin>\n"}
            global ExitError
            input = """import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(workdir = '%s')
test.%s()
""" % (cwd, tempdir, condition)
            stdout, stderr, status = self.call_python(input, python="python")
            if close_true[condition]:
                unexpected = (status != 0)
            else:
                unexpected = (status == 0)
            if unexpected:
                msg = "Unexpected exit status from python:  %s\n"
                raise ExitError(msg % status + stdout + stderr)
            if status != exit_status[condition]:
                        msg = "Expected exit status %d, got %d\n"
                        raise ExitError(msg % (exit_status[condition], status))
            if stderr != result_string[condition]:
                msg = "Expected error output:\n%sGot error output:\n%s"
                raise ExitError(msg % (result_string[condition], stderr))
            if preserved:
                if not os.path.exists(tempdir):
                    msg = "Working directory %s was mistakenly removed\n"
                    raise ExitError(msg % tempdir + stdout)
            else:
                if os.path.exists(tempdir):
                    msg = "Working directory %s was mistakenly preserved\n"
                    raise ExitError(msg % tempdir + stdout)

        run_env = TestCmd.TestCmd(workdir = '')
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:
            cwd = self.orig_cwd
            _clear_dict(os.environ, 'PRESERVE', 'PRESERVE_PASS', 'PRESERVE_FAIL', 'PRESERVE_NO_RESULT')
            _test_it(cwd, 'dir01', 'pass_test', 0)
            _test_it(cwd, 'dir02', 'fail_test', 0)
            _test_it(cwd, 'dir03', 'no_result', 0)
            os.environ['PRESERVE'] = '1'
            _test_it(cwd, 'dir04', 'pass_test', 1)
            _test_it(cwd, 'dir05', 'fail_test', 1)
            _test_it(cwd, 'dir06', 'no_result', 1)
            os.environ['PRESERVE'] = ''  # del os.environ['PRESERVE']
            os.environ['PRESERVE_PASS'] = '1'
            _test_it(cwd, 'dir07', 'pass_test', 1)
            _test_it(cwd, 'dir08', 'fail_test', 0)
            _test_it(cwd, 'dir09', 'no_result', 0)
            os.environ['PRESERVE_PASS'] = ''  # del os.environ['PRESERVE_PASS']
            os.environ['PRESERVE_FAIL'] = '1'
            _test_it(cwd, 'dir10', 'pass_test', 0)
            _test_it(cwd, 'dir11', 'fail_test', 1)
            _test_it(cwd, 'dir12', 'no_result', 0)
            os.environ['PRESERVE_FAIL'] = ''  # del os.environ['PRESERVE_FAIL']
            os.environ['PRESERVE_NO_RESULT'] = '1'
            _test_it(cwd, 'dir13', 'pass_test', 0)
            _test_it(cwd, 'dir14', 'fail_test', 0)
            _test_it(cwd, 'dir15', 'no_result', 1)
            os.environ['PRESERVE_NO_RESULT'] = '' # del os.environ['PRESERVE_NO_RESULT']
        finally:
            _clear_dict(os.environ, 'PRESERVE', 'PRESERVE_PASS', 'PRESERVE_FAIL', 'PRESERVE_NO_RESULT')



class fail_test_TestCase(TestCmdTestCase):
    def test_fail_test(self):
        """Test fail_test()"""
        run_env = TestCmd.TestCmd(workdir = '')
        run_env.write('run', """import sys
sys.stdout.write("run:  STDOUT\\n")
sys.stderr.write("run:  STDERR\\n")
""")
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
TestCmd.fail_test(condition = 1)
""" % self.orig_cwd, status = 1, stderr = "FAILED test at line 4 of <stdin>\n")

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')
test.run()
test.fail_test(condition = (test.status == 0))
""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s\n\tat line 6 of <stdin>\n" % run_env.workpath('run'))

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', description = 'xyzzy', workdir = '')
test.run()
test.fail_test(condition = (test.status == 0))
""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s [xyzzy]\n\tat line 6 of <stdin>\n" % run_env.workpath('run'))

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')
test.run()
def xxx():
    sys.stderr.write("printed on failure\\n")
test.fail_test(condition = (test.status == 0), function = xxx)
""" % self.orig_cwd, status = 1, stderr = "printed on failure\nFAILED test of %s\n\tat line 8 of <stdin>\n" % run_env.workpath('run'))

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def test1(self):
    self.run()
    self.fail_test(condition = (self.status == 0))
def test2(self):
    test1(self)
test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = ''))
""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s\n\tat line 6 of <stdin> (test1)\n\tfrom line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run'))

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def test1(self):
    self.run()
    self.fail_test(condition = (self.status == 0), skip = 1)
def test2(self):
    test1(self)
test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = ''))
""" % self.orig_cwd, status = 1, stderr = "FAILED test of %s\n\tat line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run'))



class interpreter_TestCase(TestCmdTestCase):
    def test_interpreter(self):
        """Test interpreter()"""
        run_env = TestCmd.TestCmd(workdir = '')
        run_env.write('run', """import sys
sys.stdout.write("run:  STDOUT\\n")
sys.stderr.write("run:  STDERR\\n")
""")
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        test = TestCmd.TestCmd(program = 'run', workdir = '')
        test.interpreter_set('foo')
        assert test.interpreter == 'foo', 'did not set interpreter'
        test.interpreter_set('python')
        assert test.interpreter == 'python', 'did not set interpreter'
        test.run()



class match_TestCase(TestCmdTestCase):
    def test_match_default(self):
        """Test match() default behavior"""
        test = TestCmd.TestCmd()
        assert test.match("abcde\n", "a.*e\n")
        assert test.match("12345\nabcde\n", "1\\d+5\na.*e\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert test.match(lines, regexes)

    def test_match_custom_function(self):
        """Test match() using a custom function"""
        def match_length(lines, matches):
            return len(lines) == len(matches)
        test = TestCmd.TestCmd(match=match_length)
        assert not test.match("123\n", "1\n")
        assert test.match("123\n", "111\n")
        assert not test.match("123\n123\n", "1\n1\n")
        assert test.match("123\n123\n", "111\n111\n")
        lines = ["123\n", "123\n"]
        regexes = ["1\n", "1\n"]
        assert test.match(lines, regexes)       # due to equal numbers of lines

    def test_match_TestCmd_function(self):
        """Test match() using a TestCmd function"""
        test = TestCmd.TestCmd(match = TestCmd.match_exact)
        assert not test.match("abcde\n", "a.*e\n")
        assert test.match("abcde\n", "abcde\n")
        assert not test.match("12345\nabcde\n", "1\d+5\na.*e\n")
        assert test.match("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match(lines, regexes)
        assert test.match(lines, lines)

    def test_match_static_method(self):
        """Test match() using a static method"""
        test = TestCmd.TestCmd(match=TestCmd.TestCmd.match_exact)
        assert not test.match("abcde\n", "a.*e\n")
        assert test.match("abcde\n", "abcde\n")
        assert not test.match("12345\nabcde\n", "1\d+5\na.*e\n")
        assert test.match("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match(lines, regexes)
        assert test.match(lines, lines)

    def test_match_string(self):
        """Test match() using a string to fetch the match method"""
        test = TestCmd.TestCmd(match='match_exact')
        assert not test.match("abcde\n", "a.*e\n")
        assert test.match("abcde\n", "abcde\n")
        assert not test.match("12345\nabcde\n", "1\d+5\na.*e\n")
        assert test.match("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match(lines, regexes)
        assert test.match(lines, lines)



class match_exact_TestCase(TestCmdTestCase):
    def test_match_exact_function(self):
        """Test calling the TestCmd.match_exact() function"""
        assert not TestCmd.match_exact("abcde\\n", "a.*e\\n")
        assert TestCmd.match_exact("abcde\\n", "abcde\\n")

    def test_match_exact_instance_method(self):
        """Test calling the TestCmd.TestCmd().match_exact() instance method"""
        test = TestCmd.TestCmd()
        assert not test.match_exact("abcde\\n", "a.*e\\n")
        assert test.match_exact("abcde\\n", "abcde\\n")

    def test_match_exact_static_method(self):
        """Test calling the TestCmd.TestCmd.match_exact() static method"""
        assert not TestCmd.TestCmd.match_exact("abcde\\n", "a.*e\\n")
        assert TestCmd.TestCmd.match_exact("abcde\\n", "abcde\\n")

    def test_evaluation(self):
        """Test match_exact() evaluation"""
        test = TestCmd.TestCmd()
        assert not test.match_exact("abcde\n", "a.*e\n")
        assert test.match_exact("abcde\n", "abcde\n")
        assert not test.match_exact(["12345\n", "abcde\n"], ["1[0-9]*5\n", "a.*e\n"])
        assert test.match_exact(["12345\n", "abcde\n"], ["12345\n", "abcde\n"])
        assert not test.match_exact(UserList.UserList(["12345\n", "abcde\n"]),
                                    ["1[0-9]*5\n", "a.*e\n"])
        assert test.match_exact(UserList.UserList(["12345\n", "abcde\n"]),
                                ["12345\n", "abcde\n"])
        assert not test.match_exact(["12345\n", "abcde\n"],
                                    UserList.UserList(["1[0-9]*5\n", "a.*e\n"]))
        assert test.match_exact(["12345\n", "abcde\n"],
                                UserList.UserList(["12345\n", "abcde\n"]))
        assert not test.match_exact("12345\nabcde\n", "1[0-9]*5\na.*e\n")
        assert test.match_exact("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match_exact(lines, regexes)
        assert test.match_exact(lines, lines)



class match_re_dotall_TestCase(TestCmdTestCase):
    def test_match_re_dotall_function(self):
        """Test calling the TestCmd.match_re_dotall() function"""
        assert TestCmd.match_re_dotall("abcde\nfghij\n", "a.*j\n")

    def test_match_re_dotall_instance_method(self):
        """Test calling the TestCmd.TestCmd().match_re_dotall() instance method"""
        test = TestCmd.TestCmd()
        test.match_re_dotall("abcde\\nfghij\\n", "a.*j\\n")

    def test_match_re_dotall_static_method(self):
        """Test calling the TestCmd.TestCmd.match_re_dotall() static method"""
        assert TestCmd.TestCmd.match_re_dotall("abcde\nfghij\n", "a.*j\n")

    def test_error(self):
        """Test handling a compilation error in TestCmd.match_re_dotall()"""
        run_env = TestCmd.TestCmd(workdir = '')
        cwd = os.getcwd()
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:
            script_input = """import sys
sys.path = ['%s'] + sys.path
import TestCmd
assert TestCmd.match_re_dotall("abcde", "a.*(e")
sys.exit(0)
""" % cwd
            stdout, stderr, status = self.call_python(script_input)
            assert status == 1, status
            expect1 = "Regular expression error in '^a.*(e$': missing )\n"
            expect2 = "Regular expression error in '^a.*(e$': unbalanced parenthesis\n"
            assert (stderr.find(expect1) != -1 or
                    stderr.find(expect2) != -1), repr(stderr)
        finally:
            os.chdir(cwd)

    def test_evaluation(self):
        """Test match_re_dotall() evaluation"""
        test = TestCmd.TestCmd()
        assert test.match_re_dotall("abcde\nfghij\n", "a.*e\nf.*j\n")
        assert test.match_re_dotall("abcde\nfghij\n", "a[^j]*j\n")
        assert test.match_re_dotall("abcde\nfghij\n", "abcde\nfghij\n")
        assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
                                    ["1[0-9]*5\n", "a.*e\n", "f.*j\n"])
        assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
                                    ["1.*j\n"])
        assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
                                    ["12345\n", "abcde\n", "fghij\n"])
        assert test.match_re_dotall(UserList.UserList(["12345\n",
                                                       "abcde\n",
                                                       "fghij\n"]),
                                    ["1[0-9]*5\n", "a.*e\n", "f.*j\n"])
        assert test.match_re_dotall(UserList.UserList(["12345\n",
                                                       "abcde\n",
                                                       "fghij\n"]),
                                    ["1.*j\n"])
        assert test.match_re_dotall(UserList.UserList(["12345\n",
                                                       "abcde\n",
                                                       "fghij\n"]),
                                    ["12345\n", "abcde\n", "fghij\n"])
        assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
                                    UserList.UserList(["1[0-9]*5\n",
                                                       "a.*e\n",
                                                       "f.*j\n"]))
        assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
                                    UserList.UserList(["1.*j\n"]))
        assert test.match_re_dotall(["12345\n", "abcde\n", "fghij\n"],
                                    UserList.UserList(["12345\n",
                                                       "abcde\n",
                                                       "fghij\n"]))
        assert test.match_re_dotall("12345\nabcde\nfghij\n",
                                    "1[0-9]*5\na.*e\nf.*j\n")
        assert test.match_re_dotall("12345\nabcde\nfghij\n", "1.*j\n")
        assert test.match_re_dotall("12345\nabcde\nfghij\n",
                                    "12345\nabcde\nfghij\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert test.match_re_dotall(lines, regexes)
        assert test.match_re_dotall(lines, lines)



class match_re_TestCase(TestCmdTestCase):
    def test_match_re_function(self):
        """Test calling the TestCmd.match_re() function"""
        assert TestCmd.match_re("abcde\n", "a.*e\n")

    def test_match_re_instance_method(self):
        """Test calling the TestCmd.TestCmd().match_re() instance method"""
        test = TestCmd.TestCmd()
        assert test.match_re("abcde\n", "a.*e\n")

    def test_match_re_static_method(self):
        """Test calling the TestCmd.TestCmd.match_re() static method"""
        assert TestCmd.TestCmd.match_re("abcde\n", "a.*e\n")

    def test_error(self):
        """Test handling a compilation error in TestCmd.match_re()"""
        run_env = TestCmd.TestCmd(workdir = '')
        cwd = os.getcwd()
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:
            script_input = """import sys
sys.path = ['%s'] + sys.path
import TestCmd
assert TestCmd.match_re("abcde\\n", "a.*(e\\n")
sys.exit(0)
""" % cwd
            stdout, stderr, status = self.call_python(script_input)
            assert status == 1, status
            expect1 = "Regular expression error in '^a.*(e$': missing )\n"
            expect2 = "Regular expression error in '^a.*(e$': unbalanced parenthesis\n"
            assert (stderr.find(expect1) != -1 or
                    stderr.find(expect2) != -1), repr(stderr)
        finally:
            os.chdir(cwd)

    def test_evaluation(self):
        """Test match_re() evaluation"""
        test = TestCmd.TestCmd()
        assert test.match_re("abcde\n", "a.*e\n")
        assert test.match_re("abcde\n", "abcde\n")
        assert test.match_re(["12345\n", "abcde\n"], ["1[0-9]*5\n", "a.*e\n"])
        assert test.match_re(["12345\n", "abcde\n"], ["12345\n", "abcde\n"])
        assert test.match_re(UserList.UserList(["12345\n", "abcde\n"]),
                             ["1[0-9]*5\n", "a.*e\n"])
        assert test.match_re(UserList.UserList(["12345\n", "abcde\n"]),
                             ["12345\n", "abcde\n"])
        assert test.match_re(["12345\n", "abcde\n"],
                             UserList.UserList(["1[0-9]*5\n", "a.*e\n"]))
        assert test.match_re(["12345\n", "abcde\n"],
                             UserList.UserList(["12345\n", "abcde\n"]))
        assert test.match_re("12345\nabcde\n", "1[0-9]*5\na.*e\n")
        assert test.match_re("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert test.match_re(lines, regexes)
        assert test.match_re(lines, lines)



class match_stderr_TestCase(TestCmdTestCase):
    def test_match_stderr_default(self):
        """Test match_stderr() default behavior"""
        test = TestCmd.TestCmd()
        assert test.match_stderr("abcde\n", "a.*e\n")
        assert test.match_stderr("12345\nabcde\n", "1\\d+5\na.*e\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert test.match_stderr(lines, regexes)

    def test_match_stderr_not_affecting_match_stdout(self):
        """Test match_stderr() not affecting match_stdout() behavior"""
        test = TestCmd.TestCmd(match_stderr=TestCmd.TestCmd.match_exact)

        assert not test.match_stderr("abcde\n", "a.*e\n")
        assert test.match_stderr("abcde\n", "abcde\n")
        assert not test.match_stderr("12345\nabcde\n", "1\\d+5\na.*e\n")
        assert test.match_stderr("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match_stderr(lines, regexes)
        assert test.match_stderr(lines, lines)

        assert test.match_stdout("abcde\n", "a.*e\n")
        assert test.match_stdout("12345\nabcde\n", "1\\d+5\na.*e\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert test.match_stdout(lines, regexes)

    def test_match_stderr_custom_function(self):
        """Test match_stderr() using a custom function"""
        def match_length(lines, matches):
            return len(lines) == len(matches)
        test = TestCmd.TestCmd(match_stderr=match_length)
        assert not test.match_stderr("123\n", "1\n")
        assert test.match_stderr("123\n", "111\n")
        assert not test.match_stderr("123\n123\n", "1\n1\n")
        assert test.match_stderr("123\n123\n", "111\n111\n")
        lines = ["123\n", "123\n"]
        regexes = ["1\n", "1\n"]
        assert test.match_stderr(lines, regexes)    # equal numbers of lines

    def test_match_stderr_TestCmd_function(self):
        """Test match_stderr() using a TestCmd function"""
        test = TestCmd.TestCmd(match_stderr = TestCmd.match_exact)
        assert not test.match_stderr("abcde\n", "a.*e\n")
        assert test.match_stderr("abcde\n", "abcde\n")
        assert not test.match_stderr("12345\nabcde\n", "1\d+5\na.*e\n")
        assert test.match_stderr("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match_stderr(lines, regexes)
        assert test.match_stderr(lines, lines)

    def test_match_stderr_static_method(self):
        """Test match_stderr() using a static method"""
        test = TestCmd.TestCmd(match_stderr=TestCmd.TestCmd.match_exact)
        assert not test.match_stderr("abcde\n", "a.*e\n")
        assert test.match_stderr("abcde\n", "abcde\n")
        assert not test.match_stderr("12345\nabcde\n", "1\d+5\na.*e\n")
        assert test.match_stderr("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match_stderr(lines, regexes)
        assert test.match_stderr(lines, lines)

    def test_match_stderr_string(self):
        """Test match_stderr() using a string to fetch the match method"""
        test = TestCmd.TestCmd(match_stderr='match_exact')
        assert not test.match_stderr("abcde\n", "a.*e\n")
        assert test.match_stderr("abcde\n", "abcde\n")
        assert not test.match_stderr("12345\nabcde\n", "1\d+5\na.*e\n")
        assert test.match_stderr("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match_stderr(lines, regexes)
        assert test.match_stderr(lines, lines)



class match_stdout_TestCase(TestCmdTestCase):
    def test_match_stdout_default(self):
        """Test match_stdout() default behavior"""
        test = TestCmd.TestCmd()
        assert test.match_stdout("abcde\n", "a.*e\n")
        assert test.match_stdout("12345\nabcde\n", "1\\d+5\na.*e\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert test.match_stdout(lines, regexes)

    def test_match_stdout_not_affecting_match_stderr(self):
        """Test match_stdout() not affecting match_stderr() behavior"""
        test = TestCmd.TestCmd(match_stdout=TestCmd.TestCmd.match_exact)

        assert not test.match_stdout("abcde\n", "a.*e\n")
        assert test.match_stdout("abcde\n", "abcde\n")
        assert not test.match_stdout("12345\nabcde\n", "1\\d+5\na.*e\n")
        assert test.match_stdout("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match_stdout(lines, regexes)
        assert test.match_stdout(lines, lines)

        assert test.match_stderr("abcde\n", "a.*e\n")
        assert test.match_stderr("12345\nabcde\n", "1\\d+5\na.*e\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert test.match_stderr(lines, regexes)

    def test_match_stdout_custom_function(self):
        """Test match_stdout() using a custom function"""
        def match_length(lines, matches):
            return len(lines) == len(matches)
        test = TestCmd.TestCmd(match_stdout=match_length)
        assert not test.match_stdout("123\n", "1\n")
        assert test.match_stdout("123\n", "111\n")
        assert not test.match_stdout("123\n123\n", "1\n1\n")
        assert test.match_stdout("123\n123\n", "111\n111\n")
        lines = ["123\n", "123\n"]
        regexes = ["1\n", "1\n"]
        assert test.match_stdout(lines, regexes)    # equal numbers of lines

    def test_match_stdout_TestCmd_function(self):
        """Test match_stdout() using a TestCmd function"""
        test = TestCmd.TestCmd(match_stdout = TestCmd.match_exact)
        assert not test.match_stdout("abcde\n", "a.*e\n")
        assert test.match_stdout("abcde\n", "abcde\n")
        assert not test.match_stdout("12345\nabcde\n", "1\d+5\na.*e\n")
        assert test.match_stdout("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match_stdout(lines, regexes)
        assert test.match_stdout(lines, lines)

    def test_match_stdout_static_method(self):
        """Test match_stdout() using a static method"""
        test = TestCmd.TestCmd(match_stdout=TestCmd.TestCmd.match_exact)
        assert not test.match_stdout("abcde\n", "a.*e\n")
        assert test.match_stdout("abcde\n", "abcde\n")
        assert not test.match_stdout("12345\nabcde\n", "1\d+5\na.*e\n")
        assert test.match_stdout("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match_stdout(lines, regexes)
        assert test.match_stdout(lines, lines)

    def test_match_stdout_string(self):
        """Test match_stdout() using a string to fetch the match method"""
        test = TestCmd.TestCmd(match_stdout='match_exact')
        assert not test.match_stdout("abcde\n", "a.*e\n")
        assert test.match_stdout("abcde\n", "abcde\n")
        assert not test.match_stdout("12345\nabcde\n", "1\d+5\na.*e\n")
        assert test.match_stdout("12345\nabcde\n", "12345\nabcde\n")
        lines = ["vwxyz\n", "67890\n"]
        regexes = ["v[^a-u]*z\n", "6[^ ]+0\n"]
        assert not test.match_stdout(lines, regexes)
        assert test.match_stdout(lines, lines)



class no_result_TestCase(TestCmdTestCase):
    def test_no_result(self):
        """Test no_result()"""
        run_env = TestCmd.TestCmd(workdir = '')
        run_env.write('run', """import sys
sys.stdout.write("run:  STDOUT\\n")
sys.stderr.write("run:  STDERR\\n")
""")
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
TestCmd.no_result(condition = 1)
""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test at line 4 of <stdin>\n")

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')
test.run()
test.no_result(condition = (test.status == 0))
""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test of %s\n\tat line 6 of <stdin>\n" % run_env.workpath('run'))

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', description = 'xyzzy', workdir = '')
test.run()
test.no_result(condition = (test.status == 0))
""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test of %s [xyzzy]\n\tat line 6 of <stdin>\n" % run_env.workpath('run'))

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')
test.run()
def xxx():
    sys.stderr.write("printed on no result\\n")
test.no_result(condition = (test.status == 0), function = xxx)
""" % self.orig_cwd, status = 2, stderr = "printed on no result\nNO RESULT for test of %s\n\tat line 8 of <stdin>\n" % run_env.workpath('run'))

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def test1(self):
    self.run()
    self.no_result(condition = (self.status == 0))
def test2(self):
    test1(self)
test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = ''))
""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test of %s\n\tat line 6 of <stdin> (test1)\n\tfrom line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run'))

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
def test1(self):
    self.run()
    self.no_result(condition = (self.status == 0), skip = 1)
def test2(self):
    test1(self)
test2(TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = ''))
""" % self.orig_cwd, status = 2, stderr = "NO RESULT for test of %s\n\tat line 8 of <stdin> (test2)\n\tfrom line 9 of <stdin>\n" % run_env.workpath('run'))



class pass_test_TestCase(TestCmdTestCase):
    def test_pass_test(self):
        """Test pass_test()"""
        run_env = TestCmd.TestCmd(workdir = '')
        run_env.write('run', """import sys
sys.stdout.write("run:  STDOUT\\n")
sys.stderr.write("run:  STDERR\\n")
""")
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
TestCmd.pass_test(condition = 1)
""" % self.orig_cwd, stderr = "PASSED\n")

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')
test.run()
test.pass_test(condition = (test.status == 0))
""" % self.orig_cwd, stderr = "PASSED\n")

        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')
test.run()
def brag():
    sys.stderr.write("printed on success\\n")
test.pass_test(condition = (test.status == 0), function = brag)
""" % self.orig_cwd, stderr = "printed on success\nPASSED\n")

        # TODO(sgk): SHOULD ALSO TEST FAILURE CONDITIONS



class preserve_TestCase(TestCmdTestCase):
    def test_preserve(self):
        """Test preserve()"""
        def cleanup_test(test, cond=None, stdout=""):
            io = StringIO.StringIO()
            save = sys.stdout
            sys.stdout = io
            try:
                if cond:
                    test.cleanup(cond)
                else:
                    test.cleanup()
                o = io.getvalue()
                assert o == stdout, "o = `%s', stdout = `%s'" % (o, stdout)
            finally:
                sys.stdout = save

        test = TestCmd.TestCmd(workdir = '')
        wdir = test.workdir
        try:
            test.write('file1', "Test file #1\n")
            #test.cleanup()
            cleanup_test(test, )
            assert not os.path.exists(wdir)
        finally:
            if os.path.exists(wdir):
                shutil.rmtree(wdir, ignore_errors = 1)
                test._dirlist.remove(wdir)

        test = TestCmd.TestCmd(workdir = '')
        wdir = test.workdir
        try:
            test.write('file2', "Test file #2\n")
            test.preserve('pass_test')
            cleanup_test(test, 'pass_test', "Preserved directory %s\n" % wdir)
            assert os.path.isdir(wdir)
            cleanup_test(test, 'fail_test')
            assert not os.path.exists(wdir)
        finally:
            if os.path.exists(wdir):
                shutil.rmtree(wdir, ignore_errors = 1)
                test._dirlist.remove(wdir)

        test = TestCmd.TestCmd(workdir = '')
        wdir = test.workdir
        try:
            test.write('file3', "Test file #3\n")
            test.preserve('fail_test')
            cleanup_test(test, 'fail_test', "Preserved directory %s\n" % wdir)
            assert os.path.isdir(wdir)
            cleanup_test(test, 'pass_test')
            assert not os.path.exists(wdir)
        finally:
            if os.path.exists(wdir):
                shutil.rmtree(wdir, ignore_errors = 1)
                test._dirlist.remove(wdir)

        test = TestCmd.TestCmd(workdir = '')
        wdir = test.workdir
        try:
            test.write('file4', "Test file #4\n")
            test.preserve('fail_test', 'no_result')
            cleanup_test(test, 'fail_test', "Preserved directory %s\n" % wdir)
            assert os.path.isdir(wdir)
            cleanup_test(test, 'no_result', "Preserved directory %s\n" % wdir)
            assert os.path.isdir(wdir)
            cleanup_test(test, 'pass_test')
            assert not os.path.exists(wdir)
        finally:
            if os.path.exists(wdir):
                shutil.rmtree(wdir, ignore_errors = 1)
                test._dirlist.remove(wdir)

        test = TestCmd.TestCmd(workdir = '')
        wdir = test.workdir
        try:
            test.preserve()
            cleanup_test(test, 'pass_test', "Preserved directory %s\n" % wdir)
            assert os.path.isdir(wdir)
            cleanup_test(test, 'fail_test', "Preserved directory %s\n" % wdir)
            assert os.path.isdir(wdir)
            cleanup_test(test, 'no_result', "Preserved directory %s\n" % wdir)
            assert os.path.isdir(wdir)
        finally:
            if os.path.exists(wdir):
                shutil.rmtree(wdir, ignore_errors = 1)
                test._dirlist.remove(wdir)



class program_TestCase(TestCmdTestCase):
    def test_program(self):
        """Test program()"""
        test = TestCmd.TestCmd()
        assert test.program is None, 'initialized program?'
        test = TestCmd.TestCmd(program = 'test')
        assert test.program == os.path.join(os.getcwd(), 'test'), 'uninitialized program'
        test.program_set('foo')
        assert test.program == os.path.join(os.getcwd(), 'foo'), 'did not set program'



class read_TestCase(TestCmdTestCase):
    def test_read(self):
        """Test read()"""
        test = TestCmd.TestCmd(workdir = '', subdir = 'foo')
        wdir_file1 = os.path.join(test.workdir, 'file1')
        wdir_file2 = os.path.join(test.workdir, 'file2')
        wdir_foo_file3 = os.path.join(test.workdir, 'foo', 'file3')
        wdir_file4 = os.path.join(test.workdir, 'file4')
        wdir_file5 = os.path.join(test.workdir, 'file5')

        open(wdir_file1, 'wb').write("")
        open(wdir_file2, 'wb').write("Test\nfile\n#2.\n")
        open(wdir_foo_file3, 'wb').write("Test\nfile\n#3.\n")
        open(wdir_file4, 'wb').write("Test\nfile\n#4.\n")
        open(wdir_file5, 'wb').write("Test\r\nfile\r\n#5.\r\n")

        try:
            contents = test.read('no_file')
        except IOError:  # expect "No such file or directory"
            pass
        except:
            raise

        try:
            test.read(test.workpath('file_x'), mode = 'w')
        except ValueError:  # expect "mode must begin with 'r'
            pass
        except:
            raise

        def _file_matches(file, contents, expected):
            assert contents == expected, \
                "Expected contents of " + str(file) + "==========\n" + \
                expected + \
                "Actual contents of " + str(file) + "============\n" + \
                contents

        _file_matches(wdir_file1, test.read('file1'), "")
        _file_matches(wdir_file2, test.read('file2'), "Test\nfile\n#2.\n")
        _file_matches(wdir_foo_file3, test.read(['foo', 'file3']),
                        "Test\nfile\n#3.\n")
        _file_matches(wdir_foo_file3,
                      test.read(UserList.UserList(['foo', 'file3'])),
                        "Test\nfile\n#3.\n")
        _file_matches(wdir_file4, test.read('file4', mode = 'r'),
                        "Test\nfile\n#4.\n")
        _file_matches(wdir_file5, test.read('file5', mode = 'rb'),
                        "Test\r\nfile\r\n#5.\r\n")



class rmdir_TestCase(TestCmdTestCase):
    def test_rmdir(self):
        """Test rmdir()"""
        test = TestCmd.TestCmd(workdir = '')

        try:
            test.rmdir(['no', 'such', 'dir'])
        except EnvironmentError:
            pass
        else:
            raise Exception("did not catch expected EnvironmentError")

        test.subdir(['sub'],
                    ['sub', 'dir'],
                    ['sub', 'dir', 'one'])

        s = test.workpath('sub')
        s_d = test.workpath('sub', 'dir')
        s_d_o = test.workpath('sub', 'dir', 'one')

        try:
            test.rmdir(['sub'])
        except EnvironmentError:
            pass
        else:
            raise Exception("did not catch expected EnvironmentError")

        assert os.path.isdir(s_d_o), "%s is gone?" % s_d_o

        try:
            test.rmdir(['sub'])
        except EnvironmentError:
            pass
        else:
            raise Exception("did not catch expected EnvironmentError")

        assert os.path.isdir(s_d_o), "%s is gone?" % s_d_o

        test.rmdir(['sub', 'dir', 'one'])

        assert not os.path.exists(s_d_o), "%s exists?" % s_d_o
        assert os.path.isdir(s_d), "%s is gone?" % s_d

        test.rmdir(['sub', 'dir'])

        assert not os.path.exists(s_d), "%s exists?" % s_d
        assert os.path.isdir(s), "%s is gone?" % s

        test.rmdir('sub')

        assert not os.path.exists(s), "%s exists?" % s



class run_TestCase(TestCmdTestCase):
    def test_run(self):
        """Test run()"""

        t = self.setup_run_scripts()

        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:
            test = TestCmd.TestCmd(program = t.script,
                                   interpreter = 'python',
                                   workdir = '',
                                   subdir = 'script_subdir')

            test.run()
            self.run_match(test.stdout(), t.script, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(test.stderr(), t.script, "STDERR", t.workdir,
                           repr([]))

            test.run(arguments = 'arg1 arg2 arg3')
            self.run_match(test.stdout(), t.script, "STDOUT", t.workdir,
                           repr(['arg1', 'arg2', 'arg3']))
            self.run_match(test.stderr(), t.script, "STDERR", t.workdir,
                           repr(['arg1', 'arg2', 'arg3']))

            test.run(program = t.scriptx, arguments = 'foo')
            self.run_match(test.stdout(), t.scriptx, "STDOUT", t.workdir,
                           repr(['foo']))
            self.run_match(test.stderr(), t.scriptx, "STDERR", t.workdir,
                           repr(['foo']))

            test.run(chdir = os.curdir, arguments = 'x y z')
            self.run_match(test.stdout(), t.script, "STDOUT", test.workdir,
                           repr(['x', 'y', 'z']))
            self.run_match(test.stderr(), t.script, "STDERR", test.workdir,
                           repr(['x', 'y', 'z']))

            test.run(chdir = 'script_subdir')
            script_subdir = test.workpath('script_subdir')
            self.run_match(test.stdout(), t.script, "STDOUT", script_subdir,
                           repr([]))
            self.run_match(test.stderr(), t.script, "STDERR", script_subdir,
                           repr([]))

            test.run(program = t.script1, interpreter = ['python', '-x'])
            self.run_match(test.stdout(), t.script1, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(test.stderr(), t.script1, "STDERR", t.workdir,
                           repr([]))

            try:
                test.run(chdir = 'no_subdir')
            except OSError:
                pass

            test.run(program = 'no_script', interpreter = 'python')
            assert test.status != None, test.status

            try:
                test.run(program = 'no_script', interpreter = 'no_interpreter')
            except OSError:
                # Python versions that use subprocess throw an OSError
                # exception when they try to execute something that
                # isn't there.
                pass
            else:
                # Python versions that use os.popen3() or the Popen3
                # class run things through the shell, which just returns
                # a non-zero exit status.
                assert test.status != None, test.status

            testx = TestCmd.TestCmd(program = t.scriptx,
                                    workdir = '',
                                    subdir = 't.scriptx_subdir')

            testx.run()
            self.run_match(testx.stdout(), t.scriptx, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(testx.stderr(), t.scriptx, "STDERR", t.workdir,
                           repr([]))

            testx.run(arguments = 'foo bar')
            self.run_match(testx.stdout(), t.scriptx, "STDOUT", t.workdir,
                           repr(['foo', 'bar']))
            self.run_match(testx.stderr(), t.scriptx, "STDERR", t.workdir,
                           repr(['foo', 'bar']))

            testx.run(program = t.script, interpreter = 'python', arguments = 'bar')
            self.run_match(testx.stdout(), t.script, "STDOUT", t.workdir,
                           repr(['bar']))
            self.run_match(testx.stderr(), t.script, "STDERR", t.workdir,
                           repr(['bar']))

            testx.run(chdir = os.curdir, arguments = 'baz')
            self.run_match(testx.stdout(), t.scriptx, "STDOUT", testx.workdir,
                           repr(['baz']))
            self.run_match(testx.stderr(), t.scriptx, "STDERR", testx.workdir,
                           repr(['baz']))

            testx.run(chdir = 't.scriptx_subdir')
            t.scriptx_subdir = testx.workpath('t.scriptx_subdir')
            self.run_match(testx.stdout(), t.scriptx, "STDOUT", t.scriptx_subdir,
                           repr([]))
            self.run_match(testx.stderr(), t.scriptx, "STDERR", t.scriptx_subdir,
                           repr([]))

            testx.run(program = t.script1, interpreter = ('python', '-x'))
            self.run_match(testx.stdout(), t.script1, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(testx.stderr(), t.script1, "STDERR", t.workdir,
                           repr([]))

            s = os.path.join('.', t.scriptx)
            testx.run(program = [s])
            self.run_match(testx.stdout(), t.scriptx, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(testx.stderr(), t.scriptx, "STDERR", t.workdir,
                           repr([]))

            try:
                testx.run(chdir = 'no_subdir')
            except OSError:
                pass

            try:
                testx.run(program = 'no_program')
            except OSError:
                # Python versions that use subprocess throw an OSError
                # exception when they try to execute something that
                # isn't there.
                pass
            else:
                # Python versions that use os.popen3() or the Popen3
                # class run things through the shell, which just returns
                # a non-zero exit status.
                assert test.status != None

            test1 = TestCmd.TestCmd(program = t.script1,
                                    interpreter = ['python', '-x'],
                                    workdir = '')

            test1.run()
            self.run_match(test1.stdout(), t.script1, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(test1.stderr(), t.script1, "STDERR", t.workdir,
                           repr([]))

        finally:
            os.chdir(t.orig_cwd)

    def test_run_subclass(self):
        """Test run() through a subclass with different signatures"""

        t = self.setup_run_scripts()

        # Everything before this prepared our "source directory."
        # Now do the real test.

        class MyTestCmdSubclass(TestCmd.TestCmd):
            def start(self, additional_argument=None, **kw):
                return TestCmd.TestCmd.start(self, **kw)

        try:
            test = MyTestCmdSubclass(program = t.script,
                                     interpreter = 'python',
                                     workdir = '',
                                     subdir = 'script_subdir')

            test.run()
            self.run_match(test.stdout(), t.script, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(test.stderr(), t.script, "STDERR", t.workdir,
                           repr([]))
        finally:
            os.chdir(t.orig_cwd)


class run_verbose_TestCase(TestCmdTestCase):
    def test_run_verbose(self):
        """Test the run() method's verbose attribute"""

        # Prepare our "source directory."
        t = self.setup_run_scripts()

        save_stdout = sys.stderr
        save_stderr = sys.stderr

        try:
            # Test calling TestCmd() with an explicit verbose = 1.

            test = TestCmd.TestCmd(program = t.script,
                                   interpreter = 'python',
                                   workdir = '',
                                   verbose = 1)
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            test.run(arguments = ['arg1 arg2'])
            o = sys.stdout.getvalue()
            assert o == '', o
            e = sys.stderr.getvalue()
            expect = 'python "%s" "arg1 arg2"\n' % t.script_path
            assert expect == e, (expect, e)
    
            testx = TestCmd.TestCmd(program = t.scriptx,
                                    workdir = '',
                                    verbose = 1)
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            testx.run(arguments = ['arg1 arg2'])
            expect = '"%s" "arg1 arg2"\n' % t.scriptx_path
            o = sys.stdout.getvalue()
            assert o == '', o
            e = sys.stderr.getvalue()
            assert expect == e, (expect, e)

            # Test calling TestCmd() with an explicit verbose = 2.

            outerr_fmt = """\
============ STATUS: 0
============ BEGIN STDOUT (len=%s):
%s============ END STDOUT
============ BEGIN STDERR (len=%s)
%s============ END STDERR
"""

            out_fmt = """\
============ STATUS: 0
============ BEGIN STDOUT (len=%s):
%s============ END STDOUT
"""

            err_fmt = """\
============ STATUS: 0
============ BEGIN STDERR (len=%s)
%s============ END STDERR
"""

            test = TestCmd.TestCmd(program = t.script,
                                   interpreter = 'python',
                                   workdir = '',
                                   verbose = 2)
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            test.run(arguments = ['arg1 arg2'])

            line_fmt = "script:  %s:  %s:  ['arg1 arg2']\n"
            stdout_line = line_fmt % ('STDOUT', t.sub_dir)
            stderr_line = line_fmt % ('STDERR', t.sub_dir)
            expect = outerr_fmt % (len(stdout_line), stdout_line,
                                   len(stderr_line), stderr_line)
            o = sys.stdout.getvalue()
            assert expect == o, (expect, o)

            expect = 'python "%s" "arg1 arg2"\n' % t.script_path
            e = sys.stderr.getvalue()
            assert e == expect, (e, expect)
    
            testx = TestCmd.TestCmd(program = t.scriptx,
                                    workdir = '',
                                    verbose = 2)
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            testx.run(arguments = ['arg1 arg2'])

            line_fmt = "scriptx.bat:  %s:  %s:  ['arg1 arg2']\n"
            stdout_line = line_fmt % ('STDOUT', t.sub_dir)
            stderr_line = line_fmt % ('STDERR', t.sub_dir)
            expect = outerr_fmt % (len(stdout_line), stdout_line,
                                   len(stderr_line), stderr_line)
            o = sys.stdout.getvalue()
            assert expect == o, (expect, o)

            expect = '"%s" "arg1 arg2"\n' % t.scriptx_path
            e = sys.stderr.getvalue()
            assert e == expect, (e, expect)

            # Test calling TestCmd() with an explicit verbose = 3.

            test = TestCmd.TestCmd(program = t.scriptout,
                                   interpreter = 'python',
                                   workdir = '',
                                   verbose = 2)
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            test.run(arguments = ['arg1 arg2'])

            line_fmt = "scriptout:  %s:  %s:  ['arg1 arg2']\n"
            stdout_line = line_fmt % ('STDOUT', t.sub_dir)
            expect = out_fmt % (len(stdout_line), stdout_line)
            o = sys.stdout.getvalue()
            assert expect == o, (expect, o)

            e = sys.stderr.getvalue()
            expect = 'python "%s" "arg1 arg2"\n' % (t.scriptout_path)
            assert e == expect, (e, expect)

            test = TestCmd.TestCmd(program = t.scriptout,
                                   interpreter = 'python',
                                   workdir = '',
                                   verbose = 3)
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            test.run(arguments = ['arg1 arg2'])

            line_fmt = "scriptout:  %s:  %s:  ['arg1 arg2']\n"
            stdout_line = line_fmt % ('STDOUT', t.sub_dir)
            expect = outerr_fmt % (len(stdout_line), stdout_line,
                                   '0', '')
            o = sys.stdout.getvalue()
            assert expect == o, (expect, o)

            e = sys.stderr.getvalue()
            expect = 'python "%s" "arg1 arg2"\n' % (t.scriptout_path)
            assert e == expect, (e, expect)

            # Test letting TestCmd() pick up verbose = 2 from the environment.

            os.environ['TESTCMD_VERBOSE'] = '2'

            test = TestCmd.TestCmd(program = t.script,
                                   interpreter = 'python',
                                   workdir = '')
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            test.run(arguments = ['arg1 arg2'])

            line_fmt = "script:  %s:  %s:  ['arg1 arg2']\n"
            stdout_line = line_fmt % ('STDOUT', t.sub_dir)
            stderr_line = line_fmt % ('STDERR', t.sub_dir)
            expect = outerr_fmt % (len(stdout_line), stdout_line,
                                   len(stderr_line), stderr_line)
            o = sys.stdout.getvalue()
            assert expect == o, (expect, o)

            expect = 'python "%s" "arg1 arg2"\n' % t.script_path
            e = sys.stderr.getvalue()
            assert e == expect, (e, expect)
    
            testx = TestCmd.TestCmd(program = t.scriptx,
                                    workdir = '')
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            testx.run(arguments = ['arg1 arg2'])

            line_fmt = "scriptx.bat:  %s:  %s:  ['arg1 arg2']\n"
            stdout_line = line_fmt % ('STDOUT', t.sub_dir)
            stderr_line = line_fmt % ('STDERR', t.sub_dir)
            expect = outerr_fmt % (len(stdout_line), stdout_line,
                                   len(stderr_line), stderr_line)
            o = sys.stdout.getvalue()
            assert expect == o, (expect, o)

            expect = '"%s" "arg1 arg2"\n' % t.scriptx_path
            e = sys.stderr.getvalue()
            assert e == expect, (e, expect)

            # Test letting TestCmd() pick up verbose = 1 from the environment.

            os.environ['TESTCMD_VERBOSE'] = '1'

            test = TestCmd.TestCmd(program = t.script,
                                   interpreter = 'python',
                                   workdir = '',
                                   verbose = 1)
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            test.run(arguments = ['arg1 arg2'])
            o = sys.stdout.getvalue()
            assert o == '', o
            e = sys.stderr.getvalue()
            expect = 'python "%s" "arg1 arg2"\n' % t.script_path
            assert expect == e, (expect, e)
    
            testx = TestCmd.TestCmd(program = t.scriptx,
                                    workdir = '',
                                    verbose = 1)
    
            sys.stdout = StringIO.StringIO()
            sys.stderr = StringIO.StringIO()
    
            testx.run(arguments = ['arg1 arg2'])
            expect = '"%s" "arg1 arg2"\n' % t.scriptx_path
            o = sys.stdout.getvalue()
            assert o == '', o
            e = sys.stderr.getvalue()
            assert expect == e, (expect, e)

        finally:
            sys.stdout = save_stdout
            sys.stderr = save_stderr
            os.chdir(t.orig_cwd)
            os.environ['TESTCMD_VERBOSE'] = ''



class set_diff_function_TestCase(TestCmdTestCase):
    def test_set_diff_function(self):
        """Test set_diff_function()"""
        self.popen_python(r"""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd()
test.diff("a\n", "a\n")
test.set_diff_function('diff_re')
test.diff(".\n", "a\n")
sys.exit(0)
""" % self.orig_cwd)

    def test_set_diff_function_stdout(self):
        """Test set_diff_function():  stdout"""
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd()
print "diff:"
test.diff("a\\n", "a\\n")
print "diff_stdout:"
test.diff_stdout("a\\n", "a\\n")
test.set_diff_function(stdout='diff_re')
print "diff:"
test.diff(".\\n", "a\\n")
print "diff_stdout:"
test.diff_stdout(".\\n", "a\\n")
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
diff:
diff_stdout:
diff:
1c1
< .
---
> a
diff_stdout:
""")

    def test_set_diff_function_stderr(self):
        """Test set_diff_function():  stderr """
        self.popen_python("""import sys
sys.path = ['%s'] + sys.path
import TestCmd
test = TestCmd.TestCmd()
print "diff:"
test.diff("a\\n", "a\\n")
print "diff_stderr:"
test.diff_stderr("a\\n", "a\\n")
test.set_diff_function(stderr='diff_re')
print "diff:"
test.diff(".\\n", "a\\n")
print "diff_stderr:"
test.diff_stderr(".\\n", "a\\n")
sys.exit(0)
""" % self.orig_cwd,
                          stdout="""\
diff:
diff_stderr:
diff:
1c1
< .
---
> a
diff_stderr:
""")



class set_match_function_TestCase(TestCmdTestCase):
    def test_set_match_function(self):
        """Test set_match_function()"""
        test = TestCmd.TestCmd()
        assert test.match("abcde\n", "a.*e\n")
        assert test.match("abcde\n", "abcde\n")

        test.set_match_function('match_exact')

        assert not test.match("abcde\n", "a.*e\n")
        assert test.match("abcde\n", "abcde\n")

    def test_set_match_function_stdout(self):
        """Test set_match_function():  stdout """
        test = TestCmd.TestCmd()
        assert test.match("abcde\n", "a.*e\n")
        assert test.match("abcde\n", "abcde\n")
        assert test.match_stdout("abcde\n", "a.*e\n")
        assert test.match_stdout("abcde\n", "abcde\n")

        test.set_match_function(stdout='match_exact')

        assert test.match("abcde\n", "a.*e\n")
        assert test.match("abcde\n", "abcde\n")
        assert not test.match_stdout("abcde\n", "a.*e\n")
        assert test.match_stdout("abcde\n", "abcde\n")

    def test_set_match_function_stderr(self):
        """Test set_match_function():  stderr """
        test = TestCmd.TestCmd()
        assert test.match("abcde\n", "a.*e\n")
        assert test.match("abcde\n", "abcde\n")
        assert test.match_stderr("abcde\n", "a.*e\n")
        assert test.match_stderr("abcde\n", "abcde\n")

        test.set_match_function(stderr='match_exact')

        assert test.match("abcde\n", "a.*e\n")
        assert test.match("abcde\n", "abcde\n")
        assert not test.match_stderr("abcde\n", "a.*e\n")
        assert test.match_stderr("abcde\n", "abcde\n")



class sleep_TestCase(TestCmdTestCase):
    def test_sleep(self):
        """Test sleep()"""
        test = TestCmd.TestCmd()

        start = time.time()
        test.sleep()
        end = time.time()
        diff = end - start
        assert diff > 0.9, "only slept %f seconds (start %f, end %f), not default" % (diff, start, end)

        start = time.time()
        test.sleep(3)
        end = time.time()
        diff = end - start
        assert diff > 2.9, "only slept %f seconds (start %f, end %f), not 3" % (diff, start, end)



class stderr_TestCase(TestCmdTestCase):
    def test_stderr(self):
        """Test stderr()"""
        run_env = TestCmd.TestCmd(workdir = '')
        run_env.write('run1', """import sys
sys.stdout.write("run1 STDOUT %s\\n" % sys.argv[1:])
sys.stdout.write("run1 STDOUT second line\\n")
sys.stderr.write("run1 STDERR %s\\n" % sys.argv[1:])
sys.stderr.write("run1 STDERR second line\\n")
""")
        run_env.write('run2', """import sys
sys.stdout.write("run2 STDOUT %s\\n" % sys.argv[1:])
sys.stdout.write("run2 STDOUT second line\\n")
sys.stderr.write("run2 STDERR %s\\n" % sys.argv[1:])
sys.stderr.write("run2 STDERR second line\\n")
""")
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        test = TestCmd.TestCmd(interpreter = 'python', workdir = '')
        try:
            output = test.stderr()
        except IndexError:
            pass
        else:
            raise IndexError("got unexpected output:\n" + output)
        test.program_set('run1')
        test.run(arguments = 'foo bar')
        test.program_set('run2')
        test.run(arguments = 'snafu')
        # XXX SHOULD TEST ABSOLUTE NUMBER AS WELL
        output = test.stderr()
        assert output == "run2 STDERR ['snafu']\nrun2 STDERR second line\n", output
        output = test.stderr(run = -1)
        assert output == "run1 STDERR ['foo', 'bar']\nrun1 STDERR second line\n", output



class command_args_TestCase(TestCmdTestCase):
    def test_command_args(self):
        """Test command_args()"""
        run_env = TestCmd.TestCmd(workdir = '')
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        test = TestCmd.TestCmd(workdir = '')

        r = test.command_args('prog')
        expect = [run_env.workpath('prog')]
        assert r == expect, (expect, r)

        r = test.command_args(test.workpath('new_prog'))
        expect = [test.workpath('new_prog')]
        assert r == expect, (expect, r)

        r = test.command_args('prog', 'python')
        expect = ['python', run_env.workpath('prog')]
        assert r == expect, (expect, r)

        r = test.command_args('prog', 'python', 'arg1 arg2')
        expect = ['python', run_env.workpath('prog'), 'arg1', 'arg2']
        assert r == expect, (expect, r)

        test.program_set('default_prog')
        default_prog = run_env.workpath('default_prog')

        r = test.command_args()
        expect = [default_prog]
        assert r == expect, (expect, r)

        r = test.command_args(interpreter='PYTHON')
        expect = ['PYTHON', default_prog]
        assert r == expect, (expect, r)

        r = test.command_args(interpreter='PYTHON', arguments='arg3 arg4')
        expect = ['PYTHON', default_prog, 'arg3', 'arg4']
        assert r == expect, (expect, r)

        test.interpreter_set('default_python')

        r = test.command_args()
        expect = ['default_python', default_prog]
        assert r == expect, (expect, r)

        r = test.command_args(arguments='arg5 arg6')
        expect = ['default_python', default_prog, 'arg5', 'arg6']
        assert r == expect, (expect, r)

        r = test.command_args('new_prog_1')
        expect = [run_env.workpath('new_prog_1')]
        assert r == expect, (expect, r)

        r = test.command_args(program='new_prog_2')
        expect = [run_env.workpath('new_prog_2')]
        assert r == expect, (expect, r)



class start_TestCase(TestCmdTestCase):
    def setup_run_scripts(self):
        t = TestCmdTestCase.setup_run_scripts(self)
        t.recv_script = 'script_recv'
        t.recv_script_path = t.run_env.workpath(t.sub_dir, t.recv_script)
        t.recv_out_path = t.run_env.workpath('script_recv.out')
        text = """\
import os
import sys

class Unbuffered:
    def __init__(self, file):
        self.file = file
    def write(self, arg):
        self.file.write(arg)
        self.file.flush()
    def __getattr__(self, attr):
        return getattr(self.file, attr)

sys.stdout = Unbuffered(sys.stdout)
sys.stderr = Unbuffered(sys.stderr)

sys.stdout.write('script_recv:  STDOUT\\n')
sys.stderr.write('script_recv:  STDERR\\n')
logfp = open(r'%s', 'wb')
while 1:
    line = sys.stdin.readline()
    if not line:
        break
    logfp.write('script_recv:  ' + line)
    sys.stdout.write('script_recv:  STDOUT:  ' + line)
    sys.stderr.write('script_recv:  STDERR:  ' + line)
logfp.close()
        """ % t.recv_out_path
        t.run_env.write(t.recv_script_path, text)
        os.chmod(t.recv_script_path, 0644)  # XXX UNIX-specific
        return t

    def test_start(self):
        """Test start()"""

        t = self.setup_run_scripts()

        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:
            test = TestCmd.TestCmd(program = t.script,
                                   interpreter = 'python',
                                   workdir = '',
                                   subdir = 'script_subdir')

            p = test.start()
            self.run_match(p.stdout.read(), t.script, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(p.stderr.read(), t.script, "STDERR", t.workdir,
                           repr([]))
            p.wait()

            p = test.start(arguments='arg1 arg2 arg3')
            self.run_match(p.stdout.read(), t.script, "STDOUT", t.workdir,
                           repr(['arg1', 'arg2', 'arg3']))
            self.run_match(p.stderr.read(), t.script, "STDERR", t.workdir,
                           repr(['arg1', 'arg2', 'arg3']))
            p.wait()

            p = test.start(program=t.scriptx, arguments='foo')
            self.run_match(p.stdout.read(), t.scriptx, "STDOUT", t.workdir,
                           repr(['foo']))
            self.run_match(p.stderr.read(), t.scriptx, "STDERR", t.workdir,
                           repr(['foo']))
            p.wait()

            p = test.start(program=t.script1, interpreter=['python', '-x'])
            self.run_match(p.stdout.read(), t.script1, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(p.stderr.read(), t.script1, "STDERR", t.workdir,
                           repr([]))
            p.wait()

            p = test.start(program='no_script', interpreter='python')
            status = p.wait()
            assert status != None, status

            try:
                p = test.start(program='no_script', interpreter='no_interpreter')
            except OSError:
                # Python versions that use subprocess throw an OSError
                # exception when they try to execute something that
                # isn't there.
                pass
            else:
                status = p.wait()
                # Python versions that use os.popen3() or the Popen3
                # class run things through the shell, which just returns
                # a non-zero exit status.
                assert status != None, status

            testx = TestCmd.TestCmd(program = t.scriptx,
                                    workdir = '',
                                    subdir = 't.scriptx_subdir')

            p = testx.start()
            self.run_match(p.stdout.read(), t.scriptx, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(p.stderr.read(), t.scriptx, "STDERR", t.workdir,
                           repr([]))
            p.wait()

            p = testx.start(arguments='foo bar')
            self.run_match(p.stdout.read(), t.scriptx, "STDOUT", t.workdir,
                           repr(['foo', 'bar']))
            self.run_match(p.stderr.read(), t.scriptx, "STDERR", t.workdir,
                           repr(['foo', 'bar']))
            p.wait()

            p = testx.start(program=t.script, interpreter='python', arguments='bar')
            self.run_match(p.stdout.read(), t.script, "STDOUT", t.workdir,
                           repr(['bar']))
            self.run_match(p.stderr.read(), t.script, "STDERR", t.workdir,
                           repr(['bar']))
            p.wait()

            p = testx.start(program=t.script1, interpreter=('python', '-x'))
            self.run_match(p.stdout.read(), t.script1, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(p.stderr.read(), t.script1, "STDERR", t.workdir,
                           repr([]))
            p.wait()

            s = os.path.join('.', t.scriptx)
            p = testx.start(program=[s])
            self.run_match(p.stdout.read(), t.scriptx, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(p.stderr.read(), t.scriptx, "STDERR", t.workdir,
                           repr([]))
            p.wait()

            try:
                testx.start(program='no_program')
            except OSError:
                # Python versions that use subprocess throw an OSError
                # exception when they try to execute something that
                # isn't there.
                pass
            else:
                # Python versions that use os.popen3() or the Popen3
                # class run things through the shell, which just dies
                # trying to execute the non-existent program before
                # we can wait() for it.
                try:
                    p = p.wait()
                except OSError:
                    pass

            test1 = TestCmd.TestCmd(program = t.script1,
                                    interpreter = ['python', '-x'],
                                    workdir = '')

            p = test1.start()
            self.run_match(p.stdout.read(), t.script1, "STDOUT", t.workdir,
                           repr([]))
            self.run_match(p.stderr.read(), t.script1, "STDERR", t.workdir,
                           repr([]))
            p.wait()

        finally:
            os.chdir(t.orig_cwd)

    def test_finish(self):
        """Test finish()"""

        t = self.setup_run_scripts()

        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:

            test = TestCmd.TestCmd(program = t.recv_script,
                                   interpreter = 'python',
                                   workdir = '',
                                   subdir = 'script_subdir')

            test.start(stdin=1)
            test.finish()
            expect_stdout = """\
script_recv:  STDOUT
"""
            expect_stderr = """\
script_recv:  STDERR
"""
            stdout = test.stdout()
            assert stdout == expect_stdout, stdout
            stderr = test.stderr()
            assert stderr == expect_stderr, stderr

            p = test.start(stdin=1)
            p.send('input\n')
            test.finish(p)
            expect_stdout = """\
script_recv:  STDOUT
script_recv:  STDOUT:  input
"""
            expect_stderr = """\
script_recv:  STDERR
script_recv:  STDERR:  input
"""
            stdout = test.stdout()
            assert stdout == expect_stdout, stdout
            stderr = test.stderr()
            assert stderr == expect_stderr, stderr

            p = test.start(combine=1, stdin=1)
            p.send('input\n')
            test.finish(p)
            expect_stdout = """\
script_recv:  STDOUT
script_recv:  STDERR
script_recv:  STDOUT:  input
script_recv:  STDERR:  input
"""
            expect_stderr = ""
            stdout = test.stdout()
            assert stdout == expect_stdout, stdout
            stderr = test.stderr()
            assert stderr == expect_stderr, stderr

        finally:
            os.chdir(t.orig_cwd)

    def test_recv(self):
        """Test the recv() method of objects returned by start()"""

        t = self.setup_run_scripts()

        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:
            test = TestCmd.TestCmd(program = t.script,
                                   interpreter = 'python',
                                   workdir = '',
                                   subdir = 'script_subdir')

            p = test.start()
            stdout = p.recv()
            while stdout == '':
                import time
                time.sleep(1)
                stdout = p.recv()
            self.run_match(stdout, t.script, "STDOUT", t.workdir,
                           repr([]))
            p.wait()

        finally:
            os.chdir(t.orig_cwd)

    def test_recv_err(self):
        """Test the recv_err() method of objects returned by start()"""

        t = self.setup_run_scripts()

        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:

            test = TestCmd.TestCmd(program = t.script,
                                   interpreter = 'python',
                                   workdir = '',
                                   subdir = 'script_subdir')

            p = test.start()
            stderr = p.recv_err()
            while stderr == '':
                import time
                time.sleep(1)
                stderr = p.recv_err()
            self.run_match(stderr, t.script, "STDERR", t.workdir,
                           repr([]))
            p.wait()


        finally:
            os.chdir(t.orig_cwd)

    def test_send(self):
        """Test the send() method of objects returned by start()"""

        t = self.setup_run_scripts()

        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:

            test = TestCmd.TestCmd(program = t.recv_script,
                                   interpreter = 'python',
                                   workdir = '',
                                   subdir = 'script_subdir')

            p = test.start(stdin=1)
            input = 'stdin.write() input to the receive script\n'
            p.stdin.write(input)
            p.stdin.close()
            p.wait()
            result = open(t.recv_out_path, 'rb').read()
            expect = 'script_recv:  ' + input
            assert result == expect, repr(result)

            p = test.start(stdin=1)
            input = 'send() input to the receive script\n'
            p.send(input)
            p.stdin.close()
            p.wait()
            result = open(t.recv_out_path, 'rb').read()
            expect = 'script_recv:  ' + input
            assert result == expect, repr(result)

        finally:
            os.chdir(t.orig_cwd)

    # TODO(sgk):  figure out how to eliminate the race conditions here.
    def __FLAKY__test_send_recv(self):
        """Test the send_recv() method of objects returned by start()"""

        t = self.setup_run_scripts()

        # Everything before this prepared our "source directory."
        # Now do the real test.
        try:

            test = TestCmd.TestCmd(program = t.recv_script,
                                   interpreter = 'python',
                                   workdir = '',
                                   subdir = 'script_subdir')

            def do_send_recv(p, input):
                send, stdout, stderr = p.send_recv(input)
                stdout = self.translate_newlines(stdout)
                stderr = self.translate_newlines(stderr)
                return send, stdout, stderr

            p = test.start(stdin=1)
            input = 'input to the receive script\n'
            send, stdout, stderr = do_send_recv(p, input)
            # Buffering issues and a race condition prevent this from
            # being completely deterministic, so check for both null
            # output and the first write() on each stream.
            assert stdout in ("", "script_recv:  STDOUT\n"), stdout
            assert stderr in ("", "script_recv:  STDERR\n"), stderr
            send, stdout, stderr = do_send_recv(p, input)
            assert stdout in ("", "script_recv:  STDOUT\n"), stdout
            assert stderr in ("", "script_recv:  STDERR\n"), stderr
            p.stdin.close()
            stdout = self.translate_newlines(p.recv())
            stderr = self.translate_newlines(p.recv_err())
            assert stdout in ("", "script_recv:  STDOUT\n"), stdout
            assert stderr in ("", "script_recv:  STDERR\n"), stderr
            p.wait()
            stdout = self.translate_newlines(p.recv())
            stderr = self.translate_newlines(p.recv_err())
            expect_stdout = """\
script_recv:  STDOUT
script_recv:  STDOUT:  input to the receive script
script_recv:  STDOUT:  input to the receive script
"""
            expect_stderr = """\
script_recv:  STDERR
script_recv:  STDERR:  input to the receive script
script_recv:  STDERR:  input to the receive script
"""
            assert stdout == expect_stdout, stdout
            assert stderr == expect_stderr, stderr
            result = open(t.recv_out_path, 'rb').read()
            expect = ('script_recv:  ' + input) * 2
            assert result == expect, (result, stdout, stderr)

        finally:
            os.chdir(t.orig_cwd)



class stdin_TestCase(TestCmdTestCase):
    def test_stdin(self):
        """Test stdin()"""
        run_env = TestCmd.TestCmd(workdir = '')
        run_env.write('run', """import fileinput
for line in fileinput.input():
    print 'Y'.join(line[:-1].split('X'))
""")
        run_env.write('input', "X on X this X line X\n")
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        test = TestCmd.TestCmd(program = 'run', interpreter = 'python', workdir = '')
        test.run(arguments = 'input')
        assert test.stdout() == "Y on Y this Y line Y\n"
        test.run(stdin = "X is X here X tooX\n")
        assert test.stdout() == "Y is Y here Y tooY\n"
        test.run(stdin = """X here X
X there X
""")
        assert test.stdout() == "Y here Y\nY there Y\n"
        test.run(stdin = ["X line X\n", "X another X\n"])
        assert test.stdout() == "Y line Y\nY another Y\n"



class stdout_TestCase(TestCmdTestCase):
    def test_stdout(self):
        """Test stdout()"""
        run_env = TestCmd.TestCmd(workdir = '')
        run_env.write('run1', """import sys
sys.stdout.write("run1 STDOUT %s\\n" % sys.argv[1:])
sys.stdout.write("run1 STDOUT second line\\n")
sys.stderr.write("run1 STDERR %s\\n" % sys.argv[1:])
sys.stderr.write("run1 STDERR second line\\n")
""")
        run_env.write('run2', """import sys
sys.stdout.write("run2 STDOUT %s\\n" % sys.argv[1:])
sys.stdout.write("run2 STDOUT second line\\n")
sys.stderr.write("run2 STDERR %s\\n" % sys.argv[1:])
sys.stderr.write("run2 STDERR second line\\n")
""")
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        test = TestCmd.TestCmd(interpreter = 'python', workdir = '')
        try:
            output = test.stdout()
        except IndexError:
            pass
        else:
            raise IndexError("got unexpected output:\n\t`%s'\n" % output)
        test.program_set('run1')
        test.run(arguments = 'foo bar')
        test.program_set('run2')
        test.run(arguments = 'snafu')
        # XXX SHOULD TEST ABSOLUTE NUMBER AS WELL
        output = test.stdout()
        assert output == "run2 STDOUT ['snafu']\nrun2 STDOUT second line\n", output
        output = test.stdout(run = -1)
        assert output == "run1 STDOUT ['foo', 'bar']\nrun1 STDOUT second line\n", output



class subdir_TestCase(TestCmdTestCase):
    def test_subdir(self):
        """Test subdir()"""
        test = TestCmd.TestCmd(workdir = '', subdir = ['no', 'such', 'subdir'])
        assert not os.path.exists(test.workpath('no'))

        test = TestCmd.TestCmd(workdir = '', subdir = 'foo')
        assert test.subdir('bar') == 1
        assert test.subdir(['foo', 'succeed']) == 1
        if os.name != "nt":
            os.chmod(test.workpath('foo'), 0500)
            assert test.subdir(['foo', 'fail']) == 0
        assert test.subdir(['sub', 'dir', 'ectory'], 'sub') == 1
        assert test.subdir('one',
                           UserList.UserList(['one', 'two']),
                           ['one', 'two', 'three']) == 3
        assert os.path.isdir(test.workpath('foo'))
        assert os.path.isdir(test.workpath('bar'))
        assert os.path.isdir(test.workpath('foo', 'succeed'))
        if os.name != "nt":
            assert not os.path.exists(test.workpath('foo', 'fail'))
        assert os.path.isdir(test.workpath('sub'))
        assert not os.path.exists(test.workpath('sub', 'dir'))
        assert not os.path.exists(test.workpath('sub', 'dir', 'ectory'))
        assert os.path.isdir(test.workpath('one', 'two', 'three'))



class symlink_TestCase(TestCmdTestCase):
    def test_symlink(self):
        """Test symlink()"""
        try: os.symlink
        except AttributeError: return

        test = TestCmd.TestCmd(workdir = '', subdir = 'foo')
        wdir_file1 = os.path.join(test.workdir, 'file1')
        wdir_target1 = os.path.join(test.workdir, 'target1')
        wdir_foo_file2 = os.path.join(test.workdir, 'foo', 'file2')
        wdir_target2 = os.path.join(test.workdir, 'target2')
        wdir_foo_target2 = os.path.join(test.workdir, 'foo', 'target2')

        test.symlink('target1', 'file1')
        assert os.path.islink(wdir_file1)
        assert not os.path.exists(wdir_file1)
        open(wdir_target1, 'w').write("")
        assert os.path.exists(wdir_file1)

        test.symlink('target2', ['foo', 'file2'])
        assert os.path.islink(wdir_foo_file2)
        assert not os.path.exists(wdir_foo_file2)
        open(wdir_target2, 'w').write("")
        assert not os.path.exists(wdir_foo_file2)
        open(wdir_foo_target2, 'w').write("")
        assert os.path.exists(wdir_foo_file2)



class tempdir_TestCase(TestCmdTestCase):
    def setUp(self):
        TestCmdTestCase.setUp(self)
        self._tempdir = tempfile.mktemp()
        os.mkdir(self._tempdir)
        os.chdir(self._tempdir)

    def tearDown(self):
        TestCmdTestCase.tearDown(self)
        os.rmdir(self._tempdir)

    def test_tempdir(self):
        """Test tempdir()"""
        test = TestCmd.TestCmd()
        tdir1 = test.tempdir()
        assert os.path.isdir(tdir1)
        test.workdir_set(None)
        test.cleanup()
        assert not os.path.exists(tdir1)

        test = TestCmd.TestCmd()
        tdir2 = test.tempdir('temp')
        assert os.path.isdir(tdir2)
        tdir3 = test.tempdir()
        assert os.path.isdir(tdir3)
        test.workdir_set(None)
        test.cleanup()
        assert not os.path.exists(tdir2)
        assert not os.path.exists(tdir3)


timeout_script = """\
import sys
import time
seconds = int(sys.argv[1])
sys.stdout.write('sleeping %s\\n' % seconds)
sys.stdout.flush()
time.sleep(seconds)
sys.stdout.write('slept %s\\n' % seconds)
sys.stdout.flush()
sys.exit(0)
"""

class timeout_TestCase(TestCmdTestCase):
    def test_initialization(self):
        """Test initialization timeout"""
        test = TestCmd.TestCmd(workdir='', timeout=2)
        test.write('sleep.py', timeout_script)

        test.run([sys.executable, test.workpath('sleep.py'), '4'])
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 4\n', test.stdout()

        test.run([sys.executable, test.workpath('sleep.py'), '4'])
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 4\n', test.stdout()

    def test_cancellation(self):
        """Test timer cancellation after firing"""
        test = TestCmd.TestCmd(workdir='', timeout=4)
        test.write('sleep.py', timeout_script)

        test.run([sys.executable, test.workpath('sleep.py'), '6'])
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 6\n', test.stdout()

        test.run([sys.executable, test.workpath('sleep.py'), '2'])
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 2\nslept 2\n', test.stdout()

        test.run([sys.executable, test.workpath('sleep.py'), '6'])
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 6\n', test.stdout()

    def test_run(self):
        """Test run() timeout"""
        test = TestCmd.TestCmd(workdir='', timeout=8)
        test.write('sleep.py', timeout_script)

        test.run([sys.executable, test.workpath('sleep.py'), '2'],
                 timeout=4)
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 2\nslept 2\n', test.stdout()

        test.run([sys.executable, test.workpath('sleep.py'), '6'],
                 timeout=4)
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 6\n', test.stdout()

    def test_set_timeout(self):
        """Test set_timeout()"""
        test = TestCmd.TestCmd(workdir='', timeout=2)
        test.write('sleep.py', timeout_script)

        test.run([sys.executable, test.workpath('sleep.py'), '4'])
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 4\n', test.stdout()

        test.set_timeout(None)

        test.run([sys.executable, test.workpath('sleep.py'), '4'])
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 4\nslept 4\n', test.stdout()

        test.set_timeout(6)

        test.run([sys.executable, test.workpath('sleep.py'), '4'])
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 4\nslept 4\n', test.stdout()

        test.run([sys.executable, test.workpath('sleep.py'), '8'])
        assert test.stderr() == '', test.stderr()
        assert test.stdout() == 'sleeping 8\n', test.stdout()



class unlink_TestCase(TestCmdTestCase):
    def test_unlink(self):
        """Test unlink()"""
        test = TestCmd.TestCmd(workdir = '', subdir = 'foo')
        wdir_file1 = os.path.join(test.workdir, 'file1')
        wdir_file2 = os.path.join(test.workdir, 'file2')
        wdir_foo_file3a = os.path.join(test.workdir, 'foo', 'file3a')
        wdir_foo_file3b = os.path.join(test.workdir, 'foo', 'file3b')
        wdir_foo_file4 = os.path.join(test.workdir, 'foo', 'file4')
        wdir_file5 = os.path.join(test.workdir, 'file5')

        open(wdir_file1, 'w').write("")
        open(wdir_file2, 'w').write("")
        open(wdir_foo_file3a, 'w').write("")
        open(wdir_foo_file3b, 'w').write("")
        open(wdir_foo_file4, 'w').write("")
        open(wdir_file5, 'w').write("")

        try:
            contents = test.unlink('no_file')
        except OSError: # expect "No such file or directory"
            pass
        except:
            raise

        test.unlink("file1")
        assert not os.path.exists(wdir_file1)

        test.unlink(wdir_file2)
        assert not os.path.exists(wdir_file2)

        test.unlink(['foo', 'file3a'])
        assert not os.path.exists(wdir_foo_file3a)

        test.unlink(UserList.UserList(['foo', 'file3b']))
        assert not os.path.exists(wdir_foo_file3b)

        test.unlink([test.workdir, 'foo', 'file4'])
        assert not os.path.exists(wdir_foo_file4)

        # Make it so we can't unlink file5.
        # For UNIX, remove write permission from the dir and the file.
        # For Windows, open the file.
        os.chmod(test.workdir, 0500)
        os.chmod(wdir_file5, 0400)
        f = open(wdir_file5, 'r')

        try:
            try:
                test.unlink('file5')
            except OSError: # expect "Permission denied"
                pass
            except:
                raise
        finally:
            os.chmod(test.workdir, 0700)
            os.chmod(wdir_file5, 0600)
            f.close()



class touch_TestCase(TestCmdTestCase):
    def test_touch(self):
        """Test touch()"""
        test = TestCmd.TestCmd(workdir = '', subdir = 'sub')

        wdir_file1 = os.path.join(test.workdir, 'file1')
        wdir_sub_file2 = os.path.join(test.workdir, 'sub', 'file2')

        open(wdir_file1, 'w').write("")
        open(wdir_sub_file2, 'w').write("")

        file1_old_time = os.path.getmtime(wdir_file1)
        file2_old_time = os.path.getmtime(wdir_sub_file2)

        test.sleep()

        test.touch(wdir_file1)

        file1_new_time = os.path.getmtime(wdir_file1)
        assert file1_new_time > file1_old_time

        test.touch('file1', file1_old_time)

        result = os.path.getmtime(wdir_file1)
        # Sub-second granularity of file systems may still vary.
        # On Windows, the two times may be off by a microsecond.
        assert int(result) == int(file1_old_time), (result, file1_old_time)

        test.touch(['sub', 'file2'])

        file2_new_time = os.path.getmtime(wdir_sub_file2)
        assert file2_new_time > file2_old_time



class verbose_TestCase(TestCmdTestCase):
    def test_verbose(self):
        """Test verbose()"""
        test = TestCmd.TestCmd()
        assert test.verbose == 0, 'verbose already initialized?'
        test = TestCmd.TestCmd(verbose = 1)
        assert test.verbose == 1, 'did not initialize verbose'
        test.verbose = 2
        assert test.verbose == 2, 'did not set verbose'



class workdir_TestCase(TestCmdTestCase):
    def test_workdir(self):
        """Test workdir()"""
        run_env = TestCmd.TestCmd(workdir = '')
        os.chdir(run_env.workdir)
        # Everything before this prepared our "source directory."
        # Now do the real test.
        test = TestCmd.TestCmd()
        assert test.workdir is None

        test = TestCmd.TestCmd(workdir = None)
        assert test.workdir is None

        test = TestCmd.TestCmd(workdir = '')
        assert test.workdir != None
        assert os.path.isdir(test.workdir)

        test = TestCmd.TestCmd(workdir = 'dir')
        assert test.workdir != None
        assert os.path.isdir(test.workdir)

        no_such_subdir = os.path.join('no', 'such', 'subdir')
        try:
            test = TestCmd.TestCmd(workdir = no_such_subdir)
        except OSError:  # expect "No such file or directory"
            pass
        except:
            raise

        test = TestCmd.TestCmd(workdir = 'foo')
        workdir_foo = test.workdir
        assert workdir_foo != None

        test.workdir_set('bar')
        workdir_bar = test.workdir
        assert workdir_bar != None

        try:
            test.workdir_set(no_such_subdir)
        except OSError:
            pass  # expect "No such file or directory"
        except:
            raise
        assert workdir_bar == test.workdir

        assert os.path.isdir(workdir_foo)
        assert os.path.isdir(workdir_bar)



class workdirs_TestCase(TestCmdTestCase):
    def test_workdirs(self):
        """Test workdirs()"""
        test = TestCmd.TestCmd()
        assert test.workdir is None
        test.workdir_set('')
        wdir1 = test.workdir
        test.workdir_set('')
        wdir2 = test.workdir
        assert os.path.isdir(wdir1)
        assert os.path.isdir(wdir2)
        test.cleanup()
        assert not os.path.exists(wdir1)
        assert not os.path.exists(wdir2)



class workpath_TestCase(TestCmdTestCase):
    def test_workpath(self):
        """Test workpath()"""
        test = TestCmd.TestCmd()
        assert test.workdir is None

        test = TestCmd.TestCmd(workdir = '')
        wpath = test.workpath('foo', 'bar')
        assert wpath == os.path.join(test.workdir, 'foo', 'bar')



class readable_TestCase(TestCmdTestCase):
    def test_readable(self):
        """Test readable()"""
        test = TestCmd.TestCmd(workdir = '', subdir = 'foo')
        test.write('file1', "Test file #1\n")
        test.write(['foo', 'file2'], "Test file #2\n")

        try: symlink = os.symlink
        except AttributeError: pass
        else: symlink('no_such_file', test.workpath('dangling_symlink'))

        test.readable(test.workdir, 0)
        # XXX skip these tests if euid == 0?
        assert not _is_readable(test.workdir)
        assert not _is_readable(test.workpath('file1'))
        assert not _is_readable(test.workpath('foo'))
        assert not _is_readable(test.workpath('foo', 'file2'))

        test.readable(test.workdir, 1)
        assert _is_readable(test.workdir)
        assert _is_readable(test.workpath('file1'))
        assert _is_readable(test.workpath('foo'))
        assert _is_readable(test.workpath('foo', 'file2'))

        test.readable(test.workdir, 0)
        # XXX skip these tests if euid == 0?
        assert not _is_readable(test.workdir)
        assert not _is_readable(test.workpath('file1'))
        assert not _is_readable(test.workpath('foo'))
        assert not _is_readable(test.workpath('foo', 'file2'))

        test.readable(test.workpath('file1'), 1)
        assert _is_readable(test.workpath('file1'))

        test.readable(test.workpath('file1'), 0)
        assert not _is_readable(test.workpath('file1'))

        test.readable(test.workdir, 1)



class writable_TestCase(TestCmdTestCase):
    def test_writable(self):
        """Test writable()"""
        test = TestCmd.TestCmd(workdir = '', subdir = 'foo')
        test.write('file1', "Test file #1\n")
        test.write(['foo', 'file2'], "Test file #2\n")

        try: symlink = os.symlink
        except AttributeError: pass
        else: symlink('no_such_file', test.workpath('dangling_symlink'))

        test.writable(test.workdir, 0)
        # XXX skip these tests if euid == 0?
        assert not _is_writable(test.workdir)
        assert not _is_writable(test.workpath('file1'))
        assert not _is_writable(test.workpath('foo'))
        assert not _is_writable(test.workpath('foo', 'file2'))

        test.writable(test.workdir, 1)
        assert _is_writable(test.workdir)
        assert _is_writable(test.workpath('file1'))
        assert _is_writable(test.workpath('foo'))
        assert _is_writable(test.workpath('foo', 'file2'))

        test.writable(test.workdir, 0)
        # XXX skip these tests if euid == 0?
        assert not _is_writable(test.workdir)
        assert not _is_writable(test.workpath('file1'))
        assert not _is_writable(test.workpath('foo'))
        assert not _is_writable(test.workpath('foo', 'file2'))

        test.writable(test.workpath('file1'), 1)
        assert _is_writable(test.workpath('file1'))

        test.writable(test.workpath('file1'), 0)
        assert not _is_writable(test.workpath('file1'))



class executable_TestCase(TestCmdTestCase):
    def test_executable(self):
        """Test executable()"""
        test = TestCmd.TestCmd(workdir = '', subdir = 'foo')
        test.write('file1', "Test file #1\n")
        test.write(['foo', 'file2'], "Test file #2\n")

        try: symlink = os.symlink
        except AttributeError: pass
        else: symlink('no_such_file', test.workpath('dangling_symlink'))

        def make_executable(fname):
            st = os.stat(fname)
            os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|0100))

        def make_non_executable(fname):
            st = os.stat(fname)
            os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~0100))

        test.executable(test.workdir, 0)
        # XXX skip these tests if euid == 0?
        assert not _is_executable(test.workdir)
        make_executable(test.workdir)
        assert not _is_executable(test.workpath('file1'))
        assert not _is_executable(test.workpath('foo'))
        make_executable(test.workpath('foo'))
        assert not _is_executable(test.workpath('foo', 'file2'))
        make_non_executable(test.workpath('foo'))
        make_non_executable(test.workdir)

        test.executable(test.workdir, 1)
        assert _is_executable(test.workdir)
        assert _is_executable(test.workpath('file1'))
        assert _is_executable(test.workpath('foo'))
        assert _is_executable(test.workpath('foo', 'file2'))

        test.executable(test.workdir, 0)
        # XXX skip these tests if euid == 0?
        assert not _is_executable(test.workdir)
        make_executable(test.workdir)
        assert not _is_executable(test.workpath('file1'))
        assert not _is_executable(test.workpath('foo'))
        make_executable(test.workpath('foo'))
        assert not _is_executable(test.workpath('foo', 'file2'))

        test.executable(test.workpath('file1'), 1)
        assert _is_executable(test.workpath('file1'))

        test.executable(test.workpath('file1'), 0)
        assert not _is_executable(test.workpath('file1'))

        test.executable(test.workdir, 1)



class write_TestCase(TestCmdTestCase):
    def test_write(self):
        """Test write()"""
        test = TestCmd.TestCmd(workdir = '', subdir = 'foo')
        test.write('file1', "Test file #1\n")
        test.write(['foo', 'file2'], "Test file #2\n")
        try:
            test.write(['bar', 'file3'], "Test file #3 (should not get created)\n")
        except IOError:  # expect "No such file or directory"
            pass
        except:
            raise
        test.write(test.workpath('file4'), "Test file #4.\n")
        test.write(test.workpath('foo', 'file5'), "Test file #5.\n")
        try:
            test.write(test.workpath('bar', 'file6'), "Test file #6 (should not get created)\n")
        except IOError:  # expect "No such file or directory"
            pass
        except:
            raise

        try:
            test.write('file7', "Test file #8.\n", mode = 'r')
        except ValueError: # expect "mode must begin with 'w'
            pass
        except:
            raise

        test.write('file8', "Test file #8.\n", mode = 'w')
        test.write('file9', "Test file #9.\r\n", mode = 'wb')

        if os.name != "nt":
            os.chmod(test.workdir, 0500)
            try:
                test.write('file10', "Test file #10 (should not get created).\n")
            except IOError:  # expect "Permission denied"
                pass
            except:
                raise

        assert os.path.isdir(test.workpath('foo'))
        assert not os.path.exists(test.workpath('bar'))
        assert os.path.isfile(test.workpath('file1'))
        assert os.path.isfile(test.workpath('foo', 'file2'))
        assert not os.path.exists(test.workpath('bar', 'file3'))
        assert os.path.isfile(test.workpath('file4'))
        assert os.path.isfile(test.workpath('foo', 'file5'))
        assert not os.path.exists(test.workpath('bar', 'file6'))
        assert not os.path.exists(test.workpath('file7'))
        assert os.path.isfile(test.workpath('file8'))
        assert os.path.isfile(test.workpath('file9'))
        if os.name != "nt":
            assert not os.path.exists(test.workpath('file10'))

        assert open(test.workpath('file8'), 'r').read() == "Test file #8.\n"
        assert open(test.workpath('file9'), 'rb').read() == "Test file #9.\r\n"



class variables_TestCase(TestCmdTestCase):
    def test_variables(self):
        """Test global variables"""
        run_env = TestCmd.TestCmd(workdir = '')

        variables = [
            'fail_test',
            'no_result',
            'pass_test',
            'match_exact',
            'match_re',
            'match_re_dotall',
            'python',
            '_python_',
            'TestCmd',
        ]

        script = "import TestCmd\n" + \
                 '\n'.join([ "print TestCmd.%s\n" % v for v in variables ])
        run_env.run(program=sys.executable, stdin=script)
        stderr = run_env.stderr()
        assert stderr == "", stderr

        script = "from TestCmd import *\n" + \
                 '\n'.join([ "print %s" % v for v in variables ])
        run_env.run(program=sys.executable, stdin=script)
        stderr = run_env.stderr()
        assert stderr == "", stderr



if __name__ == "__main__":
    tclasses = [
        __init__TestCase,
        basename_TestCase,
        cleanup_TestCase,
        chmod_TestCase,
        combine_TestCase,
        command_args_TestCase,
        description_TestCase,
        diff_TestCase,
        diff_stderr_TestCase,
        diff_stdout_TestCase,
        exit_TestCase,
        fail_test_TestCase,
        interpreter_TestCase,
        match_TestCase,
        match_exact_TestCase,
        match_re_dotall_TestCase,
        match_re_TestCase,
        match_stderr_TestCase,
        match_stdout_TestCase,
        no_result_TestCase,
        pass_test_TestCase,
        preserve_TestCase,
        program_TestCase,
        read_TestCase,
        rmdir_TestCase,
        run_TestCase,
        run_verbose_TestCase,
        set_diff_function_TestCase,
        set_match_function_TestCase,
        sleep_TestCase,
        start_TestCase,
        stderr_TestCase,
        stdin_TestCase,
        stdout_TestCase,
        subdir_TestCase,
        symlink_TestCase,
        tempdir_TestCase,
        timeout_TestCase,
        unlink_TestCase,
        touch_TestCase,
        verbose_TestCase,
        workdir_TestCase,
        workdirs_TestCase,
        workpath_TestCase,
        writable_TestCase,
        write_TestCase,
        variables_TestCase,
    ]
    if sys.platform != 'win32':
        tclasses.extend([
            executable_TestCase,
            readable_TestCase,
        ])
    suite = unittest.TestSuite()
    for tclass in tclasses:
        names = unittest.getTestCaseNames(tclass, 'test_')
        suite.addTests([ tclass(n) for n in names ])
    if not unittest.TextTestRunner().run(suite).wasSuccessful():
        sys.exit(1)

# Local Variables:
# tab-width:4
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=4 shiftwidth=4: