1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367
|
# mypy: allow-untyped-defs
from __future__ import annotations
from itertools import zip_longest
import os
from pathlib import Path
import sys
import textwrap
from _pytest.compat import getfuncargnames
from _pytest.config import ExitCode
from _pytest.fixtures import deduplicate_names
from _pytest.fixtures import TopRequest
from _pytest.monkeypatch import MonkeyPatch
from _pytest.pytester import get_public_names
from _pytest.pytester import Pytester
from _pytest.python import Function
import pytest
def test_getfuncargnames_functions():
"""Test getfuncargnames for normal functions"""
def f():
raise NotImplementedError()
assert not getfuncargnames(f)
def g(arg):
raise NotImplementedError()
assert getfuncargnames(g) == ("arg",)
def h(arg1, arg2="hello"):
raise NotImplementedError()
assert getfuncargnames(h) == ("arg1",)
def j(arg1, arg2, arg3="hello"):
raise NotImplementedError()
assert getfuncargnames(j) == ("arg1", "arg2")
def test_getfuncargnames_methods():
"""Test getfuncargnames for normal methods"""
class A:
def f(self, arg1, arg2="hello"):
raise NotImplementedError()
def g(self, /, arg1, arg2="hello"):
raise NotImplementedError()
def h(self, *, arg1, arg2="hello"):
raise NotImplementedError()
def j(self, arg1, *, arg2, arg3="hello"):
raise NotImplementedError()
def k(self, /, arg1, *, arg2, arg3="hello"):
raise NotImplementedError()
assert getfuncargnames(A().f) == ("arg1",)
assert getfuncargnames(A().g) == ("arg1",)
assert getfuncargnames(A().h) == ("arg1",)
assert getfuncargnames(A().j) == ("arg1", "arg2")
assert getfuncargnames(A().k) == ("arg1", "arg2")
def test_getfuncargnames_staticmethod():
"""Test getfuncargnames for staticmethods"""
class A:
@staticmethod
def static(arg1, arg2, x=1):
raise NotImplementedError()
assert getfuncargnames(A.static, cls=A) == ("arg1", "arg2")
def test_getfuncargnames_staticmethod_inherited() -> None:
"""Test getfuncargnames for inherited staticmethods (#8061)"""
class A:
@staticmethod
def static(arg1, arg2, x=1):
raise NotImplementedError()
class B(A):
pass
assert getfuncargnames(B.static, cls=B) == ("arg1", "arg2")
@pytest.mark.skipif(
sys.version_info >= (3, 13),
reason="""\
In python 3.13, this will raise FutureWarning:
functools.partial will be a method descriptor in future Python versions;
wrap it in staticmethod() if you want to preserve the old behavior
But the wrapped 'functools.partial' is tested by 'test_getfuncargnames_staticmethod_partial' below.
""",
)
def test_getfuncargnames_partial():
"""Check getfuncargnames for methods defined with functools.partial (#5701)"""
import functools
def check(arg1, arg2, i):
raise NotImplementedError()
class T:
test_ok = functools.partial(check, i=2)
values = getfuncargnames(T().test_ok, name="test_ok")
assert values == ("arg1", "arg2")
def test_getfuncargnames_staticmethod_partial():
"""Check getfuncargnames for staticmethods defined with functools.partial (#5701)"""
import functools
def check(arg1, arg2, i):
raise NotImplementedError()
class T:
test_ok = staticmethod(functools.partial(check, i=2))
values = getfuncargnames(T().test_ok, name="test_ok")
assert values == ("arg1", "arg2")
@pytest.mark.pytester_example_path("fixtures/fill_fixtures")
class TestFillFixtures:
def test_funcarg_lookupfails(self, pytester: Pytester) -> None:
pytester.copy_example()
result = pytester.runpytest() # "--collect-only")
assert result.ret != 0
result.stdout.fnmatch_lines(
"""
*def test_func(some)*
*fixture*some*not found*
*xyzsomething*
"""
)
def test_detect_recursive_dependency_error(self, pytester: Pytester) -> None:
pytester.copy_example()
result = pytester.runpytest()
result.stdout.fnmatch_lines(
["*recursive dependency involving fixture 'fix1' detected*"]
)
def test_funcarg_basic(self, pytester: Pytester) -> None:
pytester.copy_example()
item = pytester.getitem(Path("test_funcarg_basic.py"))
assert isinstance(item, Function)
# Execute's item's setup, which fills fixtures.
item.session._setupstate.setup(item)
del item.funcargs["request"]
assert len(get_public_names(item.funcargs)) == 2
assert item.funcargs["some"] == "test_func"
assert item.funcargs["other"] == 42
def test_funcarg_lookup_modulelevel(self, pytester: Pytester) -> None:
pytester.copy_example()
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_funcarg_lookup_classlevel(self, pytester: Pytester) -> None:
p = pytester.copy_example()
result = pytester.runpytest(p)
result.stdout.fnmatch_lines(["*1 passed*"])
def test_conftest_funcargs_only_available_in_subdir(
self, pytester: Pytester
) -> None:
pytester.copy_example()
result = pytester.runpytest("-v")
result.assert_outcomes(passed=2)
def test_extend_fixture_module_class(self, pytester: Pytester) -> None:
testfile = pytester.copy_example()
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"])
result = pytester.runpytest(testfile)
result.stdout.fnmatch_lines(["*1 passed*"])
def test_extend_fixture_conftest_module(self, pytester: Pytester) -> None:
p = pytester.copy_example()
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"])
result = pytester.runpytest(str(next(Path(str(p)).rglob("test_*.py"))))
result.stdout.fnmatch_lines(["*1 passed*"])
def test_extend_fixture_conftest_conftest(self, pytester: Pytester) -> None:
p = pytester.copy_example()
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"])
result = pytester.runpytest(str(next(Path(str(p)).rglob("test_*.py"))))
result.stdout.fnmatch_lines(["*1 passed*"])
def test_extend_fixture_conftest_plugin(self, pytester: Pytester) -> None:
pytester.makepyfile(
testplugin="""
import pytest
@pytest.fixture
def foo():
return 7
"""
)
pytester.syspathinsert()
pytester.makeconftest(
"""
import pytest
pytest_plugins = 'testplugin'
@pytest.fixture
def foo(foo):
return foo + 7
"""
)
pytester.makepyfile(
"""
def test_foo(foo):
assert foo == 14
"""
)
result = pytester.runpytest("-s")
assert result.ret == 0
def test_extend_fixture_plugin_plugin(self, pytester: Pytester) -> None:
# Two plugins should extend each order in loading order
pytester.makepyfile(
testplugin0="""
import pytest
@pytest.fixture
def foo():
return 7
"""
)
pytester.makepyfile(
testplugin1="""
import pytest
@pytest.fixture
def foo(foo):
return foo + 7
"""
)
pytester.syspathinsert()
pytester.makepyfile(
"""
pytest_plugins = ['testplugin0', 'testplugin1']
def test_foo(foo):
assert foo == 14
"""
)
result = pytester.runpytest()
assert result.ret == 0
def test_override_parametrized_fixture_conftest_module(
self, pytester: Pytester
) -> None:
"""Test override of the parametrized fixture with non-parametrized one on the test module level."""
pytester.makeconftest(
"""
import pytest
@pytest.fixture(params=[1, 2, 3])
def spam(request):
return request.param
"""
)
testfile = pytester.makepyfile(
"""
import pytest
@pytest.fixture
def spam():
return 'spam'
def test_spam(spam):
assert spam == 'spam'
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"])
result = pytester.runpytest(testfile)
result.stdout.fnmatch_lines(["*1 passed*"])
def test_override_parametrized_fixture_conftest_conftest(
self, pytester: Pytester
) -> None:
"""Test override of the parametrized fixture with non-parametrized one on the conftest level."""
pytester.makeconftest(
"""
import pytest
@pytest.fixture(params=[1, 2, 3])
def spam(request):
return request.param
"""
)
subdir = pytester.mkpydir("subdir")
subdir.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def spam():
return 'spam'
"""
),
encoding="utf-8",
)
testfile = subdir.joinpath("test_spam.py")
testfile.write_text(
textwrap.dedent(
"""\
def test_spam(spam):
assert spam == "spam"
"""
),
encoding="utf-8",
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"])
result = pytester.runpytest(testfile)
result.stdout.fnmatch_lines(["*1 passed*"])
def test_override_non_parametrized_fixture_conftest_module(
self, pytester: Pytester
) -> None:
"""Test override of the non-parametrized fixture with parametrized one on the test module level."""
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def spam():
return 'spam'
"""
)
testfile = pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[1, 2, 3])
def spam(request):
return request.param
params = {'spam': 1}
def test_spam(spam):
assert spam == params['spam']
params['spam'] += 1
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*3 passed*"])
result = pytester.runpytest(testfile)
result.stdout.fnmatch_lines(["*3 passed*"])
def test_override_non_parametrized_fixture_conftest_conftest(
self, pytester: Pytester
) -> None:
"""Test override of the non-parametrized fixture with parametrized one on the conftest level."""
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def spam():
return 'spam'
"""
)
subdir = pytester.mkpydir("subdir")
subdir.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture(params=[1, 2, 3])
def spam(request):
return request.param
"""
),
encoding="utf-8",
)
testfile = subdir.joinpath("test_spam.py")
testfile.write_text(
textwrap.dedent(
"""\
params = {'spam': 1}
def test_spam(spam):
assert spam == params['spam']
params['spam'] += 1
"""
),
encoding="utf-8",
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*3 passed*"])
result = pytester.runpytest(testfile)
result.stdout.fnmatch_lines(["*3 passed*"])
def test_override_autouse_fixture_with_parametrized_fixture_conftest_conftest(
self, pytester: Pytester
) -> None:
"""Test override of the autouse fixture with parametrized one on the conftest level.
This test covers the issue explained in issue 1601
"""
pytester.makeconftest(
"""
import pytest
@pytest.fixture(autouse=True)
def spam():
return 'spam'
"""
)
subdir = pytester.mkpydir("subdir")
subdir.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture(params=[1, 2, 3])
def spam(request):
return request.param
"""
),
encoding="utf-8",
)
testfile = subdir.joinpath("test_spam.py")
testfile.write_text(
textwrap.dedent(
"""\
params = {'spam': 1}
def test_spam(spam):
assert spam == params['spam']
params['spam'] += 1
"""
),
encoding="utf-8",
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*3 passed*"])
result = pytester.runpytest(testfile)
result.stdout.fnmatch_lines(["*3 passed*"])
def test_override_fixture_reusing_super_fixture_parametrization(
self, pytester: Pytester
) -> None:
"""Override a fixture at a lower level, reusing the higher-level fixture that
is parametrized (#1953).
"""
pytester.makeconftest(
"""
import pytest
@pytest.fixture(params=[1, 2])
def foo(request):
return request.param
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def foo(foo):
return foo * 2
def test_spam(foo):
assert foo in (2, 4)
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 passed*"])
def test_override_parametrize_fixture_and_indirect(
self, pytester: Pytester
) -> None:
"""Override a fixture at a lower level, reusing the higher-level fixture that
is parametrized, while also using indirect parametrization.
"""
pytester.makeconftest(
"""
import pytest
@pytest.fixture(params=[1, 2])
def foo(request):
return request.param
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def foo(foo):
return foo * 2
@pytest.fixture
def bar(request):
return request.param * 100
@pytest.mark.parametrize("bar", [42], indirect=True)
def test_spam(bar, foo):
assert bar == 4200
assert foo in (2, 4)
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 passed*"])
def test_override_top_level_fixture_reusing_super_fixture_parametrization(
self, pytester: Pytester
) -> None:
"""Same as the above test, but with another level of overwriting."""
pytester.makeconftest(
"""
import pytest
@pytest.fixture(params=['unused', 'unused'])
def foo(request):
return request.param
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[1, 2])
def foo(request):
return request.param
class Test:
@pytest.fixture
def foo(self, foo):
return foo * 2
def test_spam(self, foo):
assert foo in (2, 4)
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 passed*"])
def test_override_parametrized_fixture_with_new_parametrized_fixture(
self, pytester: Pytester
) -> None:
"""Overriding a parametrized fixture, while also parametrizing the new fixture and
simultaneously requesting the overwritten fixture as parameter, yields the same value
as ``request.param``.
"""
pytester.makeconftest(
"""
import pytest
@pytest.fixture(params=['ignored', 'ignored'])
def foo(request):
return request.param
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[10, 20])
def foo(foo, request):
assert request.param == foo
return foo * 2
def test_spam(foo):
assert foo in (20, 40)
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 passed*"])
def test_autouse_fixture_plugin(self, pytester: Pytester) -> None:
# A fixture from a plugin has no baseid set, which screwed up
# the autouse fixture handling.
pytester.makepyfile(
testplugin="""
import pytest
@pytest.fixture(autouse=True)
def foo(request):
request.function.foo = 7
"""
)
pytester.syspathinsert()
pytester.makepyfile(
"""
pytest_plugins = 'testplugin'
def test_foo(request):
assert request.function.foo == 7
"""
)
result = pytester.runpytest()
assert result.ret == 0
def test_funcarg_lookup_error(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def a_fixture(): pass
@pytest.fixture
def b_fixture(): pass
@pytest.fixture
def c_fixture(): pass
@pytest.fixture
def d_fixture(): pass
"""
)
pytester.makepyfile(
"""
def test_lookup_error(unknown):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*ERROR at setup of test_lookup_error*",
" def test_lookup_error(unknown):*",
"E fixture 'unknown' not found",
"> available fixtures:*a_fixture,*b_fixture,*c_fixture,*d_fixture*monkeypatch,*",
# sorted
"> use 'py*test --fixtures *' for help on them.",
"*1 error*",
]
)
result.stdout.no_fnmatch_line("*INTERNAL*")
def test_fixture_excinfo_leak(self, pytester: Pytester) -> None:
# on python2 sys.excinfo would leak into fixture executions
pytester.makepyfile(
"""
import sys
import traceback
import pytest
@pytest.fixture
def leak():
if sys.exc_info()[0]: # python3 bug :)
traceback.print_exc()
#fails
assert sys.exc_info() == (None, None, None)
def test_leak(leak):
if sys.exc_info()[0]: # python3 bug :)
traceback.print_exc()
assert sys.exc_info() == (None, None, None)
"""
)
result = pytester.runpytest()
assert result.ret == 0
class TestRequestBasic:
def test_request_attributes(self, pytester: Pytester) -> None:
item = pytester.getitem(
"""
import pytest
@pytest.fixture
def something(request): pass
def test_func(something): pass
"""
)
assert isinstance(item, Function)
req = TopRequest(item, _ispytest=True)
assert req.function == item.obj
assert req.keywords == item.keywords
assert hasattr(req.module, "test_func")
assert req.cls is None
assert req.function.__name__ == "test_func"
assert req.config == item.config
assert repr(req).find(req.function.__name__) != -1
def test_request_attributes_method(self, pytester: Pytester) -> None:
(item,) = pytester.getitems(
"""
import pytest
class TestB(object):
@pytest.fixture
def something(self, request):
return 1
def test_func(self, something):
pass
"""
)
assert isinstance(item, Function)
req = item._request
assert req.cls.__name__ == "TestB"
assert req.instance.__class__ == req.cls
def test_request_contains_funcarg_arg2fixturedefs(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol(
"""
import pytest
@pytest.fixture
def something(request):
pass
class TestClass(object):
def test_method(self, something):
pass
"""
)
(item1,) = pytester.genitems([modcol])
assert isinstance(item1, Function)
assert item1.name == "test_method"
arg2fixturedefs = TopRequest(item1, _ispytest=True)._arg2fixturedefs
assert len(arg2fixturedefs) == 1
assert arg2fixturedefs["something"][0].argname == "something"
@pytest.mark.skipif(
hasattr(sys, "pypy_version_info"),
reason="this method of test doesn't work on pypy",
)
def test_request_garbage(self, pytester: Pytester) -> None:
try:
import xdist # noqa: F401
except ImportError:
pass
else:
pytest.xfail("this test is flaky when executed with xdist")
pytester.makepyfile(
"""
import sys
import pytest
from _pytest.fixtures import RequestFixtureDef
import gc
@pytest.fixture(autouse=True)
def something(request):
original = gc.get_debug()
gc.set_debug(gc.DEBUG_SAVEALL)
gc.collect()
yield
try:
gc.collect()
leaked = [x for _ in gc.garbage if isinstance(_, RequestFixtureDef)]
assert leaked == []
finally:
gc.set_debug(original)
def test_func():
pass
"""
)
result = pytester.runpytest_subprocess()
result.stdout.fnmatch_lines(["* 1 passed in *"])
def test_getfixturevalue_recursive(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def something(request):
return 1
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def something(request):
return request.getfixturevalue("something") + 1
def test_func(something):
assert something == 2
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_getfixturevalue_teardown(self, pytester: Pytester) -> None:
"""
Issue #1895
`test_inner` requests `inner` fixture, which in turn requests `resource`
using `getfixturevalue`. `test_func` then requests `resource`.
`resource` is teardown before `inner` because the fixture mechanism won't consider
`inner` dependent on `resource` when it is used via `getfixturevalue`: `test_func`
will then cause the `resource`'s finalizer to be called first because of this.
"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='session')
def resource():
r = ['value']
yield r
r.pop()
@pytest.fixture(scope='session')
def inner(request):
resource = request.getfixturevalue('resource')
assert resource == ['value']
yield
assert resource == ['value']
def test_inner(inner):
pass
def test_func(resource):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 2 passed in *"])
def test_getfixturevalue(self, pytester: Pytester) -> None:
item = pytester.getitem(
"""
import pytest
@pytest.fixture
def something(request):
return 1
values = [2]
@pytest.fixture
def other(request):
return values.pop()
def test_func(something): pass
"""
)
assert isinstance(item, Function)
req = item._request
# Execute item's setup.
item.session._setupstate.setup(item)
with pytest.raises(pytest.FixtureLookupError):
req.getfixturevalue("notexists")
val = req.getfixturevalue("something")
assert val == 1
val = req.getfixturevalue("something")
assert val == 1
val2 = req.getfixturevalue("other")
assert val2 == 2
val2 = req.getfixturevalue("other") # see about caching
assert val2 == 2
assert item.funcargs["something"] == 1
assert len(get_public_names(item.funcargs)) == 2
assert "request" in item.funcargs
def test_request_addfinalizer(self, pytester: Pytester) -> None:
item = pytester.getitem(
"""
import pytest
teardownlist = []
@pytest.fixture
def something(request):
request.addfinalizer(lambda: teardownlist.append(1))
def test_func(something): pass
"""
)
assert isinstance(item, Function)
item.session._setupstate.setup(item)
item._request._fillfixtures()
# successively check finalization calls
parent = item.getparent(pytest.Module)
assert parent is not None
teardownlist = parent.obj.teardownlist
ss = item.session._setupstate
assert not teardownlist
ss.teardown_exact(None)
print(ss.stack)
assert teardownlist == [1]
def test_request_addfinalizer_failing_setup(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = [1]
@pytest.fixture
def myfix(request):
request.addfinalizer(values.pop)
assert 0
def test_fix(myfix):
pass
def test_finalizer_ran():
assert not values
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(failed=1, passed=1)
def test_request_addfinalizer_failing_setup_module(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
values = [1, 2]
@pytest.fixture(scope="module")
def myfix(request):
request.addfinalizer(values.pop)
request.addfinalizer(values.pop)
assert 0
def test_fix(myfix):
pass
"""
)
reprec = pytester.inline_run("-s")
mod = reprec.getcalls("pytest_runtest_setup")[0].item.module
assert not mod.values
def test_request_addfinalizer_partial_setup_failure(
self, pytester: Pytester
) -> None:
p = pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture
def something(request):
request.addfinalizer(lambda: values.append(None))
def test_func(something, missingarg):
pass
def test_second():
assert len(values) == 1
"""
)
result = pytester.runpytest(p)
result.stdout.fnmatch_lines(
["*1 error*"] # XXX the whole module collection fails
)
def test_request_subrequest_addfinalizer_exceptions(
self, pytester: Pytester
) -> None:
"""
Ensure exceptions raised during teardown by finalizers are suppressed
until all finalizers are called, then re-raised together in an
exception group (#2440)
"""
pytester.makepyfile(
"""
import pytest
values = []
def _excepts(where):
raise Exception('Error in %s fixture' % where)
@pytest.fixture
def subrequest(request):
return request
@pytest.fixture
def something(subrequest):
subrequest.addfinalizer(lambda: values.append(1))
subrequest.addfinalizer(lambda: values.append(2))
subrequest.addfinalizer(lambda: _excepts('something'))
@pytest.fixture
def excepts(subrequest):
subrequest.addfinalizer(lambda: _excepts('excepts'))
subrequest.addfinalizer(lambda: values.append(3))
def test_first(something, excepts):
pass
def test_second():
assert values == [3, 2, 1]
"""
)
result = pytester.runpytest()
result.assert_outcomes(passed=2, errors=1)
result.stdout.fnmatch_lines(
[
' | *ExceptionGroup: errors while tearing down fixture "subrequest" of <Function test_first> (2 sub-exceptions)', # noqa: E501
" +-+---------------- 1 ----------------",
" | Exception: Error in something fixture",
" +---------------- 2 ----------------",
" | Exception: Error in excepts fixture",
" +------------------------------------",
],
)
def test_request_getmodulepath(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol("def test_somefunc(): pass")
(item,) = pytester.genitems([modcol])
assert isinstance(item, Function)
req = TopRequest(item, _ispytest=True)
assert req.path == modcol.path
def test_request_fixturenames(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
from _pytest.pytester import get_public_names
@pytest.fixture()
def arg1():
pass
@pytest.fixture()
def farg(arg1):
pass
@pytest.fixture(autouse=True)
def sarg(tmp_path):
pass
def test_function(request, farg):
assert set(get_public_names(request.fixturenames)) == \
set(["sarg", "arg1", "request", "farg",
"tmp_path", "tmp_path_factory"])
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_request_fixturenames_dynamic_fixture(self, pytester: Pytester) -> None:
"""Regression test for #3057"""
pytester.copy_example("fixtures/test_getfixturevalue_dynamic.py")
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"])
def test_setupdecorator_and_xunit(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope='module', autouse=True)
def setup_module():
values.append("module")
@pytest.fixture(autouse=True)
def setup_function():
values.append("function")
def test_func():
pass
class TestClass(object):
@pytest.fixture(scope="class", autouse=True)
def setup_class(self):
values.append("class")
@pytest.fixture(autouse=True)
def setup_method(self):
values.append("method")
def test_method(self):
pass
def test_all():
assert values == ["module", "function", "class",
"function", "method", "function"]
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=3)
def test_fixtures_sub_subdir_normalize_sep(self, pytester: Pytester) -> None:
# this tests that normalization of nodeids takes place
b = pytester.path.joinpath("tests", "unit")
b.mkdir(parents=True)
b.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def arg1():
pass
"""
),
encoding="utf-8",
)
p = b.joinpath("test_module.py")
p.write_text("def test_func(arg1): pass", encoding="utf-8")
result = pytester.runpytest(p, "--fixtures")
assert result.ret == 0
result.stdout.fnmatch_lines(
"""
*fixtures defined*conftest*
*arg1*
"""
)
def test_show_fixtures_color_yes(self, pytester: Pytester) -> None:
pytester.makepyfile("def test_this(): assert 1")
result = pytester.runpytest("--color=yes", "--fixtures")
assert "\x1b[32mtmp_path" in result.stdout.str()
def test_newstyle_with_request(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture()
def arg(request):
pass
def test_1(arg):
pass
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_setupcontext_no_param(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[1,2])
def arg(request):
return request.param
@pytest.fixture(autouse=True)
def mysetup(request, arg):
assert not hasattr(request, "param")
def test_1(arg):
assert arg in (1,2)
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
class TestRequestSessionScoped:
@pytest.fixture(scope="session")
def session_request(self, request):
return request
@pytest.mark.parametrize("name", ["path", "module"])
def test_session_scoped_unavailable_attributes(self, session_request, name):
with pytest.raises(
AttributeError,
match=f"{name} not available in session-scoped context",
):
getattr(session_request, name)
class TestRequestMarking:
def test_applymarker(self, pytester: Pytester) -> None:
item1, _item2 = pytester.getitems(
"""
import pytest
@pytest.fixture
def something(request):
pass
class TestClass(object):
def test_func1(self, something):
pass
def test_func2(self, something):
pass
"""
)
assert isinstance(item1, Function)
req1 = TopRequest(item1, _ispytest=True)
assert "xfail" not in item1.keywords
req1.applymarker(pytest.mark.xfail)
assert "xfail" in item1.keywords
assert "skipif" not in item1.keywords
req1.applymarker(pytest.mark.skipif)
assert "skipif" in item1.keywords
with pytest.raises(ValueError):
req1.applymarker(42) # type: ignore[arg-type]
def test_accesskeywords(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture()
def keywords(request):
return request.keywords
@pytest.mark.XYZ
def test_function(keywords):
assert keywords["XYZ"]
assert "abc" not in keywords
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_accessmarker_dynamic(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture()
def keywords(request):
return request.keywords
@pytest.fixture(scope="class", autouse=True)
def marking(request):
request.applymarker(pytest.mark.XYZ("hello"))
"""
)
pytester.makepyfile(
"""
import pytest
def test_fun1(keywords):
assert keywords["XYZ"] is not None
assert "abc" not in keywords
def test_fun2(keywords):
assert keywords["XYZ"] is not None
assert "abc" not in keywords
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
class TestFixtureUsages:
def test_noargfixturedec(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def arg1():
return 1
def test_func(arg1):
assert arg1 == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_receives_funcargs(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture()
def arg1():
return 1
@pytest.fixture()
def arg2(arg1):
return arg1 + 1
def test_add(arg2):
assert arg2 == 2
def test_all(arg1, arg2):
assert arg1 == 1
assert arg2 == 2
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_receives_funcargs_scope_mismatch(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="function")
def arg1():
return 1
@pytest.fixture(scope="module")
def arg2(arg1):
return arg1 + 1
def test_add(arg2):
assert arg2 == 2
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*ScopeMismatch*Requesting fixture stack*",
"test_receives_funcargs_scope_mismatch.py:6: def arg2(arg1)",
"Requested fixture:",
"test_receives_funcargs_scope_mismatch.py:2: def arg1()",
"*1 error*",
]
)
def test_receives_funcargs_scope_mismatch_issue660(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="function")
def arg1():
return 1
@pytest.fixture(scope="module")
def arg2(arg1):
return arg1 + 1
def test_add(arg1, arg2):
assert arg2 == 2
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*ScopeMismatch*Requesting fixture stack*",
"* def arg2(arg1)",
"Requested fixture:",
"* def arg1()",
"*1 error*",
],
)
def test_invalid_scope(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="functions")
def badscope():
pass
def test_nothing(badscope):
pass
"""
)
result = pytester.runpytest_inprocess()
result.stdout.fnmatch_lines(
"*Fixture 'badscope' from test_invalid_scope.py got an unexpected scope value 'functions'"
)
@pytest.mark.parametrize("scope", ["function", "session"])
def test_parameters_without_eq_semantics(self, scope, pytester: Pytester) -> None:
pytester.makepyfile(
f"""
class NoEq1: # fails on `a == b` statement
def __eq__(self, _):
raise RuntimeError
class NoEq2: # fails on `if a == b:` statement
def __eq__(self, _):
class NoBool:
def __bool__(self):
raise RuntimeError
return NoBool()
import pytest
@pytest.fixture(params=[NoEq1(), NoEq2()], scope={scope!r})
def no_eq(request):
return request.param
def test1(no_eq):
pass
def test2(no_eq):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*4 passed*"])
def test_funcarg_parametrized_and_used_twice(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(params=[1,2])
def arg1(request):
values.append(1)
return request.param
@pytest.fixture()
def arg2(arg1):
return arg1 + 1
def test_add(arg1, arg2):
assert arg2 == arg1 + 1
assert len(values) == arg1
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 passed*"])
def test_factory_uses_unknown_funcarg_as_dependency_error(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture()
def fail(missing):
return
@pytest.fixture()
def call_fail(fail):
return
def test_missing(call_fail):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
"""
*pytest.fixture()*
*def call_fail(fail)*
*pytest.fixture()*
*def fail*
*fixture*'missing'*not found*
"""
)
def test_factory_setup_as_classes_fails(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
class arg1(object):
def __init__(self, request):
self.x = 1
arg1 = pytest.fixture()(arg1)
"""
)
reprec = pytester.inline_run()
values = reprec.getfailedcollections()
assert len(values) == 1
def test_usefixtures_marker(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="class")
def myfix(request):
request.cls.hello = "world"
values.append(1)
class TestClass(object):
def test_one(self):
assert self.hello == "world"
assert len(values) == 1
def test_two(self):
assert self.hello == "world"
assert len(values) == 1
pytest.mark.usefixtures("myfix")(TestClass)
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_empty_usefixtures_marker(self, pytester: Pytester) -> None:
"""Empty usefixtures() marker issues a warning (#12439)."""
pytester.makepyfile(
"""
import pytest
@pytest.mark.usefixtures()
def test_one():
assert 1 == 1
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
"*PytestWarning: usefixtures() in test_empty_usefixtures_marker.py::test_one"
" without arguments has no effect"
)
def test_usefixtures_ini(self, pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
usefixtures = myfix
"""
)
pytester.makeconftest(
"""
import pytest
@pytest.fixture(scope="class")
def myfix(request):
request.cls.hello = "world"
"""
)
pytester.makepyfile(
"""
class TestClass(object):
def test_one(self):
assert self.hello == "world"
def test_two(self):
assert self.hello == "world"
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_usefixtures_seen_in_showmarkers(self, pytester: Pytester) -> None:
result = pytester.runpytest("--markers")
result.stdout.fnmatch_lines(
"""
*usefixtures(fixturename1*mark tests*fixtures*
"""
)
def test_request_instance_issue203(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
class TestClass(object):
@pytest.fixture
def setup1(self, request):
assert self == request.instance
self.arg1 = 1
def test_hello(self, setup1):
assert self.arg1 == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_fixture_parametrized_with_iterator(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
def f():
yield 1
yield 2
dec = pytest.fixture(scope="module", params=f())
@dec
def arg(request):
return request.param
@dec
def arg2(request):
return request.param
def test_1(arg):
values.append(arg)
def test_2(arg2):
values.append(arg2*10)
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=4)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
assert values == [1, 2, 10, 20]
def test_setup_functions_as_fixtures(self, pytester: Pytester) -> None:
"""Ensure setup_* methods obey fixture scope rules (#517, #3094)."""
pytester.makepyfile(
"""
import pytest
DB_INITIALIZED = None
@pytest.fixture(scope="session", autouse=True)
def db():
global DB_INITIALIZED
DB_INITIALIZED = True
yield
DB_INITIALIZED = False
def setup_module():
assert DB_INITIALIZED
def teardown_module():
assert DB_INITIALIZED
class TestClass(object):
def setup_method(self, method):
assert DB_INITIALIZED
def teardown_method(self, method):
assert DB_INITIALIZED
def test_printer_1(self):
pass
def test_printer_2(self):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 2 passed in *"])
def test_parameterized_fixture_caching(self, pytester: Pytester) -> None:
"""Regression test for #12600."""
pytester.makepyfile(
"""
import pytest
from itertools import count
CACHE_MISSES = count(0)
def pytest_generate_tests(metafunc):
if "my_fixture" in metafunc.fixturenames:
# Use unique objects for parametrization (as opposed to small strings
# and small integers which are singletons).
metafunc.parametrize("my_fixture", [[1], [2]], indirect=True)
@pytest.fixture(scope='session')
def my_fixture(request):
next(CACHE_MISSES)
def test1(my_fixture):
pass
def test2(my_fixture):
pass
def teardown_module():
assert next(CACHE_MISSES) == 2
"""
)
result = pytester.runpytest()
result.stdout.no_fnmatch_line("* ERROR at teardown *")
def test_unwrapping_pytest_fixture(self, pytester: Pytester) -> None:
"""Ensure the unwrap method on `FixtureFunctionDefinition` correctly wraps and unwraps methods and functions"""
pytester.makepyfile(
"""
import pytest
import inspect
class FixtureFunctionDefTestClass:
def __init__(self) -> None:
self.i = 10
@pytest.fixture
def fixture_function_def_test_method(self):
return self.i
@pytest.fixture
def fixture_function_def_test_func():
return 9
def test_get_wrapped_func_returns_method():
obj = FixtureFunctionDefTestClass()
wrapped_function_result = (
obj.fixture_function_def_test_method._get_wrapped_function()
)
assert inspect.ismethod(wrapped_function_result)
assert wrapped_function_result() == 10
def test_get_wrapped_func_returns_function():
assert fixture_function_def_test_func._get_wrapped_function()() == 9
"""
)
result = pytester.runpytest()
result.assert_outcomes(passed=2)
def test_fixture_wrapped_looks_liked_wrapped_function(
self, pytester: Pytester
) -> None:
"""Ensure that `FixtureFunctionDefinition` behaves like the function it wrapped."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def fixture_function_def_test_func():
return 9
fixture_function_def_test_func.__doc__ = "documentation"
def test_fixture_has_same_doc():
assert fixture_function_def_test_func.__doc__ == "documentation"
"""
)
result = pytester.runpytest()
result.assert_outcomes(passed=1)
class TestFixtureManagerParseFactories:
@pytest.fixture
def pytester(self, pytester: Pytester) -> Pytester:
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def hello(request):
return "conftest"
@pytest.fixture
def fm(request):
return request._fixturemanager
@pytest.fixture
def item(request):
return request._pyfuncitem
"""
)
return pytester
def test_parsefactories_evil_objects_issue214(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
class A(object):
def __call__(self):
pass
def __getattr__(self, name):
raise RuntimeError()
a = A()
def test_hello():
pass
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1, failed=0)
def test_parsefactories_conftest(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
def test_hello(item, fm):
for name in ("fm", "hello", "item"):
faclist = fm.getfixturedefs(name, item)
assert len(faclist) == 1
fac = faclist[0]
assert fac.func.__name__ == name
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=1)
def test_parsefactories_conftest_and_module_and_class(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""\
import pytest
@pytest.fixture
def hello(request):
return "module"
class TestClass(object):
@pytest.fixture
def hello(self, request):
return "class"
def test_hello(self, item, fm):
faclist = fm.getfixturedefs("hello", item)
print(faclist)
assert len(faclist) == 3
assert faclist[0].func(item._request) == "conftest"
assert faclist[1].func(item._request) == "module"
assert faclist[2].func(item._request) == "class"
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=1)
def test_parsefactories_relative_node_ids(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
# example mostly taken from:
# https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html
runner = pytester.mkdir("runner")
package = pytester.mkdir("package")
package.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def one():
return 1
"""
),
encoding="utf-8",
)
package.joinpath("test_x.py").write_text(
textwrap.dedent(
"""\
def test_x(one):
assert one == 1
"""
),
encoding="utf-8",
)
sub = package.joinpath("sub")
sub.mkdir()
sub.joinpath("__init__.py").touch()
sub.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def one():
return 2
"""
),
encoding="utf-8",
)
sub.joinpath("test_y.py").write_text(
textwrap.dedent(
"""\
def test_x(one):
assert one == 2
"""
),
encoding="utf-8",
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
with monkeypatch.context() as mp:
mp.chdir(runner)
reprec = pytester.inline_run("..")
reprec.assertoutcome(passed=2)
def test_package_xunit_fixture(self, pytester: Pytester) -> None:
pytester.makepyfile(
__init__="""\
values = []
"""
)
package = pytester.mkdir("package")
package.joinpath("__init__.py").write_text(
textwrap.dedent(
"""\
from .. import values
def setup_module():
values.append("package")
def teardown_module():
values[:] = []
"""
),
encoding="utf-8",
)
package.joinpath("test_x.py").write_text(
textwrap.dedent(
"""\
from .. import values
def test_x():
assert values == ["package"]
"""
),
encoding="utf-8",
)
package = pytester.mkdir("package2")
package.joinpath("__init__.py").write_text(
textwrap.dedent(
"""\
from .. import values
def setup_module():
values.append("package2")
def teardown_module():
values[:] = []
"""
),
encoding="utf-8",
)
package.joinpath("test_x.py").write_text(
textwrap.dedent(
"""\
from .. import values
def test_x():
assert values == ["package2"]
"""
),
encoding="utf-8",
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_package_fixture_complex(self, pytester: Pytester) -> None:
pytester.makepyfile(
__init__="""\
values = []
"""
)
pytester.syspathinsert(pytester.path.name)
package = pytester.mkdir("package")
package.joinpath("__init__.py").write_text("", encoding="utf-8")
package.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
from .. import values
@pytest.fixture(scope="package")
def one():
values.append("package")
yield values
values.pop()
@pytest.fixture(scope="package", autouse=True)
def two():
values.append("package-auto")
yield values
values.pop()
"""
),
encoding="utf-8",
)
package.joinpath("test_x.py").write_text(
textwrap.dedent(
"""\
from .. import values
def test_package_autouse():
assert values == ["package-auto"]
def test_package(one):
assert values == ["package-auto", "package"]
"""
),
encoding="utf-8",
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_collect_custom_items(self, pytester: Pytester) -> None:
pytester.copy_example("fixtures/custom_item")
result = pytester.runpytest("foo")
result.stdout.fnmatch_lines(["*passed*"])
class TestAutouseDiscovery:
@pytest.fixture
def pytester(self, pytester: Pytester) -> Pytester:
pytester.makeconftest(
"""
import pytest
@pytest.fixture(autouse=True)
def perfunction(request, tmp_path):
pass
@pytest.fixture()
def arg1(tmp_path):
pass
@pytest.fixture(autouse=True)
def perfunction2(arg1):
pass
@pytest.fixture
def fm(request):
return request._fixturemanager
@pytest.fixture
def item(request):
return request._pyfuncitem
"""
)
return pytester
def test_parsefactories_conftest(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
from _pytest.pytester import get_public_names
def test_check_setup(item, fm):
autousenames = list(fm._getautousenames(item))
assert len(get_public_names(autousenames)) == 2
assert "perfunction2" in autousenames
assert "perfunction" in autousenames
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=1)
def test_two_classes_separated_autouse(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
class TestA(object):
values = []
@pytest.fixture(autouse=True)
def setup1(self):
self.values.append(1)
def test_setup1(self):
assert self.values == [1]
class TestB(object):
values = []
@pytest.fixture(autouse=True)
def setup2(self):
self.values.append(1)
def test_setup2(self):
assert self.values == [1]
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_setup_at_classlevel(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
class TestClass(object):
@pytest.fixture(autouse=True)
def permethod(self, request):
request.instance.funcname = request.function.__name__
def test_method1(self):
assert self.funcname == "test_method1"
def test_method2(self):
assert self.funcname == "test_method2"
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=2)
@pytest.mark.xfail(reason="'enabled' feature not implemented")
def test_setup_enabled_functionnode(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def enabled(parentnode, markers):
return "needsdb" in markers
@pytest.fixture(params=[1,2])
def db(request):
return request.param
@pytest.fixture(enabled=enabled, autouse=True)
def createdb(db):
pass
def test_func1(request):
assert "db" not in request.fixturenames
@pytest.mark.needsdb
def test_func2(request):
assert "db" in request.fixturenames
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=2)
def test_callables_nocode(self, pytester: Pytester) -> None:
"""An imported mock.call would break setup/factory discovery due to
it being callable and __code__ not being a code object."""
pytester.makepyfile(
"""
class _call(tuple):
def __call__(self, *k, **kw):
pass
def __getattr__(self, k):
return self
call = _call()
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(failed=0, passed=0)
def test_autouse_in_conftests(self, pytester: Pytester) -> None:
a = pytester.mkdir("a")
b = pytester.mkdir("a1")
conftest = pytester.makeconftest(
"""
import pytest
@pytest.fixture(autouse=True)
def hello():
xxx
"""
)
conftest.rename(a.joinpath(conftest.name))
a.joinpath("test_something.py").write_text(
"def test_func(): pass", encoding="utf-8"
)
b.joinpath("test_otherthing.py").write_text(
"def test_func(): pass", encoding="utf-8"
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
"""
*1 passed*1 error*
"""
)
def test_autouse_in_module_and_two_classes(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(autouse=True)
def append1():
values.append("module")
def test_x():
assert values == ["module"]
class TestA(object):
@pytest.fixture(autouse=True)
def append2(self):
values.append("A")
def test_hello(self):
assert values == ["module", "module", "A"], values
class TestA2(object):
def test_world(self):
assert values == ["module", "module", "A", "module"], values
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=3)
class TestAutouseManagement:
def test_autouse_conftest_mid_directory(self, pytester: Pytester) -> None:
pkgdir = pytester.mkpydir("xyz123")
pkgdir.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture(autouse=True)
def app():
import sys
sys._myapp = "hello"
"""
),
encoding="utf-8",
)
sub = pkgdir.joinpath("tests")
sub.mkdir()
t = sub.joinpath("test_app.py")
t.touch()
t.write_text(
textwrap.dedent(
"""\
import sys
def test_app():
assert sys._myapp == "hello"
"""
),
encoding="utf-8",
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=1)
def test_funcarg_and_setup(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="module")
def arg():
values.append(1)
return 0
@pytest.fixture(scope="module", autouse=True)
def something(arg):
values.append(2)
def test_hello(arg):
assert len(values) == 2
assert values == [1,2]
assert arg == 0
def test_hello2(arg):
assert len(values) == 2
assert values == [1,2]
assert arg == 0
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_uses_parametrized_resource(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(params=[1,2])
def arg(request):
return request.param
@pytest.fixture(autouse=True)
def something(arg):
values.append(arg)
def test_hello():
if len(values) == 1:
assert values == [1]
elif len(values) == 2:
assert values == [1, 2]
else:
0/0
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=2)
def test_session_parametrized_function(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="session", params=[1,2])
def arg(request):
return request.param
@pytest.fixture(scope="function", autouse=True)
def append(request, arg):
if request.function.__name__ == "test_some":
values.append(arg)
def test_some():
pass
def test_result(arg):
assert len(values) == arg
assert values[:arg] == [1,2][:arg]
"""
)
reprec = pytester.inline_run("-v", "-s")
reprec.assertoutcome(passed=4)
def test_class_function_parametrization_finalization(
self, pytester: Pytester
) -> None:
p = pytester.makeconftest(
"""
import pytest
import pprint
values = []
@pytest.fixture(scope="function", params=[1,2])
def farg(request):
return request.param
@pytest.fixture(scope="class", params=list("ab"))
def carg(request):
return request.param
@pytest.fixture(scope="function", autouse=True)
def append(request, farg, carg):
def fin():
values.append("fin_%s%s" % (carg, farg))
request.addfinalizer(fin)
"""
)
pytester.makepyfile(
"""
import pytest
class TestClass(object):
def test_1(self):
pass
class TestClass2(object):
def test_2(self):
pass
"""
)
reprec = pytester.inline_run("-v", "-s", "--confcutdir", pytester.path)
reprec.assertoutcome(passed=8)
config = reprec.getcalls("pytest_unconfigure")[0].config
values = config.pluginmanager._getconftestmodules(p)[0].values
assert values == ["fin_a1", "fin_a2", "fin_b1", "fin_b2"] * 2
def test_scope_ordering(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="function", autouse=True)
def fappend2():
values.append(2)
@pytest.fixture(scope="class", autouse=True)
def classappend3():
values.append(3)
@pytest.fixture(scope="module", autouse=True)
def mappend():
values.append(1)
class TestHallo(object):
def test_method(self):
assert values == [1,3,2]
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_parametrization_setup_teardown_ordering(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
def pytest_generate_tests(metafunc):
if metafunc.cls is None:
assert metafunc.function is test_finish
if metafunc.cls is not None:
metafunc.parametrize("item", [1,2], scope="class")
class TestClass(object):
@pytest.fixture(scope="class", autouse=True)
def addteardown(self, item, request):
values.append("setup-%d" % item)
request.addfinalizer(lambda: values.append("teardown-%d" % item))
def test_step1(self, item):
values.append("step1-%d" % item)
def test_step2(self, item):
values.append("step2-%d" % item)
def test_finish():
print(values)
assert values == ["setup-1", "step1-1", "step2-1", "teardown-1",
"setup-2", "step1-2", "step2-2", "teardown-2",]
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=5)
def test_ordering_autouse_before_explicit(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(autouse=True)
def fix1():
values.append(1)
@pytest.fixture()
def arg1():
values.append(2)
def test_hello(arg1):
assert values == [1,2]
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
@pytest.mark.parametrize("param1", ["", "params=[1]"], ids=["p00", "p01"])
@pytest.mark.parametrize("param2", ["", "params=[1]"], ids=["p10", "p11"])
def test_ordering_dependencies_torndown_first(
self, pytester: Pytester, param1, param2
) -> None:
"""#226"""
pytester.makepyfile(
f"""
import pytest
values = []
@pytest.fixture({param1})
def arg1(request):
request.addfinalizer(lambda: values.append("fin1"))
values.append("new1")
@pytest.fixture({param2})
def arg2(request, arg1):
request.addfinalizer(lambda: values.append("fin2"))
values.append("new2")
def test_arg(arg2):
pass
def test_check():
assert values == ["new1", "new2", "fin2", "fin1"]
"""
)
reprec = pytester.inline_run("-s")
reprec.assertoutcome(passed=2)
def test_reordering_catastrophic_performance(self, pytester: Pytester) -> None:
"""Check that a certain high-scope parametrization pattern doesn't cause
a catasrophic slowdown.
Regression test for #12355.
"""
pytester.makepyfile("""
import pytest
params = tuple("abcdefghijklmnopqrstuvwxyz")
@pytest.mark.parametrize(params, [range(len(params))] * 3, scope="module")
def test_parametrize(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z):
pass
""")
result = pytester.runpytest()
result.assert_outcomes(passed=3)
class TestFixtureMarker:
def test_parametrize(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=["a", "b", "c"])
def arg(request):
return request.param
values = []
def test_param(arg):
values.append(arg)
def test_result():
assert values == list("abc")
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=4)
def test_multiple_parametrization_issue_736(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[1,2,3])
def foo(request):
return request.param
@pytest.mark.parametrize('foobar', [4,5,6])
def test_issue(foo, foobar):
assert foo in [1,2,3]
assert foobar in [4,5,6]
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=9)
@pytest.mark.parametrize(
"param_args",
["'fixt, val'", "'fixt,val'", "['fixt', 'val']", "('fixt', 'val')"],
)
def test_override_parametrized_fixture_issue_979(
self, pytester: Pytester, param_args
) -> None:
"""Make sure a parametrized argument can override a parametrized fixture.
This was a regression introduced in the fix for #736.
"""
pytester.makepyfile(
f"""
import pytest
@pytest.fixture(params=[1, 2])
def fixt(request):
return request.param
@pytest.mark.parametrize({param_args}, [(3, 'x'), (4, 'x')])
def test_foo(fixt, val):
pass
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_scope_session(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="module")
def arg():
values.append(1)
return 1
def test_1(arg):
assert arg == 1
def test_2(arg):
assert arg == 1
assert len(values) == 1
class TestClass(object):
def test3(self, arg):
assert arg == 1
assert len(values) == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=3)
def test_scope_session_exc(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="session")
def fix():
values.append(1)
pytest.skip('skipping')
def test_1(fix):
pass
def test_2(fix):
pass
def test_last():
assert values == [1]
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(skipped=2, passed=1)
def test_scope_session_exc_two_fix(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
m = []
@pytest.fixture(scope="session")
def a():
values.append(1)
pytest.skip('skipping')
@pytest.fixture(scope="session")
def b(a):
m.append(1)
def test_1(b):
pass
def test_2(b):
pass
def test_last():
assert values == [1]
assert m == []
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(skipped=2, passed=1)
def test_scope_exc(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_foo="""
def test_foo(fix):
pass
""",
test_bar="""
def test_bar(fix):
pass
""",
conftest="""
import pytest
reqs = []
@pytest.fixture(scope="session")
def fix(request):
reqs.append(1)
pytest.skip()
@pytest.fixture
def req_list():
return reqs
""",
test_real="""
def test_last(req_list):
assert req_list == [1]
""",
)
reprec = pytester.inline_run()
reprec.assertoutcome(skipped=2, passed=1)
def test_scope_module_uses_session(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="module")
def arg():
values.append(1)
return 1
def test_1(arg):
assert arg == 1
def test_2(arg):
assert arg == 1
assert len(values) == 1
class TestClass(object):
def test3(self, arg):
assert arg == 1
assert len(values) == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=3)
def test_scope_module_and_finalizer(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
finalized_list = []
created_list = []
@pytest.fixture(scope="module")
def arg(request):
created_list.append(1)
assert request.scope == "module"
request.addfinalizer(lambda: finalized_list.append(1))
@pytest.fixture
def created(request):
return len(created_list)
@pytest.fixture
def finalized(request):
return len(finalized_list)
"""
)
pytester.makepyfile(
test_mod1="""
def test_1(arg, created, finalized):
assert created == 1
assert finalized == 0
def test_2(arg, created, finalized):
assert created == 1
assert finalized == 0""",
test_mod2="""
def test_3(arg, created, finalized):
assert created == 2
assert finalized == 1""",
test_mode3="""
def test_4(arg, created, finalized):
assert created == 3
assert finalized == 2
""",
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=4)
def test_scope_mismatch_various(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
finalized = []
created = []
@pytest.fixture(scope="function")
def arg(request):
pass
"""
)
pytester.makepyfile(
test_mod1="""
import pytest
@pytest.fixture(scope="session")
def arg(request):
request.getfixturevalue("arg")
def test_1(arg):
pass
"""
)
result = pytester.runpytest()
assert result.ret != 0
result.stdout.fnmatch_lines(
["*ScopeMismatch*You tried*function*session*request*"]
)
def test_scope_mismatch_already_computed_dynamic(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_it="""
import pytest
@pytest.fixture(scope="function")
def fixfunc(): pass
@pytest.fixture(scope="module")
def fixmod(fixfunc): pass
def test_it(request, fixfunc):
request.getfixturevalue("fixmod")
""",
)
result = pytester.runpytest()
assert result.ret == ExitCode.TESTS_FAILED
result.stdout.fnmatch_lines(
[
"*ScopeMismatch*Requesting fixture stack*",
"test_it.py:6: def fixmod(fixfunc)",
"Requested fixture:",
"test_it.py:3: def fixfunc()",
]
)
def test_dynamic_scope(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
def pytest_addoption(parser):
parser.addoption("--extend-scope", action="store_true", default=False)
def dynamic_scope(fixture_name, config):
if config.getoption("--extend-scope"):
return "session"
return "function"
@pytest.fixture(scope=dynamic_scope)
def dynamic_fixture(calls=[]):
calls.append("call")
return len(calls)
"""
)
pytester.makepyfile(
"""
def test_first(dynamic_fixture):
assert dynamic_fixture == 1
def test_second(dynamic_fixture):
assert dynamic_fixture == 2
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
reprec = pytester.inline_run("--extend-scope")
reprec.assertoutcome(passed=1, failed=1)
def test_dynamic_scope_bad_return(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def dynamic_scope(**_):
return "wrong-scope"
@pytest.fixture(scope=dynamic_scope)
def fixture():
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
"Fixture 'fixture' from test_dynamic_scope_bad_return.py "
"got an unexpected scope value 'wrong-scope'"
)
def test_register_only_with_mark(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture()
def arg():
return 1
"""
)
pytester.makepyfile(
test_mod1="""
import pytest
@pytest.fixture()
def arg(arg):
return arg + 1
def test_1(arg):
assert arg == 2
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_parametrize_and_scope(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module", params=["a", "b", "c"])
def arg(request):
return request.param
values = []
def test_param(arg):
values.append(arg)
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=3)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
assert len(values) == 3
assert "a" in values
assert "b" in values
assert "c" in values
def test_scope_mismatch(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture(scope="function")
def arg(request):
pass
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="session")
def arg(arg):
pass
def test_mismatch(arg):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*ScopeMismatch*", "*1 error*"])
def test_parametrize_separated_order(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module", params=[1, 2])
def arg(request):
return request.param
values = []
def test_1(arg):
values.append(arg)
def test_2(arg):
values.append(arg)
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=4)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
assert values == [1, 1, 2, 2]
def test_module_parametrized_ordering(self, pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
console_output_style=classic
"""
)
pytester.makeconftest(
"""
import pytest
@pytest.fixture(scope="session", params="s1 s2".split())
def sarg():
pass
@pytest.fixture(scope="module", params="m1 m2".split())
def marg():
pass
"""
)
pytester.makepyfile(
test_mod1="""
def test_func(sarg):
pass
def test_func1(marg):
pass
""",
test_mod2="""
def test_func2(sarg):
pass
def test_func3(sarg, marg):
pass
def test_func3b(sarg, marg):
pass
def test_func4(marg):
pass
""",
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
"""
test_mod1.py::test_func[s1] PASSED
test_mod2.py::test_func2[s1] PASSED
test_mod2.py::test_func3[s1-m1] PASSED
test_mod2.py::test_func3b[s1-m1] PASSED
test_mod2.py::test_func3[s1-m2] PASSED
test_mod2.py::test_func3b[s1-m2] PASSED
test_mod1.py::test_func[s2] PASSED
test_mod2.py::test_func2[s2] PASSED
test_mod2.py::test_func3[s2-m1] PASSED
test_mod2.py::test_func3b[s2-m1] PASSED
test_mod2.py::test_func4[m1] PASSED
test_mod2.py::test_func3[s2-m2] PASSED
test_mod2.py::test_func3b[s2-m2] PASSED
test_mod2.py::test_func4[m2] PASSED
test_mod1.py::test_func1[m1] PASSED
test_mod1.py::test_func1[m2] PASSED
"""
)
def test_dynamic_parametrized_ordering(self, pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
console_output_style=classic
"""
)
pytester.makeconftest(
"""
import pytest
def pytest_configure(config):
class DynamicFixturePlugin(object):
@pytest.fixture(scope='session', params=['flavor1', 'flavor2'])
def flavor(self, request):
return request.param
config.pluginmanager.register(DynamicFixturePlugin(), 'flavor-fixture')
@pytest.fixture(scope='session', params=['vxlan', 'vlan'])
def encap(request):
return request.param
@pytest.fixture(scope='session', autouse='True')
def reprovision(request, flavor, encap):
pass
"""
)
pytester.makepyfile(
"""
def test(reprovision):
pass
def test2(reprovision):
pass
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
"""
test_dynamic_parametrized_ordering.py::test[flavor1-vxlan] PASSED
test_dynamic_parametrized_ordering.py::test2[flavor1-vxlan] PASSED
test_dynamic_parametrized_ordering.py::test[flavor1-vlan] PASSED
test_dynamic_parametrized_ordering.py::test2[flavor1-vlan] PASSED
test_dynamic_parametrized_ordering.py::test[flavor2-vlan] PASSED
test_dynamic_parametrized_ordering.py::test2[flavor2-vlan] PASSED
test_dynamic_parametrized_ordering.py::test[flavor2-vxlan] PASSED
test_dynamic_parametrized_ordering.py::test2[flavor2-vxlan] PASSED
"""
)
def test_class_ordering(self, pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
console_output_style=classic
"""
)
pytester.makeconftest(
"""
import pytest
values = []
@pytest.fixture(scope="function", params=[1,2])
def farg(request):
return request.param
@pytest.fixture(scope="class", params=list("ab"))
def carg(request):
return request.param
@pytest.fixture(scope="function", autouse=True)
def append(request, farg, carg):
def fin():
values.append("fin_%s%s" % (carg, farg))
request.addfinalizer(fin)
"""
)
pytester.makepyfile(
"""
import pytest
class TestClass2(object):
def test_1(self):
pass
def test_2(self):
pass
class TestClass(object):
def test_3(self):
pass
"""
)
result = pytester.runpytest("-vs")
result.stdout.re_match_lines(
r"""
test_class_ordering.py::TestClass2::test_1\[a-1\] PASSED
test_class_ordering.py::TestClass2::test_1\[a-2\] PASSED
test_class_ordering.py::TestClass2::test_2\[a-1\] PASSED
test_class_ordering.py::TestClass2::test_2\[a-2\] PASSED
test_class_ordering.py::TestClass2::test_1\[b-1\] PASSED
test_class_ordering.py::TestClass2::test_1\[b-2\] PASSED
test_class_ordering.py::TestClass2::test_2\[b-1\] PASSED
test_class_ordering.py::TestClass2::test_2\[b-2\] PASSED
test_class_ordering.py::TestClass::test_3\[a-1\] PASSED
test_class_ordering.py::TestClass::test_3\[a-2\] PASSED
test_class_ordering.py::TestClass::test_3\[b-1\] PASSED
test_class_ordering.py::TestClass::test_3\[b-2\] PASSED
"""
)
def test_parametrize_separated_order_higher_scope_first(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="function", params=[1, 2])
def arg(request):
param = request.param
request.addfinalizer(lambda: values.append("fin:%s" % param))
values.append("create:%s" % param)
return request.param
@pytest.fixture(scope="module", params=["mod1", "mod2"])
def modarg(request):
param = request.param
request.addfinalizer(lambda: values.append("fin:%s" % param))
values.append("create:%s" % param)
return request.param
values = []
def test_1(arg):
values.append("test1")
def test_2(modarg):
values.append("test2")
def test_3(arg, modarg):
values.append("test3")
def test_4(modarg, arg):
values.append("test4")
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=12)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
expected = [
"create:1",
"test1",
"fin:1",
"create:2",
"test1",
"fin:2",
"create:mod1",
"test2",
"create:1",
"test3",
"fin:1",
"create:2",
"test3",
"fin:2",
"create:1",
"test4",
"fin:1",
"create:2",
"test4",
"fin:2",
"fin:mod1",
"create:mod2",
"test2",
"create:1",
"test3",
"fin:1",
"create:2",
"test3",
"fin:2",
"create:1",
"test4",
"fin:1",
"create:2",
"test4",
"fin:2",
"fin:mod2",
]
import pprint
pprint.pprint(list(zip_longest(values, expected)))
assert values == expected
def test_parametrized_fixture_teardown_order(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[1,2], scope="class")
def param1(request):
return request.param
values = []
class TestClass(object):
@classmethod
@pytest.fixture(scope="class", autouse=True)
def setup1(self, request, param1):
values.append(1)
request.addfinalizer(self.teardown1)
@classmethod
def teardown1(self):
assert values.pop() == 1
@pytest.fixture(scope="class", autouse=True)
def setup2(self, request, param1):
values.append(2)
request.addfinalizer(self.teardown2)
@classmethod
def teardown2(self):
assert values.pop() == 2
def test(self):
pass
def test_finish():
assert not values
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
"""
*3 passed*
"""
)
assert result.ret == 0
def test_fixture_finalizer(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
import sys
@pytest.fixture
def browser(request):
def finalize():
sys.stdout.write_text('Finalized', encoding='utf-8')
request.addfinalizer(finalize)
return {}
"""
)
b = pytester.mkdir("subdir")
b.joinpath("test_overridden_fixture_finalizer.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture
def browser(browser):
browser['visited'] = True
return browser
def test_browser(browser):
assert browser['visited'] is True
"""
),
encoding="utf-8",
)
reprec = pytester.runpytest("-s")
for test in ["test_browser"]:
reprec.stdout.fnmatch_lines(["*Finalized*"])
def test_class_scope_with_normal_tests(self, pytester: Pytester) -> None:
testpath = pytester.makepyfile(
"""
import pytest
class Box(object):
value = 0
@pytest.fixture(scope='class')
def a(request):
Box.value += 1
return Box.value
def test_a(a):
assert a == 1
class Test1(object):
def test_b(self, a):
assert a == 2
class Test2(object):
def test_c(self, a):
assert a == 3"""
)
reprec = pytester.inline_run(testpath)
for test in ["test_a", "test_b", "test_c"]:
assert reprec.matchreport(test).passed
def test_request_is_clean(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(params=[1, 2])
def fix(request):
request.addfinalizer(lambda: values.append(request.param))
def test_fix(fix):
pass
"""
)
reprec = pytester.inline_run("-s")
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
assert values == [1, 2]
def test_parametrize_separated_lifecycle(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(scope="module", params=[1, 2])
def arg(request):
x = request.param
request.addfinalizer(lambda: values.append("fin%s" % x))
return request.param
def test_1(arg):
values.append(arg)
def test_2(arg):
values.append(arg)
"""
)
reprec = pytester.inline_run("-vs")
reprec.assertoutcome(passed=4)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
import pprint
pprint.pprint(values)
# assert len(values) == 6
assert values[0] == values[1] == 1
assert values[2] == "fin1"
assert values[3] == values[4] == 2
assert values[5] == "fin2"
def test_parametrize_function_scoped_finalizers_called(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="function", params=[1, 2])
def arg(request):
x = request.param
request.addfinalizer(lambda: values.append("fin%s" % x))
return request.param
values = []
def test_1(arg):
values.append(arg)
def test_2(arg):
values.append(arg)
def test_3():
assert len(values) == 8
assert values == [1, "fin1", 2, "fin2", 1, "fin1", 2, "fin2"]
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=5)
@pytest.mark.parametrize("scope", ["session", "function", "module"])
def test_finalizer_order_on_parametrization(
self, scope, pytester: Pytester
) -> None:
"""#246"""
pytester.makepyfile(
f"""
import pytest
values = []
@pytest.fixture(scope={scope!r}, params=["1"])
def fix1(request):
return request.param
@pytest.fixture(scope={scope!r})
def fix2(request, base):
def cleanup_fix2():
assert not values, "base should not have been finalized"
request.addfinalizer(cleanup_fix2)
@pytest.fixture(scope={scope!r})
def base(request, fix1):
def cleanup_base():
values.append("fin_base")
print("finalizing base")
request.addfinalizer(cleanup_base)
def test_begin():
pass
def test_baz(base, fix2):
pass
def test_other():
pass
"""
)
reprec = pytester.inline_run("-lvs")
reprec.assertoutcome(passed=3)
def test_class_scope_parametrization_ordering(self, pytester: Pytester) -> None:
"""#396"""
pytester.makepyfile(
"""
import pytest
values = []
@pytest.fixture(params=["John", "Doe"], scope="class")
def human(request):
request.addfinalizer(lambda: values.append("fin %s" % request.param))
return request.param
class TestGreetings(object):
def test_hello(self, human):
values.append("test_hello")
class TestMetrics(object):
def test_name(self, human):
values.append("test_name")
def test_population(self, human):
values.append("test_population")
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=6)
values = reprec.getcalls("pytest_runtest_call")[0].item.module.values
assert values == [
"test_hello",
"fin John",
"test_hello",
"fin Doe",
"test_name",
"test_population",
"fin John",
"test_name",
"test_population",
"fin Doe",
]
def test_parametrize_setup_function(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module", params=[1, 2])
def arg(request):
return request.param
@pytest.fixture(scope="module", autouse=True)
def mysetup(request, arg):
request.addfinalizer(lambda: values.append("fin%s" % arg))
values.append("setup%s" % arg)
values = []
def test_1(arg):
values.append(arg)
def test_2(arg):
values.append(arg)
def test_3():
import pprint
pprint.pprint(values)
if arg == 1:
assert values == ["setup1", 1, 1, ]
elif arg == 2:
assert values == ["setup1", 1, 1, "fin1",
"setup2", 2, 2, ]
"""
)
reprec = pytester.inline_run("-v")
reprec.assertoutcome(passed=6)
def test_fixture_marked_function_not_collected_as_test(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def test_app():
return 1
def test_something(test_app):
assert test_app == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_params_and_ids(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[object(), object()],
ids=['alpha', 'beta'])
def fix(request):
return request.param
def test_foo(fix):
assert 1
"""
)
res = pytester.runpytest("-v")
res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
def test_params_and_ids_yieldfixture(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[object(), object()], ids=['alpha', 'beta'])
def fix(request):
yield request.param
def test_foo(fix):
assert 1
"""
)
res = pytester.runpytest("-v")
res.stdout.fnmatch_lines(["*test_foo*alpha*", "*test_foo*beta*"])
def test_deterministic_fixture_collection(
self, pytester: Pytester, monkeypatch
) -> None:
"""#920"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module",
params=["A",
"B",
"C"])
def A(request):
return request.param
@pytest.fixture(scope="module",
params=["DDDDDDDDD", "EEEEEEEEEEEE", "FFFFFFFFFFF", "banansda"])
def B(request, A):
return request.param
def test_foo(B):
# Something funky is going on here.
# Despite specified seeds, on what is collected,
# sometimes we get unexpected passes. hashing B seems
# to help?
assert hash(B) or True
"""
)
monkeypatch.setenv("PYTHONHASHSEED", "1")
out1 = pytester.runpytest_subprocess("-v")
monkeypatch.setenv("PYTHONHASHSEED", "2")
out2 = pytester.runpytest_subprocess("-v")
output1 = [
line
for line in out1.outlines
if line.startswith("test_deterministic_fixture_collection.py::test_foo")
]
output2 = [
line
for line in out2.outlines
if line.startswith("test_deterministic_fixture_collection.py::test_foo")
]
assert len(output1) == 12
assert output1 == output2
class TestRequestScopeAccess:
pytestmark = pytest.mark.parametrize(
("scope", "ok", "error"),
[
["session", "", "path class function module"],
["module", "module path", "cls function"],
["class", "module path cls", "function"],
["function", "module path cls function", ""],
],
)
def test_setup(self, pytester: Pytester, scope, ok, error) -> None:
pytester.makepyfile(
f"""
import pytest
@pytest.fixture(scope={scope!r}, autouse=True)
def myscoped(request):
for x in {ok.split()}:
assert hasattr(request, x)
for x in {error.split()}:
pytest.raises(AttributeError, lambda:
getattr(request, x))
assert request.session
assert request.config
def test_func():
pass
"""
)
reprec = pytester.inline_run("-l")
reprec.assertoutcome(passed=1)
def test_funcarg(self, pytester: Pytester, scope, ok, error) -> None:
pytester.makepyfile(
f"""
import pytest
@pytest.fixture(scope={scope!r})
def arg(request):
for x in {ok.split()!r}:
assert hasattr(request, x)
for x in {error.split()!r}:
pytest.raises(AttributeError, lambda:
getattr(request, x))
assert request.session
assert request.config
def test_func(arg):
pass
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
class TestErrors:
def test_subfactory_missing_funcarg(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture()
def gen(qwe123):
return 1
def test_something(gen):
pass
"""
)
result = pytester.runpytest()
assert result.ret != 0
result.stdout.fnmatch_lines(
["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"]
)
def test_issue498_fixture_finalizer_failing(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def fix1(request):
def f():
raise KeyError
request.addfinalizer(f)
return object()
values = []
def test_1(fix1):
values.append(fix1)
def test_2(fix1):
values.append(fix1)
def test_3():
assert values[0] != values[1]
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
"""
*ERROR*teardown*test_1*
*KeyError*
*ERROR*teardown*test_2*
*KeyError*
*3 pass*2 errors*
"""
)
def test_setupfunc_missing_funcarg(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(autouse=True)
def gen(qwe123):
return 1
def test_something():
pass
"""
)
result = pytester.runpytest()
assert result.ret != 0
result.stdout.fnmatch_lines(
["*def gen(qwe123):*", "*fixture*qwe123*not found*", "*1 error*"]
)
def test_cached_exception_doesnt_get_longer(self, pytester: Pytester) -> None:
"""Regression test for #12204."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="session")
def bad(): 1 / 0
def test_1(bad): pass
def test_2(bad): pass
def test_3(bad): pass
"""
)
result = pytester.runpytest_inprocess("--tb=native")
assert result.ret == ExitCode.TESTS_FAILED
failures = result.reprec.getfailures() # type: ignore[attr-defined]
assert len(failures) == 3
lines1 = failures[1].longrepr.reprtraceback.reprentries[0].lines
lines2 = failures[2].longrepr.reprtraceback.reprentries[0].lines
assert len(lines1) == len(lines2)
class TestShowFixtures:
def test_funcarg_compat(self, pytester: Pytester) -> None:
config = pytester.parseconfigure("--funcargs")
assert config.option.showfixtures
def test_show_help(self, pytester: Pytester) -> None:
result = pytester.runpytest("--fixtures", "--help")
assert not result.ret
def test_show_fixtures(self, pytester: Pytester) -> None:
result = pytester.runpytest("--fixtures")
result.stdout.fnmatch_lines(
[
"tmp_path_factory [[]session scope[]] -- .../_pytest/tmpdir.py:*",
"*for the test session*",
"tmp_path -- .../_pytest/tmpdir.py:*",
"*temporary directory*",
]
)
def test_show_fixtures_verbose(self, pytester: Pytester) -> None:
result = pytester.runpytest("--fixtures", "-v")
result.stdout.fnmatch_lines(
[
"tmp_path_factory [[]session scope[]] -- .../_pytest/tmpdir.py:*",
"*for the test session*",
"tmp_path -- .../_pytest/tmpdir.py:*",
"*temporary directory*",
]
)
def test_show_fixtures_testmodule(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
'''
import pytest
@pytest.fixture
def _arg0():
""" hidden """
@pytest.fixture
def arg1():
""" hello world """
'''
)
result = pytester.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
"""
*tmp_path -- *
*fixtures defined from*
*arg1 -- test_show_fixtures_testmodule.py:6*
*hello world*
"""
)
result.stdout.no_fnmatch_line("*arg0*")
@pytest.mark.parametrize("testmod", [True, False])
def test_show_fixtures_conftest(self, pytester: Pytester, testmod) -> None:
pytester.makeconftest(
'''
import pytest
@pytest.fixture
def arg1():
""" hello world """
'''
)
if testmod:
pytester.makepyfile(
"""
def test_hello():
pass
"""
)
result = pytester.runpytest("--fixtures")
result.stdout.fnmatch_lines(
"""
*tmp_path*
*fixtures defined from*conftest*
*arg1*
*hello world*
"""
)
def test_show_fixtures_trimmed_doc(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
textwrap.dedent(
'''\
import pytest
@pytest.fixture
def arg1():
"""
line1
line2
"""
@pytest.fixture
def arg2():
"""
line1
line2
"""
'''
)
)
result = pytester.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
textwrap.dedent(
"""\
* fixtures defined from test_show_fixtures_trimmed_doc *
arg2 -- test_show_fixtures_trimmed_doc.py:10
line1
line2
arg1 -- test_show_fixtures_trimmed_doc.py:3
line1
line2
"""
)
)
def test_show_fixtures_indented_doc(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
textwrap.dedent(
'''\
import pytest
@pytest.fixture
def fixture1():
"""
line1
indented line
"""
'''
)
)
result = pytester.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
textwrap.dedent(
"""\
* fixtures defined from test_show_fixtures_indented_doc *
fixture1 -- test_show_fixtures_indented_doc.py:3
line1
indented line
"""
)
)
def test_show_fixtures_indented_doc_first_line_unindented(
self, pytester: Pytester
) -> None:
p = pytester.makepyfile(
textwrap.dedent(
'''\
import pytest
@pytest.fixture
def fixture1():
"""line1
line2
indented line
"""
'''
)
)
result = pytester.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
textwrap.dedent(
"""\
* fixtures defined from test_show_fixtures_indented_doc_first_line_unindented *
fixture1 -- test_show_fixtures_indented_doc_first_line_unindented.py:3
line1
line2
indented line
"""
)
)
def test_show_fixtures_indented_in_class(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
textwrap.dedent(
'''\
import pytest
class TestClass(object):
@pytest.fixture
def fixture1(self):
"""line1
line2
indented line
"""
'''
)
)
result = pytester.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
textwrap.dedent(
"""\
* fixtures defined from test_show_fixtures_indented_in_class *
fixture1 -- test_show_fixtures_indented_in_class.py:4
line1
line2
indented line
"""
)
)
def test_show_fixtures_different_files(self, pytester: Pytester) -> None:
"""`--fixtures` only shows fixtures from first file (#833)."""
pytester.makepyfile(
test_a='''
import pytest
@pytest.fixture
def fix_a():
"""Fixture A"""
pass
def test_a(fix_a):
pass
'''
)
pytester.makepyfile(
test_b='''
import pytest
@pytest.fixture
def fix_b():
"""Fixture B"""
pass
def test_b(fix_b):
pass
'''
)
result = pytester.runpytest("--fixtures")
result.stdout.fnmatch_lines(
"""
* fixtures defined from test_a *
fix_a -- test_a.py:4
Fixture A
* fixtures defined from test_b *
fix_b -- test_b.py:4
Fixture B
"""
)
def test_show_fixtures_with_same_name(self, pytester: Pytester) -> None:
pytester.makeconftest(
'''
import pytest
@pytest.fixture
def arg1():
"""Hello World in conftest.py"""
return "Hello World"
'''
)
pytester.makepyfile(
"""
def test_foo(arg1):
assert arg1 == "Hello World"
"""
)
pytester.makepyfile(
'''
import pytest
@pytest.fixture
def arg1():
"""Hi from test module"""
return "Hi"
def test_bar(arg1):
assert arg1 == "Hi"
'''
)
result = pytester.runpytest("--fixtures")
result.stdout.fnmatch_lines(
"""
* fixtures defined from conftest *
arg1 -- conftest.py:3
Hello World in conftest.py
* fixtures defined from test_show_fixtures_with_same_name *
arg1 -- test_show_fixtures_with_same_name.py:3
Hi from test module
"""
)
def test_fixture_disallow_twice(self):
"""Test that applying @pytest.fixture twice generates an error (#2334)."""
with pytest.raises(ValueError):
@pytest.fixture
@pytest.fixture
def foo():
raise NotImplementedError()
class TestContextManagerFixtureFuncs:
def test_simple(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def arg1():
print("setup")
yield 1
print("teardown")
def test_1(arg1):
print("test1", arg1)
def test_2(arg1):
print("test2", arg1)
assert 0
"""
)
result = pytester.runpytest("-s")
result.stdout.fnmatch_lines(
"""
*setup*
*test1 1*
*teardown*
*setup*
*test2 1*
*teardown*
"""
)
def test_scoped(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module")
def arg1():
print("setup")
yield 1
print("teardown")
def test_1(arg1):
print("test1", arg1)
def test_2(arg1):
print("test2", arg1)
"""
)
result = pytester.runpytest("-s")
result.stdout.fnmatch_lines(
"""
*setup*
*test1 1*
*test2 1*
*teardown*
"""
)
def test_setup_exception(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module")
def arg1():
pytest.fail("setup")
yield 1
def test_1(arg1):
pass
"""
)
result = pytester.runpytest("-s")
result.stdout.fnmatch_lines(
"""
*pytest.fail*setup*
*1 error*
"""
)
def test_teardown_exception(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module")
def arg1():
yield 1
pytest.fail("teardown")
def test_1(arg1):
pass
"""
)
result = pytester.runpytest("-s")
result.stdout.fnmatch_lines(
"""
*pytest.fail*teardown*
*1 passed*1 error*
"""
)
def test_yields_more_than_one(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module")
def arg1():
yield 1
yield 2
def test_1(arg1):
pass
"""
)
result = pytester.runpytest("-s")
result.stdout.fnmatch_lines(
"""
*fixture function*
*test_yields*:2*
"""
)
def test_custom_name(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(name='meow')
def arg1():
return 'mew'
def test_1(meow):
print(meow)
"""
)
result = pytester.runpytest("-s")
result.stdout.fnmatch_lines(["*mew*"])
class TestParameterizedSubRequest:
def test_call_from_fixture(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_call_from_fixture="""
import pytest
@pytest.fixture(params=[0, 1, 2])
def fix_with_param(request):
return request.param
@pytest.fixture
def get_named_fixture(request):
return request.getfixturevalue('fix_with_param')
def test_foo(request, get_named_fixture):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"The requested fixture has no parameter defined for test:",
" test_call_from_fixture.py::test_foo",
"Requested fixture 'fix_with_param' defined in:",
"test_call_from_fixture.py:4",
"Requested here:",
"test_call_from_fixture.py:9",
"*1 error in*",
]
)
def test_call_from_test(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_call_from_test="""
import pytest
@pytest.fixture(params=[0, 1, 2])
def fix_with_param(request):
return request.param
def test_foo(request):
request.getfixturevalue('fix_with_param')
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"The requested fixture has no parameter defined for test:",
" test_call_from_test.py::test_foo",
"Requested fixture 'fix_with_param' defined in:",
"test_call_from_test.py:4",
"Requested here:",
"test_call_from_test.py:8",
"*1 failed*",
]
)
def test_external_fixture(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture(params=[0, 1, 2])
def fix_with_param(request):
return request.param
"""
)
pytester.makepyfile(
test_external_fixture="""
def test_foo(request):
request.getfixturevalue('fix_with_param')
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"The requested fixture has no parameter defined for test:",
" test_external_fixture.py::test_foo",
"",
"Requested fixture 'fix_with_param' defined in:",
"conftest.py:4",
"Requested here:",
"test_external_fixture.py:2",
"*1 failed*",
]
)
def test_non_relative_path(self, pytester: Pytester) -> None:
tests_dir = pytester.mkdir("tests")
fixdir = pytester.mkdir("fixtures")
fixfile = fixdir.joinpath("fix.py")
fixfile.write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture(params=[0, 1, 2])
def fix_with_param(request):
return request.param
"""
),
encoding="utf-8",
)
testfile = tests_dir.joinpath("test_foos.py")
testfile.write_text(
textwrap.dedent(
"""\
from fix import fix_with_param
def test_foo(request):
request.getfixturevalue('fix_with_param')
"""
),
encoding="utf-8",
)
os.chdir(tests_dir)
pytester.syspathinsert(fixdir)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"The requested fixture has no parameter defined for test:",
" test_foos.py::test_foo",
"",
"Requested fixture 'fix_with_param' defined in:",
f"{fixfile}:4",
"Requested here:",
"test_foos.py:4",
"*1 failed*",
]
)
# With non-overlapping rootdir, passing tests_dir.
rootdir = pytester.mkdir("rootdir")
os.chdir(rootdir)
result = pytester.runpytest("--rootdir", rootdir, tests_dir)
result.stdout.fnmatch_lines(
[
"The requested fixture has no parameter defined for test:",
" test_foos.py::test_foo",
"",
"Requested fixture 'fix_with_param' defined in:",
f"{fixfile}:4",
"Requested here:",
f"{testfile}:4",
"*1 failed*",
]
)
def test_pytest_fixture_setup_and_post_finalizer_hook(pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_fixture_setup(fixturedef, request):
print('ROOT setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
def pytest_fixture_post_finalizer(fixturedef, request):
print('ROOT finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
"""
)
pytester.makepyfile(
**{
"tests/conftest.py": """
def pytest_fixture_setup(fixturedef, request):
print('TESTS setup hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
def pytest_fixture_post_finalizer(fixturedef, request):
print('TESTS finalizer hook called for {0} from {1}'.format(fixturedef.argname, request.node.name))
""",
"tests/test_hooks.py": """
import pytest
@pytest.fixture()
def my_fixture():
return 'some'
def test_func(my_fixture):
print('TEST test_func')
assert my_fixture == 'some'
""",
}
)
result = pytester.runpytest("-s")
assert result.ret == 0
result.stdout.fnmatch_lines(
[
"*TESTS setup hook called for my_fixture from test_func*",
"*ROOT setup hook called for my_fixture from test_func*",
"*TEST test_func*",
"*TESTS finalizer hook called for my_fixture from test_func*",
"*ROOT finalizer hook called for my_fixture from test_func*",
]
)
class TestScopeOrdering:
"""Class of tests that ensure fixtures are ordered based on their scopes (#2405)"""
@pytest.mark.parametrize("variant", ["mark", "autouse"])
def test_func_closure_module_auto(
self, pytester: Pytester, variant, monkeypatch
) -> None:
"""Semantically identical to the example posted in #2405 when ``use_mark=True``"""
monkeypatch.setenv("FIXTURE_ACTIVATION_VARIANT", variant)
pytester.makepyfile(
"""
import warnings
import os
import pytest
VAR = 'FIXTURE_ACTIVATION_VARIANT'
VALID_VARS = ('autouse', 'mark')
VARIANT = os.environ.get(VAR)
if VARIANT is None or VARIANT not in VALID_VARS:
warnings.warn("{!r} is not in {}, assuming autouse".format(VARIANT, VALID_VARS) )
variant = 'mark'
@pytest.fixture(scope='module', autouse=VARIANT == 'autouse')
def m1(): pass
if VARIANT=='mark':
pytestmark = pytest.mark.usefixtures('m1')
@pytest.fixture(scope='function', autouse=True)
def f1(): pass
def test_func(m1):
pass
"""
)
items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function)
request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "m1 f1".split()
def test_func_closure_with_native_fixtures(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
"""Sanity check that verifies the order returned by the closures and the actual fixture execution order:
The execution order may differ because of fixture inter-dependencies.
"""
monkeypatch.setattr(pytest, "FIXTURE_ORDER", [], raising=False)
pytester.makepyfile(
"""
import pytest
FIXTURE_ORDER = pytest.FIXTURE_ORDER
@pytest.fixture(scope="session")
def s1():
FIXTURE_ORDER.append('s1')
@pytest.fixture(scope="package")
def p1():
FIXTURE_ORDER.append('p1')
@pytest.fixture(scope="module")
def m1():
FIXTURE_ORDER.append('m1')
@pytest.fixture(scope='session')
def my_tmp_path_factory():
FIXTURE_ORDER.append('my_tmp_path_factory')
@pytest.fixture
def my_tmp_path(my_tmp_path_factory):
FIXTURE_ORDER.append('my_tmp_path')
@pytest.fixture
def f1(my_tmp_path):
FIXTURE_ORDER.append('f1')
@pytest.fixture
def f2():
FIXTURE_ORDER.append('f2')
def test_foo(f1, p1, m1, f2, s1): pass
"""
)
items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function)
request = TopRequest(items[0], _ispytest=True)
# order of fixtures based on their scope and position in the parameter list
assert (
request.fixturenames
== "s1 my_tmp_path_factory p1 m1 f1 f2 my_tmp_path".split()
)
pytester.runpytest()
# actual fixture execution differs: dependent fixtures must be created first ("my_tmp_path")
FIXTURE_ORDER = pytest.FIXTURE_ORDER # type: ignore[attr-defined]
assert FIXTURE_ORDER == "s1 my_tmp_path_factory p1 m1 my_tmp_path f1 f2".split()
def test_func_closure_module(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='module')
def m1(): pass
@pytest.fixture(scope='function')
def f1(): pass
def test_func(f1, m1):
pass
"""
)
items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function)
request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "m1 f1".split()
def test_func_closure_scopes_reordered(self, pytester: Pytester) -> None:
"""Test ensures that fixtures are ordered by scope regardless of the order of the parameters, although
fixtures of same scope keep the declared order
"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='session')
def s1(): pass
@pytest.fixture(scope='module')
def m1(): pass
@pytest.fixture(scope='function')
def f1(): pass
@pytest.fixture(scope='function')
def f2(): pass
class Test:
@pytest.fixture(scope='class')
def c1(cls): pass
def test_func(self, f2, f1, c1, m1, s1):
pass
"""
)
items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function)
request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "s1 m1 c1 f2 f1".split()
def test_func_closure_same_scope_closer_root_first(
self, pytester: Pytester
) -> None:
"""Auto-use fixtures of same scope are ordered by closer-to-root first"""
pytester.makeconftest(
"""
import pytest
@pytest.fixture(scope='module', autouse=True)
def m_conf(): pass
"""
)
pytester.makepyfile(
**{
"sub/conftest.py": """
import pytest
@pytest.fixture(scope='package', autouse=True)
def p_sub(): pass
@pytest.fixture(scope='module', autouse=True)
def m_sub(): pass
""",
"sub/__init__.py": "",
"sub/test_func.py": """
import pytest
@pytest.fixture(scope='module', autouse=True)
def m_test(): pass
@pytest.fixture(scope='function')
def f1(): pass
def test_func(m_test, f1):
pass
""",
}
)
items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function)
request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "p_sub m_conf m_sub m_test f1".split()
def test_func_closure_all_scopes_complex(self, pytester: Pytester) -> None:
"""Complex test involving all scopes and mixing autouse with normal fixtures"""
pytester.makeconftest(
"""
import pytest
@pytest.fixture(scope='session')
def s1(): pass
@pytest.fixture(scope='package', autouse=True)
def p1(): pass
"""
)
pytester.makepyfile(**{"__init__.py": ""})
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='module', autouse=True)
def m1(): pass
@pytest.fixture(scope='module')
def m2(s1): pass
@pytest.fixture(scope='function')
def f1(): pass
@pytest.fixture(scope='function')
def f2(): pass
class Test:
@pytest.fixture(scope='class', autouse=True)
def c1(self):
pass
def test_func(self, f2, f1, m2):
pass
"""
)
items, _ = pytester.inline_genitems()
assert isinstance(items[0], Function)
request = TopRequest(items[0], _ispytest=True)
assert request.fixturenames == "s1 p1 m1 m2 c1 f2 f1".split()
def test_parametrized_package_scope_reordering(self, pytester: Pytester) -> None:
"""A parameterized package-scoped fixture correctly reorders items to
minimize setups & teardowns.
Regression test for #12328.
"""
pytester.makepyfile(
__init__="",
conftest="""
import pytest
@pytest.fixture(scope="package", params=["a", "b"])
def fix(request):
return request.param
""",
test_1="def test1(fix): pass",
test_2="def test2(fix): pass",
)
result = pytester.runpytest("--setup-plan")
assert result.ret == ExitCode.OK
result.stdout.fnmatch_lines(
[
" SETUP P fix['a']",
" test_1.py::test1[a] (fixtures used: fix, request)",
" test_2.py::test2[a] (fixtures used: fix, request)",
" TEARDOWN P fix['a']",
" SETUP P fix['b']",
" test_1.py::test1[b] (fixtures used: fix, request)",
" test_2.py::test2[b] (fixtures used: fix, request)",
" TEARDOWN P fix['b']",
],
)
def test_multiple_packages(self, pytester: Pytester) -> None:
"""Complex test involving multiple package fixtures. Make sure teardowns
are executed in order.
.
└── root
├── __init__.py
├── sub1
│ ├── __init__.py
│ ├── conftest.py
│ └── test_1.py
└── sub2
├── __init__.py
├── conftest.py
└── test_2.py
"""
root = pytester.mkdir("root")
root.joinpath("__init__.py").write_text("values = []", encoding="utf-8")
sub1 = root.joinpath("sub1")
sub1.mkdir()
sub1.joinpath("__init__.py").touch()
sub1.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
from .. import values
@pytest.fixture(scope="package")
def fix():
values.append("pre-sub1")
yield values
assert values.pop() == "pre-sub1"
"""
),
encoding="utf-8",
)
sub1.joinpath("test_1.py").write_text(
textwrap.dedent(
"""\
from .. import values
def test_1(fix):
assert values == ["pre-sub1"]
"""
),
encoding="utf-8",
)
sub2 = root.joinpath("sub2")
sub2.mkdir()
sub2.joinpath("__init__.py").touch()
sub2.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
from .. import values
@pytest.fixture(scope="package")
def fix():
values.append("pre-sub2")
yield values
assert values.pop() == "pre-sub2"
"""
),
encoding="utf-8",
)
sub2.joinpath("test_2.py").write_text(
textwrap.dedent(
"""\
from .. import values
def test_2(fix):
assert values == ["pre-sub2"]
"""
),
encoding="utf-8",
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_class_fixture_self_instance(self, pytester: Pytester) -> None:
"""Check that plugin classes which implement fixtures receive the plugin instance
as self (see #2270).
"""
pytester.makeconftest(
"""
import pytest
def pytest_configure(config):
config.pluginmanager.register(MyPlugin())
class MyPlugin():
def __init__(self):
self.arg = 1
@pytest.fixture(scope='function')
def myfix(self):
assert isinstance(self, MyPlugin)
return self.arg
"""
)
pytester.makepyfile(
"""
class TestClass(object):
def test_1(self, myfix):
assert myfix == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_call_fixture_function_error():
"""Check if an error is raised if a fixture function is called directly (#4545)"""
@pytest.fixture
def fix():
raise NotImplementedError()
with pytest.raises(pytest.fail.Exception):
assert fix() == 1
def test_fixture_double_decorator(pytester: Pytester) -> None:
"""Check if an error is raised when using @pytest.fixture twice."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture
@pytest.fixture
def fixt():
pass
"""
)
result = pytester.runpytest()
result.assert_outcomes(errors=1)
result.stdout.fnmatch_lines(
[
"E * ValueError: @pytest.fixture is being applied more than once to the same function 'fixt'"
]
)
def test_fixture_class(pytester: Pytester) -> None:
"""Check if an error is raised when using @pytest.fixture on a class."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture
class A:
pass
"""
)
result = pytester.runpytest()
result.assert_outcomes(errors=1)
def test_fixture_param_shadowing(pytester: Pytester) -> None:
"""Parametrized arguments would be shadowed if a fixture with the same name also exists (#5036)"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=['a', 'b'])
def argroot(request):
return request.param
@pytest.fixture
def arg(argroot):
return argroot
# This should only be parametrized directly
@pytest.mark.parametrize("arg", [1])
def test_direct(arg):
assert arg == 1
# This should be parametrized based on the fixtures
def test_normal_fixture(arg):
assert isinstance(arg, str)
# Indirect should still work:
@pytest.fixture
def arg2(request):
return 2*request.param
@pytest.mark.parametrize("arg2", [1], indirect=True)
def test_indirect(arg2):
assert arg2 == 2
"""
)
# Only one test should have run
result = pytester.runpytest("-v")
result.assert_outcomes(passed=4)
result.stdout.fnmatch_lines(["*::test_direct[[]1[]]*"])
result.stdout.fnmatch_lines(["*::test_normal_fixture[[]a[]]*"])
result.stdout.fnmatch_lines(["*::test_normal_fixture[[]b[]]*"])
result.stdout.fnmatch_lines(["*::test_indirect[[]1[]]*"])
def test_fixture_named_request(pytester: Pytester) -> None:
pytester.copy_example("fixtures/test_fixture_named_request.py")
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*'request' is a reserved word for fixtures, use another name:",
" *test_fixture_named_request.py:8",
]
)
def test_indirect_fixture_does_not_break_scope(pytester: Pytester) -> None:
"""Ensure that fixture scope is respected when using indirect fixtures (#570)"""
pytester.makepyfile(
"""
import pytest
instantiated = []
@pytest.fixture(scope="session")
def fixture_1(request):
instantiated.append(("fixture_1", request.param))
@pytest.fixture(scope="session")
def fixture_2(request):
instantiated.append(("fixture_2", request.param))
scenarios = [
("A", "a1"),
("A", "a2"),
("B", "b1"),
("B", "b2"),
("C", "c1"),
("C", "c2"),
]
@pytest.mark.parametrize(
"fixture_1,fixture_2", scenarios, indirect=["fixture_1", "fixture_2"]
)
def test_create_fixtures(fixture_1, fixture_2):
pass
def test_check_fixture_instantiations():
assert instantiated == [
('fixture_1', 'A'),
('fixture_2', 'a1'),
('fixture_2', 'a2'),
('fixture_1', 'B'),
('fixture_2', 'b1'),
('fixture_2', 'b2'),
('fixture_1', 'C'),
('fixture_2', 'c1'),
('fixture_2', 'c2'),
]
"""
)
result = pytester.runpytest()
result.assert_outcomes(passed=7)
def test_fixture_parametrization_nparray(pytester: Pytester) -> None:
pytest.importorskip("numpy")
pytester.makepyfile(
"""
from numpy import linspace
from pytest import fixture
@fixture(params=linspace(1, 10, 10))
def value(request):
return request.param
def test_bug(value):
assert value == value
"""
)
result = pytester.runpytest()
result.assert_outcomes(passed=10)
def test_fixture_arg_ordering(pytester: Pytester) -> None:
"""
This test describes how fixtures in the same scope but without explicit dependencies
between them are created. While users should make dependencies explicit, often
they rely on this order, so this test exists to catch regressions in this regard.
See #6540 and #6492.
"""
p1 = pytester.makepyfile(
"""
import pytest
suffixes = []
@pytest.fixture
def fix_1(): suffixes.append("fix_1")
@pytest.fixture
def fix_2(): suffixes.append("fix_2")
@pytest.fixture
def fix_3(): suffixes.append("fix_3")
@pytest.fixture
def fix_4(): suffixes.append("fix_4")
@pytest.fixture
def fix_5(): suffixes.append("fix_5")
@pytest.fixture
def fix_combined(fix_1, fix_2, fix_3, fix_4, fix_5): pass
def test_suffix(fix_combined):
assert suffixes == ["fix_1", "fix_2", "fix_3", "fix_4", "fix_5"]
"""
)
result = pytester.runpytest("-vv", str(p1))
assert result.ret == 0
def test_yield_fixture_with_no_value(pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(name='custom')
def empty_yield():
if False:
yield
def test_fixt(custom):
pass
"""
)
expected = "E ValueError: custom did not yield a value"
result = pytester.runpytest()
result.assert_outcomes(errors=1)
result.stdout.fnmatch_lines([expected])
assert result.ret == ExitCode.TESTS_FAILED
def test_deduplicate_names() -> None:
items = deduplicate_names("abacd")
assert items == ("a", "b", "c", "d")
items = deduplicate_names((*items, "g", "f", "g", "e", "b"))
assert items == ("a", "b", "c", "d", "g", "f", "e")
def test_staticmethod_classmethod_fixture_instance(pytester: Pytester) -> None:
"""Ensure that static and class methods get and have access to a fresh
instance.
This also ensures `setup_method` works well with static and class methods.
Regression test for #12065.
"""
pytester.makepyfile(
"""
import pytest
class Test:
ran_setup_method = False
ran_fixture = False
def setup_method(self):
assert not self.ran_setup_method
self.ran_setup_method = True
@pytest.fixture(autouse=True)
def fixture(self):
assert not self.ran_fixture
self.ran_fixture = True
def test_method(self):
assert self.ran_setup_method
assert self.ran_fixture
@staticmethod
def test_1(request):
assert request.instance.ran_setup_method
assert request.instance.ran_fixture
@classmethod
def test_2(cls, request):
assert request.instance.ran_setup_method
assert request.instance.ran_fixture
"""
)
result = pytester.runpytest()
assert result.ret == ExitCode.OK
result.assert_outcomes(passed=3)
def test_scoped_fixture_caching(pytester: Pytester) -> None:
"""Make sure setup and finalization is only run once when using scoped fixture
multiple times."""
pytester.makepyfile(
"""
from __future__ import annotations
from typing import Generator
import pytest
executed: list[str] = []
@pytest.fixture(scope="class")
def fixture_1() -> Generator[None, None, None]:
executed.append("fix setup")
yield
executed.append("fix teardown")
class TestFixtureCaching:
def test_1(self, fixture_1: None) -> None:
assert executed == ["fix setup"]
def test_2(self, fixture_1: None) -> None:
assert executed == ["fix setup"]
def test_expected_setup_and_teardown() -> None:
assert executed == ["fix setup", "fix teardown"]
"""
)
result = pytester.runpytest()
assert result.ret == 0
def test_scoped_fixture_caching_exception(pytester: Pytester) -> None:
"""Make sure setup & finalization is only run once for scoped fixture, with a cached exception."""
pytester.makepyfile(
"""
from __future__ import annotations
import pytest
executed_crash: list[str] = []
@pytest.fixture(scope="class")
def fixture_crash(request: pytest.FixtureRequest) -> None:
executed_crash.append("fix_crash setup")
def my_finalizer() -> None:
executed_crash.append("fix_crash teardown")
request.addfinalizer(my_finalizer)
raise Exception("foo")
class TestFixtureCachingException:
@pytest.mark.xfail
def test_crash_1(self, fixture_crash: None) -> None:
...
@pytest.mark.xfail
def test_crash_2(self, fixture_crash: None) -> None:
...
def test_crash_expected_setup_and_teardown() -> None:
assert executed_crash == ["fix_crash setup", "fix_crash teardown"]
"""
)
result = pytester.runpytest()
assert result.ret == 0
def test_scoped_fixture_teardown_order(pytester: Pytester) -> None:
"""
Make sure teardowns happen in reverse order of setup with scoped fixtures, when
a later test only depends on a subset of scoped fixtures.
Regression test for https://github.com/pytest-dev/pytest/issues/1489
"""
pytester.makepyfile(
"""
from typing import Generator
import pytest
last_executed = ""
@pytest.fixture(scope="module")
def fixture_1() -> Generator[None, None, None]:
global last_executed
assert last_executed == ""
last_executed = "fixture_1_setup"
yield
assert last_executed == "fixture_2_teardown"
last_executed = "fixture_1_teardown"
@pytest.fixture(scope="module")
def fixture_2() -> Generator[None, None, None]:
global last_executed
assert last_executed == "fixture_1_setup"
last_executed = "fixture_2_setup"
yield
assert last_executed == "run_test"
last_executed = "fixture_2_teardown"
def test_fixture_teardown_order(fixture_1: None, fixture_2: None) -> None:
global last_executed
assert last_executed == "fixture_2_setup"
last_executed = "run_test"
def test_2(fixture_1: None) -> None:
# This would previously queue an additional teardown of fixture_1,
# despite fixture_1's value being cached, which caused fixture_1 to be
# torn down before fixture_2 - violating the rule that teardowns should
# happen in reverse order of setup.
pass
"""
)
result = pytester.runpytest()
assert result.ret == 0
def test_subfixture_teardown_order(pytester: Pytester) -> None:
"""
Make sure fixtures don't re-register their finalization in parent fixtures multiple
times, causing ordering failure in their teardowns.
Regression test for #12135
"""
pytester.makepyfile(
"""
import pytest
execution_order = []
@pytest.fixture(scope="class")
def fixture_1():
...
@pytest.fixture(scope="class")
def fixture_2(fixture_1):
execution_order.append("setup 2")
yield
execution_order.append("teardown 2")
@pytest.fixture(scope="class")
def fixture_3(fixture_1):
execution_order.append("setup 3")
yield
execution_order.append("teardown 3")
class TestFoo:
def test_initialize_fixtures(self, fixture_2, fixture_3):
...
# This would previously reschedule fixture_2's finalizer in the parent fixture,
# causing it to be torn down before fixture 3.
def test_reschedule_fixture_2(self, fixture_2):
...
# Force finalization directly on fixture_1
# Otherwise the cleanup would sequence 3&2 before 1 as normal.
@pytest.mark.parametrize("fixture_1", [None], indirect=["fixture_1"])
def test_finalize_fixture_1(self, fixture_1):
...
def test_result():
assert execution_order == ["setup 2", "setup 3", "teardown 3", "teardown 2"]
"""
)
result = pytester.runpytest()
assert result.ret == 0
def test_parametrized_fixture_scope_allowed(pytester: Pytester) -> None:
"""
Make sure scope from parametrize does not affect fixture's ability to be
depended upon.
Regression test for #13248
"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="session")
def my_fixture(request):
return getattr(request, "param", None)
@pytest.fixture(scope="session")
def another_fixture(my_fixture):
return my_fixture
@pytest.mark.parametrize("my_fixture", ["a value"], indirect=True, scope="function")
def test_foo(another_fixture):
assert another_fixture == "a value"
"""
)
result = pytester.runpytest()
result.assert_outcomes(passed=1)
def test_collect_positional_only(pytester: Pytester) -> None:
"""Support the collection of tests with positional-only arguments (#13376)."""
pytester.makepyfile(
"""
import pytest
class Test:
@pytest.fixture
def fix(self):
return 1
def test_method(self, /, fix):
assert fix == 1
"""
)
result = pytester.runpytest()
result.assert_outcomes(passed=1)
def test_parametrization_dependency_pruning(pytester: Pytester) -> None:
"""Test that when a fixture is dynamically shadowed by parameterization, it
is properly pruned and not executed."""
pytester.makepyfile(
"""
import pytest
# This fixture should never run because shadowed_fixture is parametrized.
@pytest.fixture
def boom():
raise RuntimeError("BOOM!")
# This fixture is shadowed by metafunc.parametrize in pytest_generate_tests.
@pytest.fixture
def shadowed_fixture(boom):
return "fixture_value"
# Dynamically parametrize shadowed_fixture, replacing the fixture with direct values.
def pytest_generate_tests(metafunc):
if "shadowed_fixture" in metafunc.fixturenames:
metafunc.parametrize("shadowed_fixture", ["param1", "param2"])
# This test should receive shadowed_fixture as a parametrized value, and
# boom should not explode.
def test_shadowed(shadowed_fixture):
assert shadowed_fixture in ["param1", "param2"]
"""
)
result = pytester.runpytest()
result.assert_outcomes(passed=2)
def test_fixture_closure_with_overrides(pytester: Pytester) -> None:
"""Test that an item's static fixture closure properly includes transitive
dependencies through overridden fixtures (#13773)."""
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def db(): pass
@pytest.fixture
def app(db): pass
"""
)
pytester.makepyfile(
"""
import pytest
# Overrides conftest-level `app` and requests it.
@pytest.fixture
def app(app): pass
class TestClass:
# Overrides module-level `app` and requests it.
@pytest.fixture
def app(self, app): pass
def test_something(self, request, app):
# Both dynamic and static fixture closures should include 'db'.
assert 'db' in request.fixturenames
assert 'db' in request.node.fixturenames
# No dynamic dependencies, should be equal.
assert set(request.fixturenames) == set(request.node.fixturenames)
"""
)
result = pytester.runpytest("-v")
result.assert_outcomes(passed=1)
def test_fixture_closure_with_overrides_and_intermediary(pytester: Pytester) -> None:
"""Test that an item's static fixture closure properly includes transitive
dependencies through overridden fixtures (#13773).
A more complicated case than test_fixture_closure_with_overrides, adds an
intermediary so the override chain is not direct.
"""
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def db(): pass
@pytest.fixture
def app(db): pass
@pytest.fixture
def intermediate(app): pass
"""
)
pytester.makepyfile(
"""
import pytest
# Overrides conftest-level `app` and requests it.
@pytest.fixture
def app(intermediate): pass
class TestClass:
# Overrides module-level `app` and requests it.
@pytest.fixture
def app(self, app): pass
def test_something(self, request, app):
# Both dynamic and static fixture closures should include 'db'.
assert 'db' in request.fixturenames
assert 'db' in request.node.fixturenames
# No dynamic dependencies, should be equal.
assert set(request.fixturenames) == set(request.node.fixturenames)
"""
)
result = pytester.runpytest("-v")
result.assert_outcomes(passed=1)
def test_fixture_closure_with_broken_override_chain(pytester: Pytester) -> None:
"""Test that an item's static fixture closure properly includes transitive
dependencies through overridden fixtures (#13773).
A more complicated case than test_fixture_closure_with_overrides, one of the
fixtures in the chain doesn't call its super, so it shouldn't be included.
"""
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def db(): pass
@pytest.fixture
def app(db): pass
"""
)
pytester.makepyfile(
"""
import pytest
# Overrides conftest-level `app` and *doesn't* request it.
@pytest.fixture
def app(): pass
class TestClass:
# Overrides module-level `app` and requests it.
@pytest.fixture
def app(self, app): pass
def test_something(self, request, app):
# Both dynamic and static fixture closures should include 'db'.
assert 'db' not in request.fixturenames
assert 'db' not in request.node.fixturenames
# No dynamic dependencies, should be equal.
assert set(request.fixturenames) == set(request.node.fixturenames)
"""
)
result = pytester.runpytest("-v")
result.assert_outcomes(passed=1)
def test_fixture_closure_handles_circular_dependencies(pytester: Pytester) -> None:
"""Test that getfixtureclosure properly handles circular dependencies.
The test will error in the runtest phase due to the fixture loop,
but the closure computation still completes.
"""
pytester.makepyfile(
"""
import pytest
# Direct circular dependency.
@pytest.fixture
def fix_a(fix_b): pass
@pytest.fixture
def fix_b(fix_a): pass
# Indirect circular dependency through multiple fixtures.
@pytest.fixture
def fix_x(fix_y): pass
@pytest.fixture
def fix_y(fix_z): pass
@pytest.fixture
def fix_z(fix_x): pass
def test_circular_deps(fix_a, fix_x):
pass
"""
)
items, _hookrec = pytester.inline_genitems()
assert isinstance(items[0], Function)
assert items[0].fixturenames == ["fix_a", "fix_x", "fix_b", "fix_y", "fix_z"]
def test_fixture_closure_handles_diamond_dependencies(pytester: Pytester) -> None:
"""Test that getfixtureclosure properly handles diamond dependencies."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def db(): pass
@pytest.fixture
def user(db): pass
@pytest.fixture
def session(db): pass
@pytest.fixture
def app(user, session): pass
def test_diamond_deps(request, app):
assert request.node.fixturenames == ["request", "app", "user", "db", "session"]
assert request.fixturenames == ["request", "app", "user", "db", "session"]
"""
)
result = pytester.runpytest("-v")
result.assert_outcomes(passed=1)
def test_fixture_closure_with_complex_override_and_shared_deps(
pytester: Pytester,
) -> None:
"""Test that shared dependencies in override chains are processed only once."""
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def db(): pass
@pytest.fixture
def cache(): pass
@pytest.fixture
def settings(): pass
@pytest.fixture
def app(db, cache, settings): pass
"""
)
pytester.makepyfile(
"""
import pytest
# Override app, but also directly use cache and settings.
# This creates multiple paths to the same fixtures.
@pytest.fixture
def app(app, cache, settings): pass
class TestClass:
# Another override that uses both app and cache.
@pytest.fixture
def app(self, app, cache): pass
def test_shared_deps(self, request, app):
assert request.node.fixturenames == ["request", "app", "db", "cache", "settings"]
"""
)
result = pytester.runpytest("-v")
result.assert_outcomes(passed=1)
def test_fixture_closure_with_parametrize_ignore(pytester: Pytester) -> None:
"""Test that getfixtureclosure properly handles parametrization argnames
which override a fixture."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def fix1(fix2): pass
@pytest.fixture
def fix2(fix3): pass
@pytest.fixture
def fix3(): pass
@pytest.mark.parametrize('fix2', ['2'])
def test_it(request, fix1):
assert request.node.fixturenames == ["request", "fix1", "fix2"]
assert request.fixturenames == ["request", "fix1", "fix2"]
"""
)
result = pytester.runpytest("-v")
result.assert_outcomes(passed=1)
|