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
|
#The MIT License (MIT)
#Copyright (c) 2014 Microsoft Corporation
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
"""End to end test.
"""
import json
import logging
import os.path
import sys
import unittest
from six.moves import xrange
from struct import unpack, pack
# from six.moves.builtins import *
import time
import six
if six.PY2:
import urllib as urllib
else:
import urllib.parse as urllib
import uuid
import pytest
import azure.cosmos.base as base
import azure.cosmos.consistent_hash_ring as consistent_hash_ring
import azure.cosmos.documents as documents
import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.errors as errors
import azure.cosmos.hash_partition_resolver as hash_partition_resolver
from azure.cosmos.http_constants import HttpHeaders, StatusCodes, SubStatusCodes
import azure.cosmos.murmur_hash as murmur_hash
import azure.cosmos.range_partition_resolver as range_partition_resolver
import azure.cosmos.range as partition_range
import test.test_config as test_config
import test.test_partition_resolver as test_partition_resolver
import azure.cosmos.base as base
#IMPORTANT NOTES:
# Most test cases in this file create collections in your Azure Cosmos account.
# Collections are billing entities. By running these test cases, you may incur monetary costs on your account.
# To Run the test, replace the two member fields (masterKey and host) with values
# associated with your Azure Cosmos account.
@pytest.mark.usefixtures("teardown")
class CRUDTests(unittest.TestCase):
"""Python CRUD Tests.
"""
configs = test_config._test_config
host = configs.host
masterKey = configs.masterKey
connectionPolicy = configs.connectionPolicy
client = cosmos_client.CosmosClient(host, {'masterKey': masterKey}, connectionPolicy)
databseForTest = configs.create_database_if_not_exist(client)
def __AssertHTTPFailureWithStatus(self, status_code, func, *args, **kwargs):
"""Assert HTTP failure with status.
:Parameters:
- `status_code`: int
- `func`: function
"""
try:
func(*args, **kwargs)
self.assertFalse(True, 'function should fail.')
except errors.HTTPFailure as inst:
self.assertEqual(inst.status_code, status_code)
@classmethod
def setUpClass(cls):
if (cls.masterKey == '[YOUR_KEY_HERE]' or
cls.host == '[YOUR_ENDPOINT_HERE]'):
raise Exception(
"You must specify your Azure Cosmos account values for "
"'masterKey' and 'host' at the top of this class to run the "
"tests.")
def setUp(self):
self.client = cosmos_client.CosmosClient(self.host, {'masterKey': self.masterKey}, self.connectionPolicy)
def test_database_crud_self_link(self):
self._test_database_crud(False)
def test_database_crud_name_based(self):
self._test_database_crud(True)
def _test_database_crud(self, is_name_based):
# read databases.
databases = list(self.client.ReadDatabases())
# create a database.
before_create_databases_count = len(databases)
database_definition = { 'id': str(uuid.uuid4()) }
created_db = self.client.CreateDatabase(database_definition)
self.assertEqual(created_db['id'], database_definition['id'])
# Read databases after creation.
databases = list(self.client.ReadDatabases())
self.assertEqual(len(databases),
before_create_databases_count + 1,
'create should increase the number of databases')
# query databases.
databases = list(self.client.QueryDatabases({
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name':'@id', 'value': database_definition['id'] }
]
}))
self.assert_(databases,
'number of results for the query should be > 0')
# read database.
self.client.ReadDatabase(self.GetDatabaseLink(created_db, is_name_based))
# delete database.
self.client.DeleteDatabase(self.GetDatabaseLink(created_db, is_name_based))
# read database after deletion
self.__AssertHTTPFailureWithStatus(StatusCodes.NOT_FOUND,
self.client.ReadDatabase,
self.GetDatabaseLink(created_db, is_name_based))
def test_sql_query_crud(self):
# create two databases.
db1 = self.client.CreateDatabase({ 'id': 'database 1' })
db2 = self.client.CreateDatabase({ 'id': 'database 2' })
# query with parameters.
databases = list(self.client.QueryDatabases({
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name':'@id', 'value': 'database 1' }
]
}))
self.assertEqual(1, len(databases), 'Unexpected number of query results.')
# query without parameters.
databases = list(self.client.QueryDatabases({
'query': 'SELECT * FROM root r WHERE r.id="database non-existing"'
}))
self.assertEqual(0, len(databases), 'Unexpected number of query results.')
# query with a string.
databases = list(self.client.QueryDatabases('SELECT * FROM root r WHERE r.id="database 2"'))
self.assertEqual(1, len(databases), 'Unexpected number of query results.')
self.client.DeleteDatabase(db1['_self'])
self.client.DeleteDatabase(db2['_self'])
def test_collection_crud_self_link(self):
self._test_collection_crud(False)
def test_collection_crud_name_based(self):
self._test_collection_crud(True)
def _test_collection_crud(self, is_name_based):
created_db = self.databseForTest
collections = list(self.client.ReadContainers(self.GetDatabaseLink(created_db, is_name_based)))
# create a collection
before_create_collections_count = len(collections)
collection_definition = { 'id': 'test_collection_crud ' + str(uuid.uuid4()), 'indexingPolicy': {'indexingMode': 'consistent'} }
created_collection = self.client.CreateContainer(self.GetDatabaseLink(created_db, is_name_based),
collection_definition)
self.assertEqual(collection_definition['id'], created_collection['id'])
self.assertEqual('consistent', created_collection['indexingPolicy']['indexingMode'])
# read collections after creation
collections = list(self.client.ReadContainers(self.GetDatabaseLink(created_db, is_name_based)))
self.assertEqual(len(collections),
before_create_collections_count + 1,
'create should increase the number of collections')
# query collections
collections = list(self.client.QueryContainers(
self.GetDatabaseLink(created_db, is_name_based),
{
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name':'@id', 'value': collection_definition['id'] }
]
}))
# Replacing indexing policy is allowed.
lazy_policy = {'indexingMode': 'lazy'}
created_collection['indexingPolicy'] = lazy_policy
replaced_collection = self.client.ReplaceContainer(self.GetDocumentCollectionLink(created_db, created_collection, is_name_based), created_collection)
self.assertEqual('lazy', replaced_collection['indexingPolicy']['indexingMode'])
# Replacing collection Id should fail.
change_collection = created_collection.copy()
change_collection['id'] = 'try_change_id'
self.__AssertHTTPFailureWithStatus(StatusCodes.BAD_REQUEST,
self.client.ReplaceContainer,
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
change_collection)
self.assertTrue(collections)
# delete collection
self.client.DeleteContainer(self.GetDocumentCollectionLink(created_db, created_collection, is_name_based))
# read collection after deletion
self.__AssertHTTPFailureWithStatus(StatusCodes.NOT_FOUND,
self.client.ReadContainer,
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based))
def test_partitioned_collection(self):
created_db = self.databseForTest
collection_definition = { 'id': 'test_partitioned_collection ' + str(uuid.uuid4()),
'partitionKey':
{
'paths': ['/id'],
'kind': documents.PartitionKind.Hash
}
}
options = { 'offerThroughput': 10100 }
created_collection = self.client.CreateContainer(self.GetDatabaseLink(created_db),
collection_definition,
options)
self.assertEqual(collection_definition.get('id'), created_collection.get('id'))
self.assertEqual(collection_definition.get('partitionKey').get('paths')[0], created_collection.get('partitionKey').get('paths')[0])
self.assertEqual(collection_definition.get('partitionKey').get('kind'), created_collection.get('partitionKey').get('kind'))
offers = self.GetCollectionOffers(self.client, created_collection['_rid'])
self.assertEqual(1, len(offers))
expected_offer = offers[0]
self.assertEqual(expected_offer.get('content').get('offerThroughput'), options.get('offerThroughput'))
self.client.DeleteContainer(self.GetDocumentCollectionLink(created_db, created_collection))
def test_partitioned_collection_quota(self):
created_db = self.databseForTest
options = { 'offerThroughput': 20000 }
created_collection = self.configs.create_multi_partition_collection_if_not_exist(self.client)
read_options = { 'populatePartitionKeyRangeStatistics': True, 'populateQuotaInfo': True}
retrieved_collection = self.client.ReadContainer(created_collection.get('_self'), read_options)
self.assertTrue(retrieved_collection.get("statistics") != None)
self.assertTrue(self.client.last_response_headers.get("x-ms-resource-usage") != None)
def test_partitioned_collection_partition_key_extraction(self):
created_db = self.databseForTest
collection_definition = { 'id': 'test_partitioned_collection_partition_key_extraction ' + str(uuid.uuid4()),
'partitionKey':
{
'paths': ['/address/state'],
'kind': documents.PartitionKind.Hash
}
}
created_collection = self.client.CreateContainer(self.GetDatabaseLink(created_db),
collection_definition)
document_definition = {'id': 'document1',
'address' : { 'street' : '1 Microsoft Way',
'city' : 'Redmond',
'state' : 'WA',
'zip code' : 98052
}
}
# create document without partition key being specified
created_document = self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection),
document_definition)
self.assertEqual(created_document.get('id'), document_definition.get('id'))
self.assertEqual(created_document.get('address').get('state'), document_definition.get('address').get('state'))
# create document by specifying a different partition key in options than what's in the document will result in BadRequest(status code 400)
document_definition['id'] = 'document2'
options = { 'partitionKey': 'NY' }
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.CreateItem,
self.GetDocumentCollectionLink(created_db, created_collection),
document_definition,
options)
collection_definition1 = { 'id': 'test_partitioned_collection_partition_key_extraction1 ' + str(uuid.uuid4()),
'partitionKey':
{
'paths': ['/address'],
'kind': documents.PartitionKind.Hash
}
}
created_collection1 = self.client.CreateContainer(self.GetDatabaseLink(created_db),
collection_definition1)
# Create document with partitionkey not present as a leaf level property but a dict
options = {}
created_document = self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection1),
document_definition, options)
self.assertEqual(options['partitionKey'], documents.Undefined)
collection_definition2 = { 'id': 'test_partitioned_collection_partition_key_extraction2 ' + str(uuid.uuid4()),
'partitionKey':
{
'paths': ['/address/state/city'],
'kind': documents.PartitionKind.Hash
}
}
created_collection2 = self.client.CreateContainer(self.GetDatabaseLink(created_db),
collection_definition2)
# Create document with partitionkey not present in the document
options = {}
created_document = self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection2),
document_definition, options)
self.assertEqual(options['partitionKey'], documents.Undefined)
self.client.DeleteContainer(self.GetDocumentCollectionLink(created_db, created_collection))
self.client.DeleteContainer(self.GetDocumentCollectionLink(created_db, created_collection1))
self.client.DeleteContainer(self.GetDocumentCollectionLink(created_db, created_collection2))
def test_partitioned_collection_partition_key_extraction_special_chars(self):
created_db = self.databseForTest
collection_definition1 = { 'id': 'test_partitioned_collection_partition_key_extraction_special_chars1 ' + str(uuid.uuid4()),
'partitionKey':
{
'paths': ['/\"level\' 1*()\"/\"le/vel2\"'],
'kind': documents.PartitionKind.Hash
}
}
created_collection1 = self.client.CreateContainer(self.GetDatabaseLink(created_db),
collection_definition1)
document_definition = {'id': 'document1',
"level' 1*()" : { "le/vel2" : 'val1' }
}
options = {}
self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection1),
document_definition, options)
self.assertEqual(options['partitionKey'], 'val1')
collection_definition2 = { 'id': 'test_partitioned_collection_partition_key_extraction_special_chars2 ' + str(uuid.uuid4()),
'partitionKey':
{
'paths': ['/\'level\" 1*()\'/\'le/vel2\''],
'kind': documents.PartitionKind.Hash
}
}
created_collection2 = self.client.CreateContainer(self.GetDatabaseLink(created_db),
collection_definition2)
document_definition = {'id': 'document2',
'level\" 1*()' : { 'le/vel2' : 'val2' }
}
options = {}
self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection2),
document_definition, options)
self.assertEqual(options['partitionKey'], 'val2')
self.client.DeleteContainer(self.GetDocumentCollectionLink(created_db, created_collection1))
self.client.DeleteContainer(self.GetDocumentCollectionLink(created_db, created_collection2))
def test_partitioned_collection_path_parser(self):
test_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(test_dir, "BaselineTest.PathParser.json")) as json_file:
entries = json.loads(json_file.read())
for entry in entries:
parts = base.ParsePaths([entry['path']])
self.assertEqual(parts, entry['parts'])
paths = ["/\"Ke \\ \\\" \\\' \\? \\a \\\b \\\f \\\n \\\r \\\t \\v y1\"/*"]
parts = [ "Ke \\ \\\" \\\' \\? \\a \\\b \\\f \\\n \\\r \\\t \\v y1", "*" ]
self.assertEqual(parts, base.ParsePaths(paths))
paths = ["/'Ke \\ \\\" \\\' \\? \\a \\\b \\\f \\\n \\\r \\\t \\v y1'/*"]
parts = [ "Ke \\ \\\" \\\' \\? \\a \\\b \\\f \\\n \\\r \\\t \\v y1", "*" ]
self.assertEqual(parts, base.ParsePaths(paths))
def test_partitioned_collection_document_crud_and_query(self):
created_db = self.databseForTest
created_collection = self.configs.create_multi_partition_collection_if_not_exist(self.client)
document_definition = {'id': 'document',
'key': 'value'}
created_document = self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection),
document_definition)
self.assertEqual(created_document.get('id'), document_definition.get('id'))
self.assertEqual(created_document.get('key'), document_definition.get('key'))
# For ReadDocument, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
#self.__AssertHTTPFailureWithStatus(
# StatusCodes.BAD_REQUEST,
# client.ReadItem,
# self.GetDocumentLink(created_db, created_collection, created_document))
# read document
options = { 'partitionKey': document_definition.get('id') }
read_document = self.client.ReadItem(
self.GetDocumentLink(created_db, created_collection, created_document),
options)
self.assertEqual(read_document.get('id'), created_document.get('id'))
self.assertEqual(read_document.get('key'), created_document.get('key'))
# Read document feed doesn't require partitionKey as it's always a cross partition query
documentlist = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, created_collection)))
self.assertEqual(1, len(documentlist))
# replace document
document_definition['key'] = 'new value'
replaced_document = self.client.ReplaceItem(
self.GetDocumentLink(created_db, created_collection, created_document),
document_definition)
self.assertEqual(replaced_document.get('key'), document_definition.get('key'))
# upsert document(create scenario)
document_definition['id'] = 'document2'
document_definition['key'] = 'value2'
upserted_document = self.client.UpsertItem(self.GetDocumentCollectionLink(created_db, created_collection),
document_definition)
self.assertEqual(upserted_document.get('id'), document_definition.get('id'))
self.assertEqual(upserted_document.get('key'), document_definition.get('key'))
documentlist = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, created_collection)))
self.assertEqual(2, len(documentlist))
# For DeleteDocument, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.DeleteItem,
self.GetDocumentLink(created_db, created_collection, upserted_document))
# delete document
options = { 'partitionKey': upserted_document.get('id') }
self.client.DeleteItem(
self.GetDocumentLink(created_db, created_collection, upserted_document),
options)
# query document on the partition key specified in the predicate will pass even without setting enableCrossPartitionQuery or passing in the partitionKey value
documentlist = list(self.client.QueryItems(
self.GetDocumentCollectionLink(created_db, created_collection),
{
'query': 'SELECT * FROM root r WHERE r.id=\'' + replaced_document.get('id') + '\''
}))
self.assertEqual(1, len(documentlist))
# query document on any property other than partitionKey will fail without setting enableCrossPartitionQuery or passing in the partitionKey value
try:
list(self.client.QueryItems(
self.GetDocumentCollectionLink(created_db, created_collection),
{
'query': 'SELECT * FROM root r WHERE r.key=\'' + replaced_document.get('key') + '\''
}))
except Exception:
pass
# cross partition query
options = { 'enableCrossPartitionQuery': True }
documentlist = list(self.client.QueryItems(
self.GetDocumentCollectionLink(created_db, created_collection),
{
'query': 'SELECT * FROM root r WHERE r.key=\'' + replaced_document.get('key') + '\''
}, options))
self.assertEqual(1, len(documentlist))
# query document by providing the partitionKey value
options = { 'partitionKey': replaced_document.get('id') }
documentlist = list(self.client.QueryItems(
self.GetDocumentCollectionLink(created_db, created_collection),
{
'query': 'SELECT * FROM root r WHERE r.key=\'' + replaced_document.get('key') + '\''
}, options))
self.assertEqual(1, len(documentlist))
def test_partitioned_collection_permissions(self):
created_db = self.databseForTest
collection_definition = { 'id': 'sample collection ' + str(uuid.uuid4()),
'partitionKey':
{
'paths': ['/key'],
'kind': documents.PartitionKind.Hash
}
}
collection_definition['id'] = 'test_partitioned_collection_permissions all collection'
all_collection = self.client.CreateContainer(self.GetDatabaseLink(created_db),
collection_definition)
collection_definition['id'] = 'test_partitioned_collection_permissions read collection'
read_collection = self.client.CreateContainer(self.GetDatabaseLink(created_db),
collection_definition)
user = self.client.CreateUser(self.GetDatabaseLink(created_db), { 'id': 'user' })
permission_definition = {
'id': 'all permission',
'permissionMode': documents.PermissionMode.All,
'resource': self.GetDocumentCollectionLink(created_db, all_collection),
'resourcePartitionKey' : [1]
}
all_permission = self.client.CreatePermission(self.GetUserLink(created_db, user), permission_definition)
permission_definition = {
'id': 'read permission',
'permissionMode': documents.PermissionMode.Read,
'resource': self.GetDocumentCollectionLink(created_db, read_collection),
'resourcePartitionKey' : [1]
}
read_permission = self.client.CreatePermission(self.GetUserLink(created_db, user), permission_definition)
resource_tokens = {}
# storing the resource tokens based on Resource IDs
resource_tokens[all_collection['_rid']] = (all_permission['_token'])
resource_tokens[read_collection['_rid']] = (read_permission['_token'])
restricted_client = cosmos_client.CosmosClient(
CRUDTests.host, {'resourceTokens': resource_tokens}, CRUDTests.connectionPolicy)
document_definition = {'id': 'document1',
'key': 1
}
# Create document in all_collection should succeed since the partitionKey is 1 which is what specified as resourcePartitionKey in permission object and it has all permissions
created_document = restricted_client.CreateItem(
self.GetDocumentCollectionLink(created_db, all_collection, False),
document_definition)
# Create document in read_collection should fail since it has only read permissions for this collection
self.__AssertHTTPFailureWithStatus(
StatusCodes.FORBIDDEN,
restricted_client.CreateItem,
self.GetDocumentCollectionLink(created_db, read_collection, False),
document_definition)
# Read document feed should succeed for this collection. Note that I need to pass in partitionKey here since permission has resourcePartitionKey defined
options = { 'partitionKey': document_definition.get('key') }
documentlist = list(restricted_client.ReadItems(
self.GetDocumentCollectionLink(created_db, read_collection, False),
options))
self.assertEqual(0, len(documentlist))
document_definition['key'] = 2
options = { 'partitionKey': document_definition.get('key') }
# Create document should fail since the partitionKey is 2 which is different that what is specified as resourcePartitionKey in permission object
self.__AssertHTTPFailureWithStatus(
StatusCodes.FORBIDDEN,
restricted_client.CreateItem,
self.GetDocumentCollectionLink(created_db, all_collection, False),
document_definition,
options)
document_definition['key'] = 1
options = { 'partitionKey': document_definition.get('key') }
# Delete document should succeed since the partitionKey is 1 which is what specified as resourcePartitionKey in permission object
created_document = restricted_client.DeleteItem(
self.GetDocumentLink(created_db, all_collection, created_document, False),
options)
# Delete document in read_collection should fail since it has only read permissions for this collection
self.__AssertHTTPFailureWithStatus(
StatusCodes.FORBIDDEN,
restricted_client.DeleteItem,
self.GetDocumentCollectionLink(created_db, read_collection, False),
options)
self.client.DeleteContainer(self.GetDocumentCollectionLink(created_db, all_collection))
self.client.DeleteContainer(self.GetDocumentCollectionLink(created_db, read_collection))
def test_partitioned_collection_execute_stored_procedure(self):
created_db = self.databseForTest
created_collection = self.configs.create_multi_partition_collection_with_custom_pk_if_not_exist(self.client)
sproc = {
'id': 'storedProcedure' + str(uuid.uuid4()),
'body': (
'function () {' +
' var client = getContext().getCollection();' +
' client.createDocument(client.getSelfLink(), { id: \'testDoc\', pk : 2}, {}, function(err, docCreated, options) { ' +
' if(err) throw new Error(\'Error while creating document: \' + err.message);' +
' else {' +
' getContext().getResponse().setBody(1);' +
' }' +
' });}')
}
created_sproc = self.client.CreateStoredProcedure(self.GetDocumentCollectionLink(created_db, created_collection), sproc)
# Partiton Key value same as what is specified in the stored procedure body
self.client.ExecuteStoredProcedure(self.GetStoredProcedureLink(created_db, created_collection, created_sproc),
None, { 'partitionKey' : 2})
# Partiton Key value different than what is specified in the stored procedure body will cause a bad request(400) error
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.ExecuteStoredProcedure,
self.GetStoredProcedureLink(created_db, created_collection, created_sproc),
None,
{ 'partitionKey' : 3})
def test_partitioned_collection_attachment_crud_and_query(self):
class ReadableStream(object):
"""Customized file-like stream.
"""
def __init__(self, chunks = ['first chunk ', 'second chunk']):
"""Initialization.
:Parameters:
- `chunks`: list
"""
if six.PY2:
self._chunks = list(chunks)
else:
# python3: convert to bytes
self._chunks = [chunk.encode() for chunk in chunks]
def read(self, n=-1):
"""Simulates the read method in a file stream.
:Parameters:
- `n`: int
:Returns:
bytes or str
"""
if self._chunks:
return self._chunks.pop(0)
else:
return ''
def __len__(self):
"""To make len(ReadableStream) work.
"""
return sum([len(chunk) for chunk in self._chunks])
db = self.databseForTest
collection_definition = {'id': 'test_partitioned_collection_attachment_crud_and_query ' + str(uuid.uuid4()),
'partitionKey': {'paths': ['/id'],'kind': 'Hash'}}
collection = self.client.CreateContainer(db['_self'], collection_definition)
document_definition = {'id': 'sample document' + str(uuid.uuid4()),
'key': 'value'}
document = self.client.CreateItem(self.GetDocumentCollectionLink(db, collection),
document_definition)
content_stream = ReadableStream()
options = { 'slug': 'sample attachment',
'contentType': 'application/text' }
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
#self.__AssertHTTPFailureWithStatus(
# StatusCodes.BAD_REQUEST,
# client.CreateAttachmentAndUploadMedia,
# self.GetDocumentLink(db, collection, document),
# content_stream,
# options)
content_stream = ReadableStream()
# Setting the partitionKey as part of options is required for attachment CRUD
options = { 'slug': 'sample attachment' + str(uuid.uuid4()),
'contentType': 'application/text',
'partitionKey' : document_definition.get('id') }
# create attachment and upload media
attachment = self.client.CreateAttachmentAndUploadMedia(
self.GetDocumentLink(db, collection, document), content_stream, options)
self.assertEqual(attachment['id'], options['slug'])
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
try:
list(self.client.ReadAttachments(
self.GetDocumentLink(db, collection, document)))
except Exception:
pass
# Read attachment feed requires partitionKey to be passed
options = { 'partitionKey': document_definition.get('id') }
attachmentlist = list(self.client.ReadAttachments(
self.GetDocumentLink(db, collection, document), options))
self.assertEqual(1, len(attachmentlist))
content_stream = ReadableStream()
options = { 'slug': 'new attachment' + str(uuid.uuid4()),
'contentType': 'application/text' }
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.UpsertAttachmentAndUploadMedia,
self.GetDocumentLink(db, collection, document),
content_stream,
options)
content_stream = ReadableStream()
# Setting the partitionKey as part of options is required for attachment CRUD
options = { 'slug': 'new attachment' + str(uuid.uuid4()),
'contentType': 'application/text',
'partitionKey' : document_definition.get('id') }
# upsert attachment and upload media
attachment = self.client.UpsertAttachmentAndUploadMedia(
self.GetDocumentLink(db, collection, document), content_stream, options)
self.assertEqual(attachment['id'], options['slug'])
options = { 'partitionKey': document_definition.get('id') }
attachmentlist = list(self.client.ReadAttachments(
self.GetDocumentLink(db, collection, document), options))
self.assertEqual(2, len(attachmentlist))
# create attachment with media link
dynamic_attachment = {
'id': 'dynamic attachment' + str(uuid.uuid4()),
'media': 'http://xstore.',
'MediaType': 'Book',
'Author':'My Book Author',
'Title':'My Book Title',
'contentType':'application/text'
}
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.CreateAttachment,
self.GetDocumentLink(db, collection, document),
dynamic_attachment)
# create dynamic attachment
options = { 'partitionKey': document_definition.get('id') }
attachment = self.client.CreateAttachment(self.GetDocumentLink(db, collection, document),
dynamic_attachment, options)
self.assertEqual(attachment['MediaType'], dynamic_attachment['MediaType'])
self.assertEqual(attachment['Author'], dynamic_attachment['Author'])
# Read Attachment feed
options = { 'partitionKey': document_definition.get('id') }
attachmentlist = list(self.client.ReadAttachments(
self.GetDocumentLink(db, collection, document), options))
self.assertEqual(3, len(attachmentlist))
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
#self.__AssertHTTPFailureWithStatus(
# StatusCodes.BAD_REQUEST,
# client.ReadAttachment,
# self.GetAttachmentLink(db, collection, document, attachment))
# Read attachment
options = { 'partitionKey': document_definition.get('id') }
read_attachment = self.client.ReadAttachment(self.GetAttachmentLink(db, collection, document, attachment),
options)
self.assertEqual(attachment['id'], read_attachment['id'])
attachment['Author'] = 'new author'
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.ReplaceAttachment,
self.GetAttachmentLink(db, collection, document, attachment),
attachment)
# replace the attachment
options = { 'partitionKey': document_definition.get('id') }
replaced_attachment = self.client.ReplaceAttachment(self.GetAttachmentLink(db, collection, document, attachment), attachment, options)
self.assertEqual(attachment['id'], replaced_attachment['id'])
self.assertEqual(attachment['Author'], replaced_attachment['Author'])
attachment['id'] = 'new dynamic attachment' + str(uuid.uuid4())
attachment['Title'] = 'new title'
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.UpsertAttachment,
self.GetDocumentLink(db, collection, document),
attachment)
# upsert attachment(create scenario)
options = { 'partitionKey': document_definition.get('id') }
upserted_attachment = self.client.UpsertAttachment(self.GetDocumentLink(db, collection, document), attachment, options)
self.assertEqual(attachment['id'], upserted_attachment['id'])
self.assertEqual(attachment['Title'], upserted_attachment['Title'])
# query attachments will fail without passing in the partitionKey value
try:
list(self.client.QueryAttachments(
self.GetDocumentLink(db, collection, document),
{
'query': 'SELECT * FROM root r WHERE r.MediaType=\'' + dynamic_attachment.get('MediaType') + '\''
}))
except Exception:
pass
# query attachments by providing the partitionKey value
options = { 'partitionKey': document_definition.get('id') }
attachmentlist = list(self.client.QueryAttachments(
self.GetDocumentLink(db, collection, document),
{
'query': 'SELECT * FROM root r WHERE r.MediaType=\'' + dynamic_attachment.get('MediaType') + '\''
}, options))
self.assertEqual(2, len(attachmentlist))
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.DeleteAttachment,
self.GetAttachmentLink(db, collection, document, attachment))
# deleting attachment
options = { 'partitionKey': document_definition.get('id') }
self.client.DeleteAttachment(self.GetAttachmentLink(db, collection, document, attachment), options)
self.client.DeleteContainer(collection['_self'])
def test_partitioned_collection_partition_key_value_types(self):
created_db = self.databseForTest
created_collection = self.configs.create_multi_partition_collection_with_custom_pk_if_not_exist(self.client)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk' : None,
'spam': 'eggs'}
# create document with partitionKey set as None here
self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection),
document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'spam': 'eggs'}
# create document with partitionKey set as Undefined here
self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection),
document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk' : True,
'spam': 'eggs'}
# create document with bool partitionKey
self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection),
document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk' : 'value',
'spam': 'eggs'}
# create document with string partitionKey
self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection),
document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk' : 100,
'spam': 'eggs'}
# create document with int partitionKey
self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection),
document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk' : 10.50,
'spam': 'eggs'}
# create document with float partitionKey
self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection),
document_definition)
def test_partitioned_collection_conflict_crud_and_query(self):
created_db = self.databseForTest
created_collection = self.configs.create_multi_partition_collection_if_not_exist(self.client)
conflict_definition = {'id': 'new conflict',
'resourceId' : 'doc1',
'operationType' : 'create',
'resourceType' : 'document'
}
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
#self.__AssertHTTPFailureWithStatus(
# StatusCodes.BAD_REQUEST,
# client.ReadConflict,
# self.GetConflictLink(created_db, created_collection, conflict_definition))
# read conflict here will return resource not found(404) since there is no conflict here
options = { 'partitionKey': conflict_definition.get('id') }
self.__AssertHTTPFailureWithStatus(
StatusCodes.NOT_FOUND,
self.client.ReadConflict,
self.GetConflictLink(created_db, created_collection, conflict_definition),
options)
# Read conflict feed doesn't requires partitionKey to be specified as it's a cross partition thing
conflictlist = list(self.client.ReadConflicts(self.GetDocumentCollectionLink(created_db, created_collection)))
self.assertEqual(0, len(conflictlist))
# Currently, we require to have the partitionKey to be specified as part of options otherwise we get BadRequest(status code 400)
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.DeleteConflict,
self.GetConflictLink(created_db, created_collection, conflict_definition))
# delete conflict here will return resource not found(404) since there is no conflict here
options = { 'partitionKey': conflict_definition.get('id') }
self.__AssertHTTPFailureWithStatus(
StatusCodes.NOT_FOUND,
self.client.DeleteConflict,
self.GetConflictLink(created_db, created_collection, conflict_definition),
options)
# query conflicts on any property other than partitionKey will fail without setting enableCrossPartitionQuery or passing in the partitionKey value
try:
list(self.client.QueryConflicts(
self.GetDocumentCollectionLink(created_db, created_collection),
{
'query': 'SELECT * FROM root r WHERE r.resourceType=\'' + conflict_definition.get('resourceType') + '\''
}))
except Exception:
pass
# cross partition query
options = { 'enableCrossPartitionQuery': True }
conflictlist = list(self.client.QueryConflicts(
self.GetDocumentCollectionLink(created_db, created_collection),
{
'query': 'SELECT * FROM root r WHERE r.resourceType=\'' + conflict_definition.get('resourceType') + '\''
}, options))
self.assertEqual(0, len(conflictlist))
# query conflicts by providing the partitionKey value
options = { 'partitionKey': conflict_definition.get('id') }
conflictlist = list(self.client.QueryConflicts(
self.GetDocumentCollectionLink(created_db, created_collection),
{
'query': 'SELECT * FROM root r WHERE r.resourceType=\'' + conflict_definition.get('resourceType') + '\''
}, options))
self.assertEqual(0, len(conflictlist))
def test_document_crud_self_link(self):
self._test_document_crud(False)
def test_document_crud_name_based(self):
self._test_document_crud(True)
def _test_document_crud(self, is_name_based):
# create database
created_db = self.databseForTest
# create collection
created_collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# read documents
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based)))
# create a document
before_create_documents_count = len(documents)
document_definition = {'name': 'sample document',
'spam': 'eggs',
'key': 'value'}
# Should throw an error because automatic id generation is disabled.
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.CreateItem,
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
document_definition,
{'disableAutomaticIdGeneration': True})
created_document = self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
document_definition)
self.assertEqual(created_document['name'],
document_definition['name'])
self.assertTrue(created_document['id'] != None)
# duplicated documents are allowed when 'id' is not provided.
duplicated_document = self.client.CreateItem(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
document_definition)
self.assertEqual(duplicated_document['name'],
document_definition['name'])
self.assert_(duplicated_document['id'])
self.assertNotEqual(duplicated_document['id'],
created_document['id'])
# duplicated documents are not allowed when 'id' is provided.
duplicated_definition_with_id = document_definition.copy()
duplicated_definition_with_id['id'] = created_document['id']
self.__AssertHTTPFailureWithStatus(StatusCodes.CONFLICT,
self.client.CreateItem,
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
duplicated_definition_with_id)
# read documents after creation
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based)))
self.assertEqual(
len(documents),
before_create_documents_count + 2,
'create should increase the number of documents')
# query documents
documents = list(self.client.QueryItems(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
{
'query': 'SELECT * FROM root r WHERE r.name=@name',
'parameters': [
{ 'name':'@name', 'value':document_definition['name'] }
]
}))
self.assert_(documents)
documents = list(self.client.QueryItems(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
{
'query': 'SELECT * FROM root r WHERE r.name=@name',
'parameters': [
{ 'name':'@name', 'value':document_definition['name'] }
]
},
{ 'enableScanInQuery': True}))
self.assert_(documents)
# replace document.
created_document['name'] = 'replaced document'
created_document['spam'] = 'not eggs'
old_etag = created_document['_etag']
replaced_document = self.client.ReplaceItem(
self.GetDocumentLink(created_db, created_collection, created_document, is_name_based),
created_document)
self.assertEqual(replaced_document['name'],
'replaced document',
'document id property should change')
self.assertEqual(replaced_document['spam'],
'not eggs',
'property should have changed')
self.assertEqual(created_document['id'],
replaced_document['id'],
'document id should stay the same')
#replace document based on condition
replaced_document['name'] = 'replaced document based on condition'
replaced_document['spam'] = 'new spam field'
#should fail for stale etag
self.__AssertHTTPFailureWithStatus(
StatusCodes.PRECONDITION_FAILED, self.client.ReplaceItem,
self.GetDocumentLink(created_db, created_collection, replaced_document, is_name_based),
replaced_document, { 'accessCondition' : { 'type': 'IfMatch', 'condition': old_etag } })
#should pass for most recent etag
replaced_document_conditional = self.client.ReplaceItem(
self.GetDocumentLink(created_db, created_collection, replaced_document, is_name_based),
replaced_document, { 'accessCondition' : { 'type': 'IfMatch', 'condition': replaced_document['_etag'] } })
self.assertEqual(replaced_document_conditional['name'],
'replaced document based on condition',
'document id property should change')
self.assertEqual(replaced_document_conditional['spam'],
'new spam field',
'property should have changed')
self.assertEqual(replaced_document_conditional['id'],
replaced_document['id'],
'document id should stay the same')
# read document
one_document_from_read = self.client.ReadItem(
self.GetDocumentLink(created_db, created_collection, replaced_document, is_name_based))
self.assertEqual(replaced_document['id'],
one_document_from_read['id'])
# delete document
self.client.DeleteItem(self.GetDocumentLink(created_db, created_collection, replaced_document, is_name_based))
# read documents after deletion
self.__AssertHTTPFailureWithStatus(StatusCodes.NOT_FOUND,
self.client.ReadItem,
self.GetDocumentLink(created_db, created_collection, replaced_document, is_name_based))
def test_partitioning(self):
# create test database
created_db = self.databseForTest
# Create bunch of collections participating in partitioning
collection0 = self.client.CreateContainer(
self.GetDatabaseLink(created_db, True),
{ 'id': 'test_partitioning coll_0' + str(uuid.uuid4()) })
collection1 = self.client.CreateContainer(
self.GetDatabaseLink(created_db, True),
{ 'id': 'test_partitioning coll_1' + str(uuid.uuid4())})
collection2 = self.client.CreateContainer(
self.GetDatabaseLink(created_db, True),
{ 'id': 'test_partitioning coll_2' + str(uuid.uuid4())})
# Register the collection links for partitioning through partition resolver
collection_links = [self.GetDocumentCollectionLink(created_db, collection0, True), self.GetDocumentCollectionLink(created_db, collection1, True), self.GetDocumentCollectionLink(created_db, collection2, True)]
partition_resolver = test_partition_resolver.TestPartitionResolver(collection_links)
self.client.RegisterPartitionResolver(self.GetDatabaseLink(created_db, True), partition_resolver)
# create a document using the document definition
document_definition = { 'id': '0',
'name': 'sample document',
'key': 'value' }
self.client.CreateItem(
self.GetDatabaseLink(created_db, True),
document_definition)
# Read the documents in collection1 and verify that the count is 1 now
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, collection0, True)))
self.assertEqual(1, len(documents))
# Verify that it contains the document with Id 0
self.assertEqual('0', documents[0]['id'])
document_definition['id'] = '1'
self.client.CreateItem(
self.GetDatabaseLink(created_db, True),
document_definition)
# Read the documents in collection1 and verify that the count is 1 now
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, collection1, True)))
self.assertEqual(1, len(documents))
# Verify that it contains the document with Id 1
self.assertEqual('1', documents[0]['id'])
document_definition['id'] = '2'
self.client.CreateItem(
self.GetDatabaseLink(created_db, True),
document_definition)
# Read the documents in collection2 and verify that the count is 1 now
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, collection2, True)))
self.assertEqual(1, len(documents))
# Verify that it contains the document with Id 2
self.assertEqual('2', documents[0]['id'])
# Updating the value of "key" property to test UpsertDocument(replace scenario)
document_definition['id'] = '0'
document_definition['key'] = 'new value'
self.client.UpsertItem(
self.GetDatabaseLink(created_db, True),
document_definition)
# Read the documents in collection0 and verify that the count is still 1
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, collection0, True)))
self.assertEqual(1, len(documents))
# Verify that it contains the document with new key value
self.assertEqual(document_definition['key'], documents[0]['key'])
# Query documents in all collections(since no partition key specified) using query string
documents = list(self.client.QueryItems(
self.GetDatabaseLink(created_db, True),
{
'query': 'SELECT * FROM root r WHERE r.id=\'2\''
}))
self.assertEqual(1, len(documents))
# Updating the value of id property to test UpsertDocument(create scenario)
document_definition['id'] = '4'
self.client.UpsertItem(
self.GetDatabaseLink(created_db, True),
document_definition)
# Read the documents in collection1 and verify that the count is 2 now
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, collection1, True)))
self.assertEqual(2, len(documents))
# Query documents in all collections(since no partition key specified) using query spec
documents = list(self.client.QueryItems(
self.GetDatabaseLink(created_db, True),
{
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name':'@id', 'value':document_definition['id'] }
]
}))
self.assertEqual(1, len(documents))
# Query documents in collection(with partition key of '4' specified) which resolves to collection1
documents = list(self.client.QueryItems(
self.GetDatabaseLink(created_db, True),
{
'query': 'SELECT * FROM root r'
}, {}, document_definition['id']))
self.assertEqual(2, len(documents))
# Query documents in collection(with partition key '5' specified) which resolves to collection2 but non existent document in that collection
documents = list(self.client.QueryItems(
self.GetDatabaseLink(created_db, True),
{
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name':'@id', 'value':document_definition['id'] }
]
}, {}, '5'))
self.assertEqual(0, len(documents))
self.client.DeleteContainer(collection0['_self'])
self.client.DeleteContainer(collection1['_self'])
self.client.DeleteContainer(collection2['_self'])
# Partitioning test(with paging)
def test_partition_paging(self):
# create test database
created_db = self.databseForTest
# Create bunch of collections participating in partitioning
collection0 = self.client.CreateContainer(
self.GetDatabaseLink(created_db, True),
{ 'id': 'test_partition_paging coll_0 ' + str(uuid.uuid4()) })
collection1 = self.client.CreateContainer(
self.GetDatabaseLink(created_db, True),
{ 'id': 'test_partition_paging coll_1 ' + str(uuid.uuid4()) })
# Register the collection links for partitioning through partition resolver
collection_links = [self.GetDocumentCollectionLink(created_db, collection0, True), self.GetDocumentCollectionLink(created_db, collection1, True)]
partition_resolver = test_partition_resolver.TestPartitionResolver(collection_links)
self.client.RegisterPartitionResolver(self.GetDatabaseLink(created_db, True), partition_resolver)
# Create document definition used to create documents
document_definition = { 'id': '0',
'name': 'sample document',
'key': 'value' }
# Create 10 documents each with a different id starting from 0 to 9
for i in xrange(0, 10):
document_definition['id'] = str(i)
self.client.CreateItem(
self.GetDatabaseLink(created_db, True),
document_definition)
# Query the documents to ensure that you get the correct count(no paging)
documents = list(self.client.QueryItems(
self.GetDatabaseLink(created_db, True),
{
'query': 'SELECT * FROM root r WHERE r.id < \'7\''
}))
self.assertEqual(7, len(documents))
# Query the documents with maxItemCount to restrict the max number of documents returned
queryIterable = self.client.QueryItems(
self.GetDatabaseLink(created_db, True),
{
'query': 'SELECT * FROM root r WHERE r.id < \'7\''
}, {'maxItemCount':3})
# Query again and count the number of documents(with paging)
docCount = 0
for _ in queryIterable:
docCount += 1
self.assertEqual(7, docCount)
# Query again to test fetch_next_block to ensure that it returns the correct number of documents everytime it's called
queryIterable = self.client.QueryItems(
self.GetDatabaseLink(created_db, True),
{
'query': 'SELECT * FROM root r WHERE r.id < \'7\''
}, {'maxItemCount':3})
# Documents with id 0, 2, 4(in collection0)
self.assertEqual(3, len(queryIterable.fetch_next_block()))
# Documents with id 6(in collection0)
self.assertEqual(1, len(queryIterable.fetch_next_block()))
# Documents with id 1, 3, 5(in collection1)
self.assertEqual(3, len(queryIterable.fetch_next_block()))
# No more documents
self.assertEqual(0, len(queryIterable.fetch_next_block()))
# Set maxItemCount to -1 to lift the limit on max documents returned by the query
queryIterable = self.client.QueryItems(
self.GetDatabaseLink(created_db, True),
{
'query': 'SELECT * FROM root r WHERE r.id < \'7\''
}, {'maxItemCount':-1})
# Documents with id 0, 2, 4, 6(all docs in collection0 adhering to query condition)
self.assertEqual(4, len(queryIterable.fetch_next_block()))
# Documents with id 1, 3, 5(all docs in collection1 adhering to query condition)
self.assertEqual(3, len(queryIterable.fetch_next_block()))
# No more documents
self.assertEqual(0, len(queryIterable.fetch_next_block()))
self.client.DeleteContainer(collection0['_self'])
self.client.DeleteContainer(collection1['_self'])
def test_hash_partition_resolver(self):
created_db = self.databseForTest
# Create bunch of collections participating in partitioning
collection0 = { 'id': 'coll_0 ' + str(uuid.uuid4()) }
collection1 = { 'id': 'coll_1 ' + str(uuid.uuid4()) }
collection_links = [self.GetDocumentCollectionLink(created_db, collection0, True), self.GetDocumentCollectionLink(created_db, collection1, True)]
id_partition_key_extractor = lambda document: document['id']
hashpartition_resolver = hash_partition_resolver.HashPartitionResolver(id_partition_key_extractor, collection_links)
# create a document using the document definition
document_definition = { 'id': '0',
'name': 'sample document',
'key': 'value' }
document_definition['id'] = '2'
collection_link = hashpartition_resolver.ResolveForCreate(document_definition)
read_collection_links = hashpartition_resolver.ResolveForRead(document_definition['id'])
self.assertEqual(1, len(read_collection_links))
self.assertEqual(collection_link, read_collection_links[0])
def test_consistent_hash_ring(self):
created_db = { 'id': 'db' }
collection_links = list()
expected_partition_list = list()
total_collections_count = 2
collection = { 'id': 'coll' }
for i in xrange(0, total_collections_count):
collection['id'] = 'coll' + str(i)
collection_link = self.GetDocumentCollectionLink(created_db, collection, True)
collection_links.append(collection_link)
expected_partition_list.append(('dbs/db/colls/coll0', 1076200484))
expected_partition_list.append(('dbs/db/colls/coll0', 1302652881))
expected_partition_list.append(('dbs/db/colls/coll0', 2210251988))
expected_partition_list.append(('dbs/db/colls/coll1', 2341558382))
expected_partition_list.append(('dbs/db/colls/coll0', 2348251587))
expected_partition_list.append(('dbs/db/colls/coll0', 2887945459))
expected_partition_list.append(('dbs/db/colls/coll1', 2894403633))
expected_partition_list.append(('dbs/db/colls/coll1', 3031617259))
expected_partition_list.append(('dbs/db/colls/coll1', 3090861424))
expected_partition_list.append(('dbs/db/colls/coll1', 4222475028))
id_partition_key_extractor = lambda document: document['id']
hashpartition_resolver = hash_partition_resolver.HashPartitionResolver(id_partition_key_extractor, collection_links, 5)
actual_partition_list = hashpartition_resolver.consistent_hash_ring._GetSerializedPartitionList()
self.assertEqual(len(expected_partition_list), len(actual_partition_list))
for i in xrange(0, len(expected_partition_list)):
self.assertEqual(actual_partition_list[i][0], expected_partition_list[i][0])
self.assertEqual(actual_partition_list[i][1], expected_partition_list[i][1])
# Querying for a document and verifying that it's in the expected collection
read_collection_links = hashpartition_resolver.ResolveForRead("beadledom")
self.assertEqual(1, len(read_collection_links))
collection['id'] = 'coll1'
collection_link = self.GetDocumentCollectionLink(created_db, collection, True)
self.assertTrue(collection_link in read_collection_links)
# Querying for a document and verifying that it's in the expected collection
read_collection_links = hashpartition_resolver.ResolveForRead("999")
self.assertEqual(1, len(read_collection_links))
collection['id'] = 'coll0'
collection_link = self.GetDocumentCollectionLink(created_db, collection, True)
self.assertTrue(collection_link in read_collection_links)
def test_murmur_hash(self):
str = 'afdgdd'
bytes = bytearray(str, encoding='utf-8')
hash_value = murmur_hash._MurmurHash._ComputeHash(bytes)
self.assertEqual(1099701186, hash_value)
num = 374.0
bytes = bytearray(pack('d', num))
hash_value = murmur_hash._MurmurHash._ComputeHash(bytes)
self.assertEqual(3717946798, hash_value)
self._validate_bytes("", 0x1B873593, bytearray(b'\xEE\xA8\xA2\x67'), 1738713326)
self._validate_bytes("1", 0xE82562E4, bytearray(b'\xD0\x92\x24\xED'), 3978597072)
self._validate_bytes("00", 0xB4C39035, bytearray(b'\xFA\x09\x64\x1B'), 459540986)
self._validate_bytes("eyetooth", 0x8161BD86, bytearray(b'\x98\x62\x1C\x6F'), 1864131224)
self._validate_bytes("acid", 0x4DFFEAD7, bytearray(b'\x36\x92\xC0\xB9'), 3116405302)
self._validate_bytes("elevation", 0x1A9E1828, bytearray(b'\xA9\xB6\x40\xDF'), 3745560233)
self._validate_bytes("dent", 0xE73C4579, bytearray(b'\xD4\x59\xE1\xD3'), 3554761172)
self._validate_bytes("homeland", 0xB3DA72CA, bytearray(b'\x06\x4D\x72\xBB'), 3144830214)
self._validate_bytes("glamor", 0x8078A01B, bytearray(b'\x89\x89\xA2\xA7'), 2812447113)
self._validate_bytes("flags", 0x4D16CD6C, bytearray(b'\x52\x87\x66\x02'), 40273746)
self._validate_bytes("democracy", 0x19B4FABD, bytearray(b'\xE4\x55\xD6\xB0'), 2966836708)
self._validate_bytes("bumble", 0xE653280E, bytearray(b'\xFE\xD7\xC3\x0C'), 214161406)
self._validate_bytes("catch", 0xB2F1555F, bytearray(b'\x98\x4B\xB6\xCD'), 3451276184)
self._validate_bytes("omnomnomnivore", 0x7F8F82B0, bytearray(b'\x38\xC4\xCD\xFF'), 4291675192)
self._validate_bytes("The quick brown fox jumps over the lazy dog", 0x4C2DB001, bytearray(b'\x6D\xAB\x8D\xC9'), 3381504877)
def _validate_bytes(self, str, seed, expected_hash_bytes, expected_value):
hash_value = murmur_hash._MurmurHash._ComputeHash(bytearray(str, encoding='utf-8'), seed)
bytes = bytearray(pack('I', hash_value))
self.assertEqual(expected_value, hash_value)
self.assertEqual(expected_hash_bytes, bytes)
def test_get_bytes(self):
actual_bytes = consistent_hash_ring._ConsistentHashRing._GetBytes("documentdb")
expected_bytes = bytearray(b'\x64\x6F\x63\x75\x6D\x65\x6E\x74\x64\x62')
self.assertEqual(expected_bytes, actual_bytes)
actual_bytes = consistent_hash_ring._ConsistentHashRing._GetBytes("azure")
expected_bytes = bytearray(b'\x61\x7A\x75\x72\x65')
self.assertEqual(expected_bytes, actual_bytes)
actual_bytes = consistent_hash_ring._ConsistentHashRing._GetBytes("json")
expected_bytes = bytearray(b'\x6A\x73\x6F\x6E')
self.assertEqual(expected_bytes, actual_bytes)
actual_bytes = consistent_hash_ring._ConsistentHashRing._GetBytes("nosql")
expected_bytes = bytearray(b'\x6E\x6F\x73\x71\x6C')
self.assertEqual(expected_bytes, actual_bytes)
def test_range_partition_resolver(self):
# create test database
created_db = self.databseForTest
# Create bunch of collections participating in partitioning
collection0 = { 'id': 'coll_0' }
collection1 = { 'id': 'coll_1' }
collection2 = { 'id': 'coll_2' }
collection_links = [self.GetDocumentCollectionLink(created_db, collection0, True), self.GetDocumentCollectionLink(created_db, collection1, True), self.GetDocumentCollectionLink(created_db, collection2, True)]
val_partition_key_extractor = lambda document: document['val']
ranges =[partition_range.Range(0,400), partition_range.Range(401,800), partition_range.Range(501,1200)]
partition_map = dict([(ranges[0],collection_links[0]), (ranges[1],collection_links[1]), (ranges[2],collection_links[2])])
rangepartition_resolver = range_partition_resolver.RangePartitionResolver(val_partition_key_extractor, partition_map)
# create a document using the document definition
document_definition = { 'id': '0',
'name': 'sample document',
'val': 0 }
document_definition['val'] = 400
collection_link = rangepartition_resolver.ResolveForCreate(document_definition)
self.assertEquals(collection_links[0], collection_link)
read_collection_links = rangepartition_resolver.ResolveForRead(600)
self.assertEqual(2, len(read_collection_links))
self.assertTrue(collection_links[1] in read_collection_links)
self.assertTrue(collection_links[2] in read_collection_links)
read_collection_links = rangepartition_resolver.ResolveForRead(partition_range.Range(250, 500))
self.assertEqual(2, len(read_collection_links))
self.assertTrue(collection_links[0] in read_collection_links)
self.assertTrue(collection_links[1] in read_collection_links)
read_collection_links = rangepartition_resolver.ResolveForRead(list([partition_range.Range(250, 500), partition_range.Range(600, 1000)]))
self.assertEqual(3, len(read_collection_links))
self.assertTrue(collection_links[0] in read_collection_links)
self.assertTrue(collection_links[1] in read_collection_links)
self.assertTrue(collection_links[2] in read_collection_links)
read_collection_links = rangepartition_resolver.ResolveForRead(list([50, 100, 600, 1000]))
self.assertEqual(3, len(read_collection_links))
self.assertTrue(collection_links[0] in read_collection_links)
self.assertTrue(collection_links[1] in read_collection_links)
self.assertTrue(collection_links[2] in read_collection_links)
read_collection_links = rangepartition_resolver.ResolveForRead(list([100, None]))
self.assertEqual(3, len(read_collection_links))
self.assertTrue(collection_links[0] in read_collection_links)
self.assertTrue(collection_links[1] in read_collection_links)
self.assertTrue(collection_links[2] in read_collection_links)
# Upsert test for Document resource - selflink version
def test_document_upsert_self_link(self):
self._test_document_upsert(False)
# Upsert test for Document resource - name based routing version
def test_document_upsert_name_based(self):
self._test_document_upsert(True)
def _test_document_upsert(self, is_name_based):
# create database
created_db = self.databseForTest
# create collection
created_collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# read documents and check count
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based)))
before_create_documents_count = len(documents)
# create document definition
document_definition = {'id': 'doc',
'name': 'sample document',
'spam': 'eggs',
'key': 'value'}
# create document using Upsert API
created_document = self.client.UpsertItem(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
document_definition)
# verify id property
self.assertEqual(created_document['id'],
document_definition['id'])
# read documents after creation and verify updated count
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based)))
self.assertEqual(
len(documents),
before_create_documents_count + 1,
'create should increase the number of documents')
# update document
created_document['name'] = 'replaced document'
created_document['spam'] = 'not eggs'
# should replace document since it already exists
upserted_document = self.client.UpsertItem(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
created_document)
# verify the changed properties
self.assertEqual(upserted_document['name'],
created_document['name'],
'document id property should change')
self.assertEqual(upserted_document['spam'],
created_document['spam'],
'property should have changed')
# verify id property
self.assertEqual(upserted_document['id'],
created_document['id'],
'document id should stay the same')
# read documents after upsert and verify count doesn't increases again
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based)))
self.assertEqual(
len(documents),
before_create_documents_count + 1,
'number of documents should remain same')
created_document['id'] = 'new id'
# Upsert should create new document since the id is different
new_document = self.client.UpsertItem(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based),
created_document)
# verify id property
self.assertEqual(created_document['id'],
new_document['id'],
'document id should be same')
# read documents after upsert and verify count increases
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based)))
self.assertEqual(
len(documents),
before_create_documents_count + 2,
'upsert should increase the number of documents')
# delete documents
self.client.DeleteItem(self.GetDocumentLink(created_db, created_collection, upserted_document, is_name_based))
self.client.DeleteItem(self.GetDocumentLink(created_db, created_collection, new_document, is_name_based))
# read documents after delete and verify count is same as original
documents = list(self.client.ReadItems(
self.GetDocumentCollectionLink(created_db, created_collection, is_name_based)))
self.assertEqual(
len(documents),
before_create_documents_count,
'number of documents should remain same')
def test_spatial_index_self_link(self):
self._test_spatial_index(False)
def test_spatial_index_name_based(self):
self._test_spatial_index(True)
def _test_spatial_index(self, is_name_based):
db = self.databseForTest
# partial policy specified
collection = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based),
{
'id': 'collection with spatial index ' + str(uuid.uuid4()),
'indexingPolicy': {
'includedPaths': [
{
'path': '/"Location"/?',
'indexes': [
{
'kind': 'Spatial',
'dataType': 'Point'
}
]
},
{
'path': '/'
}
]
}
})
self.client.CreateItem(self.GetDocumentCollectionLink(db, collection, is_name_based), {
'id': 'loc1',
'Location': {
'type': 'Point',
'coordinates': [ 20.0, 20.0 ]
}
})
self.client.CreateItem(self.GetDocumentCollectionLink(db, collection, is_name_based), {
'id': 'loc2',
'Location': {
'type': 'Point',
'coordinates': [ 100.0, 100.0 ]
}
})
results = list(self.client.QueryItems(
self.GetDocumentCollectionLink(db, collection, is_name_based),
"SELECT * FROM root WHERE (ST_DISTANCE(root.Location, {type: 'Point', coordinates: [20.1, 20]}) < 20000) "))
self.assertEqual(1, len(results))
self.assertEqual('loc1', results[0]['id'])
def test_attachment_crud_self_link(self):
self._test_attachment_crud(False)
def test_attachment_crud_name_based(self):
self._test_attachment_crud(True)
def _test_attachment_crud(self, is_name_based):
class ReadableStream(object):
"""Customized file-like stream.
"""
def __init__(self, chunks = ['first chunk ', 'second chunk']):
"""Initialization.
:Parameters:
- `chunks`: list
"""
if six.PY2:
self._chunks = list(chunks)
else:
# python3: convert to bytes
self._chunks = [chunk.encode() for chunk in chunks]
def read(self, n=-1):
"""Simulates the read method in a file stream.
:Parameters:
- `n`: int
:Returns:
str or bytes
"""
if self._chunks:
return self._chunks.pop(0)
else:
return ''
def __len__(self):
"""To make len(ReadableStream) work.
"""
return sum([len(chunk) for chunk in self._chunks])
# Should do attachment CRUD operations successfully
self.client.connection_policy.MediaReadMode = documents.MediaReadMode.Buffered
# create database
db = self.databseForTest
# create collection
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# create document
document = self.client.CreateItem(self.GetDocumentCollectionLink(db, collection, is_name_based),
{ 'id': 'sample document',
'spam': 'eggs',
'key': 'value' })
# list all attachments
attachments = list(self.client.ReadAttachments(self.GetDocumentLink(db, collection, document, is_name_based)))
initial_count = len(attachments)
valid_media_options = { 'slug': 'attachment name',
'contentType': 'application/text' }
invalid_media_options = { 'slug': 'attachment name',
'contentType': 'junt/test' }
# create attachment with invalid content-type
content_stream = ReadableStream()
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST,
self.client.CreateAttachmentAndUploadMedia,
self.GetDocumentLink(db, collection, document, is_name_based),
content_stream,
invalid_media_options)
content_stream = ReadableStream()
# create streamed attachment with valid content-type
valid_attachment = self.client.CreateAttachmentAndUploadMedia(
self.GetDocumentLink(db, collection, document, is_name_based), content_stream, valid_media_options)
self.assertEqual(valid_attachment['id'],
'attachment name',
'id of created attachment should be the'
' same as the one in the request')
content_stream = ReadableStream()
# create colliding attachment
self.__AssertHTTPFailureWithStatus(
StatusCodes.CONFLICT,
self.client.CreateAttachmentAndUploadMedia,
self.GetDocumentLink(db, collection, document, is_name_based),
content_stream,
valid_media_options)
content_stream = ReadableStream()
# create attachment with media link
dynamic_attachment = {
'id': 'dynamic attachment',
'media': 'http://xstore.',
'MediaType': 'Book',
'Author':'My Book Author',
'Title':'My Book Title',
'contentType':'application/text'
}
attachment = self.client.CreateAttachment(self.GetDocumentLink(db, collection, document, is_name_based),
dynamic_attachment)
self.assertEqual(attachment['MediaType'],
'Book',
'invalid media type')
self.assertEqual(attachment['Author'],
'My Book Author',
'invalid property value')
# list all attachments
attachments = list(self.client.ReadAttachments(self.GetDocumentLink(db, collection, document, is_name_based)))
self.assertEqual(len(attachments),
initial_count + 2,
'number of attachments should\'ve increased by 2')
attachment['Author'] = 'new author'
# replace the attachment
self.client.ReplaceAttachment(self.GetAttachmentLink(db, collection, document, attachment, is_name_based), attachment)
self.assertEqual(attachment['MediaType'],
'Book',
'invalid media type')
self.assertEqual(attachment['Author'],
'new author',
'invalid property value')
# read attachment media
media_response = self.client.ReadMedia(valid_attachment['media'])
self.assertEqual(media_response,
'first chunk second chunk')
content_stream = ReadableStream(['modified first chunk ',
'modified second chunk'])
# update attachment media
self.client.UpdateMedia(valid_attachment['media'],
content_stream,
valid_media_options)
# read attachment media after update
# read media buffered
media_response = self.client.ReadMedia(valid_attachment['media'])
self.assertEqual(media_response,
'modified first chunk modified second chunk')
# read media streamed
self.client.connection_policy.MediaReadMode = (
documents.MediaReadMode.Streamed)
media_response = self.client.ReadMedia(valid_attachment['media'])
self.assertEqual(media_response.read(),
b'modified first chunk modified second chunk')
# share attachment with a second document
document = self.client.CreateItem(self.GetDocumentCollectionLink(db, collection, is_name_based),
{'id': 'document 2'})
second_attachment = {
'id': valid_attachment['id'],
'contentType': valid_attachment['contentType'],
'media': valid_attachment['media'] }
attachment = self.client.CreateAttachment(self.GetDocumentLink(db, collection, document, is_name_based),
second_attachment)
self.assertEqual(valid_attachment['id'],
attachment['id'],
'id mismatch')
self.assertEqual(valid_attachment['media'],
attachment['media'],
'media mismatch')
self.assertEqual(valid_attachment['contentType'],
attachment['contentType'],
'contentType mismatch')
# deleting attachment
self.client.DeleteAttachment(self.GetAttachmentLink(db, collection, document, attachment, is_name_based))
# read attachments after deletion
attachments = list(self.client.ReadAttachments(self.GetDocumentLink(db, collection, document, is_name_based)))
self.assertEqual(len(attachments), 0)
# Upsert test for Attachment resource - selflink version
def test_attachment_upsert_self_link(self):
self._test_attachment_upsert(False)
# Upsert test for Attachment resource - name based routing version
def test_attachment_upsert_name_based(self):
self._test_attachment_upsert(True)
def _test_attachment_upsert(self, is_name_based):
class ReadableStream(object):
"""Customized file-like stream.
"""
def __init__(self, chunks = ['first chunk ', 'second chunk']):
"""Initialization.
:Parameters:
- `chunks`: list
"""
if six.PY2:
self._chunks = list(chunks)
else:
# python3: convert to bytes
self._chunks = [chunk.encode() for chunk in chunks]
def read(self, n=-1):
"""Simulates the read method in a file stream.
:Parameters:
- `n`: int
:Returns:
str or bytes
"""
if self._chunks:
return self._chunks.pop(0)
else:
return ''
def __len__(self):
"""To make len(ReadableStream) work.
"""
return sum([len(chunk) for chunk in self._chunks])
# create database
db = self.databseForTest
# create collection
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# create document
document = self.client.CreateItem(self.GetDocumentCollectionLink(db, collection, is_name_based),
{ 'id': 'sample document' + str(uuid.uuid4()),
'spam': 'eggs',
'key': 'value' })
# list all attachments and check count
attachments = list(self.client.ReadAttachments(self.GetDocumentLink(db, collection, document, is_name_based)))
initial_count = len(attachments)
valid_media_options = { 'slug': 'attachment name',
'contentType': 'application/text' }
content_stream = ReadableStream()
# create streamed attachment with valid content-type using Upsert API
valid_attachment = self.client.UpsertAttachmentAndUploadMedia(
self.GetDocumentLink(db, collection, document, is_name_based), content_stream, valid_media_options)
# verify id property
self.assertEqual(valid_attachment['id'],
'attachment name',
'id of created attachment should be the same')
valid_media_options = { 'slug': 'new attachment name',
'contentType': 'application/text' }
content_stream = ReadableStream()
# Upsert should create new attachment since since id is different
new_valid_attachment = self.client.UpsertAttachmentAndUploadMedia(
self.GetDocumentLink(db, collection, document, is_name_based), content_stream, valid_media_options)
# verify id property
self.assertEqual(new_valid_attachment['id'],
'new attachment name',
'id of new attachment should be the same')
# read all attachments and verify updated count
attachments = list(self.client.ReadAttachments(self.GetDocumentLink(db, collection, document, is_name_based)))
self.assertEqual(len(attachments),
initial_count + 2,
'number of attachments should have increased by 2')
# create attachment with media link
attachment_definition = {
'id': 'dynamic attachment',
'media': 'http://xstore.',
'MediaType': 'Book',
'Author':'My Book Author',
'Title':'My Book Title',
'contentType':'application/text'
}
# create dynamic attachment using Upsert API
dynamic_attachment = self.client.UpsertAttachment(self.GetDocumentLink(db, collection, document, is_name_based),
attachment_definition)
# verify id property
self.assertEqual(dynamic_attachment['id'],
attachment_definition['id'],
'id of attachment should be the same')
# read all attachments and verify updated count
attachments = list(self.client.ReadAttachments(self.GetDocumentLink(db, collection, document, is_name_based)))
self.assertEqual(len(attachments),
initial_count + 3,
'number of attachments should have increased by 3')
dynamic_attachment['Author'] = 'new author'
# replace the attachment using Upsert API
upserted_attachment = self.client.UpsertAttachment(self.GetDocumentLink(db, collection, document, is_name_based), dynamic_attachment)
# verify id property remains same
self.assertEqual(dynamic_attachment['id'],
upserted_attachment['id'],
'id should stay the same')
# verify author property gets updated
self.assertEqual(upserted_attachment['Author'],
dynamic_attachment['Author'],
'invalid property value')
# read all attachments and verify count doesn't increases again
attachments = list(self.client.ReadAttachments(self.GetDocumentLink(db, collection, document, is_name_based)))
self.assertEqual(len(attachments),
initial_count + 3,
'number of attachments should remain same')
dynamic_attachment['id'] = 'new dynamic attachment'
# Upsert should create new attachment since id is different
new_attachment = self.client.UpsertAttachment(self.GetDocumentLink(db, collection, document, is_name_based), dynamic_attachment)
# verify id property remains same
self.assertEqual(dynamic_attachment['id'],
new_attachment['id'],
'id should be same')
# read all attachments and verify count increases
attachments = list(self.client.ReadAttachments(self.GetDocumentLink(db, collection, document, is_name_based)))
self.assertEqual(len(attachments),
initial_count + 4,
'number of attachments should have increased')
# deleting attachments
self.client.DeleteAttachment(self.GetAttachmentLink(db, collection, document, valid_attachment, is_name_based))
self.client.DeleteAttachment(self.GetAttachmentLink(db, collection, document, new_valid_attachment, is_name_based))
self.client.DeleteAttachment(self.GetAttachmentLink(db, collection, document, upserted_attachment, is_name_based))
self.client.DeleteAttachment(self.GetAttachmentLink(db, collection, document, new_attachment, is_name_based))
# wait to ensure deletes are propagated for multimaster enabled accounts
if self.configs.IS_MULTIMASTER_ENABLED:
time.sleep(2)
# read all attachments and verify count remains same
attachments = list(self.client.ReadAttachments(self.GetDocumentLink(db, collection, document, is_name_based)))
self.assertEqual(len(attachments),
initial_count,
'number of attachments should remain the same')
def test_user_crud_self_link(self):
self._test_user_crud(False)
def test_user_crud_name_based(self):
self._test_user_crud(True)
def _test_user_crud(self, is_name_based):
# Should do User CRUD operations successfully.
# create database
db = self.databseForTest
# list users
users = list(self.client.ReadUsers(self.GetDatabaseLink(db, is_name_based)))
before_create_count = len(users)
# create user
user_id = 'new user' + str(uuid.uuid4())
user = self.client.CreateUser(self.GetDatabaseLink(db, is_name_based), { 'id': user_id })
self.assertEqual(user['id'], user_id, 'user id error')
# list users after creation
users = list(self.client.ReadUsers(self.GetDatabaseLink(db, is_name_based)))
self.assertEqual(len(users), before_create_count + 1)
# query users
results = list(self.client.QueryUsers(
self.GetDatabaseLink(db, is_name_based),
{
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name':'@id', 'value':user_id }
]
}))
self.assertTrue(results)
# replace user
change_user = user.copy()
replaced_user_id = 'replaced user' + str(uuid.uuid4())
user['id'] = replaced_user_id
replaced_user = self.client.ReplaceUser(self.GetUserLink(db, change_user, is_name_based), user)
self.assertEqual(replaced_user['id'],
replaced_user_id,
'user id should change')
self.assertEqual(user['id'],
replaced_user['id'],
'user id should stay the same')
# read user
user = self.client.ReadUser(self.GetUserLink(db, replaced_user, is_name_based))
self.assertEqual(replaced_user['id'], user['id'])
# delete user
self.client.DeleteUser(self.GetUserLink(db, user, is_name_based))
# read user after deletion
self.__AssertHTTPFailureWithStatus(StatusCodes.NOT_FOUND,
self.client.ReadUser,
self.GetUserLink(db, user, is_name_based))
# Upsert test for User resource - selflink version
def test_user_upsert_self_link(self):
self._test_user_upsert(False)
# Upsert test for User resource - named based routing version
def test_user_upsert_name_based(self):
self._test_user_upsert(True)
def _test_user_upsert(self, is_name_based):
# create database
db = self.databseForTest
# read users and check count
users = list(self.client.ReadUsers(self.GetDatabaseLink(db, is_name_based)))
before_create_count = len(users)
# create user using Upsert API
user_id = 'user' + str(uuid.uuid4())
user = self.client.UpsertUser(self.GetDatabaseLink(db, is_name_based), { 'id': user_id })
# verify id property
self.assertEqual(user['id'], user_id, 'user id error')
# read users after creation and verify updated count
users = list(self.client.ReadUsers(self.GetDatabaseLink(db, is_name_based)))
self.assertEqual(len(users), before_create_count + 1)
# Should replace the user since it already exists, there is no public property to change here
upserted_user = self.client.UpsertUser(self.GetDatabaseLink(db, is_name_based), user)
# verify id property
self.assertEqual(upserted_user['id'],
user['id'],
'user id should remain same')
# read users after upsert and verify count doesn't increases again
users = list(self.client.ReadUsers(self.GetDatabaseLink(db, is_name_based)))
self.assertEqual(len(users), before_create_count + 1)
user['id'] = 'new user' + str(uuid.uuid4())
# Upsert should create new user since id is different
new_user = self.client.UpsertUser(self.GetDatabaseLink(db, is_name_based), user)
# verify id property
self.assertEqual(new_user['id'], user['id'], 'user id error')
# read users after upsert and verify count increases
users = list(self.client.ReadUsers(self.GetDatabaseLink(db, is_name_based)))
self.assertEqual(len(users), before_create_count + 2)
# delete users
self.client.DeleteUser(self.GetUserLink(db, upserted_user, is_name_based))
self.client.DeleteUser(self.GetUserLink(db, new_user, is_name_based))
# read users after delete and verify count remains the same
users = list(self.client.ReadUsers(self.GetDatabaseLink(db, is_name_based)))
self.assertEqual(len(users), before_create_count)
def test_permission_crud_self_link(self):
self._test_permission_crud(False)
def test_permission_crud_name_based(self):
self._test_permission_crud(True)
def _test_permission_crud(self, is_name_based):
# Should do Permission CRUD operations successfully
# create database
db = self.databseForTest
# create user
user = self.client.CreateUser(self.GetDatabaseLink(db, is_name_based), { 'id': 'new user' + str(uuid.uuid4())})
# list permissions
permissions = list(self.client.ReadPermissions(self.GetUserLink(db, user, is_name_based)))
before_create_count = len(permissions)
permission = {
'id': 'new permission',
'permissionMode': documents.PermissionMode.Read,
'resource': 'dbs/AQAAAA==/colls/AQAAAJ0fgTc=' # A random one.
}
# create permission
permission = self.client.CreatePermission(self.GetUserLink(db, user, is_name_based), permission)
self.assertEqual(permission['id'],
'new permission',
'permission id error')
# list permissions after creation
permissions = list(self.client.ReadPermissions(self.GetUserLink(db, user, is_name_based)))
self.assertEqual(len(permissions), before_create_count + 1)
# query permissions
results = list(self.client.QueryPermissions(
self.GetUserLink(db, user, is_name_based),
{
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name':'@id', 'value':permission['id'] }
]
}))
self.assert_(results)
# replace permission
change_permission = permission.copy()
permission['id'] = 'replaced permission'
replaced_permission = self.client.ReplacePermission(self.GetPermissionLink(db, user, change_permission, is_name_based),
permission)
self.assertEqual(replaced_permission['id'],
'replaced permission',
'permission id should change')
self.assertEqual(permission['id'],
replaced_permission['id'],
'permission id should stay the same')
# read permission
permission = self.client.ReadPermission(self.GetPermissionLink(db, user, replaced_permission, is_name_based))
self.assertEqual(replaced_permission['id'], permission['id'])
# delete permission
self.client.DeletePermission(self.GetPermissionLink(db, user, replaced_permission, is_name_based))
# read permission after deletion
self.__AssertHTTPFailureWithStatus(StatusCodes.NOT_FOUND,
self.client.ReadPermission,
self.GetPermissionLink(db, user, permission, is_name_based))
# Upsert test for Permission resource - selflink version
def test_permission_upsert_self_link(self):
self._test_permission_upsert(False)
# Upsert test for Permission resource - name based routing version
def test_permission_upsert_name_based(self):
self._test_permission_upsert(True)
def _test_permission_upsert(self, is_name_based):
# create database
db = self.databseForTest
# create user
user = self.client.CreateUser(self.GetDatabaseLink(db, is_name_based), { 'id': 'new user' + str(uuid.uuid4())})
# read permissions and check count
permissions = list(self.client.ReadPermissions(self.GetUserLink(db, user, is_name_based)))
before_create_count = len(permissions)
permission_definition = {
'id': 'permission',
'permissionMode': documents.PermissionMode.Read,
'resource': 'dbs/AQAAAA==/colls/AQAAAJ0fgTc=' # A random one.
}
# create permission using Upsert API
created_permission = self.client.UpsertPermission(self.GetUserLink(db, user, is_name_based), permission_definition)
# verify id property
self.assertEqual(created_permission['id'],
permission_definition['id'],
'permission id error')
# read permissions after creation and verify updated count
permissions = list(self.client.ReadPermissions(self.GetUserLink(db, user, is_name_based)))
self.assertEqual(len(permissions), before_create_count + 1)
# update permission mode
permission_definition['permissionMode'] = documents.PermissionMode.All
# should repace the permission since it already exists
upserted_permission = self.client.UpsertPermission(self.GetUserLink(db, user, is_name_based),
permission_definition)
# verify id property
self.assertEqual(upserted_permission['id'],
created_permission['id'],
'permission id should remain same')
# verify changed property
self.assertEqual(upserted_permission['permissionMode'],
permission_definition['permissionMode'],
'permissionMode should change')
# read permissions and verify count doesn't increases again
permissions = list(self.client.ReadPermissions(self.GetUserLink(db, user, is_name_based)))
self.assertEqual(len(permissions), before_create_count + 1)
# update permission id
created_permission['id'] = 'new permission'
# resource needs to be changed along with the id in order to create a new permission
created_permission['resource'] = 'dbs/N9EdAA==/colls/N9EdAIugXgA='
# should create new permission since id has changed
new_permission = self.client.UpsertPermission(self.GetUserLink(db, user, is_name_based),
created_permission)
# verify id and resource property
self.assertEqual(new_permission['id'],
created_permission['id'],
'permission id should be same')
self.assertEqual(new_permission['resource'],
created_permission['resource'],
'permission resource should be same')
# read permissions and verify count increases
permissions = list(self.client.ReadPermissions(self.GetUserLink(db, user, is_name_based)))
self.assertEqual(len(permissions), before_create_count + 2)
# delete permissions
self.client.DeletePermission(self.GetPermissionLink(db, user, upserted_permission, is_name_based))
self.client.DeletePermission(self.GetPermissionLink(db, user, new_permission, is_name_based))
# read permissions and verify count remains the same
permissions = list(self.client.ReadPermissions(self.GetUserLink(db, user, is_name_based)))
self.assertEqual(len(permissions), before_create_count)
def test_authorization(self):
def __SetupEntities(client):
"""
Sets up entities for this test.
:Parameters:
- `client`: cosmos_client.CosmosClient
:Returns:
dict
"""
# create database
db = self.databseForTest
# create collection1
collection1 = client.CreateContainer(
db['_self'], { 'id': 'test_authorization ' + str(uuid.uuid4()) })
# create document1
document1 = client.CreateItem(collection1['_self'],
{ 'id': 'coll1doc1',
'spam': 'eggs',
'key': 'value' })
# create document 2
document2 = client.CreateItem(
collection1['_self'],
{ 'id': 'coll1doc2', 'spam': 'eggs2', 'key': 'value2' })
# create attachment
dynamic_attachment = {
'id': 'dynamic attachment',
'media': 'http://xstore.',
'MediaType': 'Book',
'Author': 'My Book Author',
'Title': 'My Book Title',
'contentType': 'application/text'
}
attachment = client.CreateAttachment(document1['_self'],
dynamic_attachment)
# create collection 2
collection2 = client.CreateContainer(
db['_self'],
{ 'id': 'test_authorization2 ' + str(uuid.uuid4()) })
# create user1
user1 = client.CreateUser(db['_self'], { 'id': 'user1' })
permission = {
'id': 'permission On Coll1',
'permissionMode': documents.PermissionMode.Read,
'resource': collection1['_self']
}
# create permission for collection1
permission_on_coll1 = client.CreatePermission(user1['_self'],
permission)
self.assertTrue(permission_on_coll1['_token'] != None,
'permission token is invalid')
permission = {
'id': 'permission On Doc1',
'permissionMode': documents.PermissionMode.All,
'resource': document2['_self']
}
# create permission for document 2
permission_on_doc2 = client.CreatePermission(user1['_self'],
permission)
self.assertTrue(permission_on_doc2['_token'] != None,
'permission token is invalid')
# create user 2
user2 = client.CreateUser(db['_self'], { 'id': 'user2' })
permission = {
'id': 'permission On coll2',
'permissionMode': documents.PermissionMode.All,
'resource': collection2['_self']
}
# create permission on collection 2
permission_on_coll2 = client.CreatePermission(
user2['_self'], permission)
entities = {
'db': db,
'coll1': collection1,
'coll2': collection2,
'doc1': document1,
'doc2': document2,
'user1': user1,
'user2': user2,
'attachment': attachment,
'permissionOnColl1': permission_on_coll1,
'permissionOnDoc2': permission_on_doc2,
'permissionOnColl2': permission_on_coll2
}
return entities
# Client without any authorization will fail.
client = cosmos_client.CosmosClient(CRUDTests.host, {}, CRUDTests.connectionPolicy)
self.__AssertHTTPFailureWithStatus(StatusCodes.UNAUTHORIZED,
list,
client.ReadDatabases())
# Client with master key.
client = cosmos_client.CosmosClient(CRUDTests.host,
{'masterKey': CRUDTests.masterKey}, CRUDTests.connectionPolicy)
# setup entities
entities = __SetupEntities(client)
resource_tokens = {}
resource_tokens[entities['coll1']['_rid']] = (
entities['permissionOnColl1']['_token'])
resource_tokens[entities['doc1']['_rid']] = (
entities['permissionOnColl1']['_token'])
col1_client = cosmos_client.CosmosClient(
CRUDTests.host, {'resourceTokens': resource_tokens}, CRUDTests.connectionPolicy)
# 1. Success-- Use Col1 Permission to Read
success_coll1 = col1_client.ReadContainer(
entities['coll1']['_self'])
# 2. Failure-- Use Col1 Permission to delete
self.__AssertHTTPFailureWithStatus(StatusCodes.FORBIDDEN,
col1_client.DeleteContainer,
success_coll1['_self'])
# 3. Success-- Use Col1 Permission to Read All Docs
success_documents = list(col1_client.ReadItems(
success_coll1['_self']))
self.assertTrue(success_documents != None,
'error reading documents')
self.assertEqual(len(success_documents),
2,
'Expected 2 Documents to be succesfully read')
# 4. Success-- Use Col1 Permission to Read Col1Doc1
success_doc = col1_client.ReadItem(entities['doc1']['_self'])
self.assertTrue(success_doc != None, 'error reading document')
self.assertEqual(
success_doc['id'],
entities['doc1']['id'],
'Expected to read children using parent permissions')
col2_client = cosmos_client.CosmosClient(
CRUDTests.host,
{ 'permissionFeed': [ entities['permissionOnColl2'] ] }, CRUDTests.connectionPolicy)
doc = {
'CustomProperty1': 'BBBBBB',
'customProperty2': 1000,
'id': entities['doc2']['id']
}
success_doc = col2_client.CreateItem(
entities['coll2']['_self'], doc)
self.assertTrue(success_doc != None, 'error creating document')
self.assertEqual(success_doc['CustomProperty1'],
doc['CustomProperty1'],
'document should have been created successfully')
self.client.DeleteContainer(entities['coll1']['_self'])
self.client.DeleteContainer(entities['coll2']['_self'])
def test_trigger_crud_self_link(self):
self._test_trigger_crud(False)
def test_trigger_crud_name_based(self):
self._test_trigger_crud(True)
def _test_trigger_crud(self, is_name_based):
# create database
db = self.databseForTest
# create collection
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# read triggers
triggers = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection, is_name_based)))
# create a trigger
before_create_triggers_count = len(triggers)
trigger_definition = {
'id': 'sample trigger',
'serverScript': 'function() {var x = 10;}',
'triggerType': documents.TriggerType.Pre,
'triggerOperation': documents.TriggerOperation.All
}
trigger = self.client.CreateTrigger(self.GetDocumentCollectionLink(db, collection, is_name_based),
trigger_definition)
for property in trigger_definition:
if property != "serverScript":
self.assertEqual(
trigger[property],
trigger_definition[property],
'property {property} should match'.format(property=property))
else:
self.assertEqual(trigger['body'],
'function() {var x = 10;}')
# read triggers after creation
triggers = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(triggers),
before_create_triggers_count + 1,
'create should increase the number of triggers')
# query triggers
triggers = list(self.client.QueryTriggers(
self.GetDocumentCollectionLink(db, collection, is_name_based),
{
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name': '@id', 'value': trigger_definition['id']}
]
}))
self.assert_(triggers)
# replace trigger
change_trigger = trigger.copy()
trigger['body'] = 'function() {var x = 20;}'
replaced_trigger = self.client.ReplaceTrigger(self.GetTriggerLink(db, collection, change_trigger, is_name_based), trigger)
for property in trigger_definition:
if property != "serverScript":
self.assertEqual(
replaced_trigger[property],
trigger[property],
'property {property} should match'.format(property=property))
else:
self.assertEqual(replaced_trigger['body'],
'function() {var x = 20;}')
# read trigger
trigger = self.client.ReadTrigger(self.GetTriggerLink(db, collection, replaced_trigger, is_name_based))
self.assertEqual(replaced_trigger['id'], trigger['id'])
# delete trigger
self.client.DeleteTrigger(self.GetTriggerLink(db, collection, replaced_trigger, is_name_based))
# read triggers after deletion
self.__AssertHTTPFailureWithStatus(StatusCodes.NOT_FOUND,
self.client.ReadTrigger,
self.GetTriggerLink(db, collection, replaced_trigger, is_name_based))
# Upsert test for Trigger resource - selflink version
def test_trigger_upsert_self_link(self):
self._test_trigger_upsert(False)
# Upsert test for Trigger resource - name based routing version
def test_trigger_upsert_name_based(self):
self._test_trigger_upsert(True)
def _test_trigger_upsert(self, is_name_based):
# create database
db = self.databseForTest
# create collection
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# read triggers and check count
triggers = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection, is_name_based)))
before_create_triggers_count = len(triggers)
# create a trigger
trigger_definition = {
'id': 'sample trigger',
'serverScript': 'function() {var x = 10;}',
'triggerType': documents.TriggerType.Pre,
'triggerOperation': documents.TriggerOperation.All
}
# create trigger using Upsert API
created_trigger = self.client.UpsertTrigger(self.GetDocumentCollectionLink(db, collection, is_name_based),
trigger_definition)
# verify id property
self.assertEqual(created_trigger['id'],
trigger_definition['id'])
# read triggers after creation and verify updated count
triggers = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(triggers),
before_create_triggers_count + 1,
'create should increase the number of triggers')
# update trigger
created_trigger['body'] = 'function() {var x = 20;}'
# should replace trigger since it already exists
upserted_trigger = self.client.UpsertTrigger(self.GetDocumentCollectionLink(db, collection, is_name_based), created_trigger)
# verify id property
self.assertEqual(created_trigger['id'],
upserted_trigger['id'])
# verify changed properties
self.assertEqual(upserted_trigger['body'],
created_trigger['body'])
# read triggers after upsert and verify count remains same
triggers = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(triggers),
before_create_triggers_count + 1,
'upsert should keep the number of triggers same')
# update trigger
created_trigger['id'] = 'new trigger'
# should create new trigger since id is changed
new_trigger = self.client.UpsertTrigger(self.GetDocumentCollectionLink(db, collection, is_name_based), created_trigger)
# verify id property
self.assertEqual(created_trigger['id'],
new_trigger['id'])
# read triggers after upsert and verify count increases
triggers = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(triggers),
before_create_triggers_count + 2,
'upsert should increase the number of triggers')
# delete triggers
self.client.DeleteTrigger(self.GetTriggerLink(db, collection, upserted_trigger, is_name_based))
self.client.DeleteTrigger(self.GetTriggerLink(db, collection, new_trigger, is_name_based))
# read triggers after delete and verify count remains the same
triggers = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(triggers),
before_create_triggers_count,
'delete should bring the number of triggers to original')
def test_udf_crud_self_link(self):
self._test_udf_crud(False)
def test_udf_crud_name_based(self):
self._test_udf_crud(True)
def _test_udf_crud(self, is_name_based):
# create database
db = self.databseForTest
# create collection
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# read udfs
udfs = list(self.client.ReadUserDefinedFunctions(self.GetDocumentCollectionLink(db, collection, is_name_based)))
# create a udf
before_create_udfs_count = len(udfs)
udf_definition = {
'id': 'sample udf',
'body': 'function() {var x = 10;}'
}
udf = self.client.CreateUserDefinedFunction(self.GetDocumentCollectionLink(db, collection, is_name_based),
udf_definition)
for property in udf_definition:
self.assertEqual(
udf[property],
udf_definition[property],
'property {property} should match'.format(property=property))
# read udfs after creation
udfs = list(self.client.ReadUserDefinedFunctions(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(udfs),
before_create_udfs_count + 1,
'create should increase the number of udfs')
# query udfs
results = list(self.client.QueryUserDefinedFunctions(
self.GetDocumentCollectionLink(db, collection, is_name_based),
{
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{'name':'@id', 'value':udf_definition['id']}
]
}))
self.assert_(results)
# replace udf
change_udf = udf.copy()
udf['body'] = 'function() {var x = 20;}'
replaced_udf = self.client.ReplaceUserDefinedFunction(self.GetUserDefinedFunctionLink(db, collection, change_udf, is_name_based), udf)
for property in udf_definition:
self.assertEqual(
replaced_udf[property],
udf[property],
'property {property} should match'.format(property=property))
# read udf
udf = self.client.ReadUserDefinedFunction(self.GetUserDefinedFunctionLink(db, collection, replaced_udf, is_name_based))
self.assertEqual(replaced_udf['id'], udf['id'])
# delete udf
self.client.DeleteUserDefinedFunction(self.GetUserDefinedFunctionLink(db, collection, replaced_udf, is_name_based))
# read udfs after deletion
self.__AssertHTTPFailureWithStatus(StatusCodes.NOT_FOUND,
self.client.ReadUserDefinedFunction,
self.GetUserDefinedFunctionLink(db, collection, replaced_udf, is_name_based))
# Upsert test for User Defined Function resource - selflink version
def test_udf_upsert_self_link(self):
self._test_udf_upsert(False)
# Upsert test for User Defined Function resource - name based routing version
def test_udf_upsert_name_based(self):
self._test_udf_upsert(True)
def _test_udf_upsert(self, is_name_based):
# create database
db = self.databseForTest
# create collection
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# read udfs and check count
udfs = list(self.client.ReadUserDefinedFunctions(self.GetDocumentCollectionLink(db, collection, is_name_based)))
before_create_udfs_count = len(udfs)
# create a udf definition
udf_definition = {
'id': 'sample udf',
'body': 'function() {var x = 10;}'
}
# create udf using Upsert API
created_udf = self.client.UpsertUserDefinedFunction(self.GetDocumentCollectionLink(db, collection, is_name_based),
udf_definition)
# verify id property
self.assertEqual(created_udf['id'],
udf_definition['id'])
# read udfs after creation and verify updated count
udfs = list(self.client.ReadUserDefinedFunctions(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(udfs),
before_create_udfs_count + 1,
'create should increase the number of udfs')
# update udf
created_udf['body'] = 'function() {var x = 20;}'
# should replace udf since it already exists
upserted_udf = self.client.UpsertUserDefinedFunction(self.GetDocumentCollectionLink(db, collection, is_name_based), created_udf)
# verify id property
self.assertEqual(created_udf['id'],
upserted_udf['id'])
# verify changed property
self.assertEqual(upserted_udf['body'],
created_udf['body'])
# read udf and verify count doesn't increases again
udfs = list(self.client.ReadUserDefinedFunctions(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(udfs),
before_create_udfs_count + 1,
'upsert should keep the number of udfs same')
created_udf['id'] = 'new udf'
# should create new udf since the id is different
new_udf = self.client.UpsertUserDefinedFunction(self.GetDocumentCollectionLink(db, collection, is_name_based), created_udf)
# verify id property
self.assertEqual(created_udf['id'],
new_udf['id'])
# read udf and verify count increases
udfs = list(self.client.ReadUserDefinedFunctions(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(udfs),
before_create_udfs_count + 2,
'upsert should keep the number of udfs same')
# delete udfs
self.client.DeleteUserDefinedFunction(self.GetUserDefinedFunctionLink(db, collection, upserted_udf, is_name_based))
self.client.DeleteUserDefinedFunction(self.GetUserDefinedFunctionLink(db, collection, new_udf, is_name_based))
# read udf and verify count remains the same
udfs = list(self.client.ReadUserDefinedFunctions(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(udfs),
before_create_udfs_count,
'delete should keep the number of udfs same')
def test_sproc_crud_self_link(self):
self._test_sproc_crud(False)
def test_sproc_crud_name_based(self):
self._test_sproc_crud(True)
def _test_sproc_crud(self, is_name_based):
# create database
db = self.databseForTest
# create collection
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# read sprocs
sprocs = list(self.client.ReadStoredProcedures(self.GetDocumentCollectionLink(db, collection, is_name_based)))
# create a sproc
before_create_sprocs_count = len(sprocs)
sproc_definition = {
'id': 'sample sproc',
'serverScript': 'function() {var x = 10;}'
}
sproc = self.client.CreateStoredProcedure(self.GetDocumentCollectionLink(db, collection, is_name_based),
sproc_definition)
for property in sproc_definition:
if property != "serverScript":
self.assertEqual(
sproc[property],
sproc_definition[property],
'property {property} should match'.format(property=property))
else:
self.assertEqual(sproc['body'], 'function() {var x = 10;}')
# read sprocs after creation
sprocs = list(self.client.ReadStoredProcedures(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(sprocs),
before_create_sprocs_count + 1,
'create should increase the number of sprocs')
# query sprocs
sprocs = list(self.client.QueryStoredProcedures(
self.GetDocumentCollectionLink(db, collection, is_name_based),
{
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters':[
{ 'name':'@id', 'value':sproc_definition['id'] }
]
}))
self.assert_(sprocs)
# replace sproc
change_sproc = sproc.copy()
sproc['body'] = 'function() {var x = 20;}'
replaced_sproc = self.client.ReplaceStoredProcedure(self.GetStoredProcedureLink(db, collection, change_sproc, is_name_based),
sproc)
for property in sproc_definition:
if property != 'serverScript':
self.assertEqual(
replaced_sproc[property],
sproc[property],
'property {property} should match'.format(property=property))
else:
self.assertEqual(replaced_sproc['body'],
"function() {var x = 20;}")
# read sproc
sproc = self.client.ReadStoredProcedure(self.GetStoredProcedureLink(db, collection, replaced_sproc, is_name_based))
self.assertEqual(replaced_sproc['id'], sproc['id'])
# delete sproc
self.client.DeleteStoredProcedure(self.GetStoredProcedureLink(db, collection, replaced_sproc, is_name_based))
# read sprocs after deletion
self.__AssertHTTPFailureWithStatus(StatusCodes.NOT_FOUND,
self.client.ReadStoredProcedure,
self.GetStoredProcedureLink(db, collection, replaced_sproc, is_name_based))
# Upsert test for sproc resource - selflink version
def test_sproc_upsert_self_link(self):
self._test_sproc_upsert(False)
# Upsert test for sproc resource - name based routing version
def test_sproc_upsert_name_based(self):
self._test_sproc_upsert(True)
def _test_sproc_upsert(self, is_name_based):
# create database
db = self.databseForTest
# create collection
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
# read sprocs and check count
sprocs = list(self.client.ReadStoredProcedures(self.GetDocumentCollectionLink(db, collection, is_name_based)))
before_create_sprocs_count = len(sprocs)
# create a sproc definition
sproc_definition = {
'id': 'sample sproc',
'serverScript': 'function() {var x = 10;}'
}
# create sproc using Upsert API
created_sproc = self.client.UpsertStoredProcedure(self.GetDocumentCollectionLink(db, collection, is_name_based),
sproc_definition)
# verify id property
self.assertEqual(created_sproc['id'],
sproc_definition['id'])
# read sprocs after creation and verify updated count
sprocs = list(self.client.ReadStoredProcedures(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(sprocs),
before_create_sprocs_count + 1,
'create should increase the number of sprocs')
# update sproc
created_sproc['body'] = 'function() {var x = 20;}'
# should replace sproc since it already exists
upserted_sproc = self.client.UpsertStoredProcedure(self.GetDocumentCollectionLink(db, collection, is_name_based),
created_sproc)
# verify id property
self.assertEqual(created_sproc['id'],
upserted_sproc['id'])
# verify changed property
self.assertEqual(upserted_sproc['body'],
created_sproc['body'])
# read sprocs after upsert and verify count remains the same
sprocs = list(self.client.ReadStoredProcedures(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(sprocs),
before_create_sprocs_count + 1,
'upsert should keep the number of sprocs same')
# update sproc
created_sproc['id'] = 'new sproc'
# should create new sproc since id is different
new_sproc = self.client.UpsertStoredProcedure(self.GetDocumentCollectionLink(db, collection, is_name_based),
created_sproc)
# verify id property
self.assertEqual(created_sproc['id'],
new_sproc['id'])
# read sprocs after upsert and verify count increases
sprocs = list(self.client.ReadStoredProcedures(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(sprocs),
before_create_sprocs_count + 2,
'upsert should keep the number of sprocs same')
# delete sprocs
self.client.DeleteStoredProcedure(self.GetStoredProcedureLink(db, collection, upserted_sproc, is_name_based))
self.client.DeleteStoredProcedure(self.GetStoredProcedureLink(db, collection, new_sproc, is_name_based))
# read sprocs after delete and verify count remains same
sprocs = list(self.client.ReadStoredProcedures(self.GetDocumentCollectionLink(db, collection, is_name_based)))
self.assertEqual(len(sprocs),
before_create_sprocs_count,
'delete should keep the number of sprocs same')
def test_scipt_logging_execute_stored_procedure(self):
created_db = self.databseForTest
created_collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
sproc = {
'id': 'storedProcedure' + str(uuid.uuid4()),
'body': (
'function () {' +
' var mytext = \'x\';' +
' var myval = 1;' +
' try {' +
' console.log(\'The value of %s is %s.\', mytext, myval);' +
' getContext().getResponse().setBody(\'Success!\');' +
' }' +
' catch (err) {' +
' getContext().getResponse().setBody(\'inline err: [\' + err.number + \'] \' + err);' +
' }'
'}')
}
created_sproc = self.client.CreateStoredProcedure(self.GetDocumentCollectionLink(created_db, created_collection), sproc)
result = self.client.ExecuteStoredProcedure(self.GetStoredProcedureLink(created_db, created_collection, created_sproc), None)
self.assertEqual(result, 'Success!')
self.assertFalse(HttpHeaders.ScriptLogResults in self.client.last_response_headers)
options = { 'enableScriptLogging': True }
result = self.client.ExecuteStoredProcedure(self.GetStoredProcedureLink(created_db, created_collection, created_sproc), None, options)
self.assertEqual(result, 'Success!')
self.assertEqual(urllib.quote('The value of x is 1.'), self.client.last_response_headers.get(HttpHeaders.ScriptLogResults))
options = { 'enableScriptLogging': False }
result = self.client.ExecuteStoredProcedure(self.GetStoredProcedureLink(created_db, created_collection, created_sproc), None, options)
self.assertEqual(result, 'Success!')
self.assertFalse(HttpHeaders.ScriptLogResults in self.client.last_response_headers)
def test_collection_indexing_policy_self_link(self):
self._test_collection_indexing_policy(False)
def test_collection_indexing_policy_name_based(self):
self._test_collection_indexing_policy(True)
def _test_collection_indexing_policy(self, is_name_based):
# create database
db = self.databseForTest
# create collection
collection = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based),
{ 'id': 'test_collection_indexing_policy default policy' + str(uuid.uuid4()) })
self.assertEqual(collection['indexingPolicy']['indexingMode'],
documents.IndexingMode.Consistent,
'default indexing mode should be consistent')
lazy_collection_definition = {
'id': 'test_collection_indexing_policy lazy collection ' + str(uuid.uuid4()),
'indexingPolicy': {
'indexingMode': documents.IndexingMode.Lazy
}
}
self.client.DeleteContainer(self.GetDocumentCollectionLink(db, collection, is_name_based))
lazy_collection = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based),
lazy_collection_definition)
self.assertEqual(lazy_collection['indexingPolicy']['indexingMode'],
documents.IndexingMode.Lazy,
'indexing mode should be lazy')
consistent_collection_definition = {
'id': 'test_collection_indexing_policy consistent collection ' + str(uuid.uuid4()),
'indexingPolicy': {
'indexingMode': documents.IndexingMode.Consistent
}
}
self.client.DeleteContainer(self.GetDocumentCollectionLink(db, lazy_collection, is_name_based))
consistent_collection = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based), consistent_collection_definition)
self.assertEqual(collection['indexingPolicy']['indexingMode'],
documents.IndexingMode.Consistent,
'indexing mode should be consistent')
collection_definition = {
'id': 'CollectionWithIndexingPolicy',
'indexingPolicy': {
'automatic': True,
'indexingMode': documents.IndexingMode.Lazy,
'includedPaths': [
{
'path': '/',
'indexes': [
{
'kind': documents.IndexKind.Hash,
'dataType': documents.DataType.Number,
'precision': 2
}
]
}
],
'excludedPaths': [
{
'path': '/"systemMetadata"/*'
}
]
}
}
self.client.DeleteContainer(self.GetDocumentCollectionLink(db, consistent_collection, is_name_based))
collection_with_indexing_policy = self.client.CreateContainer(self.GetDatabaseLink(db, is_name_based), collection_definition)
self.assertEqual(1,
len(collection_with_indexing_policy['indexingPolicy']['includedPaths']),
'Unexpected includedPaths length')
self.assertEqual(2,
len(collection_with_indexing_policy['indexingPolicy']['excludedPaths']),
'Unexpected excluded path count')
self.client.DeleteContainer(self.GetDocumentCollectionLink(db, collection_with_indexing_policy, is_name_based))
def test_create_default_indexing_policy_self_link(self):
self._test_create_default_indexing_policy(False)
def test_create_default_indexing_policy_name_based(self):
self._test_create_default_indexing_policy(True)
def _test_create_default_indexing_policy(self, is_name_based):
# create database
db = self.databseForTest
# no indexing policy specified
collection = self.client.CreateContainer(self.GetDatabaseLink(db, is_name_based),
{'id': 'test_create_default_indexing_policy TestCreateDefaultPolicy01' + str(uuid.uuid4())})
self._check_default_indexing_policy_paths(collection['indexingPolicy'])
self.client.DeleteContainer(collection['_self'])
# partial policy specified
collection = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based),
{
'id': 'test_create_default_indexing_policy TestCreateDefaultPolicy02' + str(uuid.uuid4()),
'indexingPolicy': {
'indexingMode': documents.IndexingMode.Lazy, 'automatic': True
}
})
self._check_default_indexing_policy_paths(collection['indexingPolicy'])
self.client.DeleteContainer(collection['_self'])
# default policy
collection = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based),
{
'id': 'test_create_default_indexing_policy TestCreateDefaultPolicy03' + str(uuid.uuid4()),
'indexingPolicy': { }
})
self._check_default_indexing_policy_paths(collection['indexingPolicy'])
self.client.DeleteContainer(collection['_self'])
# missing indexes
collection = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based),
{
'id': 'test_create_default_indexing_policy TestCreateDefaultPolicy04' + str(uuid.uuid4()),
'indexingPolicy': {
'includedPaths': [
{
'path': '/*'
}
]
}
})
self._check_default_indexing_policy_paths(collection['indexingPolicy'])
self.client.DeleteContainer(collection['_self'])
# missing precision
collection = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based),
{
'id': 'test_create_default_indexing_policy TestCreateDefaultPolicy05' + str(uuid.uuid4()),
'indexingPolicy': {
'includedPaths': [
{
'path': '/*',
'indexes': [
{
'kind': documents.IndexKind.Hash,
'dataType': documents.DataType.String
},
{
'kind': documents.IndexKind.Range,
'dataType': documents.DataType.Number
}
]
}
]
}
})
self._check_default_indexing_policy_paths(collection['indexingPolicy'])
self.client.DeleteContainer(collection['_self'])
def test_create_indexing_policy_with_composite_and_spatial_indexes_self_link(self):
self._test_create_indexing_policy_with_composite_and_spatial_indexes(False)
def test_create_indexing_policy_with_composite_and_spatial_indexes_name_based(self):
self._test_create_indexing_policy_with_composite_and_spatial_indexes(True)
def _test_create_indexing_policy_with_composite_and_spatial_indexes(self, is_name_based):
# create database
db = self.databseForTest
indexing_policy = {
"spatialIndexes": [
{
"path": "/path0/*",
"types": [
"Point",
"LineString",
"Polygon"
]
},
{
"path": "/path1/*",
"types": [
"LineString",
"Polygon",
"MultiPolygon"
]
}
],
"compositeIndexes": [
[
{
"path": "/path1",
"order": "ascending"
},
{
"path": "/path2",
"order": "descending"
},
{
"path": "/path3",
"order": "ascending"
}
],
[
{
"path": "/path4",
"order": "ascending"
},
{
"path": "/path5",
"order": "descending"
},
{
"path": "/path6",
"order": "ascending"
}
]
]
}
container_id = 'composite_index_spatial_index' + str(uuid.uuid4())
container_definition = {'id': container_id, 'indexingPolicy': indexing_policy}
created_container = self.client.CreateContainer(self.GetDatabaseLink(db, is_name_based), container_definition)
read_indexing_policy = created_container['indexingPolicy']
self.assertListEqual(indexing_policy['spatialIndexes'], read_indexing_policy['spatialIndexes'])
self.assertListEqual(indexing_policy['compositeIndexes'], read_indexing_policy['compositeIndexes'])
self.client.DeleteContainer(created_container['_self'])
def _check_default_indexing_policy_paths(self, indexing_policy):
def __get_first(array):
if array:
return array[0]
else:
return None
# '/_etag' is present in excluded paths by default
self.assertEqual(1, len(indexing_policy['excludedPaths']))
# included paths should be 1: '/'.
self.assertEqual(1, len(indexing_policy['includedPaths']))
root_included_path = __get_first([included_path for included_path in indexing_policy['includedPaths']
if included_path['path'] == '/*'])
self.assertEqual(0, len(root_included_path['indexes']))
print(root_included_path['indexes'])
def test_client_request_timeout(self):
connection_policy = documents.ConnectionPolicy()
# making timeout 0 ms to make sure it will throw
connection_policy.RequestTimeout = 0
with self.assertRaises(Exception):
# client does a getDatabaseAccount on initialization, which will time out
cosmos_client.CosmosClient(CRUDTests.host,
{'masterKey': CRUDTests.masterKey},
connection_policy)
def test_query_iterable_functionality(self):
def __CreateResources(client):
"""Creates resources for this test.
:Parameters:
- `client`: cosmos_client.CosmosClient
:Returns:
dict
"""
db = self.databseForTest
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
doc1 = client.CreateItem(
collection['_self'],
{ 'id': 'doc1', 'prop1': 'value1'})
doc2 = client.CreateItem(
collection['_self'],
{ 'id': 'doc2', 'prop1': 'value2'})
doc3 = client.CreateItem(
collection['_self'],
{ 'id': 'doc3', 'prop1': 'value3'})
resources = {
'coll': collection,
'doc1': doc1,
'doc2': doc2,
'doc3': doc3
}
return resources
# Validate QueryIterable by converting it to a list.
resources = __CreateResources(self.client)
results = self.client.ReadItems(resources['coll']['_self'],
{'maxItemCount':2})
docs = list(iter(results))
self.assertEqual(3,
len(docs),
'QueryIterable should return all documents' +
' using continuation')
self.assertEqual(resources['doc1']['id'], docs[0]['id'])
self.assertEqual(resources['doc2']['id'], docs[1]['id'])
self.assertEqual(resources['doc3']['id'], docs[2]['id'])
# Validate QueryIterable iterator with 'for'.
counter = 0
# test QueryIterable with 'for'.
for doc in iter(results):
counter += 1
if counter == 1:
self.assertEqual(resources['doc1']['id'],
doc['id'],
'first document should be doc1')
elif counter == 2:
self.assertEqual(resources['doc2']['id'],
doc['id'],
'second document should be doc2')
elif counter == 3:
self.assertEqual(resources['doc3']['id'],
doc['id'],
'third document should be doc3')
self.assertEqual(counter, 3)
# Get query results page by page.
results = self.client.ReadItems(resources['coll']['_self'],
{'maxItemCount':2})
first_block = results.fetch_next_block()
self.assertEqual(2,
len(first_block),
'First block should have 2 entries.')
self.assertEqual(resources['doc1']['id'], first_block[0]['id'])
self.assertEqual(resources['doc2']['id'], first_block[1]['id'])
self.assertEqual(1,
len(results.fetch_next_block()),
'Second block should have 1 entry.')
self.assertEqual(0,
len(results.fetch_next_block()),
'Then its empty.')
def test_trigger_functionality_self_link(self):
self._test_trigger_functionality(False)
def test_trigger_functionality_name_based(self):
self._test_trigger_functionality(True)
def _test_trigger_functionality(self, is_name_based):
triggers_in_collection1 = [
{
'id': 't1',
'body': (
'function() {' +
' var item = getContext().getRequest().getBody();' +
' item.id = item.id.toUpperCase() + \'t1\';' +
' getContext().getRequest().setBody(item);' +
'}'),
'triggerType': documents.TriggerType.Pre,
'triggerOperation': documents.TriggerOperation.All
},
{
'id': 'response1',
'body': (
'function() {' +
' var prebody = getContext().getRequest().getBody();' +
' if (prebody.id != \'TESTING POST TRIGGERt1\')'
' throw \'id mismatch\';' +
' var postbody = getContext().getResponse().getBody();' +
' if (postbody.id != \'TESTING POST TRIGGERt1\')'
' throw \'id mismatch\';'
'}'),
'triggerType': documents.TriggerType.Post,
'triggerOperation': documents.TriggerOperation.All
},
{
'id': 'response2',
# can't be used because setValue is currently disabled
'body': (
'function() {' +
' var predoc = getContext().getRequest().getBody();' +
' var postdoc = getContext().getResponse().getBody();' +
' getContext().getResponse().setValue(' +
' \'predocname\', predoc.id + \'response2\');' +
' getContext().getResponse().setValue(' +
' \'postdocname\', postdoc.id + \'response2\');' +
'}'),
'triggerType': documents.TriggerType.Post,
'triggerOperation': documents.TriggerOperation.All,
}]
triggers_in_collection2 = [
{
'id': "t2",
'body': "function() { }", # trigger already stringified
'triggerType': documents.TriggerType.Pre,
'triggerOperation': documents.TriggerOperation.All
},
{
'id': "t3",
'body': (
'function() {' +
' var item = getContext().getRequest().getBody();' +
' item.id = item.id.toLowerCase() + \'t3\';' +
' getContext().getRequest().setBody(item);' +
'}'),
'triggerType': documents.TriggerType.Pre,
'triggerOperation': documents.TriggerOperation.All
}]
triggers_in_collection3 = [
{
'id': 'triggerOpType',
'body': 'function() { }',
'triggerType': documents.TriggerType.Post,
'triggerOperation': documents.TriggerOperation.Delete,
}]
def __CreateTriggers(client, database, collection, triggers, is_name_based):
"""Creates triggers.
:Parameters:
- `client`: cosmos_client.CosmosClient
- `collection`: dict
"""
for trigger_i in triggers:
trigger = client.CreateTrigger(self.GetDocumentCollectionLink(database, collection, is_name_based),
trigger_i)
for property in trigger_i:
self.assertEqual(
trigger[property],
trigger_i[property],
'property {property} should match'.format(property=property))
# create database
db = self.databseForTest
# create collections
collection1 = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based), { 'id': 'test_trigger_functionality 1 ' + str(uuid.uuid4()) })
collection2 = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based), { 'id': 'test_trigger_functionality 2 ' + str(uuid.uuid4()) })
collection3 = self.client.CreateContainer(
self.GetDatabaseLink(db, is_name_based), { 'id': 'test_trigger_functionality 3 ' + str(uuid.uuid4()) })
# create triggers
__CreateTriggers(self.client, db, collection1, triggers_in_collection1, is_name_based)
__CreateTriggers(self.client, db, collection2, triggers_in_collection2, is_name_based)
__CreateTriggers(self.client, db, collection3, triggers_in_collection3, is_name_based)
# create document
triggers_1 = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection1, is_name_based)))
self.assertEqual(len(triggers_1), 3)
document_1_1 = self.client.CreateItem(self.GetDocumentCollectionLink(db, collection1, is_name_based),
{ 'id': 'doc1',
'key': 'value' },
{ 'preTriggerInclude': 't1' })
self.assertEqual(document_1_1['id'],
'DOC1t1',
'id should be capitalized')
document_1_2 = self.client.CreateItem(
self.GetDocumentCollectionLink(db, collection1, is_name_based),
{ 'id': 'testing post trigger' },
{ 'postTriggerInclude': 'response1',
'preTriggerInclude': 't1' })
self.assertEqual(document_1_2['id'], 'TESTING POST TRIGGERt1')
document_1_3 = self.client.CreateItem(self.GetDocumentCollectionLink(db, collection1, is_name_based),
{ 'id': 'responseheaders' },
{ 'preTriggerInclude': 't1' })
self.assertEqual(document_1_3['id'], "RESPONSEHEADERSt1")
triggers_2 = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection2, is_name_based)))
self.assertEqual(len(triggers_2), 2)
document_2_1 = self.client.CreateItem(self.GetDocumentCollectionLink(db, collection2, is_name_based),
{ 'id': 'doc2',
'key2': 'value2' },
{ 'preTriggerInclude': 't2' })
self.assertEqual(document_2_1['id'],
'doc2',
'id shouldn\'t change')
document_2_2 = self.client.CreateItem(self.GetDocumentCollectionLink(db, collection2, is_name_based),
{ 'id': 'Doc3',
'prop': 'empty' },
{ 'preTriggerInclude': 't3' })
self.assertEqual(document_2_2['id'], 'doc3t3')
triggers_3 = list(self.client.ReadTriggers(self.GetDocumentCollectionLink(db, collection3, is_name_based)))
self.assertEqual(len(triggers_3), 1)
with self.assertRaises(Exception):
self.client.CreateItem(self.GetDocumentCollectionLink(db, collection3, is_name_based),
{ 'id': 'Docoptype' },
{ 'postTriggerInclude': 'triggerOpType' })
self.client.DeleteContainer(collection1['_self'])
self.client.DeleteContainer(collection2['_self'])
self.client.DeleteContainer(collection3['_self'])
def test_stored_procedure_functionality_self_link(self):
self._test_stored_procedure_functionality(False)
def test_stored_procedure_functionality_name_based(self):
self._test_stored_procedure_functionality(True)
def _test_stored_procedure_functionality(self, is_name_based):
# create database
db = self.databseForTest
# create collection
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
sproc1 = {
'id': 'storedProcedure1' + str(uuid.uuid4()),
'body': (
'function () {' +
' for (var i = 0; i < 1000; i++) {' +
' var item = getContext().getResponse().getBody();' +
' if (i > 0 && item != i - 1) throw \'body mismatch\';' +
' getContext().getResponse().setBody(i);' +
' }' +
'}')
}
retrieved_sproc = self.client.CreateStoredProcedure(self.GetDocumentCollectionLink(db, collection, is_name_based),
sproc1)
result = self.client.ExecuteStoredProcedure(self.GetStoredProcedureLink(db, collection, retrieved_sproc, is_name_based),
None)
self.assertEqual(result, 999)
sproc2 = {
'id': 'storedProcedure2' + str(uuid.uuid4()),
'body': (
'function () {' +
' for (var i = 0; i < 10; i++) {' +
' getContext().getResponse().appendValue(\'Body\', i);' +
' }' +
'}')
}
retrieved_sproc2 = self.client.CreateStoredProcedure(self.GetDocumentCollectionLink(db, collection, is_name_based),
sproc2)
result = self.client.ExecuteStoredProcedure(self.GetStoredProcedureLink(db, collection, retrieved_sproc2, is_name_based),
None)
self.assertEqual(int(result), 123456789)
sproc3 = {
'id': 'storedProcedure3' + str(uuid.uuid4()),
'body': (
'function (input) {' +
' getContext().getResponse().setBody(' +
' \'a\' + input.temp);' +
'}')
}
retrieved_sproc3 = self.client.CreateStoredProcedure(self.GetDocumentCollectionLink(db, collection, is_name_based),
sproc3)
result = self.client.ExecuteStoredProcedure(self.GetStoredProcedureLink(db, collection, retrieved_sproc3, is_name_based),
{'temp': 'so'})
self.assertEqual(result, 'aso')
def __ValidateOfferResponseBody(self, offer, expected_coll_link, expected_offer_type):
self.assert_(offer.get('id'), 'Id cannot be null.')
self.assert_(offer.get('_rid'), 'Resource Id (Rid) cannot be null.')
self.assert_(offer.get('_self'), 'Self Link cannot be null.')
self.assert_(offer.get('resource'), 'Resource Link cannot be null.')
self.assertTrue(offer['_self'].find(offer['id']) != -1,
'Offer id not contained in offer self link.')
self.assertEqual(expected_coll_link.strip('/'), offer['resource'].strip('/'))
if (expected_offer_type):
self.assertEqual(expected_offer_type, offer.get('offerType'))
def test_offer_read_and_query(self):
# Create database.
db = self.databseForTest
offers = list(self.client.ReadOffers())
initial_count = len(offers)
# Create collection.
collection = self.client.CreateContainer(db['_self'], { 'id': 'test_offer_read_and_query ' + str(uuid.uuid4()) })
offers = list(self.client.ReadOffers())
self.assertEqual(initial_count+1, len(offers))
offers = self.GetCollectionOffers(self.client, collection['_rid'])
self.assertEqual(1, len(offers))
expected_offer = offers[0]
self.__ValidateOfferResponseBody(expected_offer, collection.get('_self'), None)
# Read the offer.
read_offer = self.client.ReadOffer(expected_offer.get('_self'))
self.__ValidateOfferResponseBody(read_offer, collection.get('_self'), expected_offer.get('offerType'))
# Check if the read resource is what we expected.
self.assertEqual(expected_offer.get('id'), read_offer.get('id'))
self.assertEqual(expected_offer.get('_rid'), read_offer.get('_rid'))
self.assertEqual(expected_offer.get('_self'), read_offer.get('_self'))
self.assertEqual(expected_offer.get('resource'), read_offer.get('resource'))
# Query for the offer.
offers = list(self.client.QueryOffers(
{
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name': '@id', 'value': expected_offer['id']}
]
}))
self.assertEqual(1, len(offers))
query_one_offer = offers[0]
self.__ValidateOfferResponseBody(query_one_offer, collection.get('_self'), expected_offer.get('offerType'))
# Check if the query result is what we expected.
self.assertEqual(expected_offer.get('id'), query_one_offer.get('id'))
self.assertEqual(expected_offer.get('_rid'), query_one_offer.get('_rid'))
self.assertEqual(expected_offer.get('_self'), query_one_offer.get('_self'))
self.assertEqual(expected_offer.get('resource'), query_one_offer.get('resource'))
# Expects an exception when reading offer with bad offer link.
self.__AssertHTTPFailureWithStatus(StatusCodes.BAD_REQUEST, self.client.ReadOffer, expected_offer.get('_self')[:-1] + 'x')
# Now delete the collection.
self.client.DeleteContainer(collection.get('_self'))
# Reading fails.
self.__AssertHTTPFailureWithStatus(StatusCodes.NOT_FOUND, self.client.ReadOffer, expected_offer.get('_self'))
# Read feed now returns 0 results.
offers = list(self.client.ReadOffers())
self.assertEqual(initial_count, len(offers))
def test_offer_replace(self):
# Create database.
db = self.databseForTest
# Create collection.
collection = self.configs.create_single_partition_collection_if_not_exist(self.client)
offers = self.GetCollectionOffers(self.client, collection['_rid'])
self.assertEqual(1, len(offers))
expected_offer = offers[0]
self.__ValidateOfferResponseBody(expected_offer, collection.get('_self'), None)
# Replace the offer.
offer_to_replace = dict(expected_offer)
offer_to_replace['content']['offerThroughput'] += 100
replaced_offer = self.client.ReplaceOffer(offer_to_replace['_self'], offer_to_replace)
self.__ValidateOfferResponseBody(replaced_offer, collection.get('_self'), None)
# Check if the replaced offer is what we expect.
self.assertEqual(offer_to_replace.get('id'), replaced_offer.get('id'))
self.assertEqual(offer_to_replace.get('_rid'), replaced_offer.get('_rid'))
self.assertEqual(offer_to_replace.get('_self'), replaced_offer.get('_self'))
self.assertEqual(offer_to_replace.get('resource'), replaced_offer.get('resource'))
self.assertEqual(offer_to_replace.get('content').get('offerThroughput'), replaced_offer.get('content').get('offerThroughput'))
# Expects an exception when replacing an offer with bad id.
offer_to_replace_bad_id = dict(offer_to_replace)
offer_to_replace_bad_id['_rid'] = 'NotAllowed'
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST, self.client.ReplaceOffer, offer_to_replace_bad_id['_self'], offer_to_replace_bad_id)
# Expects an exception when replacing an offer with bad rid.
offer_to_replace_bad_rid = dict(offer_to_replace)
offer_to_replace_bad_rid['_rid'] = 'InvalidRid'
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST, self.client.ReplaceOffer, offer_to_replace_bad_rid['_self'], offer_to_replace_bad_rid)
# Expects an exception when replaceing an offer with null id and rid.
offer_to_replace_null_ids = dict(offer_to_replace)
offer_to_replace_null_ids['id'] = None
offer_to_replace_null_ids['_rid'] = None
self.__AssertHTTPFailureWithStatus(
StatusCodes.BAD_REQUEST, self.client.ReplaceOffer, offer_to_replace_null_ids['_self'], offer_to_replace_null_ids)
def test_collection_with_offer_type(self):
# create database
created_db = self.databseForTest
# create a collection
offers = list(self.client.ReadOffers())
before_offers_count = len(offers)
collection_definition = { 'id': 'test_collection_with_offer_type ' + str(uuid.uuid4()) }
collection = self.client.CreateContainer(created_db['_self'],
collection_definition,
{
'offerType': 'S2'
})
offers = list(self.client.ReadOffers())
self.assertEqual(before_offers_count + 1, len(offers))
offers = self.GetCollectionOffers(self.client, collection['_rid'])
self.assertEqual(1, len(offers))
expected_offer = offers[0]
# We should have an offer of type S2.
self.__ValidateOfferResponseBody(expected_offer, collection.get('_self'), 'S2')
self.client.DeleteContainer(collection['_self'])
def test_database_account_functionality(self):
# Validate database account functionality.
database_account = self.client.GetDatabaseAccount()
self.assertEqual(database_account.DatabasesLink, '/dbs/')
self.assertEqual(database_account.MediaLink, '/media/')
if (HttpHeaders.MaxMediaStorageUsageInMB in
self.client.last_response_headers):
self.assertEqual(
database_account.MaxMediaStorageUsageInMB,
self.client.last_response_headers[
HttpHeaders.MaxMediaStorageUsageInMB])
if (HttpHeaders.CurrentMediaStorageUsageInMB in
self.client.last_response_headers):
self.assertEqual(
database_account.CurrentMediaStorageUsageInMB,
self.client.last_response_headers[
HttpHeaders.
CurrentMediaStorageUsageInMB])
self.assertTrue(
database_account.ConsistencyPolicy['defaultConsistencyLevel']
!= None)
def test_index_progress_headers_self_link(self):
self._test_index_progress_headers(False)
def test_index_progress_headers_name_based(self):
self._test_index_progress_headers(True)
def _test_index_progress_headers(self, is_name_based):
created_db = self.databseForTest
consistent_coll = self.client.CreateContainer(self.GetDatabaseLink(created_db, is_name_based), { 'id': 'test_index_progress_headers consistent_coll ' + str(uuid.uuid4()) })
self.client.ReadContainer(self.GetDocumentCollectionLink(created_db, consistent_coll, is_name_based))
self.assertFalse(HttpHeaders.LazyIndexingProgress in self.client.last_response_headers)
self.assertTrue(HttpHeaders.IndexTransformationProgress in self.client.last_response_headers)
lazy_coll = self.client.CreateContainer(self.GetDatabaseLink(created_db, is_name_based),
{
'id': 'test_index_progress_headers lazy_coll ' + str(uuid.uuid4()),
'indexingPolicy': { 'indexingMode' : documents.IndexingMode.Lazy }
})
self.client.ReadContainer(self.GetDocumentCollectionLink(created_db, lazy_coll, is_name_based))
self.assertTrue(HttpHeaders.LazyIndexingProgress in self.client.last_response_headers)
self.assertTrue(HttpHeaders.IndexTransformationProgress in self.client.last_response_headers)
none_coll = self.client.CreateContainer(self.GetDatabaseLink(created_db, is_name_based),
{
'id': 'test_index_progress_headers none_coll ' + str(uuid.uuid4()),
'indexingPolicy': { 'indexingMode': documents.IndexingMode.NoIndex, 'automatic': False }
})
self.client.ReadContainer(self.GetDocumentCollectionLink(created_db, none_coll, is_name_based))
self.assertFalse(HttpHeaders.LazyIndexingProgress in self.client.last_response_headers)
self.assertTrue(HttpHeaders.IndexTransformationProgress in self.client.last_response_headers)
self.client.DeleteContainer(consistent_coll['_self'])
self.client.DeleteContainer(lazy_coll['_self'])
self.client.DeleteContainer(none_coll['_self'])
# To run this test, please provide your own CA certs file or download one from
# http://curl.haxx.se/docs/caextract.html
#
# def test_ssl_connection(self):
# connection_policy = documents.ConnectionPolicy()
# connection_policy.SSLConfiguration = documents.SSLConfiguration()
# connection_policy.SSLConfiguration.SSLCaCerts = './cacert.pem'
# client = cosmos_client.CosmosClient(CRUDTests.host, {'masterKey': CRUDTests.masterKey}, connection_policy)
# # Read databases after creation.
# databases = list(client.ReadDatabases())
def test_id_validation(self):
# Id shouldn't end with space.
database_definition = { 'id': 'id_with_space ' }
try:
self.client.CreateDatabase(database_definition)
self.assertFalse(True)
except ValueError as e:
self.assertEqual('Id ends with a space.', e.args[0])
# Id shouldn't contain '/'.
database_definition = { 'id': 'id_with_illegal/_char' }
try:
self.client.CreateDatabase(database_definition)
self.assertFalse(True)
except ValueError as e:
self.assertEqual('Id contains illegal chars.', e.args[0])
# Id shouldn't contain '\\'.
database_definition = { 'id': 'id_with_illegal\\_char' }
try:
self.client.CreateDatabase(database_definition)
self.assertFalse(True)
except ValueError as e:
self.assertEqual('Id contains illegal chars.', e.args[0])
# Id shouldn't contain '?'.
database_definition = { 'id': 'id_with_illegal?_char' }
try:
self.client.CreateDatabase(database_definition)
self.assertFalse(True)
except ValueError as e:
self.assertEqual('Id contains illegal chars.', e.args[0])
# Id shouldn't contain '#'.
database_definition = { 'id': 'id_with_illegal#_char' }
try:
self.client.CreateDatabase(database_definition)
self.assertFalse(True)
except ValueError as e:
self.assertEqual('Id contains illegal chars.', e.args[0])
# Id can begin with space
database_definition = { 'id': ' id_begin_space' }
db = self.client.CreateDatabase(database_definition)
self.assertTrue(True)
self.client.DeleteDatabase(db['_self'])
def test_id_case_validation(self):
# create database
created_db = self.databseForTest
uuid_string = str(uuid.uuid4())
# pascalCase
collection_definition1 = { 'id': 'sampleCollection ' + uuid_string }
# CamelCase
collection_definition2 = { 'id': 'SampleCollection ' + uuid_string }
# Verify that no collections exist
collections = list(self.client.ReadContainers(self.GetDatabaseLink(created_db, True)))
number_of_existing_collections = len(collections)
# create 2 collections with different casing of IDs
created_collection1 = self.client.CreateContainer(self.GetDatabaseLink(created_db, True),
collection_definition1)
created_collection2 = self.client.CreateContainer(self.GetDatabaseLink(created_db, True),
collection_definition2)
collections = list(self.client.ReadContainers(self.GetDatabaseLink(created_db, True)))
# verify if a total of 2 collections got created
self.assertEqual(len(collections), number_of_existing_collections + 2)
# verify that collections are created with specified IDs
self.assertEqual(collection_definition1['id'], created_collection1['id'])
self.assertEqual(collection_definition2['id'], created_collection2['id'])
self.client.DeleteContainer(created_collection1['_self'])
self.client.DeleteContainer(created_collection2['_self'])
def test_id_unicode_validation(self):
# create database
created_db = self.databseForTest
# unicode chars in Hindi for Id which translates to: "Hindi is the national language of India"
collection_definition1 = { 'id': u'हिन्दी भारत की राष्ट्रीय भाषा है' }
# Special chars for Id
collection_definition2 = { 'id': "!@$%^&*()-~`'_[]{}|;:,.<>" }
# verify that collections are created with specified IDs
created_collection1 = self.client.CreateContainer(self.GetDatabaseLink(created_db, True),
collection_definition1)
created_collection2 = self.client.CreateContainer(self.GetDatabaseLink(created_db, True),
collection_definition2)
self.assertEqual(collection_definition1['id'], created_collection1['id'])
self.assertEqual(collection_definition2['id'], created_collection2['id'])
self.client.DeleteContainer(created_collection1['_self'])
self.client.DeleteContainer(created_collection2['_self'])
def GetDatabaseLink(self, database, is_name_based=True):
if is_name_based:
return 'dbs/' + database['id']
else:
return database['_self']
def GetUserLink(self, database, user, is_name_based=True):
if is_name_based:
return self.GetDatabaseLink(database) + '/users/' + user['id']
else:
return user['_self']
def GetPermissionLink(self, database, user, permission, is_name_based=True):
if is_name_based:
return self.GetUserLink(database, user) + '/permissions/' + permission['id']
else:
return permission['_self']
def GetDocumentCollectionLink(self, database, document_collection, is_name_based=True):
if is_name_based:
return self.GetDatabaseLink(database) + '/colls/' + document_collection['id']
else:
return document_collection['_self']
def GetDocumentLink(self, database, document_collection, document, is_name_based=True):
if is_name_based:
return self.GetDocumentCollectionLink(database, document_collection) + '/docs/' + document['id']
else:
return document['_self']
def GetAttachmentLink(self, database, document_collection, document, attachment, is_name_based=True):
if is_name_based:
return self.GetDocumentLink(database, document_collection, document) + '/attachments/' + attachment['id']
else:
return attachment['_self']
def GetTriggerLink(self, database, document_collection, trigger, is_name_based=True):
if is_name_based:
return self.GetDocumentCollectionLink(database, document_collection) + '/triggers/' + trigger['id']
else:
return trigger['_self']
def GetUserDefinedFunctionLink(self, database, document_collection, user_defined_function, is_name_based=True):
if is_name_based:
return self.GetDocumentCollectionLink(database, document_collection) + '/udfs/' + user_defined_function['id']
else:
return user_defined_function['_self']
def GetStoredProcedureLink(self, database, document_collection, stored_procedure, is_name_based=True):
if is_name_based:
return self.GetDocumentCollectionLink(database, document_collection) + '/sprocs/' + stored_procedure['id']
else:
return stored_procedure['_self']
def GetConflictLink(self, database, document_collection, conflict, is_name_based=True):
if is_name_based:
return self.GetDocumentCollectionLink(database, document_collection) + '/conflicts/' + conflict['id']
else:
return conflict['_self']
def GetCollectionOffers(self, client, collection_rid):
return list(client.QueryOffers(
{
'query': 'SELECT * FROM root r WHERE r.offerResourceId=@offerResourceId',
'parameters': [
{ 'name': '@offerResourceId', 'value': collection_rid}
]
}))
if __name__ == '__main__':
try:
unittest.main()
except SystemExit as inst:
if inst.args[0] is True: # raised by sys.exit(True) when tests failed
raise
|