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
|
"""blocking adapter test"""
from datetime import datetime
import functools
import logging
import socket
import threading
import unittest
import uuid
import pika
from pika.adapters import blocking_connection
from pika.compat import as_bytes, time_now
import pika.connection
import pika.exceptions
from pika.exchange_type import ExchangeType
from tests.misc.forward_server import ForwardServer
from tests.misc.test_utils import retry_assertion
# too-many-lines
# pylint: disable=C0302
# Disable warning about access to protected member
# pylint: disable=W0212
# Disable warning Attribute defined outside __init__
# pylint: disable=W0201
# Disable warning Missing docstring
# pylint: disable=C0111
# Disable warning Too many public methods
# pylint: disable=R0904
# Disable warning Invalid variable name
# pylint: disable=C0103
LOGGER = logging.getLogger(__name__)
PARAMS_URL_TEMPLATE = (
'amqp://guest:guest@127.0.0.1:%(port)s/%%2f?socket_timeout=1')
DEFAULT_URL = PARAMS_URL_TEMPLATE % {'port': 5672}
DEFAULT_PARAMS = pika.URLParameters(DEFAULT_URL)
DEFAULT_TIMEOUT = 15
def setUpModule():
logging.basicConfig(level=logging.DEBUG)
class BlockingTestCaseBase(unittest.TestCase):
TIMEOUT = DEFAULT_TIMEOUT
def _connect(self,
url=DEFAULT_URL,
connection_class=pika.BlockingConnection,
impl_class=None):
parameters = pika.URLParameters(url)
return self._connect_params(parameters,
connection_class,
impl_class)
def _connect_params(self,
parameters,
connection_class=pika.BlockingConnection,
impl_class=None):
connection = connection_class(parameters, _impl_class=impl_class)
self.addCleanup(lambda: connection.close()
if connection.is_open else None)
# We use impl's timer directly in order to get a callback regardless
# of BlockingConnection's event dispatch modality
connection._impl._adapter_call_later(self.TIMEOUT, # pylint: disable=E1101
self._on_test_timeout)
# Patch calls into I/O loop to fail test if exceptions are
# leaked back through SelectConnection or the I/O loop.
self._instrument_io_loop_exception_leak_detection(connection)
return connection
def _instrument_io_loop_exception_leak_detection(self, connection):
"""Instrument the given connection to detect and fail test when
an exception is leaked through the I/O loop
NOTE: BlockingConnection's underlying asynchronous connection adapter
(SelectConnection) uses callbacks to communicate with its user (
BlockingConnection in this case). If BlockingConnection leaks
exceptions back into the I/O loop or the asynchronous connection
adapter, we interrupt their normal workflow and introduce a high
likelihood of state inconsistency.
"""
# Patch calls into I/O loop to fail test if exceptions are
# leaked back through SelectConnection or the I/O loop.
real_poll = connection._impl.ioloop.poll
def my_poll(*args, **kwargs):
try:
return real_poll(*args, **kwargs)
except BaseException as exc:
self.fail('Unwanted exception leaked into asynchronous layer '
'via ioloop.poll(): {!r}'.format(exc))
connection._impl.ioloop.poll = my_poll
self.addCleanup(setattr, connection._impl.ioloop, 'poll', real_poll)
real_process_timeouts = connection._impl.ioloop.process_timeouts
def my_process_timeouts(*args, **kwargs):
try:
return real_process_timeouts(*args, **kwargs)
except AssertionError:
# Our test timeout logic and unit test assert* routines rely
# on being able to pass AssertionError
raise
except BaseException as exc:
self.fail('Unwanted exception leaked into asynchronous layer '
'via ioloop.process_timeouts(): {!r}'.format(exc))
connection._impl.ioloop.process_timeouts = my_process_timeouts
self.addCleanup(setattr, connection._impl.ioloop, 'process_timeouts',
real_process_timeouts)
def _on_test_timeout(self):
"""Called when test times out"""
LOGGER.info('%s TIMED OUT (%s)', datetime.utcnow(), self)
self.fail('Test timed out')
@retry_assertion(TIMEOUT/2)
def _assert_exact_message_count_with_retries(self,
channel,
queue,
expected_count):
frame = channel.queue_declare(queue, passive=True)
self.assertEqual(frame.method.message_count, expected_count)
class TestCreateAndCloseConnection(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: Create and close connection"""
connection = self._connect()
self.assertIsInstance(connection, pika.BlockingConnection)
self.assertTrue(connection.is_open)
self.assertFalse(connection.is_closed)
self.assertFalse(connection._impl.is_closing)
connection.close()
self.assertTrue(connection.is_closed)
self.assertFalse(connection.is_open)
self.assertFalse(connection._impl.is_closing)
class TestCreateConnectionWithNoneSocketAndStackTimeouts(BlockingTestCaseBase):
def test(self):
""" BlockingConnection: create a connection with socket and stack timeouts both None
"""
params = pika.URLParameters(DEFAULT_URL)
params.socket_timeout = None
params.stack_timeout = None
with self._connect_params(params) as connection:
self.assertTrue(connection.is_open)
class TestCreateConnectionFromTwoConfigsFirstUnreachable(BlockingTestCaseBase):
def test(self):
""" BlockingConnection: create a connection from two configs, first unreachable
"""
# Reserve a port for use in connect
sock = socket.socket()
self.addCleanup(sock.close)
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
sock.close()
bad_params = pika.URLParameters(PARAMS_URL_TEMPLATE % {"port": port})
good_params = pika.URLParameters(DEFAULT_URL)
with self._connect_params([bad_params, good_params]) as connection:
self.assertNotEqual(connection._impl.params.port, bad_params.port)
self.assertEqual(connection._impl.params.port, good_params.port)
class TestCreateConnectionFromTwoUnreachableConfigs(BlockingTestCaseBase):
def test(self):
""" BlockingConnection: creating a connection from two unreachable \
configs raises AMQPConnectionError
"""
# Reserve a port for use in connect
sock = socket.socket()
self.addCleanup(sock.close)
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
sock.close()
bad_params = pika.URLParameters(PARAMS_URL_TEMPLATE % {"port": port})
with self.assertRaises(pika.exceptions.AMQPConnectionError):
self._connect_params([bad_params, bad_params])
class TestMultiCloseConnectionRaisesWrongState(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: Close connection twice raises ConnectionWrongStateError"""
connection = self._connect()
self.assertIsInstance(connection, pika.BlockingConnection)
self.assertTrue(connection.is_open)
self.assertFalse(connection.is_closed)
self.assertFalse(connection._impl.is_closing)
connection.close()
self.assertTrue(connection.is_closed)
self.assertFalse(connection.is_open)
self.assertFalse(connection._impl.is_closing)
with self.assertRaises(pika.exceptions.ConnectionWrongStateError):
connection.close()
class TestConnectionContextManagerClosesConnection(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: connection context manager closes connection"""
with self._connect() as connection:
self.assertIsInstance(connection, pika.BlockingConnection)
self.assertTrue(connection.is_open)
self.assertTrue(connection.is_closed)
class TestConnectionContextManagerExitSurvivesClosedConnection(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: connection context manager exit survives closed connection"""
with self._connect() as connection:
self.assertTrue(connection.is_open)
connection.close()
self.assertTrue(connection.is_closed)
self.assertTrue(connection.is_closed)
class TestConnectionContextManagerClosesConnectionAndPassesOriginalException(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: connection context manager closes connection and passes original exception""" # pylint: disable=C0301
class MyException(Exception):
pass
with self.assertRaises(MyException):
with self._connect() as connection:
self.assertTrue(connection.is_open)
raise MyException()
self.assertTrue(connection.is_closed)
class TestConnectionContextManagerClosesConnectionAndPassesSystemException(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: connection context manager closes connection and passes system exception""" # pylint: disable=C0301
with self.assertRaises(SystemExit):
with self._connect() as connection:
self.assertTrue(connection.is_open)
raise SystemExit()
self.assertTrue(connection.is_closed)
class TestLostConnectionResultsInIsClosedConnectionAndChannel(BlockingTestCaseBase):
def test(self):
connection = self._connect()
channel = connection.channel()
# Simulate the server dropping the socket connection
connection._impl._transport._sock.shutdown(socket.SHUT_RDWR)
with self.assertRaises(pika.exceptions.StreamLostError):
# Changing QoS should result in ConnectionClosed
channel.basic_qos()
# Now check is_open/is_closed on channel and connection
self.assertFalse(channel.is_open)
self.assertTrue(channel.is_closed)
self.assertFalse(connection.is_open)
self.assertTrue(connection.is_closed)
class TestUpdateSecret(BlockingTestCaseBase):
def test(self):
connection = self._connect()
channel = connection.channel()
# Update secret
connection.update_secret("new_secret", "reason")
# Now check is_open/is_closed on channel and connection
self.assertTrue(channel.is_open)
self.assertFalse(channel.is_closed)
self.assertTrue(connection.is_open)
self.assertFalse(connection.is_closed)
class TestUpdateSecretOnClosedRaisesWrongState(BlockingTestCaseBase):
def test(self):
connection = self._connect()
# Close Connection
connection.close()
# Attempt to update secret
with self.assertRaises(pika.exceptions.ConnectionWrongStateError):
connection.update_secret("new_secret", "reason")
# Now check is_open/is_closed on channel and connection
self.assertFalse(connection.is_open)
self.assertTrue(connection.is_closed)
class TestUpdateSecretExpectsStrings(BlockingTestCaseBase):
def test(self):
connection = self._connect()
# Attempt to update secret with integer as new_secret
with self.assertRaises(AssertionError):
connection.update_secret(1, "reason")
# Attempt to update secret with integer as reason
with self.assertRaises(AssertionError):
connection.update_secret("new_secret", 1)
class TestInvalidExchangeTypeRaisesConnectionClosed(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: ConnectionClosed raised when creating exchange with invalid type""" # pylint: disable=C0301
# This test exploits behavior specific to RabbitMQ whereby the broker
# closes the connection if an attempt is made to declare an exchange
# with an invalid exchange type
connection = self._connect()
ch = connection.channel()
exg_name = ("TestInvalidExchangeTypeRaisesConnectionClosed_" +
uuid.uuid1().hex)
with self.assertRaises(pika.exceptions.ConnectionClosed) as ex_cm:
# Attempt to create an exchange with invalid exchange type
ch.exchange_declare(exg_name, exchange_type='ZZwwInvalid')
self.assertEqual(ex_cm.exception.args[0], 503)
class TestCreateAndCloseConnectionWithChannelAndConsumer(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: Create and close connection with channel and consumer""" # pylint: disable=C0301
connection = self._connect()
ch = connection.channel()
q_name = (
'TestCreateAndCloseConnectionWithChannelAndConsumer_q' +
uuid.uuid1().hex)
body1 = 'a' * 1024
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Publish the message to the queue by way of default exchange
ch.basic_publish(exchange='', routing_key=q_name, body=body1)
# Create a consumer that uses automatic ack mode
ch.basic_consume(q_name, lambda *x: None, auto_ack=True,
exclusive=False, arguments=None)
connection.close()
self.assertTrue(connection.is_closed)
self.assertFalse(connection.is_open)
self.assertFalse(connection._impl.is_closing)
self.assertFalse(connection._impl._channels)
self.assertFalse(ch._consumer_infos)
self.assertFalse(ch._impl._consumers)
class TestUsingInvalidQueueArgument(BlockingTestCaseBase):
def test(self):
"""BlockingConnection raises expected exception when invalid queue parameter is used
"""
connection = self._connect()
ch = connection.channel()
with self.assertRaises(TypeError):
ch.queue_declare(queue=[1, 2, 3])
class TestSuddenBrokerDisconnectBeforeChannel(BlockingTestCaseBase):
def test(self):
"""BlockingConnection resets properly on TCP/IP drop during channel()
"""
with ForwardServer(remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0)) as fwd:
self.connection = self._connect(
PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]})
# Once outside the context, the connection is broken
# BlockingConnection should raise ConnectionClosed
with self.assertRaises(pika.exceptions.StreamLostError):
self.connection.channel()
self.assertTrue(self.connection.is_closed)
self.assertFalse(self.connection.is_open)
self.assertIsNone(self.connection._impl._transport)
class TestNoAccessToConnectionAfterConnectionLost(BlockingTestCaseBase):
def test(self):
"""BlockingConnection no access file descriptor after StreamLostError
"""
with ForwardServer(remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0)) as fwd:
self.connection = self._connect(
PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]})
# Once outside the context, the connection is broken
# BlockingConnection should raise ConnectionClosed
with self.assertRaises(pika.exceptions.StreamLostError):
self.connection.channel()
self.assertTrue(self.connection.is_closed)
self.assertFalse(self.connection.is_open)
self.assertIsNone(self.connection._impl._transport)
# Attempt to operate on the connection once again after ConnectionClosed
with self.assertRaises(pika.exceptions.ConnectionWrongStateError):
self.connection.channel()
class TestConnectWithDownedBroker(BlockingTestCaseBase):
def test(self):
""" BlockingConnection to downed broker results in AMQPConnectionError
"""
# Reserve a port for use in connect
sock = socket.socket()
self.addCleanup(sock.close)
sock.bind(('127.0.0.1', 0))
port = sock.getsockname()[1]
sock.close()
with self.assertRaises(pika.exceptions.AMQPConnectionError):
self.connection = self._connect(
PARAMS_URL_TEMPLATE % {"port": port})
class TestDisconnectDuringConnectionStart(BlockingTestCaseBase):
def test(self):
""" BlockingConnection TCP/IP connection loss in CONNECTION_START
"""
fwd = ForwardServer(
remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0))
fwd.start()
self.addCleanup(lambda: fwd.stop() if fwd.running else None)
class MySelectConnection(pika.SelectConnection):
assert hasattr(pika.SelectConnection, '_on_connection_start')
def _on_connection_start(self, *args, **kwargs): # pylint: disable=W0221
fwd.stop()
return super(MySelectConnection, self)._on_connection_start(
*args, **kwargs)
with self.assertRaises(pika.exceptions.ProbableAuthenticationError):
self._connect(
PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]},
impl_class=MySelectConnection)
class TestDisconnectDuringConnectionTune(BlockingTestCaseBase):
def test(self):
""" BlockingConnection TCP/IP connection loss in CONNECTION_TUNE
"""
fwd = ForwardServer(
remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0))
fwd.start()
self.addCleanup(lambda: fwd.stop() if fwd.running else None)
class MySelectConnection(pika.SelectConnection):
assert hasattr(pika.SelectConnection, '_on_connection_tune')
def _on_connection_tune(self, *args, **kwargs): # pylint: disable=W0221
fwd.stop()
return super(MySelectConnection, self)._on_connection_tune(
*args, **kwargs)
with self.assertRaises(pika.exceptions.ProbableAccessDeniedError):
self._connect(
PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]},
impl_class=MySelectConnection)
class TestDisconnectDuringConnectionProtocol(BlockingTestCaseBase):
def test(self):
""" BlockingConnection TCP/IP connection loss in CONNECTION_PROTOCOL
"""
fwd = ForwardServer(
remote_addr=(DEFAULT_PARAMS.host, DEFAULT_PARAMS.port),
local_linger_args=(1, 0))
fwd.start()
self.addCleanup(lambda: fwd.stop() if fwd.running else None)
class MySelectConnection(pika.SelectConnection):
assert hasattr(pika.SelectConnection, '_on_stream_connected')
def _on_stream_connected(self, *args, **kwargs): # pylint: disable=W0221
fwd.stop()
return super(MySelectConnection, self)._on_stream_connected(
*args, **kwargs)
with self.assertRaises(pika.exceptions.IncompatibleProtocolError):
self._connect(PARAMS_URL_TEMPLATE % {"port": fwd.server_address[1]},
impl_class=MySelectConnection)
class TestProcessDataEvents(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.process_data_events"""
connection = self._connect()
# Try with time_limit=0
start_time = time_now()
connection.process_data_events(time_limit=0)
elapsed = time_now() - start_time
self.assertLess(elapsed, 0.25)
# Try with time_limit=0.005
start_time = time_now()
connection.process_data_events(time_limit=0.005)
elapsed = time_now() - start_time
self.assertGreaterEqual(elapsed, 0.005)
self.assertLess(elapsed, 0.25)
class TestConnectionRegisterForBlockAndUnblock(BlockingTestCaseBase):
def test(self):
"""BlockingConnection register for Connection.Blocked/Unblocked"""
connection = self._connect()
# NOTE: I haven't figured out yet how to coerce RabbitMQ to emit
# Connection.Block and Connection.Unblock from the test, so we'll
# just call the registration functions for now and simulate incoming
# blocked/unblocked frames
blocked_buffer = []
connection.add_on_connection_blocked_callback(
lambda conn, frame: blocked_buffer.append((conn, frame)))
# Simulate dispatch of blocked connection
blocked_frame = pika.frame.Method(
0,
pika.spec.Connection.Blocked('reason'))
connection._impl._process_frame(blocked_frame)
connection.sleep(0) # facilitate dispatch of pending events
self.assertEqual(len(blocked_buffer), 1)
conn, frame = blocked_buffer[0]
self.assertIs(conn, connection)
self.assertIs(frame, blocked_frame)
unblocked_buffer = []
connection.add_on_connection_unblocked_callback(
lambda conn, frame: unblocked_buffer.append((conn, frame)))
# Simulate dispatch of unblocked connection
unblocked_frame = pika.frame.Method(0, pika.spec.Connection.Unblocked())
connection._impl._process_frame(unblocked_frame)
connection.sleep(0) # facilitate dispatch of pending events
self.assertEqual(len(unblocked_buffer), 1)
conn, frame = unblocked_buffer[0]
self.assertIs(conn, connection)
self.assertIs(frame, unblocked_frame)
class TestBlockedConnectionTimeout(BlockingTestCaseBase):
def test(self):
"""BlockingConnection Connection.Blocked timeout """
url = DEFAULT_URL + '&blocked_connection_timeout=0.001'
conn = self._connect(url=url)
# NOTE: I haven't figured out yet how to coerce RabbitMQ to emit
# Connection.Block and Connection.Unblock from the test, so we'll
# simulate it for now
# Simulate Connection.Blocked
conn._impl._on_connection_blocked(
conn._impl,
pika.frame.Method(
0,
pika.spec.Connection.Blocked('TestBlockedConnectionTimeout')))
# Wait for connection teardown
with self.assertRaises(pika.exceptions.ConnectionBlockedTimeout):
while True:
conn.process_data_events(time_limit=1)
class TestAddCallbackThreadsafeFromSameThread(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.add_callback_threadsafe from same thread"""
connection = self._connect()
# Test timer completion
start_time = time_now()
rx_callback = []
connection.add_callback_threadsafe(
lambda: rx_callback.append(time_now()))
while not rx_callback:
connection.process_data_events(time_limit=None)
self.assertEqual(len(rx_callback), 1)
elapsed = time_now() - start_time
self.assertLess(elapsed, 0.25)
class TestAddCallbackThreadsafeFromAnotherThread(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.add_callback_threadsafe from another thread"""
connection = self._connect()
# Test timer completion
start_time = time_now()
rx_callback = []
timer = threading.Timer(
0,
functools.partial(connection.add_callback_threadsafe,
lambda: rx_callback.append(time_now())))
self.addCleanup(timer.cancel)
timer.start()
while not rx_callback:
connection.process_data_events(time_limit=None)
self.assertEqual(len(rx_callback), 1)
elapsed = time_now() - start_time
self.assertLess(elapsed, 0.25)
class TestAddCallbackThreadsafeOnClosedConnectionRaisesWrongState(
BlockingTestCaseBase):
def test(self):
"""BlockingConnection.add_callback_threadsafe on closed connection raises ConnectionWrongStateError"""
connection = self._connect()
connection.close()
with self.assertRaises(pika.exceptions.ConnectionWrongStateError):
connection.add_callback_threadsafe(lambda: None)
class TestAddTimeoutRemoveTimeout(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.call_later and remove_timeout"""
connection = self._connect()
# Test timer completion
start_time = time_now()
rx_callback = []
timer_id = connection.call_later(
0.005,
lambda: rx_callback.append(time_now()))
while not rx_callback:
connection.process_data_events(time_limit=None)
self.assertEqual(len(rx_callback), 1)
elapsed = time_now() - start_time
self.assertLess(elapsed, 0.25)
# Test removing triggered timeout
connection.remove_timeout(timer_id)
# Test aborted timer
rx_callback = []
timer_id = connection.call_later(
0.001,
lambda: rx_callback.append(time_now()))
connection.remove_timeout(timer_id)
connection.process_data_events(time_limit=0.1)
self.assertFalse(rx_callback)
# Make sure _TimerEvt repr doesn't crash
evt = blocking_connection._TimerEvt(lambda: None)
repr(evt)
class TestViabilityOfMultipleTimeoutsWithSameDeadlineAndCallback(BlockingTestCaseBase):
def test(self):
"""BlockingConnection viability of multiple timeouts with same deadline and callback"""
connection = self._connect()
rx_callback = []
def callback():
rx_callback.append(1)
timer1 = connection.call_later(0, callback)
timer2 = connection.call_later(0, callback)
self.assertIsNot(timer1, timer2)
connection.remove_timeout(timer1)
# Wait for second timer to fire
start_wait_time = time_now()
while not rx_callback and time_now() - start_wait_time < 0.25:
connection.process_data_events(time_limit=0.001)
self.assertListEqual(rx_callback, [1])
class TestRemoveTimeoutFromTimeoutCallback(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.remove_timeout from timeout callback"""
connection = self._connect()
# Test timer completion
timer_id1 = connection.call_later(5, lambda: 0/0)
rx_timer2 = []
def on_timer2():
connection.remove_timeout(timer_id1)
connection.remove_timeout(timer_id2)
rx_timer2.append(1)
timer_id2 = connection.call_later(0, on_timer2)
while not rx_timer2:
connection.process_data_events(time_limit=None)
self.assertFalse(connection._ready_events)
class TestSleep(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.sleep"""
connection = self._connect()
# Try with duration=0
start_time = time_now()
connection.sleep(duration=0)
elapsed = time_now() - start_time
self.assertLess(elapsed, 0.25)
# Try with duration=0.005
start_time = time_now()
connection.sleep(duration=0.005)
elapsed = time_now() - start_time
self.assertGreaterEqual(elapsed, 0.005)
self.assertLess(elapsed, 0.25)
class TestConnectionProperties(BlockingTestCaseBase):
def test(self):
"""Test BlockingConnection properties"""
connection = self._connect()
self.assertTrue(connection.is_open)
self.assertFalse(connection._impl.is_closing)
self.assertFalse(connection.is_closed)
self.assertTrue(connection.basic_nack_supported)
self.assertTrue(connection.consumer_cancel_notify_supported)
self.assertTrue(connection.exchange_exchange_bindings_supported)
self.assertTrue(connection.publisher_confirms_supported)
connection.close()
self.assertFalse(connection.is_open)
self.assertFalse(connection._impl.is_closing)
self.assertTrue(connection.is_closed)
class TestCreateAndCloseChannel(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Create and close channel"""
connection = self._connect()
ch = connection.channel()
self.assertIsInstance(ch, blocking_connection.BlockingChannel)
self.assertTrue(ch.is_open)
self.assertFalse(ch.is_closed)
self.assertFalse(ch._impl.is_closing)
self.assertIs(ch.connection, connection)
ch.close()
self.assertTrue(ch.is_closed)
self.assertFalse(ch.is_open)
self.assertFalse(ch._impl.is_closing)
class TestExchangeDeclareAndDelete(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Test exchange_declare and exchange_delete"""
connection = self._connect()
ch = connection.channel()
name = "TestExchangeDeclareAndDelete_" + uuid.uuid1().hex
# Declare a new exchange
frame = ch.exchange_declare(name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, name)
self.assertIsInstance(frame.method, pika.spec.Exchange.DeclareOk)
# Check if it exists by declaring it passively
frame = ch.exchange_declare(name, passive=True)
self.assertIsInstance(frame.method, pika.spec.Exchange.DeclareOk)
# Delete the exchange
frame = ch.exchange_delete(name)
self.assertIsInstance(frame.method, pika.spec.Exchange.DeleteOk)
# Verify that it's been deleted
with self.assertRaises(pika.exceptions.ChannelClosedByBroker) as cm:
ch.exchange_declare(name, passive=True)
self.assertEqual(cm.exception.args[0], 404)
class TestExchangeBindAndUnbind(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Test exchange_bind and exchange_unbind"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestExchangeBindAndUnbind_q' + uuid.uuid1().hex
src_exg_name = 'TestExchangeBindAndUnbind_src_exg_' + uuid.uuid1().hex
dest_exg_name = 'TestExchangeBindAndUnbind_dest_exg_' + uuid.uuid1().hex
routing_key = 'TestExchangeBindAndUnbind'
# Place channel in publisher-acknowledgments mode so that we may test
# whether the queue is reachable by publishing with mandatory=True
res = ch.confirm_delivery()
self.assertIsNone(res)
# Declare both exchanges
ch.exchange_declare(src_exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, src_exg_name)
ch.exchange_declare(dest_exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, dest_exg_name)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Bind the queue to the destination exchange
ch.queue_bind(q_name, exchange=dest_exg_name, routing_key=routing_key)
# Verify that the queue is unreachable without exchange-exchange binding
with self.assertRaises(pika.exceptions.UnroutableError):
ch.basic_publish(src_exg_name, routing_key, body='', mandatory=True)
# Bind the exchanges
frame = ch.exchange_bind(destination=dest_exg_name, source=src_exg_name,
routing_key=routing_key)
self.assertIsInstance(frame.method, pika.spec.Exchange.BindOk)
# Publish a message via the source exchange
ch.basic_publish(src_exg_name, routing_key, body='TestExchangeBindAndUnbind',
mandatory=True)
# Check that the queue now has one message
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=1)
# Unbind the exchanges
frame = ch.exchange_unbind(destination=dest_exg_name,
source=src_exg_name,
routing_key=routing_key)
self.assertIsInstance(frame.method, pika.spec.Exchange.UnbindOk)
# Verify that the queue is now unreachable via the source exchange
with self.assertRaises(pika.exceptions.UnroutableError):
ch.basic_publish(src_exg_name, routing_key, body='', mandatory=True)
class TestQueueDeclareAndDelete(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Test queue_declare and queue_delete"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestQueueDeclareAndDelete_' + uuid.uuid1().hex
# Declare a new queue
frame = ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
self.assertIsInstance(frame.method, pika.spec.Queue.DeclareOk)
# Check if it exists by declaring it passively
frame = ch.queue_declare(q_name, passive=True)
self.assertIsInstance(frame.method, pika.spec.Queue.DeclareOk)
# Delete the queue
frame = ch.queue_delete(q_name)
self.assertIsInstance(frame.method, pika.spec.Queue.DeleteOk)
# Verify that it's been deleted
with self.assertRaises(pika.exceptions.ChannelClosedByBroker) as cm:
ch.queue_declare(q_name, passive=True)
self.assertEqual(cm.exception.args[0], 404)
class TestPassiveQueueDeclareOfUnknownQueueRaisesChannelClosed(
BlockingTestCaseBase):
def test(self):
"""BlockingChannel: ChannelClosed raised when passive-declaring unknown queue""" # pylint: disable=C0301
connection = self._connect()
ch = connection.channel()
q_name = ("TestPassiveQueueDeclareOfUnknownQueueRaisesChannelClosed_q_"
+ uuid.uuid1().hex)
with self.assertRaises(pika.exceptions.ChannelClosedByBroker) as ex_cm:
ch.queue_declare(q_name, passive=True)
self.assertEqual(ex_cm.exception.args[0], 404)
class TestQueueBindAndUnbindAndPurge(BlockingTestCaseBase):
def test(self):
"""BlockingChannel: Test queue_bind and queue_unbind"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestQueueBindAndUnbindAndPurge_q' + uuid.uuid1().hex
exg_name = 'TestQueueBindAndUnbindAndPurge_exg_' + uuid.uuid1().hex
routing_key = 'TestQueueBindAndUnbindAndPurge'
# Place channel in publisher-acknowledgments mode so that we may test
# whether the queue is reachable by publishing with mandatory=True
res = ch.confirm_delivery()
self.assertIsNone(res)
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Bind the queue to the exchange using routing key
frame = ch.queue_bind(q_name, exchange=exg_name,
routing_key=routing_key)
self.assertIsInstance(frame.method, pika.spec.Queue.BindOk)
# Check that the queue is empty
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
# Deposit a message in the queue
ch.basic_publish(exg_name, routing_key, body='TestQueueBindAndUnbindAndPurge',
mandatory=True)
# Check that the queue now has one message
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 1)
# Unbind the queue
frame = ch.queue_unbind(queue=q_name, exchange=exg_name,
routing_key=routing_key)
self.assertIsInstance(frame.method, pika.spec.Queue.UnbindOk)
# Verify that the queue is now unreachable via that binding
with self.assertRaises(pika.exceptions.UnroutableError):
ch.basic_publish(exg_name, routing_key,
body='TestQueueBindAndUnbindAndPurge-2',
mandatory=True)
# Purge the queue and verify that 1 message was purged
frame = ch.queue_purge(q_name)
self.assertIsInstance(frame.method, pika.spec.Queue.PurgeOk)
self.assertEqual(frame.method.message_count, 1)
# Verify that the queue is now empty
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
class TestBasicGet(BlockingTestCaseBase):
def tearDown(self):
LOGGER.info('%s TEARING DOWN (%s)', datetime.utcnow(), self)
def test(self):
"""BlockingChannel.basic_get"""
LOGGER.info('%s STARTED (%s)', datetime.utcnow(), self)
connection = self._connect()
LOGGER.info('%s CONNECTED (%s)', datetime.utcnow(), self)
ch = connection.channel()
LOGGER.info('%s CREATED CHANNEL (%s)', datetime.utcnow(), self)
q_name = 'TestBasicGet_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
LOGGER.info('%s ENABLED PUB-ACKS (%s)', datetime.utcnow(), self)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
LOGGER.info('%s DECLARED QUEUE (%s)', datetime.utcnow(), self)
# Verify result of getting a message from an empty queue
msg = ch.basic_get(q_name, auto_ack=False)
self.assertTupleEqual(msg, (None, None, None))
LOGGER.info('%s GOT FROM EMPTY QUEUE (%s)', datetime.utcnow(), self)
body = 'TestBasicGet'
# Deposit a message in the queue via default exchange
ch.basic_publish(exchange='', routing_key=q_name,
body=body, mandatory=True)
LOGGER.info('%s PUBLISHED (%s)', datetime.utcnow(), self)
# Get the message
(method, properties, body) = ch.basic_get(q_name, auto_ack=False)
LOGGER.info('%s GOT FROM NON-EMPTY QUEUE (%s)', datetime.utcnow(), self)
self.assertIsInstance(method, pika.spec.Basic.GetOk)
self.assertEqual(method.delivery_tag, 1)
self.assertFalse(method.redelivered)
self.assertEqual(method.exchange, '')
self.assertEqual(method.routing_key, q_name)
self.assertEqual(method.message_count, 0)
self.assertIsInstance(properties, pika.BasicProperties)
self.assertIsNone(properties.headers)
self.assertEqual(body, as_bytes(body))
# Ack it
ch.basic_ack(delivery_tag=method.delivery_tag)
LOGGER.info('%s ACKED (%s)', datetime.utcnow(), self)
# Verify that the queue is now empty
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
class TestBasicReject(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_reject"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicReject_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Deposit two messages in the queue via default exchange
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicReject1', mandatory=True)
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicReject2', mandatory=True)
# Get the messages
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicReject1'))
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicReject2'))
# Nack the second message
ch.basic_reject(rx_method.delivery_tag, requeue=True)
# Verify that exactly one message is present in the queue, namely the
# second one
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=1)
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicReject2'))
class TestBasicRejectNoRequeue(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_reject with requeue=False"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicRejectNoRequeue_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Deposit two messages in the queue via default exchange
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicRejectNoRequeue1', mandatory=True)
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicRejectNoRequeue2', mandatory=True)
# Get the messages
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicRejectNoRequeue1'))
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicRejectNoRequeue2'))
# Nack the second message
ch.basic_reject(rx_method.delivery_tag, requeue=False)
# Verify that no messages are present in the queue
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
class TestBasicNack(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_nack single message"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicNack_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Deposit two messages in the queue via default exchange
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicNack1', mandatory=True)
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicNack2', mandatory=True)
# Get the messages
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicNack1'))
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicNack2'))
# Nack the second message
ch.basic_nack(rx_method.delivery_tag, multiple=False, requeue=True)
# Verify that exactly one message is present in the queue, namely the
# second one
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=1)
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body, as_bytes('TestBasicNack2'))
class TestBasicNackNoRequeue(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_nack with requeue=False"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicNackNoRequeue_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Deposit two messages in the queue via default exchange
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicNackNoRequeue1', mandatory=True)
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicNackNoRequeue2', mandatory=True)
# Get the messages
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicNackNoRequeue1'))
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicNackNoRequeue2'))
# Nack the second message
ch.basic_nack(rx_method.delivery_tag, requeue=False)
# Verify that no messages are present in the queue
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
class TestBasicNackMultiple(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_nack multiple messages"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicNackMultiple_q' + uuid.uuid1().hex
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Deposit two messages in the queue via default exchange
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicNackMultiple1', mandatory=True)
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicNackMultiple2', mandatory=True)
# Get the messages
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicNackMultiple1'))
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicNackMultiple2'))
# Nack both messages via the "multiple" option
ch.basic_nack(rx_method.delivery_tag, multiple=True, requeue=True)
# Verify that both messages are present in the queue
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=2)
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicNackMultiple1'))
(rx_method, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body,
as_bytes('TestBasicNackMultiple2'))
class TestBasicRecoverWithRequeue(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_recover with requeue=True.
NOTE: the requeue=False option is not supported by RabbitMQ broker as
of this writing (using RabbitMQ 3.5.1)
"""
connection = self._connect()
ch = connection.channel()
q_name = (
'TestBasicRecoverWithRequeue_q' + uuid.uuid1().hex)
# Place channel in publisher-acknowledgments mode so that the message
# may be delivered synchronously to the queue by publishing it with
# mandatory=True
ch.confirm_delivery()
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Deposit two messages in the queue via default exchange
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicRecoverWithRequeue1', mandatory=True)
ch.basic_publish(exchange='', routing_key=q_name,
body='TestBasicRecoverWithRequeue2', mandatory=True)
rx_messages = []
num_messages = 0
for msg in ch.consume(q_name, auto_ack=False):
num_messages += 1
if num_messages == 2:
ch.basic_recover(requeue=True)
if num_messages > 2:
rx_messages.append(msg)
if num_messages == 4:
break
else:
self.fail('consumer aborted prematurely')
# Get the messages
(_, _, rx_body) = rx_messages[0]
self.assertEqual(rx_body,
as_bytes('TestBasicRecoverWithRequeue1'))
(_, _, rx_body) = rx_messages[1]
self.assertEqual(rx_body,
as_bytes('TestBasicRecoverWithRequeue2'))
class TestTxCommit(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.tx_commit"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestTxCommit_q' + uuid.uuid1().hex
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Select standard transaction mode
frame = ch.tx_select()
self.assertIsInstance(frame.method, pika.spec.Tx.SelectOk)
# Deposit a message in the queue via default exchange
ch.basic_publish(exchange='', routing_key=q_name,
body='TestTxCommit1', mandatory=True)
# Verify that queue is still empty
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
# Commit the transaction
ch.tx_commit()
# Verify that the queue has the expected message
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 1)
(_, _, rx_body) = ch.basic_get(q_name, auto_ack=False)
self.assertEqual(rx_body, as_bytes('TestTxCommit1'))
class TestTxRollback(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.tx_commit"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestTxRollback_q' + uuid.uuid1().hex
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Select standard transaction mode
frame = ch.tx_select()
self.assertIsInstance(frame.method, pika.spec.Tx.SelectOk)
# Deposit a message in the queue via default exchange
ch.basic_publish(exchange='', routing_key=q_name,
body='TestTxRollback1', mandatory=True)
# Verify that queue is still empty
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
# Roll back the transaction
ch.tx_rollback()
# Verify that the queue continues to be empty
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
class TestBasicConsumeFromUnknownQueueRaisesChannelClosed(BlockingTestCaseBase):
def test(self):
"""ChannelClosed raised when consuming from unknown queue"""
connection = self._connect()
ch = connection.channel()
q_name = ("TestBasicConsumeFromUnknownQueueRaisesChannelClosed_q_" +
uuid.uuid1().hex)
with self.assertRaises(pika.exceptions.ChannelClosedByBroker) as ex_cm:
ch.basic_consume(q_name, lambda *args: None)
self.assertEqual(ex_cm.exception.args[0], 404)
class TestPublishAndBasicPublishWithPubacksUnroutable(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914
"""BlockingChannel.publish amd basic_publish unroutable message with pubacks""" # pylint: disable=C0301
connection = self._connect()
ch = connection.channel()
exg_name = ('TestPublishAndBasicPublishUnroutable_exg_' +
uuid.uuid1().hex)
routing_key = 'TestPublishAndBasicPublishUnroutable'
# Place channel in publisher-acknowledgments mode so that publishing
# with mandatory=True will be synchronous
res = ch.confirm_delivery()
self.assertIsNone(res)
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Verify unroutable message handling using basic_publish
msg2_headers = dict(
test_name='TestPublishAndBasicPublishWithPubacksUnroutable')
msg2_properties = pika.spec.BasicProperties(headers=msg2_headers)
with self.assertRaises(pika.exceptions.UnroutableError) as cm:
ch.basic_publish(exg_name, routing_key=routing_key, body='',
properties=msg2_properties, mandatory=True)
(msg,) = cm.exception.messages
self.assertIsInstance(msg, blocking_connection.ReturnedMessage)
self.assertIsInstance(msg.method, pika.spec.Basic.Return)
self.assertEqual(msg.method.reply_code, 312)
self.assertEqual(msg.method.exchange, exg_name)
self.assertEqual(msg.method.routing_key, routing_key)
self.assertIsInstance(msg.properties, pika.BasicProperties)
self.assertEqual(msg.properties.headers, msg2_headers)
self.assertEqual(msg.body, as_bytes(''))
class TestConfirmDeliveryAfterUnroutableMessage(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914
"""BlockingChannel.confirm_delivery following unroutable message"""
connection = self._connect()
ch = connection.channel()
exg_name = ('TestConfirmDeliveryAfterUnroutableMessage_exg_' +
uuid.uuid1().hex)
routing_key = 'TestConfirmDeliveryAfterUnroutableMessage'
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Register on-return callback
returned_messages = []
ch.add_on_return_callback(lambda *args: returned_messages.append(args))
# Emit unroutable message without pubacks
ch.basic_publish(exg_name, routing_key=routing_key, body='', mandatory=True)
# Select delivery confirmations
ch.confirm_delivery()
# Verify that unroutable message is in pending events
self.assertEqual(len(ch._pending_events), 1)
self.assertIsInstance(ch._pending_events[0],
blocking_connection._ReturnedMessageEvt)
# Verify that repr of _ReturnedMessageEvt instance does crash
repr(ch._pending_events[0])
# Dispach events
connection.process_data_events()
self.assertEqual(len(ch._pending_events), 0)
# Verify that unroutable message was dispatched
((channel, method, properties, body,),) = returned_messages # pylint: disable=E0632
self.assertIs(channel, ch)
self.assertIsInstance(method, pika.spec.Basic.Return)
self.assertEqual(method.reply_code, 312)
self.assertEqual(method.exchange, exg_name)
self.assertEqual(method.routing_key, routing_key)
self.assertIsInstance(properties, pika.BasicProperties)
self.assertEqual(body, as_bytes(''))
class TestUnroutableMessagesReturnedInNonPubackMode(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914
"""BlockingChannel: unroutable messages is returned in non-puback mode""" # pylint: disable=C0301
connection = self._connect()
ch = connection.channel()
exg_name = (
'TestUnroutableMessageReturnedInNonPubackMode_exg_'
+ uuid.uuid1().hex)
routing_key = 'TestUnroutableMessageReturnedInNonPubackMode'
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Register on-return callback
returned_messages = []
ch.add_on_return_callback(
lambda *args: returned_messages.append(args))
# Emit unroutable messages without pubacks
ch.basic_publish(exg_name, routing_key=routing_key, body='msg1', mandatory=True)
ch.basic_publish(exg_name, routing_key=routing_key, body='msg2', mandatory=True)
# Process I/O until Basic.Return are dispatched
while len(returned_messages) < 2:
connection.process_data_events()
self.assertEqual(len(returned_messages), 2)
self.assertEqual(len(ch._pending_events), 0)
# Verify returned messages
(channel, method, properties, body,) = returned_messages[0]
self.assertIs(channel, ch)
self.assertIsInstance(method, pika.spec.Basic.Return)
self.assertEqual(method.reply_code, 312)
self.assertEqual(method.exchange, exg_name)
self.assertEqual(method.routing_key, routing_key)
self.assertIsInstance(properties, pika.BasicProperties)
self.assertEqual(body, as_bytes('msg1'))
(channel, method, properties, body,) = returned_messages[1]
self.assertIs(channel, ch)
self.assertIsInstance(method, pika.spec.Basic.Return)
self.assertEqual(method.reply_code, 312)
self.assertEqual(method.exchange, exg_name)
self.assertEqual(method.routing_key, routing_key)
self.assertIsInstance(properties, pika.BasicProperties)
self.assertEqual(body, as_bytes('msg2'))
class TestUnroutableMessageReturnedInPubackMode(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914
"""BlockingChannel: unroutable messages is returned in puback mode"""
connection = self._connect()
ch = connection.channel()
exg_name = (
'TestUnroutableMessageReturnedInPubackMode_exg_'
+ uuid.uuid1().hex)
routing_key = 'TestUnroutableMessageReturnedInPubackMode'
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Select delivery confirmations
ch.confirm_delivery()
# Register on-return callback
returned_messages = []
ch.add_on_return_callback(
lambda *args: returned_messages.append(args))
# Emit unroutable messages with pubacks
with self.assertRaises(pika.exceptions.UnroutableError):
ch.basic_publish(exg_name, routing_key=routing_key, body='msg1',
mandatory=True)
with self.assertRaises(pika.exceptions.UnroutableError):
ch.basic_publish(exg_name, routing_key=routing_key, body='msg2',
mandatory=True)
# Verify that unroutable messages are already in pending events
self.assertEqual(len(ch._pending_events), 2)
self.assertIsInstance(ch._pending_events[0],
blocking_connection._ReturnedMessageEvt)
self.assertIsInstance(ch._pending_events[1],
blocking_connection._ReturnedMessageEvt)
# Verify that repr of _ReturnedMessageEvt instance does crash
repr(ch._pending_events[0])
repr(ch._pending_events[1])
# Dispatch events
connection.process_data_events()
self.assertEqual(len(ch._pending_events), 0)
# Verify returned messages
(channel, method, properties, body,) = returned_messages[0]
self.assertIs(channel, ch)
self.assertIsInstance(method, pika.spec.Basic.Return)
self.assertEqual(method.reply_code, 312)
self.assertEqual(method.exchange, exg_name)
self.assertEqual(method.routing_key, routing_key)
self.assertIsInstance(properties, pika.BasicProperties)
self.assertEqual(body, as_bytes('msg1'))
(channel, method, properties, body,) = returned_messages[1]
self.assertIs(channel, ch)
self.assertIsInstance(method, pika.spec.Basic.Return)
self.assertEqual(method.reply_code, 312)
self.assertEqual(method.exchange, exg_name)
self.assertEqual(method.routing_key, routing_key)
self.assertIsInstance(properties, pika.BasicProperties)
self.assertEqual(body, as_bytes('msg2'))
class TestBasicPublishDeliveredWhenPendingUnroutable(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914
"""BlockingChannel.basic_publish msg delivered despite pending unroutable message""" # pylint: disable=C0301
connection = self._connect()
ch = connection.channel()
q_name = ('TestBasicPublishDeliveredWhenPendingUnroutable_q' +
uuid.uuid1().hex)
exg_name = ('TestBasicPublishDeliveredWhenPendingUnroutable_exg_' +
uuid.uuid1().hex)
routing_key = 'TestBasicPublishDeliveredWhenPendingUnroutable'
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Bind the queue to the exchange using routing key
ch.queue_bind(q_name, exchange=exg_name, routing_key=routing_key)
# Attempt to send an unroutable message in the queue via basic_publish
ch.basic_publish(exg_name, routing_key='',
body='unroutable-message',
mandatory=True)
# Flush connection to force Basic.Return
connection.channel().close()
# Deposit a routable message in the queue
ch.basic_publish(exg_name, routing_key=routing_key,
body='routable-message',
mandatory=True)
# Wait for the queue to get the routable message
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=1)
msg = ch.basic_get(q_name)
# Check the first message
self.assertIsInstance(msg, tuple)
rx_method, rx_properties, rx_body = msg
self.assertIsInstance(rx_method, pika.spec.Basic.GetOk)
self.assertEqual(rx_method.delivery_tag, 1)
self.assertFalse(rx_method.redelivered)
self.assertEqual(rx_method.exchange, exg_name)
self.assertEqual(rx_method.routing_key, routing_key)
self.assertIsInstance(rx_properties, pika.BasicProperties)
self.assertEqual(rx_body, as_bytes('routable-message'))
# There shouldn't be any more events now
self.assertFalse(ch._pending_events)
# Ack the message
ch.basic_ack(delivery_tag=rx_method.delivery_tag, multiple=False)
# Verify that the queue is now empty
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
class TestPublishAndConsumeWithPubacksAndQosOfOne(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914,R0915
"""BlockingChannel.basic_publish, publish, basic_consume, QoS, \
Basic.Cancel from broker
"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestPublishAndConsumeAndQos_q' + uuid.uuid1().hex
exg_name = 'TestPublishAndConsumeAndQos_exg_' + uuid.uuid1().hex
routing_key = 'TestPublishAndConsumeAndQos'
# Place channel in publisher-acknowledgments mode so that publishing
# with mandatory=True will be synchronous
res = ch.confirm_delivery()
self.assertIsNone(res)
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Bind the queue to the exchange using routing key
ch.queue_bind(q_name, exchange=exg_name, routing_key=routing_key)
# Deposit a message in the queue
msg1_headers = dict(
test_name='TestPublishAndConsumeWithPubacksAndQosOfOne')
msg1_properties = pika.spec.BasicProperties(headers=msg1_headers)
ch.basic_publish(exg_name, routing_key=routing_key,
body='via-basic_publish',
properties=msg1_properties,
mandatory=True)
# Deposit another message in the queue
ch.basic_publish(exg_name, routing_key, body='via-publish',
mandatory=True)
# Check that the queue now has two messages
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 2)
# Configure QoS for one message
ch.basic_qos(prefetch_size=0, prefetch_count=1, global_qos=False)
# Create a consumer
rx_messages = []
consumer_tag = ch.basic_consume(
q_name,
lambda *args: rx_messages.append(args),
auto_ack=False,
exclusive=False,
arguments=None)
# Wait for first message to arrive
while not rx_messages:
connection.process_data_events(time_limit=None)
self.assertEqual(len(rx_messages), 1)
# Check the first message
msg = rx_messages[0]
self.assertIsInstance(msg, tuple)
rx_ch, rx_method, rx_properties, rx_body = msg
self.assertIs(rx_ch, ch)
self.assertIsInstance(rx_method, pika.spec.Basic.Deliver)
self.assertEqual(rx_method.consumer_tag, consumer_tag)
self.assertEqual(rx_method.delivery_tag, 1)
self.assertFalse(rx_method.redelivered)
self.assertEqual(rx_method.exchange, exg_name)
self.assertEqual(rx_method.routing_key, routing_key)
self.assertIsInstance(rx_properties, pika.BasicProperties)
self.assertEqual(rx_properties.headers, msg1_headers)
self.assertEqual(rx_body, as_bytes('via-basic_publish'))
# There shouldn't be any more events now
self.assertFalse(ch._pending_events)
# Ack the message so that the next one can arrive (we configured QoS
# with prefetch_count=1)
ch.basic_ack(delivery_tag=rx_method.delivery_tag, multiple=False)
# Get the second message
while len(rx_messages) < 2:
connection.process_data_events(time_limit=None)
self.assertEqual(len(rx_messages), 2)
msg = rx_messages[1]
self.assertIsInstance(msg, tuple)
rx_ch, rx_method, rx_properties, rx_body = msg
self.assertIs(rx_ch, ch)
self.assertIsInstance(rx_method, pika.spec.Basic.Deliver)
self.assertEqual(rx_method.consumer_tag, consumer_tag)
self.assertEqual(rx_method.delivery_tag, 2)
self.assertFalse(rx_method.redelivered)
self.assertEqual(rx_method.exchange, exg_name)
self.assertEqual(rx_method.routing_key, routing_key)
self.assertIsInstance(rx_properties, pika.BasicProperties)
self.assertEqual(rx_body, as_bytes('via-publish'))
# There shouldn't be any more events now
self.assertFalse(ch._pending_events)
ch.basic_ack(delivery_tag=rx_method.delivery_tag, multiple=False)
# Verify that the queue is now empty
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
# Attempt to consume again with a short timeout
connection.process_data_events(time_limit=0.005)
self.assertEqual(len(rx_messages), 2)
# Delete the queue and wait for consumer cancellation
rx_cancellations = []
ch.add_on_cancel_callback(rx_cancellations.append)
ch.queue_delete(q_name)
ch.start_consuming()
self.assertEqual(len(rx_cancellations), 1)
frame, = rx_cancellations # pylint: disable=E0632
self.assertEqual(frame.method.consumer_tag, consumer_tag)
class TestBasicConsumeWithAckFromAnotherThread(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914,R0915
"""BlockingChannel.basic_consume with ack from another thread and \
requesting basic_ack via add_callback_threadsafe
"""
# This test simulates processing of a message on another thread and
# then requesting an ACK to be dispatched on the connection's thread
# via BlockingConnection.add_callback_threadsafe
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicConsumeWithAckFromAnotherThread_q' + uuid.uuid1().hex
exg_name = ('TestBasicConsumeWithAckFromAnotherThread_exg' +
uuid.uuid1().hex)
routing_key = 'TestBasicConsumeWithAckFromAnotherThread'
# Place channel in publisher-acknowledgments mode so that publishing
# with mandatory=True will be synchronous (for convenience)
res = ch.confirm_delivery()
self.assertIsNone(res)
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Bind the queue to the exchange using routing key
ch.queue_bind(q_name, exchange=exg_name, routing_key=routing_key)
# Publish 2 messages with mandatory=True for synchronous processing
ch.basic_publish(exg_name, routing_key, body='msg1', mandatory=True)
ch.basic_publish(exg_name, routing_key, body='last-msg', mandatory=True)
# Configure QoS for one message so that the 2nd message will be
# delivered only after the 1st one is ACKed
ch.basic_qos(prefetch_size=0, prefetch_count=1, global_qos=False)
# Create a consumer
rx_messages = []
def ackAndEnqueueMessageViaAnotherThread(rx_ch,
rx_method,
rx_properties, # pylint: disable=W0613
rx_body):
LOGGER.debug(
'%s: Got message body=%r; delivery-tag=%r',
datetime.now(), rx_body, rx_method.delivery_tag)
# Request ACK dispatch via add_callback_threadsafe from other
# thread; if last message, cancel consumer so that start_consuming
# can return
def processOnConnectionThread():
LOGGER.debug('%s: ACKing message body=%r; delivery-tag=%r',
datetime.now(),
rx_body,
rx_method.delivery_tag)
ch.basic_ack(delivery_tag=rx_method.delivery_tag,
multiple=False)
rx_messages.append(rx_body)
# NOTE on python3, `b'last-msg' != 'last-msg'`
if rx_body == b'last-msg':
LOGGER.debug('%s: Canceling consumer consumer-tag=%r',
datetime.now(),
rx_method.consumer_tag)
rx_ch.basic_cancel(rx_method.consumer_tag)
# Spawn a thread to initiate ACKing
timer = threading.Timer(0,
lambda: connection.add_callback_threadsafe(
processOnConnectionThread))
self.addCleanup(timer.cancel)
timer.start()
consumer_tag = ch.basic_consume(
q_name,
ackAndEnqueueMessageViaAnotherThread,
auto_ack=False,
exclusive=False,
arguments=None)
# Wait for both messages
LOGGER.debug('%s: calling start_consuming(); consumer tag=%r',
datetime.now(),
consumer_tag)
ch.start_consuming()
LOGGER.debug('%s: Returned from start_consuming(); consumer tag=%r',
datetime.now(),
consumer_tag)
self.assertEqual(len(rx_messages), 2)
self.assertEqual(rx_messages[0], b'msg1')
self.assertEqual(rx_messages[1], b'last-msg')
class TestConsumeGeneratorWithAckFromAnotherThread(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914,R0915
"""BlockingChannel.consume and requesting basic_ack from another \
thread via add_callback_threadsafe
"""
connection = self._connect()
ch = connection.channel()
q_name = ('TestConsumeGeneratorWithAckFromAnotherThread_q' +
uuid.uuid1().hex)
exg_name = ('TestConsumeGeneratorWithAckFromAnotherThread_exg' +
uuid.uuid1().hex)
routing_key = 'TestConsumeGeneratorWithAckFromAnotherThread'
# Place channel in publisher-acknowledgments mode so that publishing
# with mandatory=True will be synchronous (for convenience)
res = ch.confirm_delivery()
self.assertIsNone(res)
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Bind the queue to the exchange using routing key
ch.queue_bind(q_name, exchange=exg_name, routing_key=routing_key)
# Publish 2 messages with mandatory=True for synchronous processing
ch.basic_publish(exg_name, routing_key, body='msg1', mandatory=True)
ch.basic_publish(exg_name, routing_key, body='last-msg', mandatory=True)
# Configure QoS for one message so that the 2nd message will be
# delivered only after the 1st one is ACKed
ch.basic_qos(prefetch_size=0, prefetch_count=1, global_qos=False)
# Create a consumer
rx_messages = []
def ackAndEnqueueMessageViaAnotherThread(rx_ch,
rx_method,
rx_properties, # pylint: disable=W0613
rx_body):
LOGGER.debug(
'%s: Got message body=%r; delivery-tag=%r',
datetime.now(), rx_body, rx_method.delivery_tag)
# Request ACK dispatch via add_callback_threadsafe from other
# thread; if last message, cancel consumer so that consumer
# generator completes
def processOnConnectionThread():
LOGGER.debug('%s: ACKing message body=%r; delivery-tag=%r',
datetime.now(),
rx_body,
rx_method.delivery_tag)
ch.basic_ack(delivery_tag=rx_method.delivery_tag,
multiple=False)
rx_messages.append(rx_body)
# NOTE on python3, `b'last-msg' != 'last-msg'`
if rx_body == b'last-msg':
LOGGER.debug('%s: Canceling consumer consumer-tag=%r',
datetime.now(),
rx_method.consumer_tag)
# NOTE Need to use cancel() for the consumer generator
# instead of basic_cancel()
rx_ch.cancel()
# Spawn a thread to initiate ACKing
timer = threading.Timer(0,
lambda: connection.add_callback_threadsafe(
processOnConnectionThread))
self.addCleanup(timer.cancel)
timer.start()
for method, properties, body in ch.consume(q_name, auto_ack=False):
ackAndEnqueueMessageViaAnotherThread(rx_ch=ch,
rx_method=method,
rx_properties=properties,
rx_body=body)
self.assertEqual(len(rx_messages), 2)
self.assertEqual(rx_messages[0], b'msg1')
self.assertEqual(rx_messages[1], b'last-msg')
class TestTwoBasicConsumersOnSameChannel(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914
"""BlockingChannel: two basic_consume consumers on same channel
"""
connection = self._connect()
ch = connection.channel()
exg_name = 'TestPublishAndConsumeAndQos_exg_' + uuid.uuid1().hex
q1_name = 'TestTwoBasicConsumersOnSameChannel_q1' + uuid.uuid1().hex
q2_name = 'TestTwoBasicConsumersOnSameChannel_q2' + uuid.uuid1().hex
q1_routing_key = 'TestTwoBasicConsumersOnSameChannel1'
q2_routing_key = 'TestTwoBasicConsumersOnSameChannel2'
# Place channel in publisher-acknowledgments mode so that publishing
# with mandatory=True will be synchronous
ch.confirm_delivery()
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Declare the two new queues and bind them to the exchange
ch.queue_declare(q1_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q1_name))
ch.queue_bind(q1_name, exchange=exg_name, routing_key=q1_routing_key)
ch.queue_declare(q2_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q2_name))
ch.queue_bind(q2_name, exchange=exg_name, routing_key=q2_routing_key)
# Deposit messages in the queues
q1_tx_message_bodies = ['q1_message+%s' % (i,)
for i in pika.compat.xrange(100)]
for message_body in q1_tx_message_bodies:
ch.basic_publish(exg_name, q1_routing_key, body=message_body, mandatory=True)
q2_tx_message_bodies = ['q2_message+%s' % (i,)
for i in pika.compat.xrange(150)]
for message_body in q2_tx_message_bodies:
ch.basic_publish(exg_name, q2_routing_key, body=message_body, mandatory=True)
# Create the consumers
q1_rx_messages = []
q1_consumer_tag = ch.basic_consume(
q1_name,
lambda *args: q1_rx_messages.append(args),
auto_ack=False,
exclusive=False,
arguments=None)
q2_rx_messages = []
q2_consumer_tag = ch.basic_consume(
q2_name,
lambda *args: q2_rx_messages.append(args),
auto_ack=False,
exclusive=False,
arguments=None)
# Wait for all messages to be delivered
while (len(q1_rx_messages) < len(q1_tx_message_bodies) or
len(q2_rx_messages) < len(q2_tx_message_bodies)):
connection.process_data_events(time_limit=None)
self.assertEqual(len(q2_rx_messages), len(q2_tx_message_bodies))
# Verify the messages
def validate_messages(rx_messages,
routing_key,
consumer_tag,
tx_message_bodies):
self.assertEqual(len(rx_messages), len(tx_message_bodies))
for msg, expected_body in zip(rx_messages, tx_message_bodies):
self.assertIsInstance(msg, tuple)
rx_ch, rx_method, rx_properties, rx_body = msg
self.assertIs(rx_ch, ch)
self.assertIsInstance(rx_method, pika.spec.Basic.Deliver)
self.assertEqual(rx_method.consumer_tag, consumer_tag)
self.assertFalse(rx_method.redelivered)
self.assertEqual(rx_method.exchange, exg_name)
self.assertEqual(rx_method.routing_key, routing_key)
self.assertIsInstance(rx_properties, pika.BasicProperties)
self.assertEqual(rx_body, as_bytes(expected_body))
# Validate q1 consumed messages
validate_messages(rx_messages=q1_rx_messages,
routing_key=q1_routing_key,
consumer_tag=q1_consumer_tag,
tx_message_bodies=q1_tx_message_bodies)
# Validate q2 consumed messages
validate_messages(rx_messages=q2_rx_messages,
routing_key=q2_routing_key,
consumer_tag=q2_consumer_tag,
tx_message_bodies=q2_tx_message_bodies)
# There shouldn't be any more events now
self.assertFalse(ch._pending_events)
class TestBasicCancelPurgesPendingConsumerCancellationEvt(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_cancel purges pending _ConsumerCancellationEvt""" # pylint: disable=C0301
connection = self._connect()
ch = connection.channel()
q_name = ('TestBasicCancelPurgesPendingConsumerCancellationEvt_q' +
uuid.uuid1().hex)
ch.queue_declare(q_name)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
ch.basic_publish('', routing_key=q_name, body='via-publish', mandatory=True)
# Create a consumer. Not passing a 'callback' to test client-generated
# consumer tags
rx_messages = []
consumer_tag = ch.basic_consume(
q_name,
lambda *args: rx_messages.append(args))
# Wait for the published message to arrive, but don't consume it
while not ch._pending_events:
# Issue synchronous command that forces processing of incoming I/O
connection.channel().close()
self.assertEqual(len(ch._pending_events), 1)
self.assertIsInstance(ch._pending_events[0],
blocking_connection._ConsumerDeliveryEvt)
# Delete the queue and wait for broker-initiated consumer cancellation
ch.queue_delete(q_name)
while len(ch._pending_events) < 2:
# Issue synchronous command that forces processing of incoming I/O
connection.channel().close()
self.assertEqual(len(ch._pending_events), 2)
self.assertIsInstance(ch._pending_events[1],
blocking_connection._ConsumerCancellationEvt)
# Issue consumer cancellation and verify that the pending
# _ConsumerCancellationEvt instance was removed
messages = ch.basic_cancel(consumer_tag)
self.assertEqual(messages, [])
self.assertEqual(len(ch._pending_events), 0)
class TestBasicPublishWithoutPubacks(BlockingTestCaseBase):
def test(self): # pylint: disable=R0914,R0915
"""BlockingChannel.basic_publish without pubacks"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestBasicPublishWithoutPubacks_q' + uuid.uuid1().hex
exg_name = 'TestBasicPublishWithoutPubacks_exg_' + uuid.uuid1().hex
routing_key = 'TestBasicPublishWithoutPubacks'
# Declare a new exchange
ch.exchange_declare(exg_name, exchange_type=ExchangeType.direct)
self.addCleanup(connection.channel().exchange_delete, exg_name)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Bind the queue to the exchange using routing key
ch.queue_bind(q_name, exchange=exg_name, routing_key=routing_key)
# Deposit a message in the queue with mandatory=True
msg1_headers = dict(
test_name='TestBasicPublishWithoutPubacks')
msg1_properties = pika.spec.BasicProperties(headers=msg1_headers)
ch.basic_publish(exg_name, routing_key=routing_key,
body='via-basic_publish_mandatory=True',
properties=msg1_properties,
mandatory=True)
# Deposit a message in the queue with mandatory=False
ch.basic_publish(exg_name, routing_key=routing_key,
body='via-basic_publish_mandatory=False',
mandatory=False)
# Wait for the messages to arrive in queue
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=2)
# Create a consumer. Not passing a 'callback' to test client-generated
# consumer tags
rx_messages = []
consumer_tag = ch.basic_consume(
q_name,
lambda *args: rx_messages.append(args),
auto_ack=False,
exclusive=False,
arguments=None)
# Wait for first message to arrive
while not rx_messages:
connection.process_data_events(time_limit=None)
self.assertGreaterEqual(len(rx_messages), 1)
# Check the first message
msg = rx_messages[0]
self.assertIsInstance(msg, tuple)
rx_ch, rx_method, rx_properties, rx_body = msg
self.assertIs(rx_ch, ch)
self.assertIsInstance(rx_method, pika.spec.Basic.Deliver)
self.assertEqual(rx_method.consumer_tag, consumer_tag)
self.assertEqual(rx_method.delivery_tag, 1)
self.assertFalse(rx_method.redelivered)
self.assertEqual(rx_method.exchange, exg_name)
self.assertEqual(rx_method.routing_key, routing_key)
self.assertIsInstance(rx_properties, pika.BasicProperties)
self.assertEqual(rx_properties.headers, msg1_headers)
self.assertEqual(rx_body, as_bytes('via-basic_publish_mandatory=True'))
# There shouldn't be any more events now
self.assertFalse(ch._pending_events)
# Ack the message so that the next one can arrive (we configured QoS
# with prefetch_count=1)
ch.basic_ack(delivery_tag=rx_method.delivery_tag, multiple=False)
# Get the second message
while len(rx_messages) < 2:
connection.process_data_events(time_limit=None)
self.assertEqual(len(rx_messages), 2)
msg = rx_messages[1]
self.assertIsInstance(msg, tuple)
rx_ch, rx_method, rx_properties, rx_body = msg
self.assertIs(rx_ch, ch)
self.assertIsInstance(rx_method, pika.spec.Basic.Deliver)
self.assertEqual(rx_method.consumer_tag, consumer_tag)
self.assertEqual(rx_method.delivery_tag, 2)
self.assertFalse(rx_method.redelivered)
self.assertEqual(rx_method.exchange, exg_name)
self.assertEqual(rx_method.routing_key, routing_key)
self.assertIsInstance(rx_properties, pika.BasicProperties)
self.assertEqual(rx_body, as_bytes('via-basic_publish_mandatory=False'))
# There shouldn't be any more events now
self.assertFalse(ch._pending_events)
ch.basic_ack(delivery_tag=rx_method.delivery_tag, multiple=False)
# Verify that the queue is now empty
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
# Attempt to consume again with a short timeout
connection.process_data_events(time_limit=0.005)
self.assertEqual(len(rx_messages), 2)
class TestPublishFromBasicConsumeCallback(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.basic_publish from basic_consume callback
"""
connection = self._connect()
ch = connection.channel()
src_q_name = (
'TestPublishFromBasicConsumeCallback_src_q' + uuid.uuid1().hex)
dest_q_name = (
'TestPublishFromBasicConsumeCallback_dest_q' + uuid.uuid1().hex)
# Place channel in publisher-acknowledgments mode so that publishing
# with mandatory=True will be synchronous
ch.confirm_delivery()
# Declare source and destination queues
ch.queue_declare(src_q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(src_q_name))
ch.queue_declare(dest_q_name, auto_delete=True)
self.addCleanup(lambda: self._connect().channel().queue_delete(dest_q_name))
# Deposit a message in the source queue
ch.basic_publish('',
routing_key=src_q_name,
body='via-publish',
mandatory=True)
# Create a consumer
def on_consume(channel, method, props, body):
channel.basic_publish(
'', routing_key=dest_q_name, body=body,
properties=props, mandatory=True)
channel.basic_ack(method.delivery_tag)
ch.basic_consume(src_q_name,
on_consume,
auto_ack=False,
exclusive=False,
arguments=None)
# Consume from destination queue
for _, _, rx_body in ch.consume(dest_q_name, auto_ack=True):
self.assertEqual(rx_body, as_bytes('via-publish'))
break
else:
self.fail('failed to consume a messages from destination q')
class TestStopConsumingFromBasicConsumeCallback(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.stop_consuming from basic_consume callback
"""
connection = self._connect()
ch = connection.channel()
q_name = (
'TestStopConsumingFromBasicConsumeCallback_q' + uuid.uuid1().hex)
# Place channel in publisher-acknowledgments mode so that publishing
# with mandatory=True will be synchronous
ch.confirm_delivery()
# Declare the queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(connection.channel().queue_delete, q_name)
# Deposit two messages in the queue
ch.basic_publish('',
routing_key=q_name,
body='via-publish1',
mandatory=True)
ch.basic_publish('',
routing_key=q_name,
body='via-publish2',
mandatory=True)
# Create a consumer
def on_consume(channel, method, props, body): # pylint: disable=W0613
channel.stop_consuming()
channel.basic_ack(method.delivery_tag)
ch.basic_consume(q_name,
on_consume,
auto_ack=False,
exclusive=False,
arguments=None)
ch.start_consuming()
ch.close()
ch = connection.channel()
# Verify that only the second message is present in the queue
_, _, rx_body = ch.basic_get(q_name)
self.assertEqual(rx_body, as_bytes('via-publish2'))
msg = ch.basic_get(q_name)
self.assertTupleEqual(msg, (None, None, None))
class TestCloseChannelFromBasicConsumeCallback(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.close from basic_consume callback
"""
connection = self._connect()
ch = connection.channel()
q_name = (
'TestCloseChannelFromBasicConsumeCallback_q' + uuid.uuid1().hex)
# Place channel in publisher-acknowledgments mode so that publishing
# with mandatory=True will be synchronous
ch.confirm_delivery()
# Declare the queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(connection.channel().queue_delete, q_name)
# Deposit two messages in the queue
ch.basic_publish('',
routing_key=q_name,
body='via-publish1',
mandatory=True)
ch.basic_publish('',
routing_key=q_name,
body='via-publish2',
mandatory=True)
# Create a consumer
def on_consume(channel, method, props, body): # pylint: disable=W0613
channel.close()
ch.basic_consume(q_name,
on_consume,
auto_ack=False,
exclusive=False,
arguments=None)
ch.start_consuming()
self.assertTrue(ch.is_closed)
# Verify that both messages are present in the queue
ch = connection.channel()
_, _, rx_body = ch.basic_get(q_name)
self.assertEqual(rx_body, as_bytes('via-publish1'))
_, _, rx_body = ch.basic_get(q_name)
self.assertEqual(rx_body, as_bytes('via-publish2'))
class TestCloseConnectionFromBasicConsumeCallback(BlockingTestCaseBase):
def test(self):
"""BlockingConnection.close from basic_consume callback
"""
connection = self._connect()
ch = connection.channel()
q_name = (
'TestCloseConnectionFromBasicConsumeCallback_q' + uuid.uuid1().hex)
# Place channel in publisher-acknowledgments mode so that publishing
# with mandatory=True will be synchronous
ch.confirm_delivery()
# Declare the queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Deposit two messages in the queue
ch.basic_publish('',
routing_key=q_name,
body='via-publish1',
mandatory=True)
ch.basic_publish('',
routing_key=q_name,
body='via-publish2',
mandatory=True)
# Create a consumer
def on_consume(channel, method, props, body): # pylint: disable=W0613
connection.close()
ch.basic_consume(q_name,
on_consume,
auto_ack=False,
exclusive=False,
arguments=None)
ch.start_consuming()
self.assertTrue(ch.is_closed)
self.assertTrue(connection.is_closed)
# Verify that both messages are present in the queue
ch = self._connect().channel()
_, _, rx_body = ch.basic_get(q_name)
self.assertEqual(rx_body, as_bytes('via-publish1'))
_, _, rx_body = ch.basic_get(q_name)
self.assertEqual(rx_body, as_bytes('via-publish2'))
class TestStartConsumingRaisesChannelClosedOnSameChannelFailure(BlockingTestCaseBase):
def test(self):
"""start_consuming() exits with ChannelClosed exception on same channel failure
"""
connection = self._connect()
# Fail test if exception leaks back ito I/O loop
self._instrument_io_loop_exception_leak_detection(connection)
ch = connection.channel()
q_name = (
'TestStartConsumingPassesChannelClosedOnSameChannelFailure_q' +
uuid.uuid1().hex)
# Declare the queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
ch.basic_consume(q_name,
lambda *args, **kwargs: None,
auto_ack=False,
exclusive=False,
arguments=None)
# Schedule a callback that will cause a channel error on the consumer's
# channel by publishing to an unknown exchange. This will cause the
# broker to close our channel.
connection.add_callback_threadsafe(
lambda: ch.basic_publish(
exchange=q_name,
routing_key='123',
body=b'Nope this is wrong'))
with self.assertRaises(pika.exceptions.ChannelClosedByBroker):
ch.start_consuming()
class TestStartConsumingReturnsAfterCancelFromBroker(BlockingTestCaseBase):
def test(self):
"""start_consuming() returns after Cancel from broker
"""
connection = self._connect()
ch = connection.channel()
q_name = (
'TestStartConsumingExitsOnCancelFromBroker_q' + uuid.uuid1().hex)
# Declare the queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
consumer_tag = ch.basic_consume(q_name,
lambda *args, **kwargs: None,
auto_ack=False,
exclusive=False,
arguments=None)
# Schedule a callback that will run while start_consuming() is
# executing and delete the queue. This will cause the broker to cancel
# our consumer
connection.add_callback_threadsafe(
lambda: self._connect().channel().queue_delete(q_name))
ch.start_consuming()
self.assertNotIn(consumer_tag, ch._consumer_infos)
class TestNonPubAckPublishAndConsumeHugeMessage(BlockingTestCaseBase):
def test(self):
"""BlockingChannel.publish/consume huge message"""
connection = self._connect()
ch = connection.channel()
q_name = 'TestPublishAndConsumeHugeMessage_q' + uuid.uuid1().hex
body = 'a' * 1000000
# Declare a new queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Publish a message to the queue by way of default exchange
ch.basic_publish(exchange='', routing_key=q_name, body=body)
LOGGER.info('Published message body size=%s', len(body))
# Consume the message
for rx_method, rx_props, rx_body in ch.consume(q_name, auto_ack=False,
exclusive=False,
arguments=None):
self.assertIsInstance(rx_method, pika.spec.Basic.Deliver)
self.assertEqual(rx_method.delivery_tag, 1)
self.assertFalse(rx_method.redelivered)
self.assertEqual(rx_method.exchange, '')
self.assertEqual(rx_method.routing_key, q_name)
self.assertIsInstance(rx_props, pika.BasicProperties)
self.assertEqual(rx_body, as_bytes(body))
# Ack the message
ch.basic_ack(delivery_tag=rx_method.delivery_tag, multiple=False)
break
# There shouldn't be any more events now
self.assertFalse(ch._queue_consumer_generator.pending_events)
# Verify that the queue is now empty
ch.close()
ch = connection.channel()
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
class TestNonPubAckPublishAndConsumeManyMessages(BlockingTestCaseBase):
def test(self):
"""BlockingChannel non-pub-ack publish/consume many messages"""
connection = self._connect()
ch = connection.channel()
q_name = ('TestNonPubackPublishAndConsumeManyMessages_q' +
uuid.uuid1().hex)
body = 'b' * 1024
num_messages_to_publish = 500
# Declare a new queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
for _ in pika.compat.xrange(num_messages_to_publish):
# Publish a message to the queue by way of default exchange
ch.basic_publish(exchange='', routing_key=q_name, body=body)
# Consume the messages
num_consumed = 0
for rx_method, rx_props, rx_body in ch.consume(q_name,
auto_ack=False,
exclusive=False,
arguments=None):
num_consumed += 1
self.assertIsInstance(rx_method, pika.spec.Basic.Deliver)
self.assertEqual(rx_method.delivery_tag, num_consumed)
self.assertFalse(rx_method.redelivered)
self.assertEqual(rx_method.exchange, '')
self.assertEqual(rx_method.routing_key, q_name)
self.assertIsInstance(rx_props, pika.BasicProperties)
self.assertEqual(rx_body, as_bytes(body))
# Ack the message
ch.basic_ack(delivery_tag=rx_method.delivery_tag, multiple=False)
if num_consumed >= num_messages_to_publish:
break
# There shouldn't be any more events now
self.assertFalse(ch._queue_consumer_generator.pending_events)
ch.close()
self.assertIsNone(ch._queue_consumer_generator)
# Verify that the queue is now empty
ch = connection.channel()
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
class TestBasicCancelWithNonAckableConsumer(BlockingTestCaseBase):
def test(self):
"""BlockingChannel user cancels non-ackable consumer via basic_cancel"""
connection = self._connect()
ch = connection.channel()
q_name = (
'TestBasicCancelWithNonAckableConsumer_q' + uuid.uuid1().hex)
body1 = 'a' * 1024
body2 = 'b' * 2048
# Declare a new queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Publish two messages to the queue by way of default exchange
ch.basic_publish(exchange='', routing_key=q_name, body=body1)
ch.basic_publish(exchange='', routing_key=q_name, body=body2)
# Wait for queue to contain both messages
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=2)
# Create a consumer that uses automatic ack mode
consumer_tag = ch.basic_consume(q_name, lambda *x: None, auto_ack=True,
exclusive=False, arguments=None)
# Wait for all messages to be sent by broker to client
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
# Cancel the consumer
messages = ch.basic_cancel(consumer_tag)
# Both messages should have been on their way when we cancelled
self.assertEqual(len(messages), 2)
_, _, rx_body1 = messages[0]
self.assertEqual(rx_body1, as_bytes(body1))
_, _, rx_body2 = messages[1]
self.assertEqual(rx_body2, as_bytes(body2))
ch.close()
ch = connection.channel()
# Verify that the queue is now empty
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
class TestBasicCancelWithAckableConsumer(BlockingTestCaseBase):
def test(self):
"""BlockingChannel user cancels ackable consumer via basic_cancel"""
connection = self._connect()
ch = connection.channel()
q_name = (
'TestBasicCancelWithAckableConsumer_q' + uuid.uuid1().hex)
body1 = 'a' * 1024
body2 = 'b' * 2048
# Declare a new queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Publish two messages to the queue by way of default exchange
ch.basic_publish(exchange='', routing_key=q_name, body=body1)
ch.basic_publish(exchange='', routing_key=q_name, body=body2)
# Wait for queue to contain both messages
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=2)
# Create an ackable consumer
consumer_tag = ch.basic_consume(q_name, lambda *x: None, auto_ack=False,
exclusive=False, arguments=None)
# Wait for all messages to be sent by broker to client
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=0)
# Cancel the consumer
messages = ch.basic_cancel(consumer_tag)
# Both messages should have been on their way when we cancelled
self.assertEqual(len(messages), 0)
ch.close()
ch = connection.channel()
# Verify that canceling the ackable consumer restored both messages
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=2)
class TestUnackedMessageAutoRestoredToQueueOnChannelClose(BlockingTestCaseBase):
def test(self):
"""BlockingChannel unacked message restored to q on channel close """
connection = self._connect()
ch = connection.channel()
q_name = ('TestUnackedMessageAutoRestoredToQueueOnChannelClose_q' +
uuid.uuid1().hex)
body1 = 'a' * 1024
body2 = 'b' * 2048
# Declare a new queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Publish two messages to the queue by way of default exchange
ch.basic_publish(exchange='', routing_key=q_name, body=body1)
ch.basic_publish(exchange='', routing_key=q_name, body=body2)
# Consume the events, but don't ack
rx_messages = []
ch.basic_consume(q_name, lambda *args: rx_messages.append(args),
auto_ack=False, exclusive=False, arguments=None)
while len(rx_messages) != 2:
connection.process_data_events(time_limit=None)
self.assertEqual(rx_messages[0][1].delivery_tag, 1)
self.assertEqual(rx_messages[1][1].delivery_tag, 2)
# Verify no more ready messages in queue
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
# Closing channel should restore messages back to queue
ch.close()
# Verify that there are two messages in q now
ch = connection.channel()
self._assert_exact_message_count_with_retries(channel=ch,
queue=q_name,
expected_count=2)
class TestNoAckMessageNotRestoredToQueueOnChannelClose(BlockingTestCaseBase):
def test(self):
"""BlockingChannel unacked message restored to q on channel close """
connection = self._connect()
ch = connection.channel()
q_name = ('TestNoAckMessageNotRestoredToQueueOnChannelClose_q' +
uuid.uuid1().hex)
body1 = 'a' * 1024
body2 = 'b' * 2048
# Declare a new queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Publish two messages to the queue by way of default exchange
ch.basic_publish(exchange='', routing_key=q_name, body=body1)
ch.basic_publish(exchange='', routing_key=q_name, body=body2)
# Consume, but don't ack
num_messages = 0
for rx_method, _, _ in ch.consume(q_name, auto_ack=True, exclusive=False):
num_messages += 1
self.assertEqual(rx_method.delivery_tag, num_messages)
if num_messages == 2:
break
else:
self.fail('expected 2 messages, but consumed %i' % (num_messages,))
# Verify no more ready messages in queue
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
# Closing channel should not restore no-ack messages back to queue
ch.close()
# Verify that there are no messages in q now
ch = connection.channel()
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.message_count, 0)
class TestConsumeGeneratorInactivityTimeout(BlockingTestCaseBase):
def test(self):
"""BlockingChannel consume returns 3-tuple of None values on inactivity timeout """
connection = self._connect()
ch = connection.channel()
q_name = ('TestConsumeGeneratorInactivityTimeout_q' + uuid.uuid1().hex)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
# Expect to get only (None, None, None) upon inactivity timeout, since
# there are no messages in queue
for msg in ch.consume(q_name, inactivity_timeout=0.1):
self.assertEqual(msg, (None, None, None))
break
else:
self.fail('expected (None, None, None), but iterator stopped')
class TestConsumeGeneratorInterruptedByCancelFromBroker(BlockingTestCaseBase):
def test(self):
"""BlockingChannel consume generator is interrupted broker's Cancel """
connection = self._connect()
self.assertTrue(connection.consumer_cancel_notify_supported)
ch = connection.channel()
q_name = ('TestConsumeGeneratorInterruptedByCancelFromBroker_q' +
uuid.uuid1().hex)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
queue_deleted = False
for _ in ch.consume(q_name, auto_ack=False, inactivity_timeout=0.001):
if not queue_deleted:
# Delete the queue to force Basic.Cancel from the broker
ch.queue_delete(q_name)
queue_deleted = True
self.assertIsNone(ch._queue_consumer_generator)
class TestConsumeGeneratorCancelEncountersCancelFromBroker(BlockingTestCaseBase):
def test(self):
"""BlockingChannel consume generator cancel called when broker's Cancel is enqueued """
connection = self._connect()
self.assertTrue(connection.consumer_cancel_notify_supported)
ch = connection.channel()
q_name = ('TestConsumeGeneratorCancelEncountersCancelFromBroker_q' +
uuid.uuid1().hex)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=True)
for _ in ch.consume(q_name, auto_ack=False, inactivity_timeout=0.001):
# Delete the queue to force Basic.Cancel from the broker
ch.queue_delete(q_name)
# Wait for server's Basic.Cancel
while not ch._queue_consumer_generator.pending_events:
connection.process_data_events()
# Confirm it's Basic.Cancel
self.assertIsInstance(ch._queue_consumer_generator.pending_events[0],
blocking_connection._ConsumerCancellationEvt)
# Now attempt to cancel the consumer generator
ch.cancel()
self.assertIsNone(ch._queue_consumer_generator)
class TestConsumeGeneratorPassesChannelClosedOnSameChannelFailure(BlockingTestCaseBase):
def test(self):
"""consume() exits with ChannelClosed exception on same channel failure
"""
connection = self._connect()
# Fail test if exception leaks back ito I/O loop
self._instrument_io_loop_exception_leak_detection(connection)
ch = connection.channel()
q_name = (
'TestConsumeGeneratorPassesChannelClosedOnSameChannelFailure_q' +
uuid.uuid1().hex)
# Declare the queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Schedule a callback that will cause a channel error on the consumer's
# channel by publishing to an unknown exchange. This will cause the
# broker to close our channel.
connection.add_callback_threadsafe(
lambda: ch.basic_publish(
exchange=q_name,
routing_key='123',
body=b'Nope this is wrong'))
with self.assertRaises(pika.exceptions.ChannelClosedByBroker):
for _ in ch.consume(q_name):
pass
class TestChannelFlow(BlockingTestCaseBase):
def test(self):
"""BlockingChannel Channel.Flow activate and deactivate """
connection = self._connect()
ch = connection.channel()
q_name = ('TestChannelFlow_q' + uuid.uuid1().hex)
# Declare a new queue
ch.queue_declare(q_name, auto_delete=False)
self.addCleanup(lambda: self._connect().channel().queue_delete(q_name))
# Verify zero active consumers on the queue
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.consumer_count, 0)
# Create consumer
ch.basic_consume(q_name, lambda *args: None)
# Verify one active consumer on the queue now
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.consumer_count, 1)
# Activate flow from default state (active by default)
active = ch.flow(True)
self.assertEqual(active, True)
# Verify still one active consumer on the queue now
frame = ch.queue_declare(q_name, passive=True)
self.assertEqual(frame.method.consumer_count, 1)
class TestChannelRaisesWrongStateWhenDeclaringQueueOnClosedChannel(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: Declaring queue on closed channel raises ChannelWrongStateError"""
q_name = (
'TestChannelRaisesWrongStateWhenDeclaringQueueOnClosedChannel_q' +
uuid.uuid1().hex)
channel = self._connect().channel()
channel.close()
with self.assertRaises(pika.exceptions.ChannelWrongStateError):
channel.queue_declare(q_name)
class TestChannelRaisesWrongStateWhenClosingClosedChannel(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: Closing closed channel raises ChannelWrongStateError"""
channel = self._connect().channel()
channel.close()
with self.assertRaises(pika.exceptions.ChannelWrongStateError):
channel.close()
class TestChannelContextManagerClosesChannel(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: chanel context manager exit survives closed channel"""
with self._connect().channel() as channel:
self.assertTrue(channel.is_open)
self.assertTrue(channel.is_closed)
class TestChannelContextManagerExitSurvivesClosedChannel(BlockingTestCaseBase):
def test(self):
"""BlockingConnection: chanel context manager exit survives closed channel"""
with self._connect().channel() as channel:
self.assertTrue(channel.is_open)
channel.close()
self.assertTrue(channel.is_closed)
self.assertTrue(channel.is_closed)
class TestChannelContextManagerDoesNotSuppressChannelClosedByBroker(
BlockingTestCaseBase):
def test(self):
"""BlockingConnection: chanel context manager doesn't suppress ChannelClosedByBroker exception"""
exg_name = (
"TestChannelContextManagerDoesNotSuppressChannelClosedByBroker" +
uuid.uuid1().hex)
with self.assertRaises(pika.exceptions.ChannelClosedByBroker):
with self._connect().channel() as channel:
# Passively declaring non-existent exchange should force broker
# to close channel
channel.exchange_declare(exg_name, passive=True)
self.assertTrue(channel.is_closed)
if __name__ == '__main__':
unittest.main()
|