1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575
|
from __future__ import annotations
import base64
import collections
import datetime
import decimal
import enum
import gc
import sys
import typing
import uuid
import weakref
from collections import namedtuple
from dataclasses import dataclass, field, make_dataclass
from datetime import timedelta
from typing import (
Annotated,
ClassVar,
Deque,
Dict,
Final,
Generic,
List,
Literal,
NamedTuple,
NewType,
Optional,
Tuple,
TypedDict,
TypeVar,
Union,
)
import pytest
from .utils import max_call_depth, temp_module
try:
import attrs
except ImportError:
attrs = None
import msgspec
from msgspec import UNSET, Meta, Struct, UnsetType, ValidationError
UTC = datetime.timezone.utc
PY310 = sys.version_info[:2] >= (3, 10)
PY311 = sys.version_info[:2] >= (3, 11)
PY312 = sys.version_info[:2] >= (3, 12)
py310_plus = pytest.mark.skipif(not PY310, reason="3.10+ only")
py311_plus = pytest.mark.skipif(not PY311, reason="3.11+ only")
py312_plus = pytest.mark.skipif(not PY312, reason="3.12+ only")
T = TypeVar("T")
def assert_eq(x, y):
assert x == y
assert type(x) is type(y)
@pytest.fixture(params=["json", "msgpack"])
def proto(request):
if request.param == "json":
return msgspec.json
elif request.param == "msgpack":
return msgspec.msgpack
try:
from enum import StrEnum
except ImportError:
class StrEnum(str, enum.Enum):
pass
class FruitInt(enum.IntEnum):
APPLE = 1
BANANA = 2
class FruitStr(enum.Enum):
APPLE = "apple"
BANANA = "banana"
class VeggieInt(enum.IntEnum):
CARROT = 1
LETTUCE = 2
class VeggieStr(enum.Enum):
CARROT = "carrot"
LETTUCE = "banana"
class Person(Struct):
first: str
last: str
age: int
class PersonArray(Struct, array_like=True):
first: str
last: str
age: int
class PersonDict(TypedDict):
first: str
last: str
age: int
@dataclass
class PersonDataclass:
first: str
last: str
age: int
class PersonTuple(NamedTuple):
first: str
last: str
age: int
class Custom:
def __init__(self, x, y):
self.x = x
self.y = y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
class TestEncodeSubclasses:
def test_encode_dict_subclass(self, proto):
class subclass(dict):
pass
for msg in [{}, {"a": 1, "b": 2}]:
assert proto.encode(subclass(msg)) == proto.encode(msg)
@pytest.mark.parametrize("cls", [list, tuple, set, frozenset])
def test_encode_sequence_subclass(self, cls, proto):
class subclass(cls):
pass
for msg in [[], [1, 2]]:
assert proto.encode(subclass(msg)) == proto.encode(cls(msg))
class TestDecoder:
def test_decoder_runtime_type_parameters(self, proto):
dec = proto.Decoder[int](int)
assert isinstance(dec, proto.Decoder)
msg = proto.encode(2)
assert dec.decode(msg) == 2
def test_decoder_dec_hook_attribute(self, proto):
def dec_hook(typ, obj):
pass
dec = proto.Decoder()
assert dec.dec_hook is None
dec = proto.Decoder(dec_hook=None)
assert dec.dec_hook is None
dec = proto.Decoder(dec_hook=dec_hook)
assert dec.dec_hook is dec_hook
def test_decoder_dec_hook_not_callable(self, proto):
with pytest.raises(TypeError):
proto.Decoder(dec_hook=1)
def test_decode_dec_hook(self, proto):
def dec_hook(typ, obj):
assert typ is Custom
return typ(*obj)
msg = proto.encode([1, 2])
res = proto.decode(msg, type=Custom, dec_hook=dec_hook)
assert res == Custom(1, 2)
assert isinstance(res, Custom)
def test_decoder_dec_hook(self, proto):
called = False
def dec_hook(typ, obj):
nonlocal called
called = True
assert typ is Custom
return Custom(*obj)
dec = proto.Decoder(type=List[Custom], dec_hook=dec_hook)
buf = proto.encode([[1, 2], [3, 4], [5, 6]])
msg = dec.decode(buf)
assert called
assert msg == [Custom(1, 2), Custom(3, 4), Custom(5, 6)]
assert isinstance(msg[0], Custom)
def test_decoder_dec_hook_optional_custom_type(self, proto):
called = False
def dec_hook(typ, obj):
nonlocal called
called = True
dec = proto.Decoder(type=Optional[Custom], dec_hook=dec_hook)
msg = dec.decode(proto.encode(None))
assert not called
assert msg is None
@pytest.mark.parametrize("err_cls", [TypeError, ValueError])
def test_decode_dec_hook_errors_wrapped(self, err_cls, proto):
def dec_hook(typ, obj):
assert obj == "some string"
raise err_cls("Oh no!")
msg = proto.encode("some string")
with pytest.raises(msgspec.ValidationError, match="Oh no!") as rec:
proto.decode(msg, type=Custom, dec_hook=dec_hook)
assert rec.value.__cause__ is rec.value.__context__
assert type(rec.value.__cause__) is err_cls
msg = proto.encode(["some string"])
with pytest.raises(msgspec.ValidationError, match=r"Oh no! - at `\$\[0\]`"):
proto.decode(msg, type=List[Custom], dec_hook=dec_hook)
def test_decode_dec_hook_errors_passthrough(self, proto):
def dec_hook(typ, obj):
assert obj == "some string"
raise NotImplementedError("Oh no!")
msg = proto.encode("some string")
with pytest.raises(NotImplementedError, match="Oh no!"):
proto.decode(msg, type=Custom, dec_hook=dec_hook)
msg = proto.encode(["some string"])
with pytest.raises(NotImplementedError, match=r"Oh no!"):
proto.decode(msg, type=List[Custom], dec_hook=dec_hook)
def test_decode_dec_hook_wrong_type(self, proto):
dec = proto.Decoder(type=Custom, dec_hook=lambda t, o: o)
msg = proto.encode([1, 2])
with pytest.raises(
msgspec.ValidationError,
match="Expected `Custom`, got `list`",
):
dec.decode(msg)
def test_decode_dec_hook_wrong_type_in_struct(self, proto):
class Test(Struct):
point: Custom
other: int
dec = proto.Decoder(type=Test, dec_hook=lambda t, o: o)
msg = proto.encode({"point": [1, 2], "other": 3})
with pytest.raises(msgspec.ValidationError) as rec:
dec.decode(msg)
assert "Expected `Custom`, got `list` - at `$.point`" == str(rec.value)
def test_decode_dec_hook_wrong_type_generic(self, proto):
dec = proto.Decoder(type=Deque[int], dec_hook=lambda t, o: o)
msg = proto.encode([1, 2, 3])
with pytest.raises(msgspec.ValidationError) as rec:
dec.decode(msg)
assert "Expected `collections.deque`, got `list`" == str(rec.value)
def test_decode_dec_hook_isinstance_errors(self, proto):
class Metaclass(type):
def __instancecheck__(self, obj):
raise TypeError("Oh no!")
class Custom(metaclass=Metaclass):
pass
dec = proto.Decoder(type=Custom)
msg = proto.encode(1)
with pytest.raises(TypeError, match="Oh no!"):
dec.decode(msg)
@pytest.mark.skipif(
PY312,
reason=(
"Python 3.12 harcodes the C recursion limit, making this "
"behavior harder to test in CI"
),
)
class TestRecursion:
@staticmethod
def nested(n, is_array):
if is_array:
obj = []
for _ in range(n):
obj = [obj]
else:
obj = {}
for _ in range(n):
obj = {"": obj}
return obj
@pytest.mark.parametrize("is_array", [True, False])
def test_encode_highly_recursive_msg_errors(self, is_array, proto):
N = 200
obj = self.nested(N, is_array)
# Errors if above the recursion limit
with max_call_depth(N // 2):
with pytest.raises(RecursionError):
proto.encode(obj)
# Works if below the recursion limit
with max_call_depth(N * 2):
proto.encode(obj)
@pytest.mark.parametrize("is_array", [True, False])
def test_decode_highly_recursive_msg_errors(self, is_array, proto):
"""Ensure recursion is properly handled when decoding.
Test case seen in https://github.com/ijl/orjson/issues/458."""
N = 200
obj = self.nested(N, is_array)
with max_call_depth(N * 2):
msg = proto.encode(obj)
# Errors if above the recursion limit
with max_call_depth(N // 2):
with pytest.raises(RecursionError):
proto.decode(msg)
# Works if below the recursion limit
with max_call_depth(N * 2):
obj2 = proto.decode(msg)
assert obj2
class TestThreadSafe:
def test_encode_threadsafe(self, proto):
class Nested:
def __init__(self, x):
self.x = x
def enc_hook(obj):
return base64.b64encode(enc.encode(obj.x)).decode("utf-8")
enc = proto.Encoder(enc_hook=enc_hook)
res = enc.encode({"x": Nested(1)})
sol = proto.encode({"x": base64.b64encode(proto.encode(1)).decode("utf-8")})
assert res == sol
def test_decode_threadsafe(self, proto):
class Custom:
def __init__(self, node):
self.node = node
def __eq__(self, other):
return type(other) is Custom and self.node == other.node
def dec_hook(typ, obj):
msg = base64.b64decode(obj)
return Custom(dec.decode(msg))
dec = proto.Decoder(Tuple[Union[Custom, None], int], dec_hook=dec_hook)
msg = proto.encode(
(base64.b64encode(proto.encode((None, 1))).decode("utf-8"), 2)
)
sol = (Custom((None, 1)), 2)
res = dec.decode(msg)
assert res == sol
class TestIntEnum:
def test_empty_errors(self, proto):
class Empty(enum.IntEnum):
pass
with pytest.raises(TypeError, match="Enum types must have at least one item"):
proto.Decoder(Empty)
@pytest.mark.parametrize("base_cls", [enum.IntEnum, enum.Enum])
def test_encode(self, proto, base_cls):
class Test(base_cls):
A = 1
B = 2
assert proto.encode(Test.A) == proto.encode(1)
@pytest.mark.parametrize("base_cls", [enum.IntEnum, enum.Enum])
def test_decode(self, proto, base_cls):
class Test(base_cls):
A = 1
B = 2
dec = proto.Decoder(Test)
assert dec.decode(proto.encode(1)) is Test.A
assert dec.decode(proto.encode(2)) is Test.B
with pytest.raises(ValidationError, match="Invalid enum value 3"):
dec.decode(proto.encode(3))
def test_decode_nested(self, proto):
class Test(Struct):
fruit: FruitInt
dec = proto.Decoder(Test)
dec.decode(proto.encode({"fruit": 1})) == Test(FruitInt.APPLE)
with pytest.raises(
ValidationError, match=r"Invalid enum value 3 - at `\$.fruit`"
):
dec.decode(proto.encode({"fruit": 3}))
def test_intenum_missing(self, proto):
class Ex(enum.IntEnum):
A = 1
B = 2
@classmethod
def _missing_(cls, val):
if val == 3:
return cls.A
elif val == -4:
return cls.B
elif val == 5:
raise ValueError("oh no!")
else:
return None
dec = proto.Decoder(Ex)
def roundtrip(msg):
return dec.decode(proto.encode(msg))
assert roundtrip(1) is Ex.A
assert roundtrip(3) is Ex.A
assert roundtrip(-4) is Ex.B
with pytest.raises(ValidationError, match="Invalid enum value 5"):
roundtrip(5)
with pytest.raises(ValidationError, match="Invalid enum value 6"):
roundtrip(6)
def test_intflag(self, proto):
class Ex(enum.IntFlag):
A = 0b001
B = 0b010
C = 0b100
obj = Ex.A | Ex.C
msg = proto.encode(obj)
assert msg == proto.encode(int(obj))
assert proto.decode(msg, type=Ex) == obj
def test_int_lookup_reused(self):
class Test(enum.IntEnum):
A = 1
B = 2
dec = msgspec.msgpack.Decoder(Test) # noqa
count = sys.getrefcount(Test.__msgspec_cache__)
dec2 = msgspec.msgpack.Decoder(Test)
count2 = sys.getrefcount(Test.__msgspec_cache__)
assert count2 == count + 1
# Reference count decreases when decoder is dropped
del dec2
gc.collect()
count3 = sys.getrefcount(Test.__msgspec_cache__)
assert count == count3
def test_int_lookup_gc(self):
class Test(enum.IntEnum):
A = 1
B = 2
dec = msgspec.msgpack.Decoder(Test)
assert gc.is_tracked(Test.__msgspec_cache__)
# Deleting all references and running GC cleans up cycle
ref = weakref.ref(Test)
del Test
del dec
gc.collect()
assert ref() is None
@pytest.mark.parametrize(
"values",
[
[0, 1, 2, -(2**63) - 1],
[0, 1, 2, 2**63],
],
)
def test_int_lookup_values_out_of_range(self, values):
myenum = enum.IntEnum("myenum", [(f"x{i}", v) for i, v in enumerate(values)])
with pytest.raises(NotImplementedError):
msgspec.msgpack.Decoder(myenum)
def test_msgspec_cache_overwritten(self):
class Test(enum.IntEnum):
A = 1
Test.__msgspec_cache__ = 1
with pytest.raises(RuntimeError, match="__msgspec_cache__"):
msgspec.msgpack.Decoder(Test)
@pytest.mark.parametrize(
"values",
[
[0],
[1],
[-1],
[3, 4, 5, 2, 1],
[4, 3, 1, 2, 7],
[-4, -3, -2, -1, 0, 1, 2, 3, 4],
[-4, -3, -1, -2, -7],
[-4, -3, 1, 0, -2, -1],
[2**63 - 1, 2**63 - 2, 2**63 - 3],
[-(2**63) + 1, -(2**63) + 2, -(2**63) + 3],
],
)
def test_compact(self, values):
myenum = enum.IntEnum("myenum", [(f"x{i}", v) for i, v in enumerate(values)])
dec = msgspec.msgpack.Decoder(myenum)
assert hasattr(myenum, "__msgspec_cache__")
for val in myenum:
msg = msgspec.msgpack.encode(val)
val2 = dec.decode(msg)
assert val == val2
for bad in [-1000, min(values) - 1, max(values) + 1, 1000]:
with pytest.raises(ValidationError):
dec.decode(msgspec.msgpack.encode(bad))
@pytest.mark.parametrize(
"values",
[
[-(2**63), 2**63 - 1, 0],
[2**63 - 2, 2**63 - 3, 2**63 - 1],
[2**63 - 2, 2**63 - 3, 2**63 - 1, 0, 2, 3, 4, 5, 6],
],
)
def test_hashtable(self, values):
myenum = enum.IntEnum("myenum", [(f"x{i}", v) for i, v in enumerate(values)])
dec = msgspec.msgpack.Decoder(myenum)
assert hasattr(myenum, "__msgspec_cache__")
for val in myenum:
msg = msgspec.msgpack.encode(val)
val2 = dec.decode(msg)
assert val == val2
for bad in [-2000, -1, 1, 2000]:
with pytest.raises(ValidationError):
dec.decode(msgspec.msgpack.encode(bad))
@pytest.mark.parametrize(
"values",
[
[8, 16, 24, 32, 40, 48],
[-8, -16, -24, -32, -40, -48],
],
)
def test_hashtable_collisions(self, values):
myenum = enum.IntEnum("myenum", [(f"x{i}", v) for i, v in enumerate(values)])
dec = msgspec.msgpack.Decoder(myenum)
for val in myenum:
msg = msgspec.msgpack.encode(val)
val2 = dec.decode(msg)
assert val == val2
for bad in [0, 7, 9, 56, -min(values), -max(values), 2**64 - 1, -(2**63)]:
with pytest.raises(ValidationError):
dec.decode(msgspec.msgpack.encode(bad))
class TestEnum:
def test_empty_errors(self, proto):
class Empty(enum.Enum):
pass
with pytest.raises(TypeError, match="Enum types must have at least one item"):
proto.Decoder(Empty)
def test_encode_complex(self, proto):
class Complex(enum.Enum):
A = 1.5
res = proto.encode(Complex.A)
sol = proto.encode(1.5)
assert res == sol
res = proto.encode({Complex.A: 1})
sol = proto.encode({1.5: 1})
assert res == sol
def test_decode_complex_errors(self, proto):
class Complex(enum.Enum):
A = 1.5
with pytest.raises(TypeError) as rec:
proto.Decoder(Complex)
assert "Enums must contain either all str or all int values" in str(rec.value)
assert repr(Complex) in str(rec.value)
@pytest.mark.parametrize(
"values",
[
[("A", 1), ("B", 2), ("C", "c")],
[("A", "a"), ("B", "b"), ("C", 3)],
],
)
def test_mixed_value_types_errors(self, values, proto):
Bad = enum.Enum("Bad", values)
with pytest.raises(TypeError) as rec:
proto.Decoder(Bad)
assert "Enums must contain either all str or all int values" in str(rec.value)
assert repr(Bad) in str(rec.value)
@pytest.mark.parametrize("base_cls", [StrEnum, enum.Enum])
def test_encode(self, proto, base_cls):
class Test(base_cls):
A = "apple"
B = "banana"
assert proto.encode(Test.A) == proto.encode("apple")
@pytest.mark.parametrize("base_cls", [StrEnum, enum.Enum])
def test_decode(self, proto, base_cls):
class Test(base_cls):
A = "apple"
B = "banana"
dec = proto.Decoder(Test)
assert dec.decode(proto.encode("apple")) is Test.A
assert dec.decode(proto.encode("banana")) is Test.B
with pytest.raises(ValidationError, match="Invalid enum value 'cherry'"):
dec.decode(proto.encode("cherry"))
def test_decode_nested(self, proto):
class Test(Struct):
fruit: FruitStr
dec = proto.Decoder(Test)
dec.decode(proto.encode({"fruit": "apple"})) == Test(FruitStr.APPLE)
with pytest.raises(
ValidationError,
match=r"Invalid enum value 'cherry' - at `\$.fruit`",
):
dec.decode(proto.encode({"fruit": "cherry"}))
def test_str_lookup_reused(self):
class Test(enum.Enum):
A = "a"
B = "b"
dec = msgspec.msgpack.Decoder(Test) # noqa
count = sys.getrefcount(Test.__msgspec_cache__)
dec2 = msgspec.msgpack.Decoder(Test)
count2 = sys.getrefcount(Test.__msgspec_cache__)
assert count2 == count + 1
# Reference count decreases when decoder is dropped
del dec2
gc.collect()
count3 = sys.getrefcount(Test.__msgspec_cache__)
assert count == count3
def test_str_lookup_gc(self):
class Test(enum.Enum):
A = "a"
B = "b"
dec = msgspec.msgpack.Decoder(Test)
assert gc.is_tracked(Test.__msgspec_cache__)
# Deleting all references and running GC cleans up cycle
ref = weakref.ref(Test)
del Test
del dec
gc.collect()
assert ref() is None
def test_msgspec_cache_overwritten(self):
class Test(enum.Enum):
A = 1
Test.__msgspec_cache__ = 1
with pytest.raises(RuntimeError, match="__msgspec_cache__"):
msgspec.msgpack.Decoder(Test)
@pytest.mark.parametrize("length", [2, 8, 16])
@pytest.mark.parametrize("nitems", [1, 3, 6, 12, 24, 48])
def test_random_enum_same_lengths(self, rand, length, nitems):
def strgen(length):
"""Yields unique random fixed-length strings"""
seen = set()
while True:
x = rand.str(length)
if x in seen:
continue
seen.add(x)
yield x
unique_str = strgen(length).__next__
myenum = enum.Enum(
"myenum", [(unique_str(), unique_str()) for _ in range(nitems)]
)
dec = msgspec.msgpack.Decoder(myenum)
for val in myenum:
msg = msgspec.msgpack.encode(val.value)
val2 = dec.decode(msg)
assert val == val2
for _ in range(10):
key = unique_str()
with pytest.raises(ValidationError):
dec.decode(msgspec.msgpack.encode(key))
# Try bad of different lengths
for bad_length in [1, 7, 15, 30]:
assert bad_length != length
key = rand.str(bad_length)
with pytest.raises(ValidationError):
dec.decode(msgspec.msgpack.encode(key))
@pytest.mark.parametrize("nitems", [1, 3, 6, 12, 24, 48])
def test_random_enum_different_lengths(self, rand, nitems):
def strgen():
"""Yields unique random strings"""
seen = set()
while True:
x = rand.str(1, 32)
if x in seen:
continue
seen.add(x)
yield x
unique_str = strgen().__next__
myenum = enum.Enum(
"myenum", [(unique_str(), unique_str()) for _ in range(nitems)]
)
dec = msgspec.msgpack.Decoder(myenum)
for val in myenum:
msg = msgspec.msgpack.encode(val.value)
val2 = dec.decode(msg)
assert val == val2
for _ in range(10):
key = unique_str()
with pytest.raises(ValidationError):
dec.decode(msgspec.msgpack.encode(key))
def test_enum_missing(self, proto):
class Ex(enum.Enum):
A = "a"
B = "b"
@classmethod
def _missing_(cls, val):
if val == "return-A":
return cls.A
elif val == "return-B":
return cls.B
elif val == "error":
raise ValueError("oh no!")
else:
return None
dec = proto.Decoder(Ex)
def roundtrip(msg):
return dec.decode(proto.encode(msg))
assert roundtrip("a") is Ex.A
assert roundtrip("return-A") is Ex.A
assert roundtrip("return-B") is Ex.B
with pytest.raises(ValidationError, match="Invalid enum value 'error'"):
roundtrip("error")
with pytest.raises(ValidationError, match="Invalid enum value 'other'"):
roundtrip("other")
class TestLiterals:
def test_empty_errors(self):
with pytest.raises(
TypeError, match="Literal types must have at least one item"
):
msgspec.msgpack.Decoder(Literal[()])
@pytest.mark.parametrize(
"values",
[
[0, 1, 2, 2**63],
[0, 1, 2, -(2**63) - 1],
],
)
def test_int_literal_values_out_of_range(self, values):
literal = Literal[tuple(values)]
with pytest.raises(NotImplementedError):
msgspec.msgpack.Decoder(literal)
@pytest.mark.parametrize(
"typ",
[
Literal[1, False],
Literal["ok", b"bad"],
Literal[1, object()],
Union[Literal[1, 2], Literal[3, False]],
Union[Literal["one", "two"], Literal[3, False]],
Literal[Literal[1, 2], Literal[3, False]],
Literal[Literal["one", "two"], Literal[3, False]],
Literal[1, 2, List[int]],
Literal[1, 2, List],
],
)
def test_invalid_values(self, typ):
with pytest.raises(TypeError, match="not supported"):
msgspec.msgpack.Decoder(typ)
def test_decode_literal_int_str_and_none_uncached_and_cached(self):
values = (45987, "an_unlikely_string", None)
literal = Literal[values]
assert not hasattr(literal, "__msgspec_cache__")
uncached = msgspec.msgpack.Decoder(literal)
assert hasattr(literal, "__msgspec_cache__")
cached = msgspec.msgpack.Decoder(literal)
for val in values:
assert uncached.decode(msgspec.msgpack.encode(val)) == val
assert cached.decode(msgspec.msgpack.encode(val)) == val
def test_cache_refcounts(self):
literal = Literal[1, 2, "three", "four"]
dec = msgspec.msgpack.Decoder(literal) # noqa
cache = literal.__msgspec_cache__
count = sys.getrefcount(cache)
dec2 = msgspec.msgpack.Decoder(literal)
assert sys.getrefcount(cache) == count
del dec2
gc.collect()
assert sys.getrefcount(cache) == count
@pytest.mark.parametrize("val", [None, (), (1,), (1, 2), (1, 2, 3)])
def test_msgspec_cache_overwritten(self, val):
literal = Literal["a", "highly", "improbable", "set", "of", "strings"]
literal.__msgspec_cache__ = val
with pytest.raises(RuntimeError, match="__msgspec_cache__"):
msgspec.msgpack.Decoder(literal)
def test_multiple_literals(self):
integers = Literal[-1, -2, -3]
strings = Literal["apple", "banana"]
both = Union[integers, strings]
dec = msgspec.msgpack.Decoder(both)
assert not hasattr(both, "__msgspec_cache__")
for val in [-1, -2, -3, "apple", "banana"]:
assert dec.decode(msgspec.msgpack.encode(val)) == val
with pytest.raises(ValidationError, match="Invalid enum value 4"):
dec.decode(msgspec.msgpack.encode(4))
with pytest.raises(ValidationError, match="Invalid enum value 'carrot'"):
dec.decode(msgspec.msgpack.encode("carrot"))
def test_nested_literals(self):
integers = Literal[-1, -2, -3]
strings = Literal["apple", "banana"]
both = Literal[integers, strings]
dec = msgspec.msgpack.Decoder(both)
assert hasattr(both, "__msgspec_cache__")
for val in [-1, -2, -3, "apple", "banana"]:
assert dec.decode(msgspec.msgpack.encode(val)) == val
with pytest.raises(ValidationError, match="Invalid enum value 4"):
dec.decode(msgspec.msgpack.encode(4))
with pytest.raises(ValidationError, match="Invalid enum value 'carrot'"):
dec.decode(msgspec.msgpack.encode("carrot"))
def test_mix_int_and_int_literal(self):
dec = msgspec.msgpack.Decoder(Union[Literal[-1, 1], int])
for x in [-1, 1, 10]:
assert dec.decode(msgspec.msgpack.encode(x)) == x
def test_mix_str_and_str_literal(self):
dec = msgspec.msgpack.Decoder(Union[Literal["a", "b"], str])
for x in ["a", "b", "c"]:
assert dec.decode(msgspec.msgpack.encode(x)) == x
class TestUnionTypeErrors:
def test_decoder_unsupported_type(self, proto):
with pytest.raises(TypeError):
proto.Decoder(1)
def test_decoder_validates_struct_definition_unsupported_types(self, proto):
"""Struct definitions aren't validated until first use"""
class Test(Struct):
a: 1
with pytest.raises(TypeError):
proto.Decoder(Test)
@pytest.mark.parametrize("typ", [Union[int, Deque], Union[Deque, int]])
def test_err_union_with_custom_type(self, typ, proto):
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "custom type" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize(
"typ",
[
Union[dict, Person],
Union[Person, dict],
Union[PersonDict, dict],
Union[PersonDataclass, dict],
Union[Person, PersonDict],
],
)
def test_err_union_with_multiple_dict_like_types(self, typ, proto):
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "more than one dict-like type" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize(
"typ",
[
Union[PersonArray, list],
Union[tuple, PersonArray],
Union[PersonArray, PersonTuple],
Union[PersonTuple, frozenset],
],
)
def test_err_union_with_struct_array_like_and_array(self, typ, proto):
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "more than one array-like type" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize("types", [(FruitInt, int), (FruitInt, Literal[1, 2])])
def test_err_union_with_multiple_int_like_types(self, types, proto):
typ = Union[types]
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "int-like" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize(
"typ",
[
str,
Literal["one", "two"],
datetime.datetime,
datetime.date,
datetime.time,
uuid.UUID,
],
)
def test_err_union_with_multiple_str_like_types(self, typ, proto):
union = Union[FruitStr, typ]
with pytest.raises(TypeError) as rec:
proto.Decoder(union)
assert "str-like" in str(rec.value)
assert repr(union) in str(rec.value)
@pytest.mark.parametrize(
"typ,kind",
[
(Union[FruitInt, VeggieInt], "int enum"),
(Union[FruitStr, VeggieStr], "str enum"),
(Union[Dict[int, float], dict], "dict"),
(Union[List[int], List[float]], "array-like"),
(Union[List[int], tuple], "array-like"),
(Union[set, tuple], "array-like"),
(Union[Tuple[int, ...], list], "array-like"),
(Union[Tuple[int, float, str], set], "array-like"),
(Union[Deque, int, Custom], "custom"),
],
)
def test_err_union_conflicts(self, typ, kind, proto):
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert f"more than one {kind}" in str(rec.value)
assert repr(typ) in str(rec.value)
@py310_plus
def test_310_union_types(self, proto):
dec = proto.Decoder(int | str | None)
for msg in [1, "abc", None]:
assert dec.decode(proto.encode(msg)) == msg
with pytest.raises(ValidationError):
assert dec.decode(proto.encode(1.5))
class TestStructUnion:
def test_err_union_struct_mix_array_like(self, proto):
class Test1(Struct, tag=True, array_like=True):
x: int
class Test2(Struct, tag=True, array_like=False):
x: int
typ = Union[Test1, Test2]
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "not supported" in str(rec.value)
assert "array_like" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize("array_like", [False, True])
@pytest.mark.parametrize("tag1", [False, True])
def test_err_union_struct_not_tagged(self, array_like, tag1, proto):
class Test1(Struct, tag=tag1, array_like=array_like):
x: int
class Test2(Struct, array_like=array_like):
x: int
typ = Union[Test1, Test2]
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "not supported" in str(rec.value)
assert "must be tagged" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize("array_like", [False, True])
def test_err_union_conflict_with_basic_type(self, array_like, proto):
class Test1(Struct, tag=True, array_like=array_like):
x: int
class Test2(Struct, tag=True, array_like=array_like):
x: int
other = list if array_like else dict
typ = Union[Test1, Test2, other]
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "not supported" in str(rec.value)
if array_like:
assert "more than one array-like type" in str(rec.value)
else:
assert "more than one dict-like type" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize("array_like", [False, True])
def test_err_union_struct_different_fields(self, proto, array_like):
class Test1(Struct, tag_field="foo", array_like=array_like):
x: int
class Test2(Struct, tag_field="bar", array_like=array_like):
x: int
typ = Union[Test1, Test2]
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "not supported" in str(rec.value)
assert "the same `tag_field`" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize("array_like", [False, True])
def test_err_union_struct_mix_int_str_tags(self, proto, array_like):
class Test1(Struct, tag=1, array_like=array_like):
x: int
class Test2(Struct, tag="two", array_like=array_like):
x: int
typ = Union[Test1, Test2]
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "not supported" in str(rec.value)
assert "both `int` and `str` tags" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize("array_like", [False, True])
@pytest.mark.parametrize(
"tags",
[
("a", "b", "b"),
("a", "a", "b"),
("a", "b", "a"),
(1, 2, 2),
(1, 1, 2),
(1, 2, 1),
],
)
def test_err_union_struct_non_unique_tag_values(self, proto, array_like, tags):
class Test1(Struct, tag=tags[0], array_like=array_like):
x: int
class Test2(Struct, tag=tags[1], array_like=array_like):
x: int
class Test3(Struct, tag=tags[2], array_like=array_like):
x: int
typ = Union[Test1, Test2, Test3]
with pytest.raises(TypeError) as rec:
proto.Decoder(typ)
assert "not supported" in str(rec.value)
assert "unique `tag`" in str(rec.value)
assert repr(typ) in str(rec.value)
@pytest.mark.parametrize(
"tag1, tag2, unknown",
[
("Test1", "Test2", "Test3"),
(0, 1, 2),
(123, -123, 0),
],
)
def test_decode_struct_union(self, proto, tag1, tag2, unknown):
class Test1(Struct, tag=tag1):
a: int
b: int
c: int = 0
class Test2(Struct, tag=tag2):
x: int
y: int
dec = proto.Decoder(Union[Test1, Test2])
enc = proto.Encoder()
# Tag can be in any position
assert dec.decode(enc.encode({"type": tag1, "a": 1, "b": 2})) == Test1(1, 2)
assert dec.decode(enc.encode({"a": 1, "type": tag1, "b": 2})) == Test1(1, 2)
assert dec.decode(enc.encode({"x": 1, "y": 2, "type": tag2})) == Test2(1, 2)
# Optional fields still work
assert dec.decode(enc.encode({"type": tag1, "a": 1, "b": 2, "c": 3})) == Test1(
1, 2, 3
)
assert dec.decode(enc.encode({"a": 1, "b": 2, "c": 3, "type": tag1})) == Test1(
1, 2, 3
)
# Extra fields still ignored
assert dec.decode(enc.encode({"a": 1, "b": 2, "d": 4, "type": tag1})) == Test1(
1, 2
)
# Tag missing
with pytest.raises(ValidationError) as rec:
dec.decode(enc.encode({"a": 1, "b": 2}))
assert "missing required field `type`" in str(rec.value)
# Tag wrong type
with pytest.raises(ValidationError) as rec:
dec.decode(enc.encode({"type": 123.456, "a": 1, "b": 2}))
assert f"Expected `{type(tag1).__name__}`" in str(rec.value)
assert "`$.type`" in str(rec.value)
# Tag unknown
with pytest.raises(ValidationError) as rec:
dec.decode(enc.encode({"type": unknown, "a": 1, "b": 2}))
assert f"Invalid value {unknown!r} - at `$.type`" == str(rec.value)
@pytest.mark.parametrize(
"tag1, tag2, tag3, unknown",
[
("Test1", "Test2", "Test3", "Test4"),
(0, 1, 2, 3),
(123, -123, 0, -1),
],
)
def test_decode_struct_array_union(self, proto, tag1, tag2, tag3, unknown):
class Test1(Struct, tag=tag1, array_like=True):
a: int
b: int
c: int = 0
class Test2(Struct, tag=tag2, array_like=True):
x: int
y: int
class Test3(Struct, tag=tag3, array_like=True):
pass
dec = proto.Decoder(Union[Test1, Test2, Test3])
enc = proto.Encoder()
# Decoding works
assert dec.decode(enc.encode([tag1, 1, 2])) == Test1(1, 2)
assert dec.decode(enc.encode([tag2, 3, 4])) == Test2(3, 4)
assert dec.decode(enc.encode([tag3])) == Test3()
# Optional & Extra fields still respected
assert dec.decode(enc.encode([tag1, 1, 2, 3])) == Test1(1, 2, 3)
assert dec.decode(enc.encode([tag1, 1, 2, 3, 4])) == Test1(1, 2, 3)
# Missing required field
with pytest.raises(ValidationError) as rec:
dec.decode(enc.encode([tag1, 1]))
assert "Expected `array` of at least length 3, got 2" in str(rec.value)
# Type error has correct field index
with pytest.raises(ValidationError) as rec:
dec.decode(enc.encode([tag1, 1, "bad", 2]))
assert "Expected `int`, got `str` - at `$[2]`" == str(rec.value)
# Tag missing
with pytest.raises(ValidationError) as rec:
dec.decode(enc.encode([]))
assert "Expected `array` of at least length 1, got 0" == str(rec.value)
# Tag wrong type
with pytest.raises(ValidationError) as rec:
dec.decode(enc.encode([123.456, 2, 3, 4]))
assert f"Expected `{type(tag1).__name__}`" in str(rec.value)
assert "`$[0]`" in str(rec.value)
# Tag unknown
with pytest.raises(ValidationError) as rec:
dec.decode(enc.encode([unknown, 1, 2, 3]))
assert f"Invalid value {unknown!r} - at `$[0]`" == str(rec.value)
@pytest.mark.parametrize("array_like", [False, True])
def test_decode_struct_union_with_non_struct_types(self, array_like, proto):
class Test1(Struct, tag=True, array_like=array_like):
a: int
b: int
class Test2(Struct, tag=True, array_like=array_like):
x: int
y: int
dec = proto.Decoder(Union[Test1, Test2, None, int, str])
enc = proto.Encoder()
for msg in [Test1(1, 2), Test2(3, 4), None, 5, 6]:
assert dec.decode(enc.encode(msg)) == msg
with pytest.raises(ValidationError) as rec:
dec.decode(enc.encode(True))
typ = "array" if array_like else "object"
assert f"Expected `int | str | {typ} | null`, got `bool`" == str(rec.value)
@pytest.mark.parametrize("array_like", [False, True])
def test_struct_union_cached(self, array_like, proto):
from msgspec._core import _struct_lookup_cache as cache
cache.clear()
class Test1(Struct, tag=True, array_like=array_like):
a: int
b: int
class Test2(Struct, tag=True, array_like=array_like):
x: int
y: int
typ1 = Union[Test2, Test1]
typ2 = Union[Test1, Test2]
typ3 = Union[Test1, Test2, int, None]
for typ in [typ1, typ2, typ3]:
for msg in [Test1(1, 2), Test2(3, 4)]:
assert proto.decode(proto.encode(msg), type=typ) == msg
assert len(cache) == 1
assert frozenset((Test1, Test2)) in cache
def test_struct_union_cache_evicted(self, proto):
from msgspec._core import _struct_lookup_cache as cache
MAX_CACHE_SIZE = 64 # XXX: update if hardcoded value in `_core.c` changes
cache.clear()
def call_with_new_types():
class Test1(Struct, tag=True):
a: int
class Test2(Struct, tag=True):
x: int
typ = (Test1, Test2)
proto.decode(proto.encode(Test1(1)), type=Union[typ])
return frozenset(typ)
first = call_with_new_types()
assert first in cache
# Fill up the cache
for _ in range(MAX_CACHE_SIZE - 1):
call_with_new_types()
# Check that first item is still in cache and is first in order
assert len(cache) == MAX_CACHE_SIZE
assert first in cache
assert first == list(cache.keys())[0]
# Add a new item, causing an item to be popped from the cache
new = call_with_new_types()
assert len(cache) == MAX_CACHE_SIZE
assert first not in cache
assert frozenset(new) in cache
class TestGenericStruct:
def test_generic_struct_info_cached(self, proto):
class Ex(Struct, Generic[T]):
x: T
typ = Ex[int]
assert Ex[int] is typ
dec = proto.Decoder(typ)
info = typ.__msgspec_cache__
assert info is not None
assert sys.getrefcount(info) <= 4 # info + attr + decoder + func call
dec2 = proto.Decoder(typ)
assert typ.__msgspec_cache__ is info
assert sys.getrefcount(info) <= 5
del dec
del dec2
assert sys.getrefcount(info) <= 3
def test_generic_struct_invalid_types_not_cached(self, proto):
class Ex(Struct, Generic[T]):
x: Union[List[T], Tuple[float]]
for typ in [Ex, Ex[int]]:
for _ in range(2):
with pytest.raises(TypeError, match="not supported"):
proto.Decoder(typ)
assert not hasattr(typ, "__msgspec_cache__")
def test_msgspec_cache_overwritten(self, proto):
class Ex(Struct, Generic[T]):
x: T
typ = Ex[int]
typ.__msgspec_cache__ = 1
with pytest.raises(RuntimeError, match="__msgspec_cache__"):
proto.Decoder(typ)
@pytest.mark.parametrize("array_like", [False, True])
def test_generic_struct(self, proto, array_like):
class Ex(Struct, Generic[T], array_like=array_like):
x: T
y: List[T]
sol = Ex(1, [1, 2])
msg = proto.encode(sol)
res = proto.decode(msg, type=Ex)
assert res == sol
res = proto.decode(msg, type=Ex[int])
assert res == sol
res = proto.decode(msg, type=Ex[Union[int, str]])
assert res == sol
res = proto.decode(msg, type=Ex[float])
assert type(res.x) is float
with pytest.raises(ValidationError, match="Expected `str`, got `int`"):
proto.decode(msg, type=Ex[str])
@pytest.mark.parametrize("array_like", [False, True])
def test_recursive_generic_struct(self, proto, array_like):
source = f"""
from __future__ import annotations
from typing import Union, Generic, TypeVar
from msgspec import Struct
T = TypeVar("T")
class Ex(Struct, Generic[T], array_like={array_like}):
a: T
b: Union[Ex[T], None]
"""
with temp_module(source) as mod:
msg = mod.Ex(a=1, b=mod.Ex(a=2, b=None))
msg2 = mod.Ex(a=1, b=mod.Ex(a="bad", b=None))
assert proto.decode(proto.encode(msg), type=mod.Ex) == msg
assert proto.decode(proto.encode(msg2), type=mod.Ex) == msg2
assert proto.decode(proto.encode(msg), type=mod.Ex[int]) == msg
with pytest.raises(ValidationError) as rec:
proto.decode(proto.encode(msg2), type=mod.Ex[int])
if array_like:
assert "`$[1][0]`" in str(rec.value)
else:
assert "`$.b.a`" in str(rec.value)
assert "Expected `int`, got `str`" in str(rec.value)
@pytest.mark.parametrize("array_like", [False, True])
def test_generic_struct_union(self, proto, array_like):
class Test1(Struct, Generic[T], tag=True, array_like=array_like):
a: Union[T, None]
b: int
class Test2(Struct, Generic[T], tag=True, array_like=array_like):
x: T
y: int
typ = Union[Test1[T], Test2[T]]
msg1 = Test1(1, 2)
s1 = proto.encode(msg1)
msg2 = Test2("three", 4)
s2 = proto.encode(msg2)
msg3 = Test1(None, 4)
s3 = proto.encode(msg3)
assert proto.decode(s1, type=typ) == msg1
assert proto.decode(s2, type=typ) == msg2
assert proto.decode(s3, type=typ) == msg3
assert proto.decode(s1, type=typ[int]) == msg1
assert proto.decode(s3, type=typ[int]) == msg3
assert proto.decode(s2, type=typ[str]) == msg2
assert proto.decode(s3, type=typ[str]) == msg3
with pytest.raises(ValidationError) as rec:
proto.decode(s1, type=typ[str])
assert "Expected `str | null`, got `int`" in str(rec.value)
loc = "$[1]" if array_like else "$.a"
assert loc in str(rec.value)
with pytest.raises(ValidationError) as rec:
proto.decode(s2, type=typ[int])
assert "Expected `int`, got `str`" in str(rec.value)
loc = "$[1]" if array_like else "$.x"
assert loc in str(rec.value)
def test_unbound_typevars_use_bound_if_set(self, proto):
T = TypeVar("T", bound=Union[int, str])
dec = proto.Decoder(List[T])
sol = [1, "two", 3, "four"]
msg = proto.encode(sol)
assert dec.decode(msg) == sol
bad = proto.encode([1, {}])
with pytest.raises(
ValidationError,
match=r"Expected `int \| str`, got `object` - at `\$\[1\]`",
):
dec.decode(bad)
def test_unbound_typevars_with_constraints_unsupported(self, proto):
T = TypeVar("T", int, str)
with pytest.raises(TypeError) as rec:
proto.Decoder(List[T])
assert "Unbound TypeVar `~T` has constraints" in str(rec.value)
class TestStructPostInit:
@pytest.mark.parametrize("array_like", [False, True])
@pytest.mark.parametrize("union", [False, True])
def test_struct_post_init(self, array_like, union, proto):
count = 0
singleton = object()
class Ex(Struct, array_like=array_like, tag=union):
x: int
def __post_init__(self):
nonlocal count
count += 1
return singleton
if union:
class Ex2(Struct, array_like=array_like, tag=True):
pass
typ = Union[Ex, Ex2]
else:
typ = Ex
msg = Ex(1)
buf = proto.encode(msg)
res = proto.decode(buf, type=typ)
assert res == msg
assert count == 2 # 1 for Ex(), 1 for decode
assert sys.getrefcount(singleton) <= 2 # 1 for ref, 1 for call
@pytest.mark.parametrize("array_like", [False, True])
@pytest.mark.parametrize("union", [False, True])
@pytest.mark.parametrize("exc_class", [ValueError, TypeError, OSError])
def test_struct_post_init_errors(self, array_like, union, exc_class, proto):
error = False
class Ex(Struct, array_like=array_like, tag=union):
x: int
def __post_init__(self):
if error:
raise exc_class("Oh no!")
if union:
class Ex2(Struct, array_like=array_like, tag=True):
pass
typ = Union[Ex, Ex2]
else:
typ = Ex
msg = proto.encode([Ex(1)])
error = True
if exc_class in (ValueError, TypeError):
expected = ValidationError
else:
expected = exc_class
with pytest.raises(expected, match="Oh no!") as rec:
proto.decode(msg, type=List[typ])
if expected is ValidationError:
assert "- at `$[0]`" in str(rec.value)
@pytest.fixture(params=["dataclass", "attrs"])
def decorator(request):
if request.param == "dataclass":
return dataclass
elif request.param == "attrs":
if attrs is None:
pytest.skip(reason="attrs not installed")
return attrs.define
class TestGenericDataclassOrAttrs:
def test_generic_info_cached(self, decorator, proto):
@decorator
class Ex(Generic[T]):
x: T
typ = Ex[int]
assert Ex[int] is typ
dec = proto.Decoder(typ)
info = typ.__msgspec_cache__
assert info is not None
assert sys.getrefcount(info) <= 4 # info + attr + decoder + func call
dec2 = proto.Decoder(typ)
assert typ.__msgspec_cache__ is info
assert sys.getrefcount(info) <= 5
del dec
del dec2
assert sys.getrefcount(info) <= 3
def test_generic_invalid_types_not_cached(self, decorator, proto):
@decorator
class Ex(Generic[T]):
x: Union[List[T], Tuple[float]]
for typ in [Ex, Ex[int]]:
for _ in range(2):
with pytest.raises(TypeError, match="not supported"):
proto.Decoder(typ)
assert not hasattr(typ, "__msgspec_cache__")
def test_msgspec_cache_overwritten(self, decorator, proto):
@decorator
class Ex(Generic[T]):
x: T
typ = Ex[int]
typ.__msgspec_cache__ = 1
with pytest.raises(RuntimeError, match="__msgspec_cache__"):
proto.Decoder(typ)
def test_generic_dataclass(self, decorator, proto):
@decorator
class Ex(Generic[T]):
x: T
y: List[T]
sol = Ex(1, [1, 2])
msg = proto.encode(sol)
res = proto.decode(msg, type=Ex)
assert res == sol
res = proto.decode(msg, type=Ex[int])
assert res == sol
res = proto.decode(msg, type=Ex[Union[int, str]])
assert res == sol
res = proto.decode(msg, type=Ex[float])
assert type(res.x) is float
with pytest.raises(ValidationError, match="Expected `str`, got `int`"):
proto.decode(msg, type=Ex[str])
@pytest.mark.parametrize("module", ["dataclasses", "attrs"])
def test_recursive_generic(self, module, proto):
pytest.importorskip(module)
if module == "dataclasses":
import_ = "from dataclasses import dataclass as decorator"
else:
import_ = "from attrs import define as decorator"
source = f"""
from __future__ import annotations
from typing import Union, Generic, TypeVar
from msgspec import Struct
{import_}
T = TypeVar("T")
@decorator
class Ex(Generic[T]):
a: T
b: Union[Ex[T], None]
"""
with temp_module(source) as mod:
msg = mod.Ex(a=1, b=mod.Ex(a=2, b=None))
msg2 = mod.Ex(a=1, b=mod.Ex(a="bad", b=None))
assert proto.decode(proto.encode(msg), type=mod.Ex) == msg
assert proto.decode(proto.encode(msg2), type=mod.Ex) == msg2
assert proto.decode(proto.encode(msg), type=mod.Ex[int]) == msg
with pytest.raises(ValidationError) as rec:
proto.decode(proto.encode(msg2), type=mod.Ex[int])
assert "`$.b.a`" in str(rec.value)
assert "Expected `int`, got `str`" in str(rec.value)
def test_unbound_typevars_use_bound_if_set(self, proto):
T = TypeVar("T", bound=Union[int, str])
dec = proto.Decoder(List[T])
sol = [1, "two", 3, "four"]
msg = proto.encode(sol)
assert dec.decode(msg) == sol
bad = proto.encode([1, {}])
with pytest.raises(
ValidationError,
match=r"Expected `int \| str`, got `object` - at `\$\[1\]`",
):
dec.decode(bad)
def test_unbound_typevars_with_constraints_unsupported(self, proto):
T = TypeVar("T", int, str)
with pytest.raises(TypeError) as rec:
proto.Decoder(List[T])
assert "Unbound TypeVar `~T` has constraints" in str(rec.value)
class TestStructOmitDefaults:
def test_omit_defaults(self, proto):
class Test(Struct, omit_defaults=True):
a: int = 0
b: bool = False
c: Optional[str] = None
d: list = []
e: Union[list, set] = set()
f: dict = {}
cases = [
(Test(), {}),
(Test(1), {"a": 1}),
(Test(1, False), {"a": 1}),
(Test(1, True), {"a": 1, "b": True}),
(Test(1, c=None), {"a": 1}),
(Test(1, c="test"), {"a": 1, "c": "test"}),
(Test(1, d=[1]), {"a": 1, "d": [1]}),
(Test(1, e={1}), {"a": 1, "e": [1]}),
(Test(1, e=[]), {"a": 1, "e": []}),
(Test(1, f={"a": 1}), {"a": 1, "f": {"a": 1}}),
]
for obj, sol in cases:
res = proto.decode(proto.encode(obj))
assert res == sol
@pytest.mark.parametrize("typ", [tuple, list, set, frozenset, dict])
def test_omit_defaults_collections(self, proto, typ):
"""Check that using empty collections as default values are detected
regardless if they're specified by value or as a default_factory."""
class Test(Struct, omit_defaults=True):
a: typ = msgspec.field(default_factory=typ)
b: typ = msgspec.field(default=typ())
c: typ = typ()
ex = {"x": 1} if typ is dict else [1]
assert proto.encode(Test()) == proto.encode({})
for n in ["a", "b", "c"]:
assert proto.encode(Test(**{n: typ(ex)})) == proto.encode({n: ex})
def test_omit_defaults_positional(self, proto):
class Test(Struct, omit_defaults=True):
a: int
b: bool = False
cases = [
(Test(1), {"a": 1}),
(Test(1, False), {"a": 1}),
(Test(1, True), {"a": 1, "b": True}),
]
for obj, sol in cases:
res = proto.decode(proto.encode(obj))
assert res == sol
def test_omit_defaults_tagged(self, proto):
class Test(Struct, omit_defaults=True, tag=True):
a: int
b: bool = False
cases = [
(Test(1), {"type": "Test", "a": 1}),
(Test(1, False), {"type": "Test", "a": 1}),
(Test(1, True), {"type": "Test", "a": 1, "b": True}),
]
for obj, sol in cases:
res = proto.decode(proto.encode(obj))
assert res == sol
def test_omit_defaults_ignored_for_array_like(self, proto):
class Test(Struct, omit_defaults=True, array_like=True):
a: int
b: bool = False
cases = [
(Test(1), [1, False]),
(Test(1, False), [1, False]),
(Test(1, True), [1, True]),
]
for obj, sol in cases:
res = proto.decode(proto.encode(obj))
assert res == sol
class TestStructForbidUnknownFields:
def test_forbid_unknown_fields(self, proto):
class Test(Struct, forbid_unknown_fields=True):
x: int
y: int
good = Test(1, 2)
assert proto.decode(proto.encode(good), type=Test) == good
bad = proto.encode({"x": 1, "y": 2, "z": 3})
with pytest.raises(ValidationError, match="Object contains unknown field `z`"):
proto.decode(bad, type=Test)
def test_forbid_unknown_fields_array_like(self, proto):
class Test(Struct, forbid_unknown_fields=True, array_like=True):
x: int
y: int
good = Test(1, 2)
assert proto.decode(proto.encode(good), type=Test) == good
bad = proto.encode([1, 2, 3])
with pytest.raises(
ValidationError, match="Expected `array` of at most length 2"
):
proto.decode(bad, type=Test)
class PointUpper(Struct, rename="upper"):
x: int
y: int
class TestStructRename:
def test_rename_encode_struct(self, proto):
res = proto.encode(PointUpper(1, 2))
exp = proto.encode({"X": 1, "Y": 2})
assert res == exp
def test_rename_decode_struct(self, proto):
msg = proto.encode({"X": 1, "Y": 2})
res = proto.decode(msg, type=PointUpper)
assert res == PointUpper(1, 2)
def test_rename_decode_struct_wrong_type(self, proto):
msg = proto.encode({"X": 1, "Y": "bad"})
with pytest.raises(ValidationError) as rec:
proto.decode(msg, type=PointUpper)
assert "Expected `int`, got `str` - at `$.Y`" == str(rec.value)
def test_rename_decode_struct_missing_field(self, proto):
msg = proto.encode({"X": 1})
with pytest.raises(ValidationError) as rec:
proto.decode(msg, type=PointUpper)
assert "Object missing required field `Y`" == str(rec.value)
class TestStructKeywordOnly:
def test_keyword_only_object(self, proto):
class Test(Struct, kw_only=True):
a: int
b: int = 2
c: int
d: int = 4
sol = Test(a=1, b=2, c=3, d=4)
msg = proto.encode({"a": 1, "b": 2, "c": 3, "d": 4})
res = proto.decode(msg, type=Test)
assert res == sol
msg = proto.encode({"a": 1, "c": 3})
res = proto.decode(msg, type=Test)
assert res == sol
sol = Test(a=1, b=3, c=5)
msg = proto.encode({"a": 1, "b": 3, "c": 5})
res = proto.decode(msg, type=Test)
assert res == sol
msg = proto.encode({"a": 1, "b": 2})
with pytest.raises(
ValidationError,
match="missing required field `c`",
):
proto.decode(msg, type=Test)
msg = proto.encode({"c": 1, "b": 2})
with pytest.raises(
ValidationError,
match="missing required field `a`",
):
proto.decode(msg, type=Test)
def test_keyword_only_array(self, proto):
class Test(Struct, kw_only=True, array_like=True):
a: int
b: int = 2
c: int
d: int = 4
msg = proto.encode([5, 6, 7, 8])
res = proto.decode(msg, type=Test)
assert res == Test(a=5, b=6, c=7, d=8)
msg = proto.encode([5, 6, 7])
res = proto.decode(msg, type=Test)
assert res == Test(a=5, b=6, c=7, d=4)
msg = proto.encode([5, 6])
with pytest.raises(
ValidationError,
match="Expected `array` of at least length 3, got 2",
):
proto.decode(msg, type=Test)
msg = proto.encode([])
with pytest.raises(
ValidationError,
match="Expected `array` of at least length 3, got 0",
):
proto.decode(msg, type=Test)
class TestStructDefaults:
def test_struct_defaults(self, proto):
class Test(Struct):
a: int = 1
b: list = []
c: int = msgspec.field(default=2)
d: dict = msgspec.field(default_factory=dict)
sol = Test()
res = proto.decode(proto.encode(sol), type=Test)
assert res == sol
res = proto.decode(proto.encode({}), type=Test)
assert res == sol
def test_struct_default_factory_errors(self, proto):
def bad():
raise ValueError("Oh no!")
class Test(Struct):
a: int = msgspec.field(default_factory=bad)
msg = proto.encode({})
with pytest.raises(Exception, match="Oh no!"):
proto.decode(msg, type=Test)
class TestTypedDict:
def test_type_cached(self, proto):
class Ex(TypedDict):
a: int
b: str
msg = {"a": 1, "b": "two"}
dec = proto.Decoder(Ex)
info = Ex.__msgspec_cache__
assert info is not None
dec2 = proto.Decoder(Ex)
assert Ex.__msgspec_cache__ is info
assert dec.decode(proto.encode(msg)) == msg
assert dec2.decode(proto.encode(msg)) == msg
def test_msgspec_cache_overwritten(self, proto):
class Ex(TypedDict):
x: int
Ex.__msgspec_cache__ = 1
with pytest.raises(RuntimeError, match="__msgspec_cache__"):
proto.Decoder(Ex)
def test_multiple_typeddict_errors(self, proto):
class Ex1(TypedDict):
a: int
class Ex2(TypedDict):
b: int
with pytest.raises(TypeError, match="may not contain more than one TypedDict"):
proto.Decoder(Union[Ex1, Ex2])
def test_subtype_error(self, proto):
class Ex(TypedDict):
a: int
b: Union[list, tuple]
with pytest.raises(TypeError, match="may not contain more than one array-like"):
proto.Decoder(Ex)
assert not hasattr(Ex, "__msgspec_cache__")
def test_recursive_type(self, proto):
source = """
from __future__ import annotations
from typing import TypedDict, Union
class Ex(TypedDict):
a: int
b: Union[Ex, None]
"""
with temp_module(source) as mod:
msg = {"a": 1, "b": {"a": 2, "b": None}}
dec = proto.Decoder(mod.Ex)
assert dec.decode(proto.encode(msg)) == msg
with pytest.raises(ValidationError) as rec:
dec.decode(proto.encode({"a": 1, "b": {"a": "bad"}}))
assert "`$.b.a`" in str(rec.value)
assert "Expected `int`, got `str`" in str(rec.value)
def test_total_true(self, proto):
class Ex(TypedDict):
a: int
b: str
dec = proto.Decoder(Ex)
x = {"a": 1, "b": "two"}
assert dec.decode(proto.encode(x)) == x
x2 = {"a": 1, "b": "two", "c": "extra"}
assert dec.decode(proto.encode(x2)) == x
with pytest.raises(ValidationError) as rec:
dec.decode(proto.encode({"b": "two"}))
assert "Object missing required field `a`" == str(rec.value)
with pytest.raises(ValidationError) as rec:
dec.decode(proto.encode({"a": 1, "b": 2}))
assert "Expected `str`, got `int` - at `$.b`" == str(rec.value)
def test_duplicate_keys(self, proto):
"""Validating if all required keys are present is done with a count. We
need to ensure that duplicate required keys don't increment the count,
masking a missing field."""
class Ex(TypedDict):
a: int
b: str
dec = proto.Decoder(Ex)
temp = proto.encode({"a": 1, "b": "two", "x": 2})
msg = temp.replace(b"x", b"a")
assert dec.decode(msg) == {"a": 2, "b": "two"}
msg = temp.replace(b"x", b"a").replace(b"b", b"c")
with pytest.raises(ValidationError) as rec:
dec.decode(msg)
assert "Object missing required field `b`" == str(rec.value)
def test_total_false(self, proto):
class Ex(TypedDict, total=False):
a: int
b: str
dec = proto.Decoder(Ex)
x = {"a": 1, "b": "two"}
assert dec.decode(proto.encode(x)) == x
x2 = {"a": 1, "b": "two", "c": "extra"}
assert dec.decode(proto.encode(x2)) == x
x3 = {"b": "two"}
assert dec.decode(proto.encode(x3)) == x3
x4 = {}
assert dec.decode(proto.encode(x4)) == x4
@pytest.mark.parametrize("use_typing_extensions", [False, True])
def test_total_partially_optional(self, proto, use_typing_extensions):
if use_typing_extensions:
tex = pytest.importorskip("typing_extensions")
cls = tex.TypedDict
else:
cls = TypedDict
class Base(cls):
a: int
b: str
class Ex(Base, total=False):
c: str
dec = proto.Decoder(Ex)
x = {"a": 1, "b": "two", "c": "extra"}
assert dec.decode(proto.encode(x)) == x
x2 = {"a": 1, "b": "two"}
assert dec.decode(proto.encode(x2)) == x2
with pytest.raises(ValidationError) as rec:
dec.decode(proto.encode({"b": "two"}))
assert "Object missing required field `a`" == str(rec.value)
@pytest.mark.parametrize("use_typing_extensions", [False, True])
def test_broken_typeddict(self, proto, use_typing_extensions):
# Check that we don't crash if a TypedDict has incorrect
# introspection data.
if use_typing_extensions:
tex = pytest.importorskip("typing_extensions")
cls = tex.TypedDict
else:
cls = TypedDict
class Ex(cls, total=False):
c: str
Ex.__annotations__ = {"c": "str"}
Ex.__required_keys__ = {"a", "b"}
with pytest.raises(RuntimeError):
proto.Decoder(Ex)
@pytest.mark.parametrize("use_typing_extensions", [False, True])
def test_required_and_notrequired(self, proto, use_typing_extensions):
if use_typing_extensions:
module = "typing_extensions"
else:
module = "typing"
ns = pytest.importorskip(module)
if not hasattr(ns, "Required"):
pytest.skip(f"{module}.Required is not available")
source = f"""
from __future__ import annotations
from {module} import TypedDict, Required, NotRequired
class Base(TypedDict):
a: int
b: NotRequired[str]
class Ex(Base, total=False):
c: str
d: Required[bool]
"""
with temp_module(source) as mod:
dec = proto.Decoder(mod.Ex)
x = {"a": 1, "b": "two", "c": "extra", "d": False}
assert dec.decode(proto.encode(x)) == x
x2 = {"a": 1, "d": False}
assert dec.decode(proto.encode(x2)) == x2
with pytest.raises(ValidationError) as rec:
dec.decode(proto.encode({"d": False}))
assert "Object missing required field `a`" == str(rec.value)
with pytest.raises(ValidationError) as rec:
dec.decode(proto.encode({"a": 2}))
assert "Object missing required field `d`" == str(rec.value)
def test_keys_are_their_interned_values(self, proto):
"""Ensure that we're not allocating new keys here, but reusing the
existing keys on the TypedDict schema"""
class Ex(TypedDict):
key_name_1: int
key_name_2: int
dec = proto.Decoder(Ex)
msg = dec.decode(proto.encode({"key_name_1": 1, "key_name_2": 2}))
for k1, k2 in zip(sorted(Ex.__annotations__), sorted(msg)):
assert k1 is k2
def test_generic_typeddict_info_cached(self, proto):
TypedDict = pytest.importorskip("typing_extensions").TypedDict
class Ex(TypedDict, Generic[T]):
x: T
typ = Ex[int]
assert Ex[int] is typ
dec = proto.Decoder(typ)
info = typ.__msgspec_cache__
assert info is not None
assert sys.getrefcount(info) <= 4 # info + attr + decoder + func call
dec2 = proto.Decoder(typ)
assert typ.__msgspec_cache__ is info
assert sys.getrefcount(info) <= 5
del dec
del dec2
assert sys.getrefcount(info) <= 3
def test_generic_typeddict_invalid_types_not_cached(self, proto):
TypedDict = pytest.importorskip("typing_extensions").TypedDict
class Ex(TypedDict, Generic[T]):
x: Union[List[T], Tuple[float]]
for typ in [Ex, Ex[int]]:
for _ in range(2):
with pytest.raises(TypeError, match="not supported"):
proto.Decoder(typ)
assert not hasattr(typ, "__msgspec_cache__")
def test_generic_typeddict(self, proto):
TypedDict = pytest.importorskip("typing_extensions").TypedDict
class Ex(TypedDict, Generic[T]):
x: T
y: List[T]
sol = Ex(x=1, y=[1, 2])
msg = proto.encode(sol)
res = proto.decode(msg, type=Ex)
assert res == sol
res = proto.decode(msg, type=Ex[int])
assert res == sol
res = proto.decode(msg, type=Ex[Union[int, str]])
assert res == sol
res = proto.decode(msg, type=Ex[float])
assert type(res["x"]) is float
with pytest.raises(ValidationError, match="Expected `str`, got `int`"):
proto.decode(msg, type=Ex[str])
def test_recursive_generic_typeddict(self, proto):
pytest.importorskip("typing_extensions")
source = """
from __future__ import annotations
from typing import Union, Generic, TypeVar
from typing_extensions import TypedDict
T = TypeVar("T")
class Ex(TypedDict, Generic[T]):
a: T
b: Union[Ex[T], None]
"""
with temp_module(source) as mod:
msg = mod.Ex(a=1, b=mod.Ex(a=2, b=None))
msg2 = mod.Ex(a=1, b=mod.Ex(a="bad", b=None))
assert proto.decode(proto.encode(msg), type=mod.Ex) == msg
assert proto.decode(proto.encode(msg2), type=mod.Ex) == msg2
assert proto.decode(proto.encode(msg), type=mod.Ex[int]) == msg
with pytest.raises(ValidationError) as rec:
proto.decode(proto.encode(msg2), type=mod.Ex[int])
assert "`$.b.a`" in str(rec.value)
assert "Expected `int`, got `str`" in str(rec.value)
class TestNamedTuple:
def test_type_cached(self, proto):
class Ex(NamedTuple):
a: int
b: str
msg = (1, "two")
dec = proto.Decoder(Ex)
info = Ex.__msgspec_cache__
assert info is not None
dec2 = proto.Decoder(Ex)
assert Ex.__msgspec_cache__ is info
assert dec.decode(proto.encode(msg)) == msg
assert dec2.decode(proto.encode(msg)) == msg
def test_msgspec_cache_overwritten(self, proto):
class Ex(NamedTuple):
x: int
Ex.__msgspec_cache__ = 1
with pytest.raises(RuntimeError, match="__msgspec_cache__"):
proto.Decoder(Ex)
def test_multiple_namedtuple_errors(self, proto):
class Ex1(NamedTuple):
a: int
class Ex2(NamedTuple):
b: int
with pytest.raises(TypeError, match="may not contain more than one NamedTuple"):
proto.Decoder(Union[Ex1, Ex2])
def test_subtype_error(self, proto):
class Ex(NamedTuple):
a: int
b: Union[list, tuple]
with pytest.raises(TypeError, match="may not contain more than one array-like"):
proto.Decoder(Ex)
assert not hasattr(Ex, "__msgspec_cache__")
def test_recursive_type(self, proto):
source = """
from __future__ import annotations
from typing import NamedTuple, Union
class Ex(NamedTuple):
a: int
b: Union[Ex, None]
"""
with temp_module(source) as mod:
msg = mod.Ex(1, mod.Ex(2, None))
dec = proto.Decoder(mod.Ex)
assert dec.decode(proto.encode(msg)) == msg
with pytest.raises(ValidationError) as rec:
dec.decode(proto.encode(mod.Ex(1, ("bad", "two"))))
assert "`$[1][0]`" in str(rec.value)
assert "Expected `int`, got `str`" in str(rec.value)
@pytest.mark.parametrize("use_typing", [True, False])
def test_decode_namedtuple_no_defaults(self, proto, use_typing):
if use_typing:
class Example(NamedTuple):
a: int
b: int
c: int
else:
Example = namedtuple("Example", "a b c")
dec = proto.Decoder(Example)
msg = Example(1, 2, 3)
res = dec.decode(proto.encode(msg))
assert res == msg
suffix = ", got 1" if proto is msgspec.msgpack else ""
with pytest.raises(ValidationError, match=f"length 3{suffix}"):
dec.decode(proto.encode((1,)))
suffix = ", got 6" if proto is msgspec.msgpack else ""
with pytest.raises(ValidationError, match=f"length 3{suffix}"):
dec.decode(proto.encode((1, 2, 3, 4, 5, 6)))
@pytest.mark.parametrize("use_typing", [True, False])
def test_decode_namedtuple_with_defaults(self, proto, use_typing):
if use_typing:
class Example(NamedTuple):
a: int
b: int
c: int = -3
d: int = -4
e: int = -5
else:
Example = namedtuple("Example", "a b c d e", defaults=(-3, -4, -5))
dec = proto.Decoder(Example)
for args in [(1, 2), (1, 2, 3), (1, 2, 3, 4), (1, 2, 3, 4, 5)]:
msg = Example(*args)
res = dec.decode(proto.encode(msg))
assert res == msg
suffix = ", got 1" if proto is msgspec.msgpack else ""
with pytest.raises(ValidationError, match=f"length 2 to 5{suffix}"):
dec.decode(proto.encode((1,)))
suffix = ", got 6" if proto is msgspec.msgpack else ""
with pytest.raises(ValidationError, match=f"length 2 to 5{suffix}"):
dec.decode(proto.encode((1, 2, 3, 4, 5, 6)))
def test_decode_namedtuple_field_wrong_type(self, proto):
dec = proto.Decoder(PersonTuple)
msg = proto.encode((1, "bad", 2))
with pytest.raises(
ValidationError, match=r"Expected `str`, got `int` - at `\$\[0\]`"
):
dec.decode(msg)
def test_decode_namedtuple_not_array(self, proto):
dec = proto.Decoder(PersonTuple)
msg = proto.encode({})
with pytest.raises(ValidationError, match="Expected `array`, got `object`"):
dec.decode(msg)
def test_generic_namedtuple_info_cached(self, proto):
NamedTuple = pytest.importorskip("typing_extensions").NamedTuple
class Ex(NamedTuple, Generic[T]):
x: T
typ = Ex[int]
assert Ex[int] is typ
dec = proto.Decoder(typ)
info = typ.__msgspec_cache__
assert info is not None
assert sys.getrefcount(info) <= 4 # info + attr + decoder + func call
dec2 = proto.Decoder(typ)
assert typ.__msgspec_cache__ is info
assert sys.getrefcount(info) <= 5
del dec
del dec2
assert sys.getrefcount(info) <= 3
def test_generic_namedtuple_invalid_types_not_cached(self, proto):
NamedTuple = pytest.importorskip("typing_extensions").NamedTuple
class Ex(NamedTuple, Generic[T]):
x: Union[List[T], Tuple[float]]
for typ in [Ex, Ex[int]]:
for _ in range(2):
with pytest.raises(TypeError, match="not supported"):
proto.Decoder(typ)
assert not hasattr(typ, "__msgspec_cache__")
def test_generic_namedtuple(self, proto):
NamedTuple = pytest.importorskip("typing_extensions").NamedTuple
class Ex(NamedTuple, Generic[T]):
x: T
y: List[T]
sol = Ex(1, [1, 2])
msg = proto.encode(sol)
res = proto.decode(msg, type=Ex)
assert res == sol
res = proto.decode(msg, type=Ex[int])
assert res == sol
res = proto.decode(msg, type=Ex[Union[int, str]])
assert res == sol
res = proto.decode(msg, type=Ex[float])
assert type(res.x) is float
with pytest.raises(ValidationError, match="Expected `str`, got `int`"):
proto.decode(msg, type=Ex[str])
def test_recursive_generic_namedtuple(self, proto):
pytest.importorskip("typing_extensions")
source = """
from __future__ import annotations
from typing import Union, Generic, TypeVar
from typing_extensions import NamedTuple
T = TypeVar("T")
class Ex(NamedTuple, Generic[T]):
a: T
b: Union[Ex[T], None]
"""
with temp_module(source) as mod:
msg = mod.Ex(a=1, b=mod.Ex(a=2, b=None))
msg2 = mod.Ex(a=1, b=mod.Ex(a="bad", b=None))
assert proto.decode(proto.encode(msg), type=mod.Ex) == msg
assert proto.decode(proto.encode(msg2), type=mod.Ex) == msg2
assert proto.decode(proto.encode(msg), type=mod.Ex[int]) == msg
with pytest.raises(ValidationError) as rec:
proto.decode(proto.encode(msg2), type=mod.Ex[int])
assert "`$[1][0]`" in str(rec.value)
assert "Expected `int`, got `str`" in str(rec.value)
class TestDataclass:
def test_encode_dataclass_err_invalid_dataclass_fields(self, proto):
@dataclass
class Ex:
x: int
Ex.__dataclass_fields__ = ()
with pytest.raises(RuntimeError, match="is not a dict"):
proto.encode(Ex(1))
def test_encode_dataclass_class_errors(self, proto):
@dataclass
class Ex:
x: int
with pytest.raises(TypeError, match="Encoding objects of type type"):
proto.encode(Ex)
def test_encode_dataclass_no_slots(self, proto):
@dataclass
class Test:
x: int
y: int
x = Test(1, 2)
res = proto.encode(x)
sol = proto.encode({"x": 1, "y": 2})
assert res == sol
@py310_plus
def test_encode_dataclass_slots(self, proto):
@dataclass(slots=True)
class Test:
x: int
y: int
x = Test(1, 2)
res = proto.encode(x)
sol = proto.encode({"x": 1, "y": 2})
assert res == sol
@py310_plus
@pytest.mark.parametrize("slots", [True, False])
def test_encode_dataclass_missing_fields(self, proto, slots):
@dataclass(slots=slots)
class Test:
x: int
y: int
z: int
x = Test(1, 2, 3)
sol = {"x": 1, "y": 2, "z": 3}
for key in "xyz":
delattr(x, key)
del sol[key]
res = proto.decode(proto.encode(x))
assert res == sol
@py310_plus
@pytest.mark.parametrize("slots_base", [True, False])
@pytest.mark.parametrize("slots", [True, False])
def test_encode_dataclass_subclasses(self, proto, slots_base, slots):
@dataclass(slots=slots_base)
class Base:
x: int
y: int
@dataclass(slots=slots)
class Test(Base):
y: int
z: int
x = Test(1, 2, 3)
res = proto.decode(proto.encode(x))
assert res == {"x": 1, "y": 2, "z": 3}
# Missing attribute ignored
del x.y
res = proto.decode(proto.encode(x))
assert res == {"x": 1, "z": 3}
@py311_plus
def test_encode_dataclass_weakref_slot(self, proto):
@dataclass(slots=True, weakref_slot=True)
class Test:
x: int
y: int
x = Test(1, 2)
ref = weakref.ref(x) # noqa
res = proto.decode(proto.encode(x))
assert res == {"x": 1, "y": 2}
def test_encode_dataclass_classvars_ignored(self, proto):
@dataclass
class Ex:
a: int
b: ClassVar[int] = 2
msg = proto.encode(Ex(a=1))
assert msg == proto.encode({"a": 1})
def test_encode_dataclass_extra_fields_ignored(self, proto):
@dataclass
class Ex:
a: int
b: int
x = Ex(1, 2)
x.c = 3
msg = proto.encode(Ex(1, 2))
assert msg == proto.encode({"a": 1, "b": 2})
@pytest.mark.parametrize("order", ["acb", "bca", "cba"])
def test_encode_dataclass_dict_reordered(self, proto, order):
@dataclass
class Ex:
a: int
b: int
c: int
x = Ex(1, 2, 3)
x.__dict__.clear()
x.__dict__.update(dict(zip(order, range(3))))
res = proto.encode(x)
sol = proto.encode(dict(sorted(zip(order, range(3)))))
assert res == sol
@pytest.mark.parametrize("present", ["ab", "a", "b", ""])
def test_encode_dataclass_ducktyped(self, proto, present):
"""gel.Object looks like a dataclass, but the implementation doesn't
match the one from dataclasses. This ducktyped implementation tries to
mirror the one in gel for testing purposes. Ref:
https://docs.geldata.com/reference/using/python/api/types#gel.Object"""
@dataclass
class Ex:
a: int
b: int
msg = {k: v for k, v in zip("ab", range(2)) if k in present}
class Ex2:
def __getattr__(self, key):
return msg[key]
__dataclass_fields__ = {}
x = Ex2()
x.__dataclass_fields__ = Ex.__dataclass_fields__
res = proto.encode(x)
sol = proto.encode(msg)
assert res == sol
@pytest.mark.parametrize("field", "xyz")
def test_encode_dataclass_invalid_field_errors(self, proto, field):
@dataclass
class Test:
x: int
y: int
z: int
x = Test(1, 2, 3)
setattr(x, field, object())
with pytest.raises(TypeError, match="unsupported"):
proto.encode(x)
def test_type_cached(self, proto):
@dataclass
class Ex:
a: int
b: str
msg = Ex(a=1, b="two")
dec = proto.Decoder(Ex)
info = Ex.__msgspec_cache__
assert info is not None
dec2 = proto.Decoder(Ex)
assert Ex.__msgspec_cache__ is info
assert dec.decode(proto.encode(msg)) == msg
assert dec2.decode(proto.encode(msg)) == msg
def test_decode_dataclass_subclasses(self, proto):
@dataclass
class Base:
x: int
@dataclass
class Sub(Base):
y: int
msg = proto.encode({"x": 1, "y": 2})
assert proto.decode(msg, type=Base) == Base(1)
assert proto.decode(msg, type=Sub) == Sub(1, 2)
def test_multiple_dataclasses_errors(self, proto):
@dataclass
class Ex1:
a: int
@dataclass
class Ex2:
b: int
with pytest.raises(TypeError, match="may not contain more than one dataclass"):
proto.Decoder(Union[Ex1, Ex2])
def test_subtype_error(self, proto):
@dataclass
class Ex:
a: int
b: Union[list, tuple]
with pytest.raises(TypeError, match="may not contain more than one array-like"):
proto.Decoder(Ex)
assert not hasattr(Ex, "__msgspec_cache__")
def test_recursive_type(self, proto):
source = """
from __future__ import annotations
from typing import Union
from dataclasses import dataclass
@dataclass
class Ex:
a: int
b: Union[Ex, None]
"""
with temp_module(source) as mod:
msg = mod.Ex(a=1, b=mod.Ex(a=2, b=None))
dec = proto.Decoder(mod.Ex)
assert dec.decode(proto.encode(msg)) == msg
with pytest.raises(ValidationError) as rec:
dec.decode(proto.encode({"a": 1, "b": {"a": "bad"}}))
assert "`$.b.a`" in str(rec.value)
assert "Expected `int`, got `str`" in str(rec.value)
def test_classvars_ignored(self, proto):
source = """
from __future__ import annotations
from typing import ClassVar
from dataclasses import dataclass
@dataclass
class Ex:
a: int
other: ClassVar[int]
"""
with temp_module(source) as mod:
msg = mod.Ex(a=1)
dec = proto.Decoder(mod.Ex)
res = dec.decode(proto.encode({"a": 1, "other": 2}))
assert res == msg
assert not hasattr(res, "other")
def test_initvars_forbidden(self, proto):
source = """
from dataclasses import dataclass, InitVar
@dataclass
class Ex:
a: int
other: InitVar[int]
"""
with temp_module(source) as mod:
with pytest.raises(TypeError, match="`InitVar` fields are not supported"):
proto.Decoder(mod.Ex)
@pytest.mark.parametrize("slots", [False, True])
def test_decode_dataclass(self, proto, slots):
if slots:
if not PY310:
pytest.skip(reason="Python 3.10+ required")
kws = {"slots": True}
else:
kws = {}
@dataclass(**kws)
class Example:
a: int
b: int
c: int
dec = proto.Decoder(Example)
msg = Example(1, 2, 3)
res = dec.decode(proto.encode(msg))
assert res == msg
# Extra fields ignored
res = dec.decode(
proto.encode({"x": -1, "a": 1, "y": -2, "b": 2, "z": -3, "c": 3, "": -4})
)
assert res == msg
# Missing fields error
with pytest.raises(ValidationError, match="missing required field `b`"):
dec.decode(proto.encode({"a": 1}))
# Incorrect field types error
with pytest.raises(
ValidationError, match=r"Expected `int`, got `str` - at `\$.a`"
):
dec.decode(proto.encode({"a": "bad"}))
@pytest.mark.parametrize("frozen", [False, True])
@pytest.mark.parametrize("slots", [False, True])
def test_decode_dataclass_defaults(self, proto, frozen, slots):
if slots:
if not PY310:
pytest.skip(reason="Python 3.10+ required")
kws = {"slots": True}
else:
kws = {}
@dataclass(frozen=frozen, **kws)
class Example:
a: int
b: int
c: int = -3
d: int = -4
e: int = field(default_factory=lambda: -1000)
dec = proto.Decoder(Example)
for args in [(1, 2), (1, 2, 3), (1, 2, 3, 4), (1, 2, 3, 4, 5)]:
sol = Example(*args)
msg = dict(zip("abcde", args))
res = dec.decode(proto.encode(msg))
assert res == sol
# Missing fields error
with pytest.raises(ValidationError, match="missing required field `a`"):
dec.decode(proto.encode({"c": 1, "d": 2, "e": 3}))
def test_decode_dataclass_default_factory_errors(self, proto):
def bad():
raise ValueError("Oh no!")
@dataclass
class Example:
a: int = field(default_factory=bad)
with pytest.raises(ValueError, match="Oh no!"):
proto.decode(proto.encode({}), type=Example)
def test_decode_dataclass_frozen(self, proto):
@dataclass(frozen=True)
class Point:
x: int
y: int
msg = proto.encode(Point(1, 2))
res = proto.decode(msg, type=Point)
assert res == Point(1, 2)
def test_decode_dataclass_post_init(self, proto):
called = False
@dataclass
class Example:
a: int
def __post_init__(self):
nonlocal called
called = True
res = proto.decode(proto.encode({"a": 1}), type=Example)
assert res.a == 1
assert called
@pytest.mark.parametrize("exc_class", [ValueError, TypeError, OSError])
def test_decode_dataclass_post_init_errors(self, proto, exc_class):
@dataclass
class Example:
a: int
def __post_init__(self):
raise exc_class("Oh no!")
expected = (
ValidationError if exc_class in (ValueError, TypeError) else exc_class
)
with pytest.raises(expected, match="Oh no!") as rec:
proto.decode(proto.encode([{"a": 1}]), type=List[Example])
if expected is ValidationError:
assert "- at `$[0]`" in str(rec.value)
def test_decode_dataclass_not_object(self, proto):
@dataclass
class Example:
a: int
b: int
dec = proto.Decoder(Example)
msg = proto.encode([])
with pytest.raises(ValidationError, match="Expected `object`, got `array`"):
dec.decode(msg)
@pytest.mark.skipif(attrs is None, reason="attrs not installed")
class TestAttrs:
def test_factory_takes_self_not_implemented(self, proto):
"""This feature is doable, but not yet implemented"""
@attrs.define
class Test:
x: int = attrs.Factory(lambda self: 0, takes_self=True)
with pytest.raises(NotImplementedError):
proto.Decoder(Test)
@pytest.mark.parametrize("slots", [True, False])
def test_encode_attrs(self, proto, slots):
@attrs.define(slots=slots)
class Test:
x: int
y: int
x = Test(1, 2)
res = proto.encode(x)
sol = proto.encode({"x": 1, "y": 2})
assert res == sol
@pytest.mark.parametrize("slots", [True, False])
def test_encode_attrs_missing_fields(self, proto, slots):
@attrs.define(slots=slots)
class Test:
x: int
y: int
z: int
x = Test(1, 2, 3)
sol = {"x": 1, "y": 2, "z": 3}
for key in "xyz":
delattr(x, key)
del sol[key]
res = proto.decode(proto.encode(x))
assert res == sol
@pytest.mark.parametrize("slots_base", [True, False])
@pytest.mark.parametrize("slots", [True, False])
def test_encode_attrs_subclasses(self, proto, slots_base, slots):
@attrs.define(slots=slots_base)
class Base:
x: int
y: int
@attrs.define(slots=slots)
class Test(Base):
y: int
z: int
x = Test(1, 2, 3)
res = proto.decode(proto.encode(x))
assert res == {"x": 1, "y": 2, "z": 3}
# Missing attribute ignored
del x.y
res = proto.decode(proto.encode(x))
assert res == {"x": 1, "z": 3}
def test_encode_attrs_weakref_slot(self, proto):
@attrs.define(slots=True, weakref_slot=True)
class Test:
x: int
y: int
x = Test(1, 2)
ref = weakref.ref(x) # noqa
res = proto.decode(proto.encode(x))
assert res == {"x": 1, "y": 2}
@pytest.mark.parametrize("slots", [True, False])
def test_encode_attrs_skip_leading_underscore(self, proto, slots):
@attrs.define(slots=slots)
class Test:
x: int
y: int
_z: int
x = Test(1, 2, 3)
res = proto.encode(x)
sol = proto.encode({"x": 1, "y": 2})
assert res == sol
@pytest.mark.parametrize("slots", [False, True])
def test_decode_attrs(self, proto, slots):
@attrs.define(slots=slots)
class Example:
a: int
b: int
c: int
dec = proto.Decoder(Example)
msg = Example(1, 2, 3)
res = dec.decode(proto.encode(msg))
assert res == msg
# Extra fields ignored
res = dec.decode(
proto.encode({"x": -1, "a": 1, "y": -2, "b": 2, "z": -3, "c": 3, "": -4})
)
assert res == msg
# Missing fields error
with pytest.raises(ValidationError, match="missing required field `b`"):
dec.decode(proto.encode({"a": 1}))
# Incorrect field types error
with pytest.raises(
ValidationError, match=r"Expected `int`, got `str` - at `\$.a`"
):
dec.decode(proto.encode({"a": "bad"}))
@pytest.mark.parametrize("frozen", [False, True])
@pytest.mark.parametrize("slots", [False, True])
def test_decode_attrs_defaults(self, proto, frozen, slots):
@attrs.define(frozen=frozen, slots=slots)
class Example:
a: int
b: int
c: int = -3
d: int = -4
e: int = attrs.field(factory=lambda: -1000)
dec = proto.Decoder(Example)
for args in [(1, 2), (1, 2, 3), (1, 2, 3, 4), (1, 2, 3, 4, 5)]:
sol = Example(*args)
msg = dict(zip("abcde", args))
res = dec.decode(proto.encode(msg))
assert res == sol
# Missing fields error
with pytest.raises(ValidationError, match="missing required field `a`"):
dec.decode(proto.encode({"c": 1, "d": 2, "e": 3}))
def test_decode_attrs_default_factory_errors(self, proto):
def bad():
raise ValueError("Oh no!")
@attrs.define
class Example:
a: int = attrs.field(factory=bad)
with pytest.raises(ValueError, match="Oh no!"):
proto.decode(proto.encode({}), type=Example)
def test_decode_attrs_frozen(self, proto):
@attrs.define(frozen=True)
class Example:
x: int
y: int
msg = Example(1, 2)
res = proto.decode(proto.encode(msg), type=Example)
assert res == Example(1, 2)
def test_decode_attrs_post_init(self, proto):
called = False
@attrs.define
class Example:
a: int
def __attrs_post_init__(self):
nonlocal called
called = True
res = proto.decode(proto.encode({"a": 1}), type=Example)
assert res.a == 1
assert called
@pytest.mark.parametrize("exc_class", [ValueError, TypeError, OSError])
def test_decode_attrs_post_init_errors(self, proto, exc_class):
@attrs.define
class Example:
a: int
def __attrs_post_init__(self):
raise exc_class("Oh no!")
expected = (
ValidationError if exc_class in (ValueError, TypeError) else exc_class
)
with pytest.raises(expected, match="Oh no!") as rec:
proto.decode(proto.encode([{"a": 1}]), type=List[Example])
if expected is ValidationError:
assert "- at `$[0]`" in str(rec.value)
def test_decode_attrs_pre_init(self, proto):
called = False
@attrs.define
class Example:
a: int
def __attrs_pre_init__(self):
nonlocal called
called = True
res = proto.decode(proto.encode({"a": 1}), type=Example)
assert res.a == 1
assert called
def test_decode_attrs_pre_init_errors(self, proto):
@attrs.define
class Example:
a: int
def __attrs_pre_init__(self):
raise ValueError("Oh no!")
with pytest.raises(ValueError, match="Oh no!"):
proto.decode(proto.encode({"a": 1}), type=Example)
def test_decode_attrs_validators(self, proto):
def not2(self, attr, value):
if value == 2:
raise ValueError("Oh no!")
@attrs.define
class Example:
a: int = attrs.field(validator=[attrs.validators.gt(0), not2])
res = proto.decode(proto.encode({"a": 1}), type=Example)
assert res.a == 1
with pytest.raises(ValidationError):
res = proto.decode(proto.encode({"a": -1}), type=Example)
with pytest.raises(ValidationError, match="Oh no!"):
res = proto.decode(proto.encode({"a": 2}), type=Example)
def test_decode_attrs_not_object(self, proto):
@attrs.define
class Example:
a: int
b: int
dec = proto.Decoder(Example)
msg = proto.encode([])
with pytest.raises(ValidationError, match="Expected `object`, got `array`"):
dec.decode(msg)
class TestDate:
def test_encode_date(self, proto):
# All fields, zero padded
x = datetime.date(1, 2, 3)
s = proto.decode(proto.encode(x))
assert s == "0001-02-03"
# All fields, no zeros
x = datetime.date(1234, 12, 31)
s = proto.decode(proto.encode(x))
assert s == "1234-12-31"
@pytest.mark.parametrize(
"s",
[
"0001-01-01",
"9999-12-31",
"0001-02-03",
"2020-02-29",
],
)
def test_decode_date(self, proto, s):
sol = datetime.date.fromisoformat(s)
res = proto.decode(proto.encode(s), type=datetime.date)
assert type(res) is datetime.date
assert res == sol
def test_decode_date_wrong_type(self, proto):
msg = proto.encode([])
with pytest.raises(ValidationError, match="Expected `date`, got `array`"):
proto.decode(msg, type=datetime.date)
@pytest.mark.parametrize(
"s",
[
# Incorrect field lengths
"001-02-03",
"0001-2-03",
"0001-02-3",
# Trailing data
"0001-02-0300",
# Truncated
"0001-02-",
# Invalid characters
"000a-02-03",
"0001-0a-03",
"0001-02-0a",
# Year out of range
"0000-02-03",
# Month out of range
"0001-00-03",
"0001-13-03",
# Day out of range for month
"0001-02-00",
"0001-02-29",
"2000-02-30",
],
)
def test_decode_date_malformed(self, proto, s):
msg = proto.encode(s)
with pytest.raises(ValidationError, match="Invalid RFC3339"):
proto.decode(msg, type=datetime.date)
class TestTime:
@staticmethod
def parse(t_str):
t_str = t_str.replace("Z", "+00:00")
return datetime.time.fromisoformat(t_str)
@pytest.mark.parametrize(
"t",
[
"00:00:00",
"01:02:03",
"01:02:03.000004",
"12:34:56.789000",
"23:59:59.999999",
],
)
def test_encode_time_naive(self, proto, t):
res = proto.encode(self.parse(t))
sol = proto.encode(t)
assert res == sol
@pytest.mark.parametrize(
"t",
[
"00:00:00",
"01:02:03",
"01:02:03.000004",
"12:34:56.789000",
"23:59:59.999999",
],
)
def test_decode_time_naive(self, proto, t):
sol = self.parse(t)
res = proto.decode(proto.encode(t), type=datetime.time)
assert type(res) is datetime.time
assert res == sol
def test_decode_time_wrong_type(self, proto):
msg = proto.encode([])
with pytest.raises(ValidationError, match="Expected `time`, got `array`"):
proto.decode(msg, type=datetime.time)
@pytest.mark.parametrize(
"offset",
[
datetime.timedelta(0),
datetime.timedelta(days=1, microseconds=-1),
datetime.timedelta(days=-1, microseconds=1),
datetime.timedelta(days=1, seconds=-29),
datetime.timedelta(days=-1, seconds=29),
datetime.timedelta(days=0, seconds=30),
datetime.timedelta(days=0, seconds=-30),
],
)
def test_encode_time_offset_is_appx_equal_to_utc(self, proto, offset):
x = datetime.time(14, 56, 27, 123456, datetime.timezone(offset))
res = proto.encode(x)
sol = proto.encode("14:56:27.123456Z")
assert res == sol
@pytest.mark.parametrize(
"offset, t_str",
[
(
datetime.timedelta(days=1, seconds=-30),
"14:56:27.123456+23:59",
),
(
datetime.timedelta(days=-1, seconds=30),
"14:56:27.123456-23:59",
),
(
datetime.timedelta(minutes=19, seconds=32, microseconds=130000),
"14:56:27.123456+00:20",
),
],
)
def test_encode_time_offset_rounds_to_nearest_minute(self, proto, offset, t_str):
x = datetime.time(14, 56, 27, 123456, datetime.timezone(offset))
res = proto.encode(x)
sol = proto.encode(t_str)
assert res == sol
def test_encode_time_zoneinfo(self):
import zoneinfo
try:
x = datetime.time(1, 2, 3, 456789, zoneinfo.ZoneInfo("America/Chicago"))
except zoneinfo.ZoneInfoNotFoundError:
pytest.skip(reason="Failed to load timezone")
sol = msgspec.json.encode(x.isoformat())
res = msgspec.json.encode(x)
assert res == sol
@pytest.mark.parametrize(
"dt",
[
"04:05:06.000007",
"04:05:06.007",
"04:05:06",
"21:19:22.123456",
],
)
@pytest.mark.parametrize("suffix", ["", "Z", "+00:00", "-00:00"])
def test_decode_time_utc(self, proto, dt, suffix):
dt += suffix
sol = self.parse(dt)
msg = proto.encode(sol)
res = proto.decode(msg, type=datetime.time)
assert res == sol
@pytest.mark.parametrize("t", ["00:00:01", "12:01:01"])
@pytest.mark.parametrize("sign", ["-", "+"])
@pytest.mark.parametrize("hour", [0, 8, 12, 16, 23])
@pytest.mark.parametrize("minute", [0, 30])
def test_decode_time_with_timezone(self, proto, t, sign, hour, minute):
s = f"{t}{sign}{hour:02}:{minute:02}"
msg = proto.encode(s)
res = proto.decode(msg, type=datetime.time)
sol = self.parse(s)
assert res == sol
@pytest.mark.parametrize("z", ["Z", "z"])
def test_decode_time_not_case_sensitive(self, proto, z):
"""Z can be upper/lowercase"""
sol = datetime.time(4, 5, 6, 7, UTC)
res = proto.decode(proto.encode(f"04:05:06.000007{z}"), type=datetime.time)
assert res == sol
@pytest.mark.parametrize(
"lax, strict",
[
("03:04:05+0102", "03:04:05+01:02"),
("03:04:05-0102", "03:04:05-01:02"),
],
)
def test_decode_time_rfc3339_relaxed(self, lax, strict, proto):
"""msgspec supports a few relaxations of the RFC3339 format."""
sol = datetime.time.fromisoformat(strict)
msg = proto.encode(lax)
res = proto.decode(msg, type=datetime.time)
assert res == sol
@pytest.mark.parametrize(
"t, sol",
[
(
"03:04:05.1234564Z",
datetime.time(3, 4, 5, 123456, UTC),
),
(
"03:04:05.1234565Z",
datetime.time(3, 4, 5, 123457, UTC),
),
(
"03:04:05.12345650000000000001Z",
datetime.time(3, 4, 5, 123457, UTC),
),
(
"03:04:05.9999995Z",
datetime.time(3, 4, 6, 0, UTC),
),
(
"03:04:59.9999995Z",
datetime.time(3, 5, 0, 0, UTC),
),
(
"03:59:59.9999995Z",
datetime.time(4, 0, 0, 0, UTC),
),
(
"23:59:59.9999995Z",
datetime.time(0, 0, 0, 0, UTC),
),
],
)
def test_decode_time_nanos(self, proto, t, sol):
msg = proto.encode(t)
res = proto.decode(msg, type=datetime.time)
assert res == sol
@pytest.mark.parametrize(
"s",
[
# Incorrect field lengths
"1:02:03.0000004Z",
"01:2:03.0000004Z",
"01:02:3.0000004Z",
"01:02:03.0000004+5:06",
"01:02:03.0000004+05:6",
"01:02:03.0000004+056",
"01:02:03.0000004+05600",
# Trailing data
"01:02:030",
"01:02:03a",
"01:02:03.a",
"01:02:03.0a",
"01:02:03.0000004a",
"01:02:03.0000004+00:000",
"01:02:03.0000004+00000",
"01:02:03.0000004Z0",
# Truncated
"01:02:3",
# Missing +/-
"01:02:0300:00",
# Missing digits after decimal
"01:02:03.",
"01:02:03.Z",
# Invalid characters
"0a:02:03.004+05:06",
"01:0a:03.004+05:06",
"01:02:0a.004+05:06",
"01:02:03.00a+05:06",
"01:02:03.004+0a:06",
"01:02:03.004+05:0a",
"01:02:03.004+0a06",
"01:02:03.004+050a",
# Hour out of range
"24:02:03.004",
# Minute out of range
"01:60:03.004",
# Second out of range
"01:02:60.004",
# Timezone hour out of range
"01:02:03.004+24:00",
"01:02:03.004-24:00",
# Timezone minute out of range
"01:02:03.004+00:60",
"01:02:03.004-00:60",
],
)
def test_decode_time_malformed(self, proto, s):
msg = proto.encode(s)
with pytest.raises(ValidationError, match="Invalid RFC3339"):
proto.decode(msg, type=datetime.time)
class TestTimeDelta:
@pytest.mark.parametrize("neg", [False, True])
@pytest.mark.parametrize(
"td, msg",
[
(timedelta(), "P0D"),
(timedelta(1), "P1D"),
(timedelta(10), "P10D"),
(timedelta(123456789), "P123456789D"),
(timedelta(0, 1), "PT1S"),
(timedelta(0, 10), "PT10S"),
(timedelta(0, 12345), "PT12345S"),
(timedelta(0, 0, 1), "PT0.000001S"),
(timedelta(0, 0, 10), "PT0.00001S"),
(timedelta(0, 0, 100), "PT0.0001S"),
(timedelta(0, 0, 1000), "PT0.001S"),
(timedelta(0, 0, 10000), "PT0.01S"),
(timedelta(0, 0, 100000), "PT0.1S"),
(timedelta(123456789, 54321, 123456), "P123456789DT54321.123456S"),
(timedelta(0, 86399, 999999), "PT86399.999999S"),
],
)
def test_roundtrip_timedelta(self, proto, td, msg, neg):
if neg and td:
td = -td
msg = "-" + msg
buf = proto.encode(td)
res = proto.decode(buf)
assert res == msg
td2 = proto.decode(buf, type=timedelta)
assert td2 == td
@pytest.mark.parametrize(
"msg, sol",
[
("PT0S", timedelta()),
("+P1DT2S", timedelta(1, 2)),
("-P1DT2S", -timedelta(1, 2)),
("P000DT000.000S", timedelta()),
("-P000DT000.000S", timedelta()),
("P00012DT0045.670000000S", timedelta(12, 45, 670000)),
("P123456789.12345678912D", timedelta(123456789, 10666, 666580)),
("P123456789.12345678912999D", timedelta(123456789, 10666, 666580)),
("P123456789.12345678913D", timedelta(123456789, 10666, 666581)),
("PT0123H", timedelta(0, 123 * 60 * 60)),
("PT0123.456H", timedelta(0, 123.456 * 60 * 60)),
("PT0123M", timedelta(0, 123 * 60)),
("PT0123.456M", timedelta(0, 123.456 * 60)),
],
)
def test_decode_timedelta(self, proto, msg, sol):
buf = proto.encode(msg)
res = proto.decode(buf, type=timedelta)
assert res == sol
def test_decode_timedelta_case_insensitive(self, proto):
buf = proto.encode("p1dt2h3m4s")
res = proto.decode(buf, type=timedelta)
assert res == timedelta(1, 2 * 60 * 60 + 3 * 60 + 4)
@pytest.mark.parametrize(
"msg",
[
"P999999999DT86399.999999S",
"P999999998DT24H86399.999999S",
"P999999999DT86399.9999994S",
],
)
def test_decode_timedelta_max(self, proto, msg):
buf = proto.encode(msg)
res = proto.decode(buf, type=timedelta)
assert res == timedelta.max
@pytest.mark.parametrize(
"msg",
[
"-P999999999D",
"-P999999998DT24H",
"-P999999998DT23H3600S",
"-P999999998DT86399.9999995S",
],
)
def test_decode_timedelta_min(self, proto, msg):
buf = proto.encode(msg)
res = proto.decode(buf, type=timedelta)
assert res == timedelta.min
def test_decode_timedelta_wrong_type(self, proto):
bad = proto.encode([])
with pytest.raises(ValidationError, match="Expected `duration`, got `array`"):
proto.decode(bad, type=timedelta)
@pytest.mark.parametrize(
"msg",
[
# No P
"",
"-",
"+",
# Just P
"P",
"-P",
"+P",
# Missing Number
"PD",
"P.0D",
# Missing digit after decimal place
"P123.",
"P123.D",
# Missing Unit
"P0",
"P0.0",
"P0.00",
"P0.000000000000123",
# Trailing T
"PT",
"P0DT",
# Missing T
"P1D2H",
"P1D2S",
# Repeat T
"PTT0S",
# Repeat Units
"P1D2D",
"PT1H2H",
"PT1M2M",
"PT1S2S",
# Units in wrong order
"PT1H1D",
"PT1M1H",
"PT1S1M",
# Non-fractional after fractional
"PT1.2H1M",
"P1.2DT1H",
"PT1.2H0S",
# Invalid characters
"1P1D",
"P-1D",
"P1.-D",
"P1.0-D",
"P1.000000000000123-D",
"P1D-",
],
)
def test_decode_timedelta_malformed(self, proto, msg):
encoded = proto.encode(msg)
with pytest.raises(ValidationError, match="Invalid ISO8601 duration"):
proto.decode(encoded, type=timedelta)
@pytest.mark.parametrize(
"msg",
[
"P1000000000D",
"PT140737488355329S",
"P999999999DT86399.9999995S",
"-P999999999DT0.0000005S",
"P999999998DT48H",
"-P999999998DT24H01S",
],
)
def test_decode_timedelta_out_of_range(self, proto, msg):
encoded = proto.encode(msg)
with pytest.raises(ValidationError, match="Duration is out of range"):
proto.decode(encoded, type=timedelta)
@pytest.mark.parametrize("unit", ["Y", "M", "W"])
def test_decode_timedelta_unsupported_unit(self, proto, unit):
upper = f"P1{unit}"
for msg in [upper, upper.lower()]:
encoded = proto.encode(msg)
with pytest.raises(ValidationError, match="Only units 'D'"):
proto.decode(encoded, type=timedelta)
class TestUUID:
def test_encoder_uuid_format(self, proto):
assert proto.Encoder().uuid_format == "canonical"
assert proto.Encoder(uuid_format="canonical").uuid_format == "canonical"
assert proto.Encoder(uuid_format="hex").uuid_format == "hex"
if proto is msgspec.msgpack:
assert proto.Encoder(uuid_format="bytes").uuid_format == "bytes"
else:
with pytest.raises(
ValueError,
match="`uuid_format` must be 'canonical' or 'hex', got 'bytes'",
):
proto.Encoder(uuid_format="bytes")
def test_encoder_invalid_uuid_format(self, proto):
if proto is msgspec.json:
msg = "`uuid_format` must be 'canonical' or 'hex', got {!r}"
else:
msg = "`uuid_format` must be 'canonical', 'hex', or 'bytes', got {!r}"
for bad in ["bad", 1]:
with pytest.raises(ValueError, match=msg.format(bad)):
proto.Encoder(uuid_format=bad)
@pytest.mark.parametrize("format", ["canonical", "hex"])
def test_encode_uuid(self, format, proto):
u = uuid.uuid4()
enc = proto.Encoder(uuid_format=format)
res = enc.encode(u)
if format == "canonical":
sol = enc.encode(str(u))
else:
sol = enc.encode(u.hex)
assert res == sol
def test_encode_uuid_bytes(self):
u = uuid.uuid4()
enc = msgspec.msgpack.Encoder(uuid_format="bytes")
res = enc.encode(u)
sol = enc.encode(u.bytes)
assert res == sol
def test_encode_uuid_subclass(self, proto):
class Ex(uuid.UUID):
pass
s = "4184defa-4d1a-4497-a140-fd1ec0b22383"
assert proto.encode(Ex(s)) == proto.encode(s)
def test_encode_uuid_malformed_internals(self, proto):
"""Ensure that if some other code mutates the uuid object, we error
nicely rather than segfaulting"""
u = uuid.uuid4()
object.__delattr__(u, "int")
with pytest.raises(AttributeError):
proto.encode(u)
u = uuid.uuid4()
object.__setattr__(u, "int", "oops")
with pytest.raises(TypeError):
proto.encode(u)
@pytest.mark.parametrize("upper", [False, True])
@pytest.mark.parametrize("hyphens", [False, True])
def test_decode_uuid(self, proto, upper, hyphens):
u = uuid.uuid4()
s = str(u) if hyphens else u.hex
if upper:
s = s.upper()
msg = proto.encode(s)
res = proto.decode(msg, type=uuid.UUID)
assert res == u
assert res.is_safe == u.is_safe
def test_decode_uuid_from_bytes(self):
sol = uuid.uuid4()
msg = msgspec.msgpack.encode(sol.bytes)
res = msgspec.msgpack.decode(msg, type=uuid.UUID)
assert res == sol
bad_msg = msgspec.msgpack.encode(b"x" * 8)
with pytest.raises(msgspec.ValidationError, match="Invalid UUID bytes"):
msgspec.msgpack.decode(bad_msg, type=uuid.UUID)
@pytest.mark.parametrize(
"uuid_str",
[
# Truncated
"12345678-1234-1234-1234-1234567890a",
"123456781234123412341234567890a",
# Truncated segments
"1234567-1234-1234-1234-1234567890abc",
"12345678-123-1234-1234-1234567890abc",
"12345678-1234-123-1234-1234567890abc",
"12345678-1234-1234-123-1234567890abc",
"12345678-1234-1234-1234-1234567890a-",
# Invalid character
"123456x81234123412341234567890ab",
"123456x8-1234-1234-1234-1234567890ab",
"1234567x-1234-1234-1234-1234567890ab",
"12345678-123x-1234-1234-1234567890ab",
"12345678-1234-123x-1234-1234567890ab",
"12345678-1234-1234-123x-1234567890ab",
"12345678-1234-1234-1234-1234567890ax",
# Invalid dash
"12345678.1234-1234-1234-1234567890ab",
"12345678-1234.1234-1234-1234567890ab",
"12345678-1234-1234.1234-1234567890ab",
"12345678-1234-1234-1234.1234567890ab",
# Trailing data
"12345678-1234-1234-1234-1234567890ab-",
"12345678-1234-1234-1234-1234567890abc",
],
)
def test_decode_uuid_malformed(self, proto, uuid_str):
msg = proto.encode(uuid_str)
with pytest.raises(ValidationError, match="Invalid UUID"):
proto.decode(msg, type=uuid.UUID)
class TestNewType:
def test_decode_newtype(self, proto):
UserId = NewType("UserId", int)
assert proto.decode(proto.encode(1), type=UserId) == 1
with pytest.raises(ValidationError):
proto.decode(proto.encode("bad"), type=UserId)
# Nested NewId works
UserId2 = NewType("UserId2", UserId)
assert proto.decode(proto.encode(1), type=UserId2) == 1
with pytest.raises(ValidationError):
proto.decode(proto.encode("bad"), type=UserId2)
def test_decode_annotated_newtype(self, proto):
UserId = NewType("UserId", int)
dec = proto.Decoder(Annotated[UserId, msgspec.Meta(ge=0)])
assert dec.decode(proto.encode(1)) == 1
with pytest.raises(ValidationError):
dec.decode(proto.encode(-1))
def test_decode_newtype_annotated(self, proto):
UserId = NewType("UserId", Annotated[int, msgspec.Meta(ge=0)])
dec = proto.Decoder(UserId)
assert dec.decode(proto.encode(1)) == 1
with pytest.raises(ValidationError):
dec.decode(proto.encode(-1))
def test_decode_annotated_newtype_annotated(self, proto):
UserId = Annotated[
NewType("UserId", Annotated[int, msgspec.Meta(ge=0)]), msgspec.Meta(le=10)
]
dec = proto.Decoder(UserId)
assert dec.decode(proto.encode(1)) == 1
for bad in [-1, 11]:
with pytest.raises(ValidationError):
dec.decode(proto.encode(bad))
class TestTypeAlias:
@py312_plus
def test_simple(self, proto):
with temp_module("type Ex = str | None") as mod:
dec = proto.Decoder(mod.Ex)
assert dec.decode(proto.encode("test")) == "test"
assert dec.decode(proto.encode(None)) is None
with pytest.raises(ValidationError):
dec.decode(proto.encode(1))
@py312_plus
def test_generic(self, proto):
with temp_module("type Pair[T] = tuple[T, T]") as mod:
dec = proto.Decoder(mod.Pair)
assert dec.decode(proto.encode((1, 2))) == (1, 2)
for bad in [1, [1, 2, 3]]:
with pytest.raises(ValidationError):
dec.decode(proto.encode(bad))
@py312_plus
def test_parametrized_generic(self, proto):
with temp_module("type Pair[T] = tuple[T, T]") as mod:
dec = proto.Decoder(mod.Pair[int])
assert dec.decode(proto.encode((1, 2))) == (1, 2)
for bad in [1, [1, 2, 3], [1, "a"]]:
with pytest.raises(ValidationError):
dec.decode(proto.encode(bad))
@py312_plus
def test_typealias_wrapping_typealias(self, proto):
src = """
type Pair[T] = tuple[T, T]
type Pairs[T] = list[Pair[T]]
"""
with temp_module(src) as mod:
dec = proto.Decoder(mod.Pairs)
for good in [[], [(1, 2), (3, 4)]]:
assert dec.decode(proto.encode(good)) == good
for bad in [1, [1], [(1, 2, 3)]]:
with pytest.raises(ValidationError):
dec.decode(proto.encode(bad))
dec = proto.Decoder(mod.Pairs[int])
for good in [[], [(1, 2)], [(1, 2), (3, 4)]]:
assert dec.decode(proto.encode(good)) == good
for bad in [1, [1], [(1, "a")]]:
with pytest.raises(ValidationError):
dec.decode(proto.encode(bad))
@py312_plus
def test_typealias_with_constraints(self, proto):
src = """
import msgspec
from typing import Annotated
type Key = Annotated[str, msgspec.Meta(max_length=4)]
"""
with temp_module(src) as mod:
dec = proto.Decoder(mod.Key)
for good in ["", "abc", "abcd"]:
assert dec.decode(proto.encode(good)) == good
for bad in [1, "abcde"]:
with pytest.raises(ValidationError):
dec.decode(proto.encode(bad))
@py312_plus
def test_typealias_parametrized_generic_too_many_parameters(self):
with temp_module("type Pair[T] = tuple[T, T]") as mod:
with pytest.raises(TypeError):
msgspec.json.Decoder(mod.Pair[int, int])
@py312_plus
@pytest.mark.parametrize(
"src",
[
"type Ex = Ex | None",
"type Ex = tuple[Ex, int]",
"type Ex[T] = tuple[T, Ex[T]]",
"type Temp[T] = tuple[T, Temp[T]]; Ex = Temp[int]",
"type Temp[T] = tuple[T, Ex[T]]; type Ex[T] = tuple[Temp[T], T];",
],
)
def test_recursive_typealias_errors(self, src):
"""Eventually we should support this, but for now just test that it
errors cleanly"""
with temp_module(src) as mod:
with pytest.raises(RecursionError):
msgspec.json.Decoder(mod.Ex)
@py312_plus
def test_typealias_invalid_type(self):
with temp_module("type Ex = int | complex") as mod:
with pytest.raises(TypeError):
msgspec.json.Decoder(mod.Ex)
class TestDecimal:
def test_encoder_decimal_format(self, proto):
assert proto.Encoder().decimal_format == "string"
assert proto.Encoder(decimal_format="string").decimal_format == "string"
assert proto.Encoder(decimal_format="number").decimal_format == "number"
def test_encoder_invalid_decimal_format(self, proto):
with pytest.raises(ValueError, match="must be 'string' or 'number', got 'bad'"):
proto.Encoder(decimal_format="bad")
with pytest.raises(ValueError, match="must be 'string' or 'number', got 1"):
proto.Encoder(decimal_format=1)
def test_encoder_encode_decimal(self, proto):
enc = proto.Encoder()
d = decimal.Decimal("1.5")
s = str(d)
assert enc.encode(d) == enc.encode(s)
def test_Encoder_encode_decimal_string(self, proto):
enc = proto.Encoder(decimal_format="string")
d = decimal.Decimal("1.5")
sol = enc.encode(str(d))
assert enc.encode(d) == sol
buf = bytearray()
enc.encode_into(d, buf)
assert buf == sol
def test_Encoder_encode_decimal_number(self, proto):
enc = proto.Encoder(decimal_format="number")
d = decimal.Decimal("1.5")
sol = enc.encode(float(d))
assert enc.encode(d) == sol
buf = bytearray()
enc.encode_into(d, buf)
assert buf == sol
def test_encode_decimal(self, proto):
d = decimal.Decimal("1.5")
s = str(d)
assert proto.encode(d) == proto.encode(s)
@pytest.mark.parametrize(
"val", ["1.5", "InF", "-iNf", "iNfInItY", "-InFiNiTy", "NaN"]
)
def test_decode_decimal_str(self, val, proto):
sol = decimal.Decimal(val)
msg = proto.encode(sol)
res = proto.decode(msg, type=decimal.Decimal)
assert str(res) == str(sol)
assert type(res) is decimal.Decimal
def test_decode_decimal_str_invalid(self, proto):
msg = proto.encode("1..5")
with pytest.raises(ValidationError, match="Invalid decimal string"):
proto.decode(msg, type=decimal.Decimal)
@pytest.mark.parametrize("val", [-1, -1234, 1, 1234])
def test_decode_decimal_int(self, val, proto):
msg = proto.encode(val)
sol = decimal.Decimal(str(val))
res = proto.decode(msg, type=decimal.Decimal)
assert type(res) is decimal.Decimal
assert res == sol
@pytest.mark.parametrize(
"val", [0.0, 1.3, float("nan"), float("inf"), float("-inf")]
)
def test_decode_decimal_float(self, val, proto):
msg = proto.encode(val)
if msg == b"null":
pytest.skip("nonfinite values not supported")
sol = decimal.Decimal(str(val))
res = proto.decode(msg, type=decimal.Decimal)
assert str(res) == str(sol)
assert type(res) is decimal.Decimal
class TestAbstractTypes:
@pytest.mark.parametrize(
"typ",
[
typing.Collection,
typing.MutableSequence,
typing.Sequence,
collections.abc.Collection,
collections.abc.MutableSequence,
collections.abc.Sequence,
typing.MutableSet,
typing.AbstractSet,
collections.abc.MutableSet,
collections.abc.Set,
],
)
def test_abstract_sequence(self, proto, typ):
# Hacky, but it works
if "Set" in str(typ):
sol = {1, 2}
else:
sol = [1, 2]
msg = proto.encode(sol)
assert proto.decode(msg, type=typ) == sol
with pytest.raises(ValidationError, match="Expected `array`, got `str`"):
proto.decode(proto.encode("a"), type=typ)
assert proto.decode(msg, type=typ[int]) == sol
with pytest.raises(ValidationError, match="Expected `int`, got `str`"):
proto.decode(proto.encode(["a"]), type=typ[int])
@pytest.mark.parametrize(
"typ",
[
typing.MutableMapping,
typing.Mapping,
collections.abc.MutableMapping,
collections.abc.Mapping,
],
)
def test_abstract_mapping(self, proto, typ):
sol = {"x": 1, "y": 2}
msg = proto.encode(sol)
assert proto.decode(msg, type=typ) == sol
with pytest.raises(ValidationError, match="Expected `object`, got `str`"):
proto.decode(proto.encode("a"), type=typ)
assert proto.decode(msg, type=typ[str, int]) == sol
with pytest.raises(ValidationError, match="Expected `int`, got `str`"):
proto.decode(proto.encode({"a": "b"}), type=typ[str, int])
class TestUnset:
def test_unset_type_annotation_ignored(self, proto):
class Ex(Struct):
x: Union[int, UnsetType]
dec = proto.Decoder(Ex)
msg = proto.encode({"x": 1})
assert dec.decode(msg) == Ex(1)
def test_encode_unset_errors_other_contexts(self, proto):
with pytest.raises(TypeError):
proto.encode(UNSET)
@pytest.mark.parametrize("kind", ["struct", "dataclass", "attrs"])
def test_unset_encode(self, kind, proto):
if kind == "struct":
class Ex(Struct):
x: Union[int, UnsetType]
y: Union[int, UnsetType]
elif kind == "dataclass":
@dataclass
class Ex:
x: Union[int, UnsetType]
y: Union[int, UnsetType]
elif kind == "attrs":
attrs = pytest.importorskip("attrs")
@attrs.define
class Ex:
x: Union[int, UnsetType]
y: Union[int, UnsetType]
res = proto.encode(Ex(1, UNSET))
sol = proto.encode({"x": 1})
assert res == sol
res = proto.encode(Ex(UNSET, 2))
sol = proto.encode({"y": 2})
assert res == sol
res = proto.encode(Ex(UNSET, UNSET))
sol = proto.encode({})
assert res == sol
def test_unset_encode_struct_omit_defaults(self, proto):
class Ex(Struct, omit_defaults=True):
x: Union[int, UnsetType] = UNSET
y: Union[int, UnsetType] = UNSET
z: int = 0
for x, y in [(Ex(), {}), (Ex(y=2), {"y": 2}), (Ex(z=1), {"z": 1})]:
res = proto.encode(x)
sol = proto.encode(y)
assert res == sol
class TestOrder:
def test_encoder_order_attribute(self, proto):
enc = proto.Encoder()
assert enc.order is None
enc = proto.Encoder(order=None)
assert enc.order is None
enc = proto.Encoder(order="deterministic")
assert enc.order == "deterministic"
enc = proto.Encoder(order="sorted")
assert enc.order == "sorted"
def test_order_invalid(self, proto):
with pytest.raises(ValueError, match="`order` must be one of"):
proto.Encoder(order="bad")
with pytest.raises(ValueError, match="`order` must be one of"):
proto.encode(1, order="bad")
@pytest.mark.parametrize("msg", [{}, {"y": 1, "x": 2, "z": 3}])
@pytest.mark.parametrize("order", [None, "deterministic", "sorted"])
@pytest.mark.parametrize("use_encoder", [False, True])
def test_order_dict(self, msg, order, use_encoder, proto):
if use_encoder:
res = proto.Encoder(order=order).encode(msg)
else:
res = proto.encode(msg, order=order)
if order is not None:
sol = proto.encode(dict(sorted(msg.items())))
else:
sol = proto.encode(msg)
assert res == sol
def test_order_dict_non_str_errors(self, proto):
with pytest.raises(TypeError, match="Only dicts with str keys"):
proto.encode({"b": 2, 1: "a"}, order="deterministic")
def test_order_dict_unsortable(self, proto):
with pytest.raises(TypeError):
proto.encode({"x": 1, 1: 2}, order="deterministic")
@pytest.mark.parametrize("typ", [set, frozenset])
@pytest.mark.parametrize("order", ["deterministic", "sorted"])
def test_order_set(self, typ, proto, rand, order):
assert proto.encode(typ(), order=order) == proto.encode([])
msg = typ(rand.str(10) for _ in range(20))
res = proto.encode(msg, order=order)
sol = proto.encode(list(sorted(msg)))
assert res == sol
res = proto.encode(msg)
sol = proto.encode(list(msg))
assert res == sol
def test_order_set_unsortable(self, proto):
with pytest.raises(TypeError):
proto.encode({"x", 1}, order="deterministic")
@pytest.mark.parametrize("n", [0, 1, 2])
@pytest.mark.parametrize(
"kind",
[
"struct",
"dataclass",
"attrs",
"attrs-dict",
],
)
def test_order_object(self, kind, n, proto):
fields = [f"x{i}" for i in range(n)]
fields.reverse()
if kind == "struct":
cls = msgspec.defstruct("Test", fields)
elif kind == "dataclass":
cls = make_dataclass("Test", fields)
else:
attrs = pytest.importorskip("attrs")
cls = attrs.make_class("Test", fields, slots=(kind == "attrs"))
msg = cls(*range(n))
if kind in ("struct", "dataclass"):
# we currently don't guarantee field order with attrs types
sol = proto.encode(dict(zip(fields, range(n))))
res = proto.encode(msg)
assert res == sol
res = proto.encode(msg, order="deterministic")
assert res == sol
res = proto.encode(msg, order="sorted")
sol = proto.encode(dict(sorted(zip(fields, range(n)))))
assert res == sol
@pytest.mark.parametrize("kind", ["struct", "dataclass", "attrs", "attrs-dict"])
def test_order_unset(self, kind, proto):
if kind == "struct":
class Ex(Struct):
z: Union[int, UnsetType] = UNSET
x: Union[int, UnsetType] = UNSET
elif kind == "dataclass":
@dataclass
class Ex:
z: Union[int, UnsetType] = UNSET
x: Union[int, UnsetType] = UNSET
else:
attrs = pytest.importorskip("attrs")
@attrs.define(slots=(kind == "attrs"))
class Ex:
z: Union[int, UnsetType] = UNSET
x: Union[int, UnsetType] = UNSET
res = proto.encode(Ex(), order="sorted")
sol = proto.encode({})
assert res == sol
res = proto.encode(Ex(z=10), order="sorted")
sol = proto.encode({"z": 10})
assert res == sol
res = proto.encode(Ex(z=10, x=-1), order="sorted")
sol = proto.encode({"x": -1, "z": 10})
assert res == sol
def test_order_struct_omit_defaults(self, proto):
class Ex(Struct, omit_defaults=True):
z: int = 0
x: int = 1
y: int = 2
res = proto.encode(Ex(), order="sorted")
sol = proto.encode({})
assert res == sol
res = proto.encode(Ex(z=10), order="sorted")
sol = proto.encode({"z": 10})
assert res == sol
res = proto.encode(Ex(z=10, x=-1), order="sorted")
sol = proto.encode({"x": -1, "z": 10})
assert res == sol
def test_order_struct_tag(self, proto):
class Ex(Struct, tag_field="y", tag=2):
z: int
x: int
res = proto.encode(Ex(0, 1), order="sorted")
sol = proto.encode({"x": 1, "y": 2, "z": 0})
assert res == sol
@pytest.mark.parametrize("n", [0, 2, 3, 7, 15, 16, 17, 32, 100, 500, 1000, 10000])
def test_order_sort_implementation(self, rand, n):
keys = [f"x_{i}" for i in range(n)]
rand.shuffle(keys)
msg = dict(zip(keys, range(n)))
res = msgspec.json.encode(msg, order="deterministic")
sol = msgspec.json.encode(dict(sorted(msg.items())))
assert res == sol
class TestFinal:
def test_decode_final(self, proto):
dec = proto.Decoder(Final[int])
assert dec.decode(proto.encode(1)) == 1
with pytest.raises(ValidationError):
dec.decode(proto.encode("bad"))
def test_decode_final_annotated(self, proto):
dec = proto.Decoder(Final[Annotated[int, msgspec.Meta(ge=0)]])
assert dec.decode(proto.encode(1)) == 1
with pytest.raises(ValidationError):
dec.decode(proto.encode(-1))
def test_decode_final_newtype(self, proto):
UserId = NewType("UserId", int)
dec = proto.Decoder(Final[UserId])
assert dec.decode(proto.encode(1)) == 1
with pytest.raises(ValidationError):
dec.decode(proto.encode("bad"))
class TestLax:
@pytest.mark.parametrize("strict", [True, False])
def test_strict_lax_decoder(self, proto, strict):
dec = proto.Decoder(List[int], strict=strict)
assert dec.strict is strict
msg = proto.encode(["1", "2"])
if strict:
with pytest.raises(ValidationError):
dec.decode(msg)
else:
assert dec.decode(msg) == [1, 2]
def test_lax_none(self, proto):
for x in ["null", "Null", "nUll", "nuLl", "nulL"]:
msg = proto.encode(x)
assert proto.decode(msg, type=None, strict=False) is None
for x in ["xull", "nxll", "nuxl", "nulx"]:
msg = proto.encode(x)
with pytest.raises(ValidationError, match="Expected `null`, got `str`"):
proto.decode(msg, type=None, strict=False)
def test_lax_bool_true(self, proto):
for x in [1, "1", "true", "True", "tRue", "trUe", "truE"]:
msg = proto.encode(x)
assert proto.decode(msg, type=bool, strict=False) is True
for x in [-1, 3, "x", "xx", "xrue", "txue", "trxe", "trux"]:
msg = proto.encode(x)
typ = type(x).__name__
with pytest.raises(ValidationError, match=f"Expected `bool`, got `{typ}`"):
assert proto.decode(msg, type=bool, strict=False)
def test_lax_bool_false(self, proto):
for x in [0, "0", "false", "False", "fAlse", "faLse", "falSe", "falsE"]:
msg = proto.encode(x)
assert proto.decode(msg, type=bool, strict=False) is False
for x in [-1, 3, "x", "xx", "xalse", "fxlse", "faxse", "falxe", "falsx"]:
msg = proto.encode(x)
typ = type(x).__name__
with pytest.raises(ValidationError, match=f"Expected `bool`, got `{typ}`"):
assert proto.decode(msg, type=bool, strict=False)
def test_lax_int(self, proto):
for x in ["1", "-1", "123456"]:
msg = proto.encode(x)
assert proto.decode(msg, type=int, strict=False) == int(x)
for x in ["a", "1a", "1.5", "1..", "nan", "inf"]:
msg = proto.encode(x)
with pytest.raises(ValidationError, match="Expected `int`, got `str`"):
proto.decode(msg, type=int, strict=False)
def test_lax_int_from_float(self, proto):
bound = float(1 << 53)
for x in [-bound, -1.0, -0.0, 0.0, 1.0, bound]:
msg = proto.encode(x)
assert proto.decode(msg, type=int, strict=False) == int(x)
for x in [-bound - 2, -1.5, 0.001, 1.5, bound + 2]:
msg = proto.encode(x)
with pytest.raises(ValidationError, match="Expected `int`, got `float`"):
proto.decode(msg, type=int, strict=False)
def test_lax_int_constr(self, proto):
typ = Annotated[int, Meta(ge=0)]
msg = proto.encode("1")
assert proto.decode(msg, type=typ, strict=False) == 1
msg = proto.encode("-1")
with pytest.raises(ValidationError):
proto.decode(msg, type=typ, strict=False)
def test_lax_int_enum(self, proto):
class Ex(enum.IntEnum):
x = 1
y = -2
def roundtrip(msg):
return proto.decode(proto.encode(msg), type=Ex, strict=False)
assert roundtrip("1") is Ex.x
assert roundtrip("-2") is Ex.y
with pytest.raises(ValidationError, match="Invalid enum value 3"):
roundtrip("3")
with pytest.raises(ValidationError, match="Expected `int`, got `str`"):
roundtrip("A")
def test_lax_int_literal(self, proto):
typ = Literal[1, -2]
def roundtrip(msg):
return proto.decode(proto.encode(msg), type=typ, strict=False)
assert roundtrip("1") == 1
assert roundtrip("-2") == -2
with pytest.raises(ValidationError, match="Invalid enum value 3"):
roundtrip("3")
with pytest.raises(ValidationError, match="Expected `int`, got `str`"):
roundtrip("A")
def test_lax_float(self, proto):
for x in ["1", "-1", "123456", "1.5", "-1.5", "inf"]:
msg = proto.encode(x)
assert proto.decode(msg, type=float, strict=False) == float(x)
for x in ["a", "1a", "1.0.0", "1.."]:
msg = proto.encode(x)
with pytest.raises(ValidationError, match="Expected `float`, got `str`"):
proto.decode(msg, type=float, strict=False)
def test_lax_float_constr(self, proto):
msg = proto.encode("1.5")
assert proto.decode(msg, type=Annotated[float, Meta(ge=0)], strict=False) == 1.5
msg = proto.encode("-1.0")
with pytest.raises(ValidationError):
proto.decode(msg, type=Annotated[float, Meta(ge=0)], strict=False)
def test_lax_str(self, proto):
for x in ["1", "1.5", "false", "null"]:
msg = proto.encode(x)
assert proto.decode(msg, type=str, strict=False) == x
def test_lax_str_constr(self, proto):
typ = Annotated[str, Meta(max_length=10)]
msg = proto.encode("xxx")
assert proto.decode(msg, type=typ, strict=False) == "xxx"
msg = proto.encode("x" * 20)
with pytest.raises(ValidationError):
proto.decode(msg, type=typ, strict=False)
@pytest.mark.parametrize(
"x",
[
1234.0000004,
1234.0000006,
1234.000567,
1234.567,
1234.0,
0.123,
0.0,
1234,
0,
],
)
@pytest.mark.parametrize("sign", [-1, 1])
@pytest.mark.parametrize("transform", [None, str])
def test_lax_datetime(self, x, sign, transform, proto):
timestamp = x * sign
msg = proto.encode(transform(timestamp) if transform else timestamp)
sol = datetime.datetime.fromtimestamp(timestamp, UTC)
res = proto.decode(msg, type=datetime.datetime, strict=False)
assert res == sol
def test_lax_datetime_nonfinite_values(self, proto):
values = ["nan", "-inf", "inf"]
if proto is msgspec.msgpack:
values.extend([float(v) for v in values])
for val in values:
msg = proto.encode(val)
with pytest.raises(ValidationError, match="Invalid epoch timestamp"):
proto.decode(msg, type=datetime.datetime, strict=False)
@pytest.mark.parametrize("val", [-62135596801, 253402300801])
@pytest.mark.parametrize("type", [int, float, str])
def test_lax_datetime_out_of_range(self, val, type, proto):
msg = proto.encode(type(val))
with pytest.raises(ValidationError, match="out of range"):
proto.decode(msg, type=datetime.datetime, strict=False)
def test_lax_datetime_invalid_numeric_str(self, proto):
for bad in ["", "12e", "1234a", "1234-1", "1234.a"]:
msg = proto.encode(bad)
with pytest.raises(ValidationError, match="Invalid"):
proto.decode(msg, type=datetime.datetime, strict=False)
@pytest.mark.parametrize("val", [123, -123, 123.456, "123.456"])
def test_lax_datetime_naive_required(self, val, proto):
msg = proto.encode(val)
with pytest.raises(ValidationError, match="no timezone component"):
proto.decode(
msg, type=Annotated[datetime.datetime, Meta(tz=False)], strict=False
)
@pytest.mark.parametrize(
"x",
[
1234.0000004,
1234.0000006,
1234.000567,
1234.567,
1234.0,
0.123,
0.0,
1234,
0,
],
)
@pytest.mark.parametrize("sign", [-1, 1])
@pytest.mark.parametrize("transform", [None, str])
def test_lax_timedelta(self, x, sign, transform, proto):
timestamp = x * sign
msg = proto.encode(transform(timestamp) if transform else timestamp)
sol = datetime.timedelta(seconds=timestamp)
res = proto.decode(msg, type=datetime.timedelta, strict=False)
assert res == sol
def test_lax_timedelta_nonfinite_values(self, proto):
values = ["nan", "-inf", "inf"]
if proto is msgspec.msgpack:
values.extend([float(v) for v in values])
for val in values:
msg = proto.encode(val)
with pytest.raises(ValidationError, match="out of range"):
proto.decode(msg, type=datetime.timedelta, strict=False)
@pytest.mark.parametrize("val", [86400000000001, -86399999913601])
@pytest.mark.parametrize("type", [int, float, str])
def test_lax_timedelta_out_of_range(self, val, type, proto):
msg = proto.encode(type(val))
with pytest.raises(ValidationError, match="out of range"):
proto.decode(msg, type=datetime.timedelta, strict=False)
def test_lax_timedelta_invalid_numeric_str(self, proto):
for bad in ["", "12e", "1234a", "1234-1", "1234.a"]:
msg = proto.encode(bad)
with pytest.raises(ValidationError, match="Invalid"):
proto.decode(msg, type=datetime.timedelta, strict=False)
@pytest.mark.parametrize(
"x, sol",
[
("1", 1),
("0", 0),
("-1", -1),
("12.5", 12.5),
("inf", float("inf")),
("true", True),
("false", False),
("null", None),
],
)
def test_lax_union_valid(self, x, sol, proto):
typ = Union[int, float, bool, None]
msg = proto.encode(x)
assert_eq(proto.decode(msg, type=typ, strict=False), sol)
@pytest.mark.parametrize("x", ["1a", "1.5a", "falsx", "trux", "nulx"])
def test_lax_union_invalid(self, x, proto):
typ = Union[int, float, bool, None]
msg = proto.encode(x)
with pytest.raises(
ValidationError, match="Expected `int | float | bool | null`"
):
proto.decode(msg, type=typ, strict=False)
@pytest.mark.parametrize(
"x, err",
[
("-1", "`int` >= 0"),
("2000", "`int` <= 1000"),
("18446744073709551616", "`int` <= 1000"),
("-9223372036854775809", "`int` >= 0"),
("100.5", "`float` <= 100.0"),
],
)
def test_lax_union_invalid_constr(self, x, err, proto):
"""Ensure that values that parse properly but don't meet the specified
constraints error with a specific constraint error"""
msg = proto.encode(x)
typ = Union[
Annotated[int, Meta(ge=0), Meta(le=1000)],
Annotated[float, Meta(le=100)],
]
with pytest.raises(ValidationError, match=err):
proto.decode(msg, type=typ, strict=False)
@pytest.mark.parametrize(
"x, sol",
[
("1", 1),
("1.5", 1.5),
("false", False),
("true", True),
("null", None),
("2022-05-02", datetime.date(2022, 5, 2)),
],
)
def test_lax_union_extended(self, proto, x, sol):
typ = Union[int, float, bool, None, datetime.date]
msg = proto.encode(x)
assert_eq(proto.decode(msg, type=typ, strict=False), sol)
|