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
|
import gc
import itertools
import json
import platform
import re
import sys
from collections import Counter, OrderedDict, defaultdict, deque
from collections.abc import Iterable, Mapping, Sequence
from enum import Enum, IntEnum
from typing import (
Annotated,
Any,
Callable,
ClassVar,
Generic,
NamedTuple,
Optional,
TypeVar,
Union,
)
import pytest
from dirty_equals import HasRepr, IsStr
from pydantic_core import CoreSchema, core_schema
from typing_extensions import (
Literal,
Never,
NotRequired,
ParamSpec,
TypeAliasType,
TypedDict,
TypeVarTuple,
Unpack,
get_args,
)
from typing_extensions import (
TypeVar as TypingExtensionsTypeVar,
)
from pydantic import (
BaseModel,
Field,
GetCoreSchemaHandler,
Json,
PositiveInt,
PydanticSchemaGenerationError,
PydanticUserError,
TypeAdapter,
ValidationError,
ValidationInfo,
computed_field,
field_validator,
model_validator,
)
from pydantic._internal._generics import (
_GENERIC_TYPES_CACHE,
_LIMITED_DICT_SIZE,
GenericTypesCache,
LimitedDict,
generic_recursion_self_type,
iter_contained_typevars,
recursively_defined_type_refs,
replace_types,
)
from pydantic.warnings import GenericBeforeBaseModelWarning
# Note: this isn't implemented as a fixture, as pytest fixtures
# are shared between threads by pytest-run-parallel:
def get_clean_cache() -> GenericTypesCache:
generic_types_cache = _GENERIC_TYPES_CACHE.get()
if generic_types_cache is None:
generic_types_cache = GenericTypesCache()
_GENERIC_TYPES_CACHE.set(generic_types_cache)
# cleans up _GENERIC_TYPES_CACHE for checking item counts in the cache
generic_types_cache.clear()
gc.collect(0)
gc.collect(1)
gc.collect(2)
return generic_types_cache
def test_generic_name():
data_type = TypeVar('data_type')
class Result(BaseModel, Generic[data_type]):
data: data_type
assert Result[list[int]].__name__ == 'Result[list[int]]'
assert Result[list[int]].__name__ == 'Result[list[int]]'
assert Result[int].__name__ == 'Result[int]'
def test_double_parameterize_error():
data_type = TypeVar('data_type')
class Result(BaseModel, Generic[data_type]):
data: data_type
with pytest.raises(TypeError) as exc_info:
Result[int][int]
assert str(exc_info.value) == "<class 'tests.test_generics.Result[int]'> is not a generic class"
def test_value_validation():
T = TypeVar('T', bound=dict[Any, Any])
class Response(BaseModel, Generic[T]):
data: T
@field_validator('data')
@classmethod
def validate_value_nonzero(cls, v: Any):
if any(x == 0 for x in v.values()):
raise ValueError('some value is zero')
return v
@model_validator(mode='after')
def validate_sum(self) -> 'Response[T]':
data = self.data
if sum(data.values()) > 5:
raise ValueError('sum too large')
return self
assert Response[dict[int, int]](data={1: '4'}).model_dump() == {'data': {1: 4}}
with pytest.raises(ValidationError) as exc_info:
Response[dict[int, int]](data={1: 'a'})
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('data', 1),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'a',
}
]
with pytest.raises(ValidationError) as exc_info:
Response[dict[int, int]](data={1: 0})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'error': HasRepr(repr(ValueError('some value is zero')))},
'input': {1: 0},
'loc': ('data',),
'msg': 'Value error, some value is zero',
'type': 'value_error',
}
]
with pytest.raises(ValidationError) as exc_info:
Response[dict[int, int]](data={1: 3, 2: 6})
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'error': HasRepr(repr(ValueError('sum too large')))},
'input': {'data': {1: 3, 2: 6}},
'loc': (),
'msg': 'Value error, sum too large',
'type': 'value_error',
}
]
def test_methods_are_inherited():
class CustomModel(BaseModel):
def method(self):
return self.data
T = TypeVar('T')
class Model(CustomModel, Generic[T]):
data: T
instance = Model[int](data=1)
assert instance.method() == 1
def test_config_is_inherited():
class CustomGenericModel(BaseModel, frozen=True): ...
T = TypeVar('T')
class Model(CustomGenericModel, Generic[T]):
data: T
instance = Model[int](data=1)
with pytest.raises(ValidationError) as exc_info:
instance.data = 2
assert exc_info.value.errors(include_url=False) == [
{'type': 'frozen_instance', 'loc': ('data',), 'msg': 'Instance is frozen', 'input': 2}
]
def test_default_argument():
T = TypeVar('T')
class Result(BaseModel, Generic[T]):
data: T
other: bool = True
result = Result[int](data=1)
assert result.other is True
def test_default_argument_for_typevar():
T = TypeVar('T')
class Result(BaseModel, Generic[T]):
data: T = 4
result = Result[int]()
assert result.data == 4
result = Result[float]()
assert result.data == 4
result = Result[int](data=1)
assert result.data == 1
def test_classvar():
T = TypeVar('T')
class Result(BaseModel, Generic[T]):
data: T
other: ClassVar[int] = 1
assert Result.other == 1
assert Result[int].other == 1
assert Result[int](data=1).other == 1
assert 'other' not in Result.model_fields
def test_non_annotated_field():
T = TypeVar('T')
with pytest.raises(PydanticUserError, match='A non-annotated attribute was detected: `other = True`'):
class Result(BaseModel, Generic[T]):
data: T
other = True
def test_non_generic_field():
T = TypeVar('T')
class Result(BaseModel, Generic[T]):
data: T
other: bool = True
assert 'other' in Result.model_fields
assert 'other' in Result[int].model_fields
result = Result[int](data=1)
assert result.other is True
def test_must_inherit_from_generic():
with pytest.raises(TypeError) as exc_info:
class Result(BaseModel):
pass
Result[int]
assert str(exc_info.value) == (
"<class 'tests.test_generics.test_must_inherit_from_generic.<locals>.Result'> cannot be "
'parametrized because it does not inherit from typing.Generic'
)
def test_parameters_placed_on_generic():
T = TypeVar('T')
with pytest.raises(TypeError, match='Type parameters should be placed on typing.Generic, not BaseModel'):
class Result(BaseModel[T]):
pass
def test_parameters_must_be_typevar():
with pytest.raises(TypeError, match='Type parameters should be placed on typing.Generic, not BaseModel'):
class Result(BaseModel[int]):
pass
def test_subclass_can_be_genericized():
T = TypeVar('T')
class Result(BaseModel, Generic[T]):
pass
Result[T]
def test_type_var_default_referencing_other_type_var() -> None:
# Example taken from:
# https://typing.readthedocs.io/en/latest/spec/generics.html#type-parameters-as-parameters-to-generics
T = TypeVar('T')
ListDefaultT = TypingExtensionsTypeVar('ListDefaultT', default=list[T])
class Model(BaseModel, Generic[T, ListDefaultT]):
t: T
ls: ListDefaultT
assert Model[int].__pydantic_generic_metadata__['args'] == (int, list[int])
def test_parameter_count():
T = TypeVar('T')
S = TypeVar('S')
class Model(BaseModel, Generic[T, S]):
x: T
y: S
with pytest.raises(TypeError) as exc_info:
Model[int, int, int]
# This error message, which comes from `typing`, changed 'parameters' to 'arguments' in 3.11
error_message = str(exc_info.value)
assert error_message.startswith(('Too many parameters', 'Too many arguments'))
assert error_message.endswith(
" for <class 'tests.test_generics.test_parameter_count.<locals>.Model'>; actual 3, expected 2"
)
def test_arguments_count_validation() -> None:
T = TypeVar('T')
U = TypeVar('U')
V = TypingExtensionsTypeVar('V', default=int)
class Model(BaseModel, Generic[T, U, V]):
t: T
u: U
v: V
model_repr = repr(Model)
with pytest.raises(TypeError, match=f'Too many arguments for {model_repr}; actual 4, expected 3'):
Model[int, int, int, int]
with pytest.raises(TypeError, match=f'Too few arguments for {model_repr}; actual 1, expected at least 2'):
Model[int]
assert Model[int, int].__pydantic_generic_metadata__['args'] == (int, int, int)
assert Model[int, int, str].__pydantic_generic_metadata__['args'] == (int, int, str)
def test_cover_cache():
cache = get_clean_cache()
cache_size = len(cache)
T = TypeVar('T')
class Model(BaseModel, Generic[T]):
x: T
models = [] # keep references to models to get cache size
models.append(Model[int]) # adds both with-tuple and without-tuple version to cache
assert len(cache) == cache_size + 3
models.append(Model[int]) # uses the cache
assert len(cache) == cache_size + 3
del models
def test_cache_keys_are_hashable():
cache = get_clean_cache()
cache_size = len(cache)
T = TypeVar('T')
C = Callable[[str, dict[str, Any]], Iterable[str]]
class MyGenericModel(BaseModel, Generic[T]):
t: T
# Callable's first params get converted to a list, which is not hashable.
# Make sure we can handle that special case
Simple = MyGenericModel[Callable[[int], str]]
models = [] # keep references to models to get cache size
models.append(Simple)
assert len(cache) == cache_size + 3
# Nested Callables
models.append(MyGenericModel[Callable[[C], Iterable[str]]])
assert len(cache) == cache_size + 6
models.append(MyGenericModel[Callable[[Simple], Iterable[int]]])
assert len(cache) == cache_size + 9
models.append(MyGenericModel[Callable[[MyGenericModel[C]], Iterable[int]]])
assert len(cache) == cache_size + 15
class Model(BaseModel):
x: MyGenericModel[Callable[[C], Iterable[str]]]
models.append(Model)
assert len(cache) == cache_size + 15
del models
@pytest.mark.thread_unsafe(reason='GC is flaky')
@pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason='PyPy does not play nice with PyO3 gc')
def test_caches_get_cleaned_up():
cache = get_clean_cache()
initial_types_cache_size = len(cache)
T = TypeVar('T')
class MyGenericModel(BaseModel, Generic[T]):
x: T
model_config = dict(arbitrary_types_allowed=True)
n_types = 200
types = []
for i in range(n_types):
class MyType(int):
pass
types.append(MyGenericModel[MyType]) # retain a reference
assert len(cache) == initial_types_cache_size + 3 * n_types
types.clear()
gc.collect(0)
gc.collect(1)
gc.collect(2)
assert len(cache) < initial_types_cache_size + _LIMITED_DICT_SIZE
@pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason='PyPy does not play nice with PyO3 gc')
def test_caches_get_cleaned_up_with_aliased_parametrized_bases():
cache = get_clean_cache()
types_cache_size = len(cache)
def run() -> None: # Run inside nested function to get classes in local vars cleaned also
T1 = TypeVar('T1')
T2 = TypeVar('T2')
class A(BaseModel, Generic[T1, T2]):
x: T1
y: T2
B = A[int, T2]
C = B[str]
assert len(cache) == types_cache_size + 5
del C
del B
gc.collect()
run()
gc.collect(0)
gc.collect(1)
gc.collect(2)
assert len(cache) < types_cache_size + _LIMITED_DICT_SIZE
@pytest.mark.thread_unsafe(reason='GC is flaky')
@pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason='PyPy does not play nice with PyO3 gc')
@pytest.mark.skipif(sys.version_info[:2] == (3, 9), reason='The test randomly fails on Python 3.9')
def test_circular_generic_refs_get_cleaned_up():
cache = get_clean_cache()
initial_cache_size = len(cache)
def fn():
T = TypeVar('T')
C = TypeVar('C')
class Inner(BaseModel, Generic[T, C]):
a: T
b: C
class Outer(BaseModel, Generic[C]):
c: Inner[int, C]
klass = Outer[str]
assert len(cache) > initial_cache_size
assert klass in cache.values()
fn()
gc.collect(0)
gc.collect(1)
gc.collect(2)
assert len(cache) == initial_cache_size
def test_generics_work_with_many_parametrized_base_models():
cache = get_clean_cache()
cache_size = len(cache)
count_create_models = 1000
T = TypeVar('T')
C = TypeVar('C')
class A(BaseModel, Generic[T, C]):
x: T
y: C
class B(A[int, C], BaseModel, Generic[C]):
pass
models = []
for i in range(count_create_models):
class M(BaseModel):
pass
M.__name__ = f'M{i}'
models.append(M)
generics = []
for m in models:
Working = B[m]
generics.append(Working)
target_size = cache_size + count_create_models * 3 + 2
assert len(cache) < target_size + _LIMITED_DICT_SIZE
del models
del generics
def test_generics_reused() -> None:
"""https://github.com/pydantic/pydantic/issues/11747
To fix an issue with recursive generics, we introduced a change in 2.11 that would
skip caching the parameterized model under specific circumstances. The following setup
is an example of where this would happen. As a result, we ended up with two different `A[int]`
classes, although they were the same in practice.
When serializing, we check that the value instances are matching the type, but we ended up
with warnings as `isinstance(value, A[int])` fails.
The fix was reverted as a refactor (https://github.com/pydantic/pydantic/pull/11388) fixed
the underlying issue.
"""
T = TypeVar('T')
class A(BaseModel, Generic[T]):
pass
class B(BaseModel, Generic[T]):
pass
AorB = TypeAliasType('AorB', Union[A[T], B[T]], type_params=(T,))
class Main(BaseModel, Generic[T]):
ls: list[AorB[T]] = []
m = Main[int]()
m.ls.append(A[int]())
m.model_dump_json(warnings='error')
def test_generic_config():
data_type = TypeVar('data_type')
class Result(BaseModel, Generic[data_type], frozen=True):
data: data_type
result = Result[int](data=1)
assert result.data == 1
with pytest.raises(ValidationError):
result.data = 2
def test_enum_generic():
T = TypeVar('T')
class MyEnum(IntEnum):
x = 1
y = 2
class Model(BaseModel, Generic[T]):
enum: T
Model[MyEnum](enum=MyEnum.x)
Model[MyEnum](enum=2)
def test_generic():
data_type = TypeVar('data_type')
error_type = TypeVar('error_type')
class Result(BaseModel, Generic[data_type, error_type]):
data: Optional[list[data_type]] = None
error: Optional[error_type] = None
positive_number: int
@field_validator('error')
@classmethod
def validate_error(cls, v: Optional[error_type], info: ValidationInfo) -> Optional[error_type]:
values = info.data
if values.get('data', None) is None and v is None:
raise ValueError('Must provide data or error')
if values.get('data', None) is not None and v is not None:
raise ValueError('Must not provide both data and error')
return v
@field_validator('positive_number')
@classmethod
def validate_positive_number(cls, v: int) -> int:
if v < 0:
raise ValueError
return v
class Error(BaseModel):
message: str
class Data(BaseModel):
number: int
text: str
success1 = Result[Data, Error](data=[Data(number=1, text='a')], positive_number=1)
assert success1.model_dump() == {'data': [{'number': 1, 'text': 'a'}], 'error': None, 'positive_number': 1}
assert repr(success1) == (
'Result[test_generic.<locals>.Data,'
" test_generic.<locals>.Error](data=[Data(number=1, text='a')], error=None, positive_number=1)"
)
success2 = Result[Data, Error](error=Error(message='error'), positive_number=1)
assert success2.model_dump() == {'data': None, 'error': {'message': 'error'}, 'positive_number': 1}
assert repr(success2) == (
'Result[test_generic.<locals>.Data, test_generic.<locals>.Error]'
"(data=None, error=Error(message='error'), positive_number=1)"
)
with pytest.raises(ValidationError) as exc_info:
Result[Data, Error](error=Error(message='error'), positive_number=-1)
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'error': HasRepr(repr(ValueError()))},
'input': -1,
'loc': ('positive_number',),
'msg': 'Value error, ',
'type': 'value_error',
}
]
with pytest.raises(ValidationError) as exc_info:
Result[Data, Error](data=[Data(number=1, text='a')], error=Error(message='error'), positive_number=1)
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'error': HasRepr(repr(ValueError('Must not provide both data and error')))},
'input': Error(message='error'),
'loc': ('error',),
'msg': 'Value error, Must not provide both data and error',
'type': 'value_error',
}
]
def test_alongside_concrete_generics():
T = TypeVar('T')
class MyModel(BaseModel, Generic[T]):
item: T
metadata: dict[str, Any]
model = MyModel[int](item=1, metadata={})
assert model.item == 1
assert model.metadata == {}
def test_complex_nesting():
T = TypeVar('T')
class MyModel(BaseModel, Generic[T]):
item: list[dict[Union[int, T], str]]
item = [{1: 'a', 'a': 'a'}]
model = MyModel[str](item=item)
assert model.item == item
def test_required_value():
T = TypeVar('T')
class MyModel(BaseModel, Generic[T]):
a: int
with pytest.raises(ValidationError) as exc_info:
MyModel[int]()
assert exc_info.value.errors(include_url=False) == [
{'input': {}, 'loc': ('a',), 'msg': 'Field required', 'type': 'missing'}
]
def test_optional_value():
T = TypeVar('T')
class MyModel(BaseModel, Generic[T]):
a: Optional[int] = 1
model = MyModel[int]()
assert model.model_dump() == {'a': 1}
def test_custom_schema():
T = TypeVar('T')
class MyModel(BaseModel, Generic[T]):
a: int = Field(1, description='Custom')
schema = MyModel[int].model_json_schema()
assert schema['properties']['a'].get('description') == 'Custom'
def test_child_schema():
T = TypeVar('T')
class Model(BaseModel, Generic[T]):
a: T
class Child(Model[T], Generic[T]):
pass
schema = Child[int].model_json_schema()
assert schema == {
'title': 'Child[int]',
'type': 'object',
'properties': {'a': {'title': 'A', 'type': 'integer'}},
'required': ['a'],
}
def test_custom_generic_naming():
T = TypeVar('T')
class MyModel(BaseModel, Generic[T]):
value: Optional[T]
@classmethod
def model_parametrized_name(cls, params: tuple[type[Any], ...]) -> str:
param_names = [param.__name__ if hasattr(param, '__name__') else str(param) for param in params]
title = param_names[0].title()
return f'Optional{title}Wrapper'
assert repr(MyModel[int](value=1)) == 'OptionalIntWrapper(value=1)'
assert repr(MyModel[str](value=None)) == 'OptionalStrWrapper(value=None)'
def test_nested():
AT = TypeVar('AT')
class InnerT(BaseModel, Generic[AT]):
a: AT
inner_int = InnerT[int](a=8)
inner_str = InnerT[str](a='ate')
inner_dict_any = InnerT[Any](a={})
inner_int_any = InnerT[Any](a=7)
class OuterT_SameType(BaseModel, Generic[AT]):
i: InnerT[AT]
OuterT_SameType[int](i={'a': 8})
OuterT_SameType[int](i=inner_int)
OuterT_SameType[str](i=inner_str)
OuterT_SameType[int](i=inner_int_any)
with pytest.raises(ValidationError) as exc_info:
OuterT_SameType[int](i=inner_str.model_dump())
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('i', 'a'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'ate',
}
]
with pytest.raises(ValidationError) as exc_info:
OuterT_SameType[int](i=inner_str)
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('i', 'a'),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'ate',
}
]
with pytest.raises(ValidationError) as exc_info:
OuterT_SameType[int](i=inner_dict_any.model_dump())
assert exc_info.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('i', 'a'), 'msg': 'Input should be a valid integer', 'input': {}}
]
with pytest.raises(ValidationError) as exc_info:
OuterT_SameType[int](i=inner_dict_any)
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{'type': 'int_type', 'loc': ('i', 'a'), 'msg': 'Input should be a valid integer', 'input': {}}
]
def test_partial_specification():
AT = TypeVar('AT')
BT = TypeVar('BT')
class Model(BaseModel, Generic[AT, BT]):
a: AT
b: BT
partial_model = Model[int, BT]
concrete_model = partial_model[str]
concrete_model(a=1, b='abc')
with pytest.raises(ValidationError) as exc_info:
concrete_model(a='abc', b=None)
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('a',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'abc',
},
{'type': 'string_type', 'loc': ('b',), 'msg': 'Input should be a valid string', 'input': None},
]
def test_partial_specification_with_inner_typevar():
AT = TypeVar('AT')
BT = TypeVar('BT')
class Model(BaseModel, Generic[AT, BT]):
a: list[AT]
b: list[BT]
partial_model = Model[int, BT]
assert partial_model.__pydantic_generic_metadata__['parameters']
concrete_model = partial_model[int]
assert not concrete_model.__pydantic_generic_metadata__['parameters']
# nested resolution of partial models should work as expected
nested_resolved = concrete_model(a=['123'], b=['456'])
assert nested_resolved.a == [123]
assert nested_resolved.b == [456]
@pytest.mark.skipif(sys.version_info < (3, 12), reason='repr different on older versions')
def test_partial_specification_name():
AT = TypeVar('AT')
BT = TypeVar('BT')
class Model(BaseModel, Generic[AT, BT]):
a: AT
b: BT
partial_model = Model[int, BT]
assert partial_model.__name__ == 'Model[int, TypeVar]'
concrete_model = partial_model[str]
assert concrete_model.__name__ == 'Model[int, str]'
def test_partial_specification_instantiation():
AT = TypeVar('AT')
BT = TypeVar('BT')
class Model(BaseModel, Generic[AT, BT]):
a: AT
b: BT
partial_model = Model[int, BT]
partial_model(a=1, b=2)
partial_model(a=1, b='a')
with pytest.raises(ValidationError) as exc_info:
partial_model(a='a', b=2)
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('a',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'a',
}
]
def test_partial_specification_instantiation_bounded():
AT = TypeVar('AT')
BT = TypeVar('BT', bound=int)
class Model(BaseModel, Generic[AT, BT]):
a: AT
b: BT
Model(a=1, b=1)
with pytest.raises(ValidationError) as exc_info:
Model(a=1, b='a')
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('b',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'a',
}
]
partial_model = Model[int, BT]
partial_model(a=1, b=1)
with pytest.raises(ValidationError) as exc_info:
partial_model(a=1, b='a')
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('b',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'a',
}
]
def test_typevar_parametrization():
AT = TypeVar('AT')
BT = TypeVar('BT')
class Model(BaseModel, Generic[AT, BT]):
a: AT
b: BT
CT = TypeVar('CT', bound=int)
DT = TypeVar('DT', bound=int)
with pytest.raises(ValidationError) as exc_info:
Model[CT, DT](a='a', b='b')
assert exc_info.value.errors(include_url=False) == [
{
'type': 'int_parsing',
'loc': ('a',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'a',
},
{
'type': 'int_parsing',
'loc': ('b',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'input': 'b',
},
]
def test_multiple_specification():
AT = TypeVar('AT')
BT = TypeVar('BT')
class Model(BaseModel, Generic[AT, BT]):
a: AT
b: BT
CT = TypeVar('CT')
partial_model = Model[CT, CT]
concrete_model = partial_model[str]
with pytest.raises(ValidationError) as exc_info:
concrete_model(a=None, b=None)
assert exc_info.value.errors(include_url=False) == [
{'type': 'string_type', 'loc': ('a',), 'msg': 'Input should be a valid string', 'input': None},
{'type': 'string_type', 'loc': ('b',), 'msg': 'Input should be a valid string', 'input': None},
]
def test_generic_subclass_of_concrete_generic():
T = TypeVar('T')
U = TypeVar('U')
class GenericBaseModel(BaseModel, Generic[T]):
data: T
class GenericSub(GenericBaseModel[int], Generic[U]):
extra: U
ConcreteSub = GenericSub[int]
with pytest.raises(ValidationError):
ConcreteSub(data=2, extra='wrong')
with pytest.raises(ValidationError):
ConcreteSub(data='wrong', extra=2)
ConcreteSub(data=2, extra=3)
def test_generic_model_pickle(create_module):
# Using create_module because pickle doesn't support
# objects with <locals> in their __qualname__ (e.g. defined in function)
@create_module
def module():
import pickle
from typing import Generic, TypeVar
from pydantic import BaseModel
t = TypeVar('t')
class Model(BaseModel):
a: float
b: int = 10
class MyGeneric(BaseModel, Generic[t]):
value: t
original = MyGeneric[Model](value=Model(a='24'))
dumped = pickle.dumps(original)
loaded = pickle.loads(dumped)
assert loaded.value.a == original.value.a == 24
assert loaded.value.b == original.value.b == 10
assert loaded == original
def test_generic_model_from_function_pickle_fail(create_module):
@create_module
def module():
import pickle
from typing import Generic, TypeVar
import pytest
from pydantic import BaseModel
t = TypeVar('t')
class Model(BaseModel):
a: float
b: int = 10
class MyGeneric(BaseModel, Generic[t]):
value: t
def get_generic(t):
return MyGeneric[t]
original = get_generic(Model)(value=Model(a='24'))
with pytest.raises(pickle.PicklingError):
pickle.dumps(original)
def test_generic_model_redefined_without_cache_fail(create_module, monkeypatch):
# match identity checker otherwise we never get to the redefinition check
monkeypatch.setattr('pydantic._internal._utils.all_identical', lambda left, right: False)
@create_module
def module():
from typing import Generic, TypeVar
from pydantic import BaseModel
from pydantic._internal._generics import _GENERIC_TYPES_CACHE
t = TypeVar('t')
class MyGeneric(BaseModel, Generic[t]):
value: t
class Model(BaseModel): ...
concrete = MyGeneric[Model]
_GENERIC_TYPES_CACHE.get().clear() # pyright: ignore[reportOptionalMemberAccess], guaranteed to be set
second_concrete = MyGeneric[Model]
class Model(BaseModel): # same name, but type different, so it's not in cache
...
third_concrete = MyGeneric[Model]
assert concrete is not second_concrete
assert concrete is not third_concrete
assert second_concrete is not third_concrete
assert globals()['MyGeneric[Model]'] is concrete
assert globals()['MyGeneric[Model]_'] is second_concrete
assert globals()['MyGeneric[Model]__'] is third_concrete
def test_generic_model_caching_detect_order_of_union_args_basic(create_module):
# Basic variant of https://github.com/pydantic/pydantic/issues/4474
@create_module
def module():
from typing import Generic, TypeVar, Union
from pydantic import BaseModel
t = TypeVar('t')
class Model(BaseModel, Generic[t]):
data: t
int_or_float_model = Model[Union[int, float]]
float_or_int_model = Model[Union[float, int]]
assert type(int_or_float_model(data='1').data) is int
assert type(float_or_int_model(data='1').data) is float
@pytest.mark.skip(
reason="""
Depends on similar issue in CPython itself: https://github.com/python/cpython/issues/86483
Documented and skipped for possible fix later.
"""
)
def test_generic_model_caching_detect_order_of_union_args_nested(create_module):
# Nested variant of https://github.com/pydantic/pydantic/issues/4474
@create_module
def module():
from typing import Generic, TypeVar, Union
from pydantic import BaseModel
t = TypeVar('t')
class Model(BaseModel, Generic[t]):
data: t
int_or_float_model = Model[list[Union[int, float]]]
float_or_int_model = Model[list[Union[float, int]]]
assert type(int_or_float_model(data=['1']).data[0]) is int
assert type(float_or_int_model(data=['1']).data[0]) is float
def test_get_caller_frame_info(create_module):
@create_module
def module():
from pydantic._internal._generics import _get_caller_frame_info
def function():
assert _get_caller_frame_info() == (__name__, True)
another_function()
def another_function():
assert _get_caller_frame_info() == (__name__, False)
third_function()
def third_function():
assert _get_caller_frame_info() == (__name__, False)
function()
def test_get_caller_frame_info_called_from_module(create_module):
@create_module
def module():
from unittest.mock import patch
import pytest
from pydantic._internal._generics import _get_caller_frame_info
with pytest.raises(RuntimeError, match='This function must be used inside another function'):
with patch('sys._getframe', side_effect=ValueError('getframe_exc')):
_get_caller_frame_info()
@pytest.mark.thread_unsafe(reason='Deleting built-in functions')
def test_get_caller_frame_info_when_sys_getframe_undefined():
from pydantic._internal._generics import _get_caller_frame_info
getframe = sys._getframe
del sys._getframe
try:
assert _get_caller_frame_info() == (None, False)
finally: # just to make sure we always setting original attribute back
sys._getframe = getframe
def test_iter_contained_typevars():
T = TypeVar('T')
T2 = TypeVar('T2')
class Model(BaseModel, Generic[T]):
a: T
assert list(iter_contained_typevars(Model[T])) == [T]
assert list(iter_contained_typevars(Optional[list[Union[str, Model[T]]]])) == [T]
assert list(iter_contained_typevars(Optional[list[Union[str, Model[int]]]])) == []
assert list(iter_contained_typevars(Optional[list[Union[str, Model[T], Callable[[T2, T], str]]]])) == [T, T2, T]
def test_nested_identity_parameterization():
T = TypeVar('T')
T2 = TypeVar('T2')
class Model(BaseModel, Generic[T]):
a: T
assert Model[T][T][T] is Model
assert Model[T] is Model
assert Model[T2] is not Model
def test_replace_types():
T = TypeVar('T')
class Model(BaseModel, Generic[T]):
a: T
assert replace_types(T, {T: int}) is int
assert replace_types(list[Union[str, list, T]], {T: int}) == list[Union[str, list, int]]
assert replace_types(Callable, {T: int}) == Callable
assert replace_types(Callable[[int, str, T], T], {T: int}) == Callable[[int, str, int], int]
assert replace_types(T, {}) is T
assert replace_types(Model[list[T]], {T: int}) == Model[list[int]]
assert replace_types(Model[list[T]], {T: int}) == Model[list[T]][int]
assert (
replace_types(Model[list[T]], {T: int}).model_fields['a'].annotation
== Model[list[T]][int].model_fields['a'].annotation
)
assert replace_types(T, {}) is T
assert replace_types(type[T], {T: int}) == type[int]
assert replace_types(Model[T], {T: T}) == Model[T]
assert replace_types(Json[T], {T: int}) == Json[int]
# Check generic aliases (subscripted builtin types) to make sure they
# resolve correctly (don't get translated to typing versions for
# example)
assert replace_types(list[Union[str, list, T]], {T: int}) == list[Union[str, list, int]]
if sys.version_info >= (3, 10):
# Check that types.UnionType gets handled properly
assert replace_types(str | list[T] | float, {T: int}) == str | list[int] | float
def test_replace_types_with_user_defined_generic_type_field(): # noqa: C901
"""Test that using user defined generic types as generic model fields are handled correctly."""
T = TypeVar('T')
KT = TypeVar('KT')
VT = TypeVar('VT')
class CustomCounter(Counter[T]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.no_info_after_validator_function(cls, handler(Counter[get_args(source_type)[0]]))
class CustomDefaultDict(defaultdict[KT, VT]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
keys_type, values_type = get_args(source_type)
return core_schema.no_info_after_validator_function(
lambda x: cls(x.default_factory, x), handler(defaultdict[keys_type, values_type])
)
class CustomDeque(deque[T]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.no_info_after_validator_function(cls, handler(deque[get_args(source_type)[0]]))
class CustomDict(dict[KT, VT]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
keys_type, values_type = get_args(source_type)
return core_schema.no_info_after_validator_function(cls, handler(dict[keys_type, values_type]))
class CustomFrozenset(frozenset[T]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.no_info_after_validator_function(cls, handler(frozenset[get_args(source_type)[0]]))
class CustomIterable(Iterable[T]):
def __init__(self, iterable):
self.iterable = iterable
def __iter__(self):
return self
def __next__(self):
return next(self.iterable)
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.no_info_after_validator_function(cls, handler(Iterable[get_args(source_type)[0]]))
class CustomList(list[T]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.no_info_after_validator_function(cls, handler(list[get_args(source_type)[0]]))
class CustomMapping(Mapping[KT, VT]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
keys_type, values_type = get_args(source_type)
return handler(Mapping[keys_type, values_type])
class CustomOrderedDict(OrderedDict[KT, VT]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
keys_type, values_type = get_args(source_type)
return core_schema.no_info_after_validator_function(cls, handler(OrderedDict[keys_type, values_type]))
class CustomSet(set[T]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.no_info_after_validator_function(cls, handler(set[get_args(source_type)[0]]))
class CustomTuple(tuple[T]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.no_info_after_validator_function(cls, handler(tuple[get_args(source_type)[0]]))
class CustomLongTuple(tuple[T, VT]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.no_info_after_validator_function(cls, handler(tuple[get_args(source_type)]))
class Model(BaseModel, Generic[T, KT, VT]):
counter_field: CustomCounter[T]
default_dict_field: CustomDefaultDict[KT, VT]
deque_field: CustomDeque[T]
dict_field: CustomDict[KT, VT]
frozenset_field: CustomFrozenset[T]
iterable_field: CustomIterable[T]
list_field: CustomList[T]
mapping_field: CustomMapping[KT, VT]
ordered_dict_field: CustomOrderedDict[KT, VT]
set_field: CustomSet[T]
tuple_field: CustomTuple[T]
long_tuple_field: CustomLongTuple[T, VT]
assert replace_types(Model, {T: bool, KT: str, VT: int}) == Model[bool, str, int]
assert replace_types(Model[T, KT, VT], {T: bool, KT: str, VT: int}) == Model[bool, str, int]
assert replace_types(Model[T, VT, KT], {T: bool, KT: str, VT: int}) == Model[T, VT, KT][bool, int, str]
m = Model[bool, str, int](
counter_field=Counter([True, False]),
default_dict_field={'a': 1},
deque_field=[True, False],
dict_field={'a': 1},
frozenset_field=frozenset([True, False]),
iterable_field=[True, False],
list_field=[True, False],
mapping_field={'a': 2},
ordered_dict_field=OrderedDict([('a', 1)]),
set_field={True, False},
tuple_field=(True,),
long_tuple_field=(True, 42),
)
# The following assertions are just to document the current behavior, and should
# be updated if/when we do a better job of respecting the exact annotated type
assert type(m.counter_field) is CustomCounter
# assert type(m.default_dict_field) is CustomDefaultDict
assert type(m.deque_field) is CustomDeque
assert type(m.dict_field) is CustomDict
assert type(m.frozenset_field) is CustomFrozenset
assert type(m.iterable_field) is CustomIterable
assert type(m.list_field) is CustomList
assert type(m.mapping_field) is dict # this is determined in CustomMapping.__get_pydantic_core_schema__
assert type(m.ordered_dict_field) is CustomOrderedDict
assert type(m.set_field) is CustomSet
assert type(m.tuple_field) is CustomTuple
assert type(m.long_tuple_field) is CustomLongTuple
assert m.model_dump() == {
'counter_field': {False: 1, True: 1},
'default_dict_field': {'a': 1},
'deque_field': deque([True, False]),
'dict_field': {'a': 1},
'frozenset_field': frozenset({False, True}),
'iterable_field': HasRepr(IsStr(regex=r'SerializationIterator\(index=0, iterator=.*CustomIterable.*')),
'list_field': [True, False],
'mapping_field': {'a': 2},
'ordered_dict_field': {'a': 1},
'set_field': {False, True},
'tuple_field': (True,),
'long_tuple_field': (True, 42),
}
def test_custom_sequence_behavior():
T = TypeVar('T')
class CustomSequence(Sequence[T]):
pass
with pytest.raises(
PydanticSchemaGenerationError,
match=(
r'Unable to generate pydantic-core schema for .*'
' Set `arbitrary_types_allowed=True` in the model_config to ignore this error'
' or implement `__get_pydantic_core_schema__` on your type to fully support it'
),
):
class Model(BaseModel, Generic[T]):
x: CustomSequence[T]
def test_replace_types_identity_on_unchanged():
T = TypeVar('T')
U = TypeVar('U')
type_ = list[Union[str, Callable[[list], Optional[str]], U]]
assert replace_types(type_, {T: int}) is type_
def test_deep_generic():
T = TypeVar('T')
S = TypeVar('S')
R = TypeVar('R')
class OuterModel(BaseModel, Generic[T, S, R]):
a: dict[R, Optional[list[T]]]
b: Optional[Union[S, R]]
c: R
d: float
class InnerModel(BaseModel, Generic[T, R]):
c: T
d: R
class NormalModel(BaseModel):
e: int
f: str
inner_model = InnerModel[int, str]
generic_model = OuterModel[inner_model, NormalModel, int]
inner_models = [inner_model(c=1, d='a')]
generic_model(a={1: inner_models, 2: None}, b=None, c=1, d=1.5)
generic_model(a={}, b=NormalModel(e=1, f='a'), c=1, d=1.5)
generic_model(a={}, b=1, c=1, d=1.5)
assert InnerModel.__pydantic_generic_metadata__['parameters'] # i.e., InnerModel is not concrete
assert not inner_model.__pydantic_generic_metadata__['parameters'] # i.e., inner_model is concrete
def test_deep_generic_with_inner_typevar():
T = TypeVar('T')
class OuterModel(BaseModel, Generic[T]):
a: list[T]
class InnerModel(OuterModel[T], Generic[T]):
pass
assert not InnerModel[int].__pydantic_generic_metadata__['parameters'] # i.e., InnerModel[int] is concrete
assert InnerModel.__pydantic_generic_metadata__['parameters'] # i.e., InnerModel is not concrete
with pytest.raises(ValidationError):
InnerModel[int](a=['wrong'])
assert InnerModel[int](a=['1']).a == [1]
def test_deep_generic_with_referenced_generic():
T = TypeVar('T')
R = TypeVar('R')
class ReferencedModel(BaseModel, Generic[R]):
a: R
class OuterModel(BaseModel, Generic[T]):
a: ReferencedModel[T]
class InnerModel(OuterModel[T], Generic[T]):
pass
assert not InnerModel[int].__pydantic_generic_metadata__['parameters']
assert InnerModel.__pydantic_generic_metadata__['parameters']
with pytest.raises(ValidationError):
InnerModel[int](a={'a': 'wrong'})
assert InnerModel[int](a={'a': 1}).a.a == 1
def test_deep_generic_with_referenced_inner_generic():
T = TypeVar('T')
class ReferencedModel(BaseModel, Generic[T]):
a: T
class OuterModel(BaseModel, Generic[T]):
a: Optional[list[Union[ReferencedModel[T], str]]]
class InnerModel(OuterModel[T], Generic[T]):
pass
assert not InnerModel[int].__pydantic_generic_metadata__['parameters']
assert InnerModel.__pydantic_generic_metadata__['parameters']
with pytest.raises(ValidationError):
InnerModel[int](a=['s', {'a': 'wrong'}])
assert InnerModel[int](a=['s', {'a': 1}]).a[1].a == 1
assert InnerModel[int].model_fields['a'].annotation == Optional[list[Union[ReferencedModel[int], str]]]
def test_deep_generic_with_multiple_typevars():
T = TypeVar('T')
U = TypeVar('U')
class OuterModel(BaseModel, Generic[T]):
data: list[T]
class InnerModel(OuterModel[T], Generic[U, T]):
extra: U
ConcreteInnerModel = InnerModel[int, float]
assert ConcreteInnerModel.model_fields['data'].annotation == list[float]
assert ConcreteInnerModel.model_fields['extra'].annotation == int
assert ConcreteInnerModel(data=['1'], extra='2').model_dump() == {'data': [1.0], 'extra': 2}
def test_deep_generic_with_multiple_inheritance():
K = TypeVar('K')
V = TypeVar('V')
T = TypeVar('T')
class OuterModelA(BaseModel, Generic[K, V]):
data: dict[K, V]
class OuterModelB(BaseModel, Generic[T]):
stuff: list[T]
class InnerModel(OuterModelA[K, V], OuterModelB[T], Generic[K, V, T]):
extra: int
ConcreteInnerModel = InnerModel[int, float, str]
assert ConcreteInnerModel.model_fields['data'].annotation == dict[int, float]
assert ConcreteInnerModel.model_fields['stuff'].annotation == list[str]
assert ConcreteInnerModel.model_fields['extra'].annotation == int
with pytest.raises(ValidationError) as exc_info:
ConcreteInnerModel(data={1.1: '5'}, stuff=[123], extra=5)
assert exc_info.value.errors(include_url=False) == [
{'input': 123, 'loc': ('stuff', 0), 'msg': 'Input should be a valid string', 'type': 'string_type'},
{
'input': 1.1,
'loc': ('data', '1.1', '[key]'),
'msg': 'Input should be a valid integer, got a number with a fractional part',
'type': 'int_from_float',
},
]
assert ConcreteInnerModel(data={1: 5}, stuff=['123'], extra=5).model_dump() == {
'data': {1: 5},
'stuff': ['123'],
'extra': 5,
}
def test_generic_with_referenced_generic_type_1():
T = TypeVar('T')
class ModelWithType(BaseModel, Generic[T]):
# Type resolves to type origin of "type" which is non-subscriptible for
# python < 3.9 so we want to make sure it works for other versions
some_type: type[T]
class ReferenceModel(BaseModel, Generic[T]):
abstract_base_with_type: ModelWithType[T]
ReferenceModel[int]
def test_generic_with_referenced_generic_type_bound():
T = TypeVar('T', bound=int)
class ModelWithType(BaseModel, Generic[T]):
some_type: type[T]
class ReferenceModel(BaseModel, Generic[T]):
abstract_base_with_type: ModelWithType[T]
class MyInt(int): ...
ReferenceModel[MyInt]
def test_generic_with_referenced_generic_union_type_bound():
T = TypeVar('T', bound=Union[str, int])
class ModelWithType(BaseModel, Generic[T]):
some_type: type[T]
class MyInt(int): ...
class MyStr(str): ...
ModelWithType[MyInt]
ModelWithType[MyStr]
def test_generic_with_referenced_generic_type_constraints():
T = TypeVar('T', int, str)
class ModelWithType(BaseModel, Generic[T]):
some_type: type[T]
class ReferenceModel(BaseModel, Generic[T]):
abstract_base_with_type: ModelWithType[T]
ReferenceModel[int]
def test_generic_with_referenced_nested_typevar():
T = TypeVar('T')
class ModelWithType(BaseModel, Generic[T]):
# Type resolves to type origin of "collections.abc.Sequence" which is
# non-subscriptible for
# python < 3.9 so we want to make sure it works for other versions
some_type: Sequence[T]
class ReferenceModel(BaseModel, Generic[T]):
abstract_base_with_type: ModelWithType[T]
ReferenceModel[int]
def test_generic_with_callable():
T = TypeVar('T')
class Model(BaseModel, Generic[T]):
# Callable is a test for any type that accepts a list as an argument
some_callable: Callable[[Optional[int], T], None]
assert not Model[str].__pydantic_generic_metadata__['parameters']
assert Model.__pydantic_generic_metadata__['parameters']
def test_generic_with_partial_callable():
T = TypeVar('T')
U = TypeVar('U')
class Model(BaseModel, Generic[T, U]):
t: T
u: U
# Callable is a test for any type that accepts a list as an argument
some_callable: Callable[[Optional[int], str], None]
assert Model[str, U].__pydantic_generic_metadata__['parameters'] == (U,)
assert not Model[str, int].__pydantic_generic_metadata__['parameters']
def test_generic_recursive_models(create_module):
@create_module
def module():
from typing import Generic, TypeVar, Union
from pydantic import BaseModel
T = TypeVar('T')
class Model1(BaseModel, Generic[T]):
ref: 'Model2[T]'
class Model2(BaseModel, Generic[T]):
ref: Union[T, Model1[T]]
Model1.model_rebuild()
Model1 = module.Model1
Model2 = module.Model2
with pytest.raises(ValidationError) as exc_info:
Model1[str].model_validate(dict(ref=dict(ref=dict(ref=dict(ref=123)))))
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'string_type',
'loc': ('ref', 'ref', 'str'),
'msg': 'Input should be a valid string',
'input': {'ref': {'ref': 123}},
},
{
'type': 'string_type',
'loc': ('ref', 'ref', 'Model1[str]', 'ref', 'ref', 'str'),
'msg': 'Input should be a valid string',
'input': 123,
},
{
'type': 'model_type',
'loc': ('ref', 'ref', 'Model1[str]', 'ref', 'ref', 'Model1[str]'),
'msg': 'Input should be a valid dictionary or instance of Model1[str]',
'input': 123,
'ctx': {'class_name': 'Model1[str]'},
},
]
result = Model1(ref=Model2(ref=Model1(ref=Model2(ref='123'))))
assert result.model_dump() == {'ref': {'ref': {'ref': {'ref': '123'}}}}
result = Model1[str].model_validate(dict(ref=dict(ref=dict(ref=dict(ref='123')))))
assert result.model_dump() == {'ref': {'ref': {'ref': {'ref': '123'}}}}
def test_generic_recursive_models_parametrized() -> None:
"""https://github.com/pydantic/pydantic/issues/10279"""
# This test is similar (if not identical) to the previous one, although in this one,
# we make sure we can parametrize and rebuild the models (see the linked issue).
T = TypeVar('T')
class Model1(BaseModel, Generic[T]):
model2: 'Model2[T]'
S = TypeVar('S')
class Model2(BaseModel, Generic[S]):
model1: Model1[S]
Model1[str].model_rebuild()
Model2[str].model_rebuild()
def test_generic_recursive_models_parametrized_with_model() -> None:
"""https://github.com/pydantic/pydantic/issues/11748"""
T = TypeVar('T')
class Base(BaseModel, Generic[T]):
t: T
class Other(BaseModel):
child: 'Optional[Base[Other]]'
with pytest.raises(ValidationError):
# In v2.0-2.10, this unexpectedly validated fine (The core schema of Base[Other].t was an empty model).
# Since v2.11, building `Other` raised an unhandled exception.
# Now, it works as expected.
Base[Other].model_validate({'t': {}})
Base[Other].model_validate({'t': {'child': {'t': {'child': None}}}})
def test_generic_recursive_models_parametrized_with_model_subclass() -> None:
"""https://github.com/pydantic/pydantic/issues/12396.
Follow up on `test_generic_recursive_models_parametrized_with_model()`.
"""
# The code to check if `__pydantic_fields__` was set was wrongly
# checking for parent classes as well (and not in the class' `__dict__`):
class MyBaseModel(BaseModel):
pass
T = TypeVar('T')
class Base(MyBaseModel, Generic[T]):
t: T
class Other(MyBaseModel):
child: 'Optional[Base[Other]]'
with pytest.raises(ValidationError):
Base[Other].model_validate({'t': {}})
Base[Other].model_validate({'t': {'child': {'t': {'child': None}}}})
@pytest.mark.xfail(reason='Core schema generation is missing the M1 definition')
def test_generic_recursive_models_inheritance() -> None:
"""https://github.com/pydantic/pydantic/issues/9969"""
T = TypeVar('T')
class M1(BaseModel, Generic[T]):
bar: 'M1[T]'
class M2(M1[str]):
pass
M2.model_rebuild()
assert M2.__pydantic_complete__
def test_generic_recursive_models_separate_parameters(create_module):
@create_module
def module():
from typing import Generic, TypeVar, Union
from pydantic import BaseModel
T = TypeVar('T')
class Model1(BaseModel, Generic[T]):
ref: 'Model2[T]'
S = TypeVar('S')
class Model2(BaseModel, Generic[S]):
ref: Union[S, Model1[S]]
Model1.model_rebuild()
Model1 = module.Model1
# Model2 = module.Model2
with pytest.raises(ValidationError) as exc_info:
Model1[str].model_validate(dict(ref=dict(ref=dict(ref=dict(ref=123)))))
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'string_type',
'loc': ('ref', 'ref', 'str'),
'msg': 'Input should be a valid string',
'input': {'ref': {'ref': 123}},
},
{
'type': 'string_type',
'loc': ('ref', 'ref', 'Model1[str]', 'ref', 'ref', 'str'),
'msg': 'Input should be a valid string',
'input': 123,
},
{
'type': 'model_type',
'loc': ('ref', 'ref', 'Model1[str]', 'ref', 'ref', 'Model1[str]'),
'msg': 'Input should be a valid dictionary or instance of Model1[str]',
'input': 123,
'ctx': {'class_name': 'Model1[str]'},
},
]
# TODO: Unlike in the previous test, the following (commented) line currently produces this error:
# > result = Model1(ref=Model2(ref=Model1(ref=Model2(ref='123'))))
# E pydantic_core._pydantic_core.ValidationError: 1 validation error for Model2[~T]
# E ref
# E Input should be a valid dictionary [type=dict_type, input_value=Model2(ref='123'), input_type=Model2]
# The root of this problem is that Model2[T] ends up being a proper subclass of Model2 since T != S.
# I am sure we can solve this problem, just need to put a bit more effort in.
# While I don't think we should block merging this functionality on getting the next line to pass,
# I think we should come back and resolve this at some point.
# result = Model1(ref=Model2(ref=Model1(ref=Model2(ref='123'))))
# assert result.model_dump() == {'ref': {'ref': {'ref': {'ref': '123'}}}}
result = Model1[str].model_validate(dict(ref=dict(ref=dict(ref=dict(ref='123')))))
assert result.model_dump() == {'ref': {'ref': {'ref': {'ref': '123'}}}}
def test_generic_recursive_models_repeated_separate_parameters(create_module):
@create_module
def module():
from typing import Generic, TypeVar, Union
from pydantic import BaseModel
T = TypeVar('T')
class Model1(BaseModel, Generic[T]):
ref: 'Model2[T]'
ref2: Union['Model2[T]', None] = None
S = TypeVar('S')
class Model2(BaseModel, Generic[S]):
ref: Union[S, Model1[S]]
ref2: Union[S, Model1[S], None] = None
Model1.model_rebuild()
Model1 = module.Model1
# Model2 = module.Model2
with pytest.raises(ValidationError) as exc_info:
Model1[str].model_validate(dict(ref=dict(ref=dict(ref=dict(ref=123)))))
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'string_type',
'loc': ('ref', 'ref', 'str'),
'msg': 'Input should be a valid string',
'input': {'ref': {'ref': 123}},
},
{
'type': 'string_type',
'loc': ('ref', 'ref', 'Model1[str]', 'ref', 'ref', 'str'),
'msg': 'Input should be a valid string',
'input': 123,
},
{
'type': 'model_type',
'loc': ('ref', 'ref', 'Model1[str]', 'ref', 'ref', 'Model1[str]'),
'msg': 'Input should be a valid dictionary or instance of Model1[str]',
'input': 123,
'ctx': {'class_name': 'Model1[str]'},
},
]
result = Model1[str].model_validate(dict(ref=dict(ref=dict(ref=dict(ref='123')))))
assert result.model_dump() == {
'ref': {'ref': {'ref': {'ref': '123', 'ref2': None}, 'ref2': None}, 'ref2': None},
'ref2': None,
}
def test_generic_recursive_models_triple(create_module):
@create_module
def module():
from typing import Generic, TypeVar, Union
from pydantic import BaseModel
T1 = TypeVar('T1')
T2 = TypeVar('T2')
T3 = TypeVar('T3')
class A1(BaseModel, Generic[T1]):
a1: 'A2[T1]'
class A2(BaseModel, Generic[T2]):
a2: 'A3[T2]'
class A3(BaseModel, Generic[T3]):
a3: Union['A1[T3]', T3]
A1.model_rebuild()
A1 = module.A1
with pytest.raises(ValidationError) as exc_info:
A1[str].model_validate({'a1': {'a2': {'a3': 1}}})
# insert_assert(exc_info.value.errors(include_url=False))
assert exc_info.value.errors(include_url=False) == [
{
'type': 'model_type',
'loc': ('a1', 'a2', 'a3', 'A1[str]'),
'msg': 'Input should be a valid dictionary or instance of A1[str]',
'input': 1,
'ctx': {'class_name': 'A1[str]'},
},
{'type': 'string_type', 'loc': ('a1', 'a2', 'a3', 'str'), 'msg': 'Input should be a valid string', 'input': 1},
]
A1[int].model_validate({'a1': {'a2': {'a3': 1}}})
def test_generic_recursive_models_with_a_concrete_parameter(create_module):
@create_module
def module():
from typing import Generic, TypeVar, Union
from pydantic import BaseModel
V1 = TypeVar('V1')
V2 = TypeVar('V2')
V3 = TypeVar('V3')
class M1(BaseModel, Generic[V1, V2]):
a: V1
m2: 'M2[V2]'
class M2(BaseModel, Generic[V3]):
m1: Union[M1[int, V3], V3]
M1.model_rebuild()
M1 = module.M1
M1[float, str].model_validate({'a': 1.5, 'm2': {'m1': 'foo'}})
M1[float, str].model_validate({'a': 1.5, 'm2': {'m1': {'a': 3, 'm2': {'m1': 'foo'}}}})
def test_generic_recursive_models_complicated(create_module):
"""
Note: If we drop the use of LimitedDict and use WeakValueDictionary only, this test will fail if run by itself.
This is due to weird behavior with the WeakValueDictionary used for caching.
As part of the next batch of generics work, we should attempt to fix this if possible.
In the meantime, if this causes issues, or the test otherwise starts failing, please make it xfail
with strict=False
"""
@create_module
def module():
# Noqa comment because linter/type checker think the `Optional` in the `B2.a2`
# annotation comes from the module:
from typing import Generic, Optional, TypeVar, Union # noqa: F401
from pydantic import BaseModel
T1 = TypeVar('T1')
T2 = TypeVar('T2')
T3 = TypeVar('T3')
class A1(BaseModel, Generic[T1]):
a1: 'A2[T1]'
class A2(BaseModel, Generic[T2]):
a2: 'A3[T2]'
class A3(BaseModel, Generic[T3]):
a3: Union[A1[T3], T3]
A1.model_rebuild()
S1 = TypeVar('S1')
S2 = TypeVar('S2')
class B1(BaseModel, Generic[S1]):
a1: 'B2[S1]'
class B2(BaseModel, Generic[S2]):
a2: 'Optional[B1[S2]]' = None
B1.model_rebuild()
V1 = TypeVar('V1')
V2 = TypeVar('V2')
V3 = TypeVar('V3')
class M1(BaseModel, Generic[V1, V2]):
a: int
b: B1[V2]
m2: 'M2[V1]'
class M2(BaseModel, Generic[V3]):
m1: Union[M1[V3, int], V3]
M1.model_rebuild()
M1 = module.M1
M1[str, float].model_validate({'a': 1, 'b': {'a1': {'a2': {'a1': {'a2': {'a1': {}}}}}}, 'm2': {'m1': 'foo'}})
def test_generic_recursive_models_in_container(create_module):
@create_module
def module():
from typing import Generic, Optional, TypeVar
from pydantic import BaseModel
T = TypeVar('T')
class MyGenericModel(BaseModel, Generic[T]):
foobar: Optional[list['MyGenericModel[T]']]
spam: T
MyGenericModel = module.MyGenericModel
instance = MyGenericModel[int](foobar=[{'foobar': [], 'spam': 1}], spam=1)
assert type(instance.foobar[0]) == MyGenericModel[int]
def test_generic_enum():
T = TypeVar('T')
class SomeGenericModel(BaseModel, Generic[T]):
some_field: T
class SomeStringEnum(str, Enum):
A = 'A'
B = 'B'
class MyModel(BaseModel):
my_gen: SomeGenericModel[SomeStringEnum]
m = MyModel.model_validate({'my_gen': {'some_field': 'A'}})
assert m.my_gen.some_field is SomeStringEnum.A
def test_generic_literal():
FieldType = TypeVar('FieldType')
ValueType = TypeVar('ValueType')
class GModel(BaseModel, Generic[FieldType, ValueType]):
field: dict[FieldType, ValueType]
Fields = Literal['foo', 'bar']
m = GModel[Fields, str](field={'foo': 'x'})
assert m.model_dump() == {'field': {'foo': 'x'}}
def test_generic_enums():
T = TypeVar('T')
class GModel(BaseModel, Generic[T]):
x: T
class EnumA(str, Enum):
a = 'a'
class EnumB(str, Enum):
b = 'b'
class Model(BaseModel):
g_a: GModel[EnumA]
g_b: GModel[EnumB]
assert set(Model.model_json_schema()['$defs']) == {'EnumA', 'EnumB', 'GModel_EnumA_', 'GModel_EnumB_'}
def test_generic_with_user_defined_generic_field():
T = TypeVar('T')
class GenericList(list[T]):
@classmethod
def __get_pydantic_core_schema__(cls, source_type: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
return core_schema.no_info_after_validator_function(GenericList, handler(list[get_args(source_type)[0]]))
class Model(BaseModel, Generic[T]):
field: GenericList[T]
model = Model[int](field=[5])
assert model.field[0] == 5
with pytest.raises(ValidationError):
model = Model[int](field=['a'])
def test_generic_annotated():
T = TypeVar('T')
class SomeGenericModel(BaseModel, Generic[T]):
some_field: Annotated[T, Field(alias='the_alias')]
SomeGenericModel[str](the_alias='qwe')
def test_generic_subclass():
T = TypeVar('T')
class A(BaseModel, Generic[T]): ...
class B(A[T], Generic[T]): ...
class C(B[T], Generic[T]): ...
assert B[int].__name__ == 'B[int]'
assert issubclass(B[int], B)
assert issubclass(B[int], A)
assert not issubclass(B[int], C)
def test_generic_subclass_with_partial_application():
T = TypeVar('T')
S = TypeVar('S')
class A(BaseModel, Generic[T]): ...
class B(A[S], Generic[T, S]): ...
PartiallyAppliedB = B[str, T]
assert issubclass(PartiallyAppliedB[int], A)
def test_multilevel_generic_binding():
T = TypeVar('T')
S = TypeVar('S')
class A(BaseModel, Generic[T, S]): ...
class B(A[str, T], Generic[T]): ...
assert B[int].__name__ == 'B[int]'
assert issubclass(B[int], A)
def test_generic_subclass_with_extra_type():
T = TypeVar('T')
S = TypeVar('S')
class A(BaseModel, Generic[T]): ...
class B(A[S], Generic[T, S]): ...
assert B[int, str].__name__ == 'B[int, str]', B[int, str].__name__
assert issubclass(B[str, int], B)
assert issubclass(B[str, int], A)
def test_generic_subclass_with_extra_type_requires_all_params():
T = TypeVar('T')
S = TypeVar('S')
class A(BaseModel, Generic[T]): ...
with pytest.raises(
TypeError,
match=re.escape(
'All parameters must be present on typing.Generic; you should inherit from typing.Generic[~T, ~S]'
),
):
class B(A[T], Generic[S]): ...
def test_generic_subclass_with_extra_type_with_hint_message():
E = TypeVar('E', bound=BaseModel)
D = TypeVar('D')
with pytest.warns(
GenericBeforeBaseModelWarning,
match='Classes should inherit from `BaseModel` before generic classes',
):
class BaseGenericClass(Generic[E, D], BaseModel):
uid: str
name: str
with pytest.raises(
TypeError,
match=re.escape(
'All parameters must be present on typing.Generic; you should inherit from typing.Generic[~E, ~D].'
' Note: `typing.Generic` must go last:'
' `class ChildGenericClass(BaseGenericClass, typing.Generic[~E, ~D]): ...`'
),
):
with pytest.warns(
GenericBeforeBaseModelWarning,
match='Classes should inherit from `BaseModel` before generic classes',
):
class ChildGenericClass(BaseGenericClass[E, dict[str, Any]]): ...
def test_multi_inheritance_generic_binding():
T = TypeVar('T')
class A(BaseModel, Generic[T]): ...
class B(A[int], Generic[T]): ...
class C(B[str], Generic[T]): ...
assert C[float].__name__ == 'C[float]'
assert issubclass(C[float], B)
assert issubclass(C[float], A)
assert not issubclass(B[float], C)
def test_parent_field_parametrization():
T = TypeVar('T')
class A(BaseModel, Generic[T]):
a: T
class B(A, Generic[T]):
b: T
with pytest.raises(ValidationError) as exc_info:
B[int](a='a', b=1)
assert exc_info.value.errors(include_url=False) == [
{
'input': 'a',
'loc': ('a',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'type': 'int_parsing',
}
]
def test_multi_inheritance_generic_defaults():
T = TypeVar('T')
class A(BaseModel, Generic[T]):
a: T
x: str = 'a'
class B(A[int], Generic[T]):
b: Optional[T] = None
y: str = 'b'
class C(B[str], Generic[T]):
c: T
z: str = 'c'
assert C(a=1, c=...).model_dump() == {'a': 1, 'b': None, 'c': ..., 'x': 'a', 'y': 'b', 'z': 'c'}
def test_parse_generic_json():
T = TypeVar('T')
class MessageWrapper(BaseModel, Generic[T]):
message: Json[T]
class Payload(BaseModel):
payload_field: str
raw = json.dumps({'payload_field': 'payload'})
record = MessageWrapper[Payload](message=raw)
assert isinstance(record.message, Payload)
validation_schema = record.model_json_schema(mode='validation')
assert validation_schema == {
'$defs': {
'Payload': {
'properties': {'payload_field': {'title': 'Payload Field', 'type': 'string'}},
'required': ['payload_field'],
'title': 'Payload',
'type': 'object',
}
},
'properties': {
'message': {
'contentMediaType': 'application/json',
'contentSchema': {'$ref': '#/$defs/Payload'},
'title': 'Message',
'type': 'string',
}
},
'required': ['message'],
'title': 'MessageWrapper[test_parse_generic_json.<locals>.Payload]',
'type': 'object',
}
serialization_schema = record.model_json_schema(mode='serialization')
assert serialization_schema == {
'$defs': {
'Payload': {
'properties': {'payload_field': {'title': 'Payload Field', 'type': 'string'}},
'required': ['payload_field'],
'title': 'Payload',
'type': 'object',
}
},
'properties': {'message': {'$ref': '#/$defs/Payload', 'title': 'Message'}},
'required': ['message'],
'title': 'MessageWrapper[test_parse_generic_json.<locals>.Payload]',
'type': 'object',
}
def memray_limit_memory(limit):
if '--memray' in sys.argv:
return pytest.mark.limit_memory(limit)
else:
return pytest.mark.skip(reason='memray not enabled')
@memray_limit_memory('100 MB')
def test_generics_memory_use():
"""See:
- https://github.com/pydantic/pydantic/issues/3829
- https://github.com/pydantic/pydantic/pull/4083
- https://github.com/pydantic/pydantic/pull/5052
"""
T = TypeVar('T')
U = TypeVar('U')
V = TypeVar('V')
class MyModel(BaseModel, Generic[T, U, V]):
message: Json[T]
field: dict[U, V]
class Outer(BaseModel, Generic[T]):
inner: T
types = [
int,
str,
float,
bool,
bytes,
]
containers = [
list,
tuple,
set,
frozenset,
]
all = [*types, *[container[tp] for container in containers for tp in types]]
total = list(itertools.product(all, all, all))
for t1, t2, t3 in total:
class Foo(MyModel[t1, t2, t3]):
pass
class _(Outer[Foo]):
pass
@pytest.mark.skipif(
sys.version_info < (3, 11), reason='list implementation is inconsistent between python versions here'
)
@pytest.mark.xfail(reason='Generic models are not type aliases', raises=TypeError)
def test_generic_model_as_parameter_to_generic_type_alias() -> None:
T = TypeVar('T')
class GenericPydanticModel(BaseModel, Generic[T]):
x: T
GenericPydanticModelList = list[GenericPydanticModel[T]]
GenericPydanticModelList[int]
def test_double_typevar_substitution() -> None:
T = TypeVar('T')
class GenericPydanticModel(BaseModel, Generic[T]):
x: T = []
assert GenericPydanticModel[list[T]](x=[1, 2, 3]).model_dump() == {'x': [1, 2, 3]}
@pytest.fixture(autouse=True)
def ensure_contextvar_gets_reset():
# Ensure that the generic recursion contextvar is empty at the start of every test
assert not recursively_defined_type_refs()
def test_generic_recursion_contextvar():
T = TypeVar('T')
class TestingException(Exception):
pass
class Model(BaseModel, Generic[T]):
pass
# Make sure that the contextvar-managed recursive types cache begins empty
assert not recursively_defined_type_refs()
try:
with generic_recursion_self_type(Model, (int,)):
# Make sure that something has been added to the contextvar-managed recursive types cache
assert recursively_defined_type_refs()
raise TestingException
except TestingException:
pass
# Make sure that an exception causes the contextvar-managed recursive types cache to be reset
assert not recursively_defined_type_refs()
def test_limited_dict():
d = LimitedDict(10)
d[1] = '1'
d[2] = '2'
assert list(d.items()) == [(1, '1'), (2, '2')]
for no in '34567890':
d[int(no)] = no
assert list(d.items()) == [
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
(5, '5'),
(6, '6'),
(7, '7'),
(8, '8'),
(9, '9'),
(0, '0'),
]
d[11] = '11'
# reduce size to 9 after setting 11
assert len(d) == 9
assert list(d.items()) == [
(3, '3'),
(4, '4'),
(5, '5'),
(6, '6'),
(7, '7'),
(8, '8'),
(9, '9'),
(0, '0'),
(11, '11'),
]
d[12] = '12'
assert len(d) == 10
d[13] = '13'
assert len(d) == 9
def test_construct_generic_model_with_validation():
T = TypeVar('T')
class Page(BaseModel, Generic[T]):
page: int = Field(ge=42)
items: Sequence[T]
unenforced: PositiveInt = Field(lt=10)
with pytest.raises(ValidationError) as exc_info:
Page[int](page=41, items=[], unenforced=11)
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'ge': 42},
'input': 41,
'loc': ('page',),
'msg': 'Input should be greater than or equal to 42',
'type': 'greater_than_equal',
},
{
'ctx': {'lt': 10},
'input': 11,
'loc': ('unenforced',),
'msg': 'Input should be less than 10',
'type': 'less_than',
},
]
def test_construct_other_generic_model_with_validation():
# based on the test-case from https://github.com/samuelcolvin/pydantic/issues/2581
T = TypeVar('T')
class Page(BaseModel, Generic[T]):
page: int = Field(ge=42)
items: Sequence[T]
# Check we can perform this assignment, this is the actual test
concrete_model = Page[str]
print(concrete_model)
assert concrete_model.__name__ == 'Page[str]'
# Sanity check the resulting type works as expected
valid = concrete_model(page=42, items=[])
assert valid.page == 42
with pytest.raises(ValidationError) as exc_info:
concrete_model(page=41, items=[])
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'ge': 42},
'input': 41,
'loc': ('page',),
'msg': 'Input should be greater than or equal to 42',
'type': 'greater_than_equal',
}
]
def test_generic_enum_bound():
T = TypeVar('T', bound=Enum)
class MyEnum(Enum):
a = 1
class OtherEnum(Enum):
b = 2
class Model(BaseModel, Generic[T]):
x: T
m = Model(x=MyEnum.a)
assert m.x == MyEnum.a
with pytest.raises(ValidationError) as exc_info:
Model(x=1)
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'class': 'Enum'},
'input': 1,
'loc': ('x',),
'msg': 'Input should be an instance of Enum',
'type': 'is_instance_of',
}
]
m2 = Model[MyEnum](x=MyEnum.a)
assert m2.x == MyEnum.a
with pytest.raises(ValidationError) as exc_info:
Model[MyEnum](x=OtherEnum.b)
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'expected': '1'},
'input': OtherEnum.b,
'loc': ('x',),
'msg': 'Input should be 1',
'type': 'enum',
}
]
# insert_assert(Model[MyEnum].model_json_schema())
assert Model[MyEnum].model_json_schema() == {
'$defs': {'MyEnum': {'enum': [1], 'title': 'MyEnum', 'type': 'integer'}},
'properties': {'x': {'$ref': '#/$defs/MyEnum'}},
'required': ['x'],
'title': 'Model[test_generic_enum_bound.<locals>.MyEnum]',
'type': 'object',
}
def test_generic_intenum_bound():
T = TypeVar('T', bound=IntEnum)
class MyEnum(IntEnum):
a = 1
class OtherEnum(IntEnum):
b = 2
class Model(BaseModel, Generic[T]):
x: T
m = Model(x=MyEnum.a)
assert m.x == MyEnum.a
with pytest.raises(ValidationError) as exc_info:
Model(x=1)
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'class': 'IntEnum'},
'input': 1,
'loc': ('x',),
'msg': 'Input should be an instance of IntEnum',
'type': 'is_instance_of',
}
]
m2 = Model[MyEnum](x=MyEnum.a)
assert m2.x == MyEnum.a
with pytest.raises(ValidationError) as exc_info:
Model[MyEnum](x=OtherEnum.b)
assert exc_info.value.errors(include_url=False) == [
{
'ctx': {'expected': '1'},
'input': 2,
'loc': ('x',),
'msg': 'Input should be 1',
'type': 'enum',
}
]
# insert_assert(Model[MyEnum].model_json_schema())
assert Model[MyEnum].model_json_schema() == {
'$defs': {'MyEnum': {'enum': [1], 'title': 'MyEnum', 'type': 'integer'}},
'properties': {'x': {'$ref': '#/$defs/MyEnum'}},
'required': ['x'],
'title': 'Model[test_generic_intenum_bound.<locals>.MyEnum]',
'type': 'object',
}
@pytest.mark.skipif(sys.version_info < (3, 11), reason='requires python 3.11 or higher')
@pytest.mark.xfail(
reason='TODO: Variadic generic parametrization is not supported yet;'
' Issue: https://github.com/pydantic/pydantic/issues/5804'
)
def test_variadic_generic_init():
class ComponentModel(BaseModel):
pass
class Wrench(ComponentModel):
pass
class Screwdriver(ComponentModel):
pass
ComponentVar = TypeVar('ComponentVar', bound=ComponentModel)
NumberOfComponents = TypeVarTuple('NumberOfComponents')
class VariadicToolbox(BaseModel, Generic[ComponentVar, Unpack[NumberOfComponents]]):
main_component: ComponentVar
left_component_pocket: Optional[list[ComponentVar]] = Field(default_factory=list)
right_component_pocket: Optional[list[ComponentVar]] = Field(default_factory=list)
@computed_field
@property
def all_components(self) -> tuple[ComponentVar, Unpack[NumberOfComponents]]:
return (self.main_component, *self.left_component_pocket, *self.right_component_pocket)
sa, sb, w = Screwdriver(), Screwdriver(), Wrench()
my_toolbox = VariadicToolbox[Screwdriver, Screwdriver, Wrench](
main_component=sa, left_component_pocket=[w], right_component_pocket=[sb]
)
assert my_toolbox.all_components == [sa, w, sb]
@pytest.mark.skipif(sys.version_info < (3, 11), reason='requires python 3.11 or higher')
@pytest.mark.xfail(
reason='TODO: Variadic fields are not supported yet; Issue: https://github.com/pydantic/pydantic/issues/5804'
)
def test_variadic_generic_with_variadic_fields():
class ComponentModel(BaseModel):
pass
class Wrench(ComponentModel):
pass
class Screwdriver(ComponentModel):
pass
ComponentVar = TypeVar('ComponentVar', bound=ComponentModel)
NumberOfComponents = TypeVarTuple('NumberOfComponents')
class VariadicToolbox(BaseModel, Generic[ComponentVar, Unpack[NumberOfComponents]]):
toolbelt_cm_size: Optional[tuple[Unpack[NumberOfComponents]]] = Field(default_factory=tuple)
manual_toolset: Optional[tuple[ComponentVar, Unpack[NumberOfComponents]]] = Field(default_factory=tuple)
MyToolboxClass = VariadicToolbox[Screwdriver, Screwdriver, Wrench]
sa, sb, w = Screwdriver(), Screwdriver(), Wrench()
MyToolboxClass(toolbelt_cm_size=(5, 10.5, 4), manual_toolset=(sa, sb, w))
with pytest.raises(TypeError):
# Should raise error because integer 5 does not meet the bound requirements of ComponentVar
MyToolboxClass(manual_toolset=(sa, sb, 5))
@pytest.mark.skipif(
sys.version_info < (3, 11),
reason=(
'Multiple inheritance with NamedTuple and the corresponding type annotations'
" aren't supported before Python 3.11"
),
)
def test_generic_namedtuple():
T = TypeVar('T')
class FlaggedValue(NamedTuple, Generic[T]):
value: T
flag: bool
class Model(BaseModel):
f_value: FlaggedValue[float]
assert Model(f_value=(1, True)).model_dump() == {'f_value': (1, True)}
with pytest.raises(ValidationError):
Model(f_value=(1, 'abc'))
with pytest.raises(ValidationError):
Model(f_value=('abc', True))
def test_generic_none():
T = TypeVar('T')
class Container(BaseModel, Generic[T]):
value: T
assert Container[type(None)](value=None).value is None
assert Container[None](value=None).value is None
@pytest.mark.skipif(platform.python_implementation() == 'PyPy', reason='PyPy does not allow ParamSpec in generics')
def test_paramspec_is_usable():
# This used to cause a recursion error due to `P in P is True`
# This test doesn't actually test that ParamSpec works properly for validation or anything.
P = ParamSpec('P')
class MyGenericParamSpecClass(Generic[P]):
def __init__(self, func: Callable[P, None], *args: P.args, **kwargs: P.kwargs) -> None:
super().__init__()
class ParamSpecGenericModel(BaseModel, Generic[P]):
my_generic: MyGenericParamSpecClass[P]
model_config = dict(arbitrary_types_allowed=True)
def test_parametrize_with_basemodel():
T = TypeVar('T')
class SimpleGenericModel(BaseModel, Generic[T]):
pass
class Concrete(SimpleGenericModel[BaseModel]):
pass
def test_no_generic_base():
T = TypeVar('T')
class A(BaseModel, Generic[T]):
a: T
class B(A[T]):
b: T
class C(B[int]):
pass
assert C(a='1', b='2').model_dump() == {'a': 1, 'b': 2}
with pytest.raises(ValidationError) as exc_info:
C(a='a', b='b')
assert exc_info.value.errors(include_url=False) == [
{
'input': 'a',
'loc': ('a',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'type': 'int_parsing',
},
{
'input': 'b',
'loc': ('b',),
'msg': 'Input should be a valid integer, unable to parse string as an integer',
'type': 'int_parsing',
},
]
def test_reverse_order_generic_hashability():
T = TypeVar('T')
with pytest.warns(
GenericBeforeBaseModelWarning,
match='Classes should inherit from `BaseModel` before generic classes',
):
class Model(Generic[T], BaseModel):
x: T
model_config = dict(frozen=True)
m1 = Model[int](x=1)
m2 = Model[int](x=1)
assert len({m1, m2}) == 1
def test_serialize_unsubstituted_typevars_bound() -> None:
class ErrorDetails(BaseModel):
foo: str
# This version of `TypeVar` does not support `default` on Python <3.12
ErrorDataT = TypeVar('ErrorDataT', bound=ErrorDetails)
class Error(BaseModel, Generic[ErrorDataT]):
message: str
details: ErrorDataT
class MyErrorDetails(ErrorDetails):
bar: str
sample_error = Error(
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'foo': 'var',
'bar': 'baz',
},
}
sample_error = Error[ErrorDetails](
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'foo': 'var',
},
}
sample_error = Error[MyErrorDetails](
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'foo': 'var',
'bar': 'baz',
},
}
def test_serialize_unsubstituted_typevars_bound_default_supported() -> None:
class ErrorDetails(BaseModel):
foo: str
# This version of `TypeVar` always support `default`
ErrorDataT = TypingExtensionsTypeVar('ErrorDataT', bound=ErrorDetails)
class Error(BaseModel, Generic[ErrorDataT]):
message: str
details: ErrorDataT
class MyErrorDetails(ErrorDetails):
bar: str
sample_error = Error(
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'foo': 'var',
'bar': 'baz',
},
}
sample_error = Error[ErrorDetails](
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'foo': 'var',
},
}
sample_error = Error[MyErrorDetails](
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'foo': 'var',
'bar': 'baz',
},
}
@pytest.mark.parametrize(
'type_var',
[
TypingExtensionsTypeVar('ErrorDataT', default=BaseModel),
TypeVar('ErrorDataT', BaseModel, str),
],
ids=['default', 'constraint'],
)
def test_serialize_unsubstituted_typevars_variants(
type_var: TypeVar,
) -> None:
class ErrorDetails(BaseModel):
foo: str
class Error(BaseModel, Generic[type_var]): # type: ignore
message: str
details: type_var
class MyErrorDetails(ErrorDetails):
bar: str
sample_error = Error(
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {},
}
sample_error = Error[ErrorDetails](
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'foo': 'var',
},
}
sample_error = Error[MyErrorDetails](
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'foo': 'var',
'bar': 'baz',
},
}
def test_serialize_typevars_default_and_bound_with_user_model() -> None:
class MyErrorDetails(BaseModel):
bar: str
class ExtendedMyErrorDetails(MyErrorDetails):
foo: str
class MoreExtendedMyErrorDetails(ExtendedMyErrorDetails):
suu: str
T = TypingExtensionsTypeVar('T', bound=MyErrorDetails, default=ExtendedMyErrorDetails)
class Error(BaseModel, Generic[T]):
message: str
details: T
# bound small parent model
sample_error = Error[MyErrorDetails](
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz', suu='suu'),
)
assert sample_error.details.model_dump() == {
'bar': 'baz',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'bar': 'baz',
},
}
# default middle child model
sample_error = Error(
message='We just had an error',
details=MoreExtendedMyErrorDetails(foo='var', bar='baz', suu='suu'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
'suu': 'suu',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {'foo': 'var', 'bar': 'baz'},
}
# bound big child model
sample_error = Error[MoreExtendedMyErrorDetails](
message='We just had an error',
details=MoreExtendedMyErrorDetails(foo='var', bar='baz', suu='suu'),
)
assert sample_error.details.model_dump() == {
'foo': 'var',
'bar': 'baz',
'suu': 'suu',
}
assert sample_error.model_dump() == {
'message': 'We just had an error',
'details': {
'foo': 'var',
'bar': 'baz',
'suu': 'suu',
},
}
def test_typevars_default_model_validation_error() -> None:
class MyErrorDetails(BaseModel):
bar: str
class ExtendedMyErrorDetails(MyErrorDetails):
foo: str
T = TypingExtensionsTypeVar('T', bound=MyErrorDetails, default=ExtendedMyErrorDetails)
class Error(BaseModel, Generic[T]):
message: str
details: T
with pytest.raises(ValidationError):
Error(
message='We just had an error',
details=MyErrorDetails(foo='var', bar='baz'),
)
def test_generic_with_not_required_in_typed_dict() -> None:
T = TypingExtensionsTypeVar('T')
class FooStr(TypedDict):
type: NotRequired[str]
class FooGeneric(TypedDict, Generic[T]):
type: NotRequired[T]
ta_foo_str = TypeAdapter(FooStr)
assert ta_foo_str.validate_python({'type': 'tomato'}) == {'type': 'tomato'}
assert ta_foo_str.validate_python({}) == {}
ta_foo_generic = TypeAdapter(FooGeneric[str])
assert ta_foo_generic.validate_python({'type': 'tomato'}) == {'type': 'tomato'}
assert ta_foo_generic.validate_python({}) == {}
def test_generic_with_allow_extra():
T = TypeVar('T')
# This used to raise an error related to accessing the __annotations__ attribute of the Generic class
class AllowExtraGeneric(BaseModel, Generic[T], extra='allow'):
data: T
def test_generic_field():
"""Test for https://github.com/pydantic/pydantic/issues/10039.
This was originally fixed by defining a custom MRO for Pydantic models,
but the fix from https://github.com/pydantic/pydantic/pull/10666 seemed
better. Test is still kept for historical purposes.
"""
T = TypeVar('T')
class A(BaseModel, Generic[T]): ...
class B(A[T]): ...
class C(B[bool]): ...
class Model(BaseModel):
input_bool: A[bool]
Model(input_bool=C())
def test_generic_any_or_never() -> None:
T = TypeVar('T')
class GenericModel(BaseModel, Generic[T]):
f: Union[T, int]
any_json_schema = GenericModel[Any].model_json_schema()
assert any_json_schema['properties']['f'] == {'title': 'F'} # any type
never_json_schema = GenericModel[Never].model_json_schema()
assert never_json_schema['properties']['f'] == {'type': 'integer', 'title': 'F'}
def test_revalidation_against_any() -> None:
T = TypeVar('T')
class ResponseModel(BaseModel, Generic[T]):
content: T
class Product(BaseModel):
name: str
price: float
class Order(BaseModel):
id: int
product: ResponseModel[Any]
product = Product(name='Apple', price=0.5)
response1: ResponseModel[Any] = ResponseModel[Any](content=product)
response2: ResponseModel[Any] = ResponseModel(content=product)
response3: ResponseModel[Any] = ResponseModel[Product](content=product)
for response in response1, response2, response3:
order = Order(id=1, product=response)
assert isinstance(order.product.content, Product)
def test_revalidation_without_explicit_parametrization() -> None:
"""Note, this is seen in the test above as well, but is added here for thoroughness."""
T1 = TypeVar('T1', bound=BaseModel)
class InnerModel(BaseModel, Generic[T1]):
model: T1
T2 = TypeVar('T2', bound=InnerModel)
class OuterModel(BaseModel, Generic[T2]):
inner: T2
class MyModel(BaseModel):
foo: int
# Construct two instances, with and without generic annotation in the constructor:
inner1 = InnerModel[MyModel](model=MyModel(foo=42))
inner2 = InnerModel(model=MyModel(foo=42))
assert inner1 == inner2
outer1 = OuterModel[InnerModel[MyModel]](inner=inner1)
outer2 = OuterModel[InnerModel[MyModel]](inner=inner2)
# implies that validation succeeds for both
assert outer1 == outer2
def test_revalidation_with_basic_inference() -> None:
T = TypeVar('T')
class Inner(BaseModel, Generic[T]):
inner: T
class Holder(BaseModel, Generic[T]):
inner: Inner[T]
holder1 = Holder[int](inner=Inner[int](inner=1))
holder2 = Holder(inner=Inner(inner=1))
# implies that validation succeeds for both
assert holder1 == holder2
|