1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559
|
#!/usr/bin/env python
#
# A library that provides a Python interface to the Telegram Bot API
# Copyright (C) 2015-2025
# Leandro Toledo de Souza <devs@python-telegram-bot.org>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program. If not, see [http://www.gnu.org/licenses/].
import asyncio
import copy
import datetime as dtm
import inspect
import logging
import pickle
import socket
import time
from collections import defaultdict
from http import HTTPStatus
from io import BytesIO
import httpx
import pytest
from telegram import (
Bot,
BotCommand,
BotCommandScopeChat,
BotDescription,
BotName,
BotShortDescription,
CallbackQuery,
Chat,
ChatAdministratorRights,
ChatFullInfo,
ChatInviteLink,
ChatPermissions,
Dice,
InlineKeyboardButton,
InlineKeyboardMarkup,
InlineQueryResultArticle,
InlineQueryResultDocument,
InlineQueryResultsButton,
InlineQueryResultVoice,
InputFile,
InputMediaDocument,
InputMediaPhoto,
InputMessageContent,
InputPollOption,
InputTextMessageContent,
LabeledPrice,
LinkPreviewOptions,
MenuButton,
MenuButtonCommands,
MenuButtonDefault,
MenuButtonWebApp,
Message,
MessageEntity,
Poll,
PollOption,
PreparedInlineMessage,
ReactionTypeCustomEmoji,
ReactionTypeEmoji,
ReplyParameters,
SentWebAppMessage,
ShippingOption,
StarTransaction,
StarTransactions,
Update,
User,
WebAppInfo,
)
from telegram._payment.stars.staramount import StarAmount
from telegram._utils.datetime import UTC, from_timestamp, localize, to_timestamp
from telegram._utils.defaultvalue import DEFAULT_NONE
from telegram._utils.strings import to_camel_case
from telegram.constants import (
ChatAction,
InlineQueryLimit,
InlineQueryResultType,
MenuButtonType,
ParseMode,
ReactionEmoji,
)
from telegram.error import BadRequest, EndPointNotFound, InvalidToken
from telegram.ext import ExtBot, InvalidCallbackData
from telegram.helpers import escape_markdown
from telegram.request import BaseRequest, HTTPXRequest, RequestData
from telegram.warnings import PTBUserWarning
from tests.auxil.bot_method_checks import check_defaults_handling
from tests.auxil.ci_bots import FALLBACKS
from tests.auxil.envvars import GITHUB_ACTIONS
from tests.auxil.files import data_file
from tests.auxil.networking import OfflineRequest, expect_bad_request
from tests.auxil.pytest_classes import PytestBot, PytestExtBot, make_bot
from tests.auxil.slots import mro_slots
from .auxil.build_messages import make_message
from .auxil.dummy_objects import get_dummy_object
@pytest.fixture
async def one_time_message(bot, chat_id):
# mostly used in tests for edit_message and hence can't be reused
return await bot.send_message(
chat_id, "Text", disable_web_page_preview=True, disable_notification=True
)
@pytest.fixture(scope="module")
async def static_message(bot, chat_id):
# must not be edited to keep tests independent! We only use bot.send_message so that
# we have a valid message_id to e.g. reply to
return await bot.send_message(
chat_id, "Text", disable_web_page_preview=True, disable_notification=True
)
@pytest.fixture
async def media_message(bot, chat_id):
# mostly used in tests for edit_message and hence can't be reused
with data_file("telegram.ogg").open("rb") as f:
return await bot.send_voice(chat_id, voice=f, caption="my caption", read_timeout=10)
@pytest.fixture(scope="module")
def chat_permissions():
return ChatPermissions(can_send_messages=False, can_change_info=False, can_invite_users=False)
def inline_results_callback(page=None):
if not page:
return [InlineQueryResultArticle(i, str(i), None) for i in range(1, 254)]
if page <= 5:
return [
InlineQueryResultArticle(i, str(i), None)
for i in range(page * 5 + 1, (page + 1) * 5 + 1)
]
return None
@pytest.fixture(scope="module")
def inline_results():
return inline_results_callback()
BASE_GAME_SCORE = 60 # Base game score for game tests
xfail = pytest.mark.xfail(
GITHUB_ACTIONS, # This condition is only relevant for github actions game tests.
reason=(
"Can fail due to race conditions when multiple test suites "
"with the same bot token are run at the same time"
),
)
def bot_methods(ext_bot=True, include_camel_case=False, include_do_api_request=False):
arg_values = []
ids = []
non_api_methods = [
"de_json",
"de_list",
"to_dict",
"to_json",
"parse_data",
"get_bot",
"set_bot",
"initialize",
"shutdown",
"insert_callback_data",
]
if not include_do_api_request:
non_api_methods.append("do_api_request")
classes = (Bot, ExtBot) if ext_bot else (Bot,)
for cls in classes:
for name, attribute in inspect.getmembers(cls, predicate=inspect.isfunction):
if name.startswith("_") or name in non_api_methods:
continue
if not include_camel_case and any(x.isupper() for x in name):
continue
arg_values.append((cls, name, attribute))
ids.append(f"{cls.__name__}.{name}")
return pytest.mark.parametrize(
argnames=("bot_class", "bot_method_name", "bot_method"), argvalues=arg_values, ids=ids
)
class InputMessageContentLPO(InputMessageContent):
"""
This is here to cover the case of InputMediaContent classes in testing answer_ilq that have
`link_preview_options` but not `parse_mode`. Unlikely to ever happen, but better be save
than sorry …
"""
__slots__ = ("entities", "link_preview_options", "message_text", "parse_mode")
def __init__(
self,
message_text: str,
link_preview_options=DEFAULT_NONE,
*,
api_kwargs=None,
):
super().__init__(api_kwargs=api_kwargs)
self._unfreeze()
self.message_text = message_text
self.link_preview_options = link_preview_options
class TestBotWithoutRequest:
"""
Most are executed on tg.ext.ExtBot, as that class only extends the functionality of tg.bot
Behavior for init of ExtBot with missing optional dependency cachetools (for CallbackDataCache)
is tested in `test_callbackdatacache`
"""
test_flag = None
@pytest.fixture(autouse=True)
def _reset(self):
self.test_flag = None
@pytest.mark.parametrize("bot_class", [Bot, ExtBot])
def test_slot_behaviour(self, bot_class, offline_bot):
inst = bot_class(
offline_bot.token, request=OfflineRequest(1), get_updates_request=OfflineRequest(1)
)
for attr in inst.__slots__:
assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot"
async def test_no_token_passed(self):
with pytest.raises(InvalidToken, match="You must pass the token"):
Bot("")
def test_base_url_parsing_basic(self, caplog):
with caplog.at_level(logging.DEBUG):
bot = Bot(
token="!!Test String!!",
base_url="base/",
base_file_url="base/",
request=OfflineRequest(1),
get_updates_request=OfflineRequest(1),
)
assert bot.base_url == "base/!!Test String!!"
assert bot.base_file_url == "base/!!Test String!!"
assert len(caplog.records) >= 2
messages = [record.getMessage() for record in caplog.records]
assert "Set Bot API URL: base/!!Test String!!" in messages
assert "Set Bot API File URL: base/!!Test String!!" in messages
@pytest.mark.parametrize(
"insert_key", ["token", "TOKEN", "bot_token", "BOT_TOKEN", "bot-token", "BOT-TOKEN"]
)
def test_base_url_parsing_string_format(self, insert_key, caplog):
string = f"{{{insert_key}}}"
with caplog.at_level(logging.DEBUG):
bot = Bot(
token="!!Test String!!",
base_url=string,
base_file_url=string,
request=OfflineRequest(1),
get_updates_request=OfflineRequest(1),
)
assert bot.base_url == "!!Test String!!"
assert bot.base_file_url == "!!Test String!!"
assert len(caplog.records) >= 2
messages = [record.getMessage() for record in caplog.records]
assert "Set Bot API URL: !!Test String!!" in messages
assert "Set Bot API File URL: !!Test String!!" in messages
with pytest.raises(KeyError, match="unsupported insertion: unknown"):
Bot("token", base_url="{unknown}{token}")
def test_base_url_parsing_callable(self, caplog):
def build_url(_: str) -> str:
return "!!Test String!!"
with caplog.at_level(logging.DEBUG):
bot = Bot(
token="some-token",
base_url=build_url,
base_file_url=build_url,
request=OfflineRequest(1),
get_updates_request=OfflineRequest(1),
)
assert bot.base_url == "!!Test String!!"
assert bot.base_file_url == "!!Test String!!"
assert len(caplog.records) >= 2
messages = [record.getMessage() for record in caplog.records]
assert "Set Bot API URL: !!Test String!!" in messages
assert "Set Bot API File URL: !!Test String!!" in messages
async def test_repr(self):
offline_bot = Bot(token="some_token", base_file_url="")
assert repr(offline_bot) == "Bot[token=some_token]"
async def test_to_dict(self, offline_bot):
to_dict_bot = offline_bot.to_dict()
assert isinstance(to_dict_bot, dict)
assert to_dict_bot["id"] == offline_bot.id
assert to_dict_bot["username"] == offline_bot.username
assert to_dict_bot["first_name"] == offline_bot.first_name
if offline_bot.last_name:
assert to_dict_bot["last_name"] == offline_bot.last_name
async def test_initialize_and_shutdown(self, offline_bot: PytestExtBot, monkeypatch):
async def initialize(*args, **kwargs):
self.test_flag = ["initialize"]
async def stop(*args, **kwargs):
self.test_flag.append("stop")
temp_bot = PytestBot(token=offline_bot.token, request=OfflineRequest())
orig_stop = temp_bot.request.shutdown
try:
monkeypatch.setattr(temp_bot.request, "initialize", initialize)
monkeypatch.setattr(temp_bot.request, "shutdown", stop)
await temp_bot.initialize()
assert self.test_flag == ["initialize"]
assert temp_bot.bot == offline_bot.bot
await temp_bot.shutdown()
assert self.test_flag == ["initialize", "stop"]
finally:
await orig_stop()
async def test_multiple_inits_and_shutdowns(self, offline_bot, monkeypatch):
self.received = defaultdict(int)
async def initialize(*args, **kwargs):
self.received["init"] += 1
async def shutdown(*args, **kwargs):
self.received["shutdown"] += 1
monkeypatch.setattr(HTTPXRequest, "initialize", initialize)
monkeypatch.setattr(HTTPXRequest, "shutdown", shutdown)
test_bot = PytestBot(offline_bot.token)
await test_bot.initialize()
await test_bot.initialize()
await test_bot.initialize()
await test_bot.shutdown()
await test_bot.shutdown()
await test_bot.shutdown()
# 2 instead of 1 since we have to request objects for each offline_bot
assert self.received["init"] == 2
assert self.received["shutdown"] == 2
async def test_context_manager(self, monkeypatch, offline_bot):
async def initialize():
self.test_flag = ["initialize"]
async def shutdown(*args):
self.test_flag.append("stop")
monkeypatch.setattr(offline_bot, "initialize", initialize)
monkeypatch.setattr(offline_bot, "shutdown", shutdown)
async with offline_bot:
pass
assert self.test_flag == ["initialize", "stop"]
async def test_context_manager_exception_on_init(self, monkeypatch, offline_bot):
async def initialize():
raise RuntimeError("initialize")
async def shutdown():
self.test_flag = "stop"
monkeypatch.setattr(offline_bot, "initialize", initialize)
monkeypatch.setattr(offline_bot, "shutdown", shutdown)
with pytest.raises(RuntimeError, match="initialize"):
async with offline_bot:
pass
assert self.test_flag == "stop"
async def test_shutdown_at_error_in_request_in_init(self, monkeypatch, offline_bot):
async def get_me_error():
raise httpx.HTTPError("BadRequest wrong token sry :(")
async def shutdown(*args):
self.test_flag = "stop"
monkeypatch.setattr(offline_bot, "get_me", get_me_error)
monkeypatch.setattr(offline_bot, "shutdown", shutdown)
async with offline_bot:
pass
assert self.test_flag == "stop"
async def test_equality(self):
async with (
make_bot(token=FALLBACKS[0]["token"]) as a,
make_bot(token=FALLBACKS[0]["token"]) as b,
Bot(token=FALLBACKS[0]["token"]) as c,
make_bot(token=FALLBACKS[1]["token"]) as d,
):
e = Update(123456789)
f = Bot(token=FALLBACKS[0]["token"])
assert a == b
assert hash(a) == hash(b)
assert a is not b
assert a == c
assert hash(a) == hash(c)
assert a != d
assert hash(a) != hash(d)
assert a != e
assert hash(a) != hash(e)
# We cant check equality for unintialized Bot object
assert hash(a) != hash(f)
@pytest.mark.parametrize(
"attribute",
[
"id",
"username",
"first_name",
"last_name",
"name",
"can_join_groups",
"can_read_all_group_messages",
"supports_inline_queries",
"link",
],
)
async def test_get_me_and_properties_not_initialized(self, attribute):
bot = make_bot(offline=True, token="randomtoken")
try:
with pytest.raises(RuntimeError, match="not properly initialized"):
bot[attribute]
finally:
await bot.shutdown()
async def test_get_me_and_properties(self, offline_bot):
get_me_bot = await ExtBot(offline_bot.token).get_me()
assert isinstance(get_me_bot, User)
assert get_me_bot.id == offline_bot.id
assert get_me_bot.username == offline_bot.username
assert get_me_bot.first_name == offline_bot.first_name
assert get_me_bot.last_name == offline_bot.last_name
assert get_me_bot.name == offline_bot.name
assert get_me_bot.can_join_groups == offline_bot.can_join_groups
assert get_me_bot.can_read_all_group_messages == offline_bot.can_read_all_group_messages
assert get_me_bot.supports_inline_queries == offline_bot.supports_inline_queries
assert f"https://t.me/{get_me_bot.username}" == offline_bot.link
def test_bot_pickling_error(self, offline_bot):
with pytest.raises(pickle.PicklingError, match="Bot objects cannot be pickled"):
pickle.dumps(offline_bot)
def test_bot_deepcopy_error(self, offline_bot):
with pytest.raises(TypeError, match="Bot objects cannot be deepcopied"):
copy.deepcopy(offline_bot)
@pytest.mark.parametrize(
("cls", "logger_name"), [(Bot, "telegram.Bot"), (ExtBot, "telegram.ext.ExtBot")]
)
async def test_bot_method_logging(self, offline_bot: PytestExtBot, cls, logger_name, caplog):
instance = cls(offline_bot.token)
# Second argument makes sure that we ignore logs from e.g. httpx
with caplog.at_level(logging.DEBUG, logger="telegram"):
await instance.get_me()
# Only for stabilizing this test-
if len(caplog.records) == 4:
for idx, record in enumerate(caplog.records):
print(record)
if record.getMessage().startswith("Task was destroyed but it is pending"):
caplog.records.pop(idx)
if record.getMessage().startswith("Task exception was never retrieved"):
caplog.records.pop(idx)
assert len(caplog.records) == 2
assert all(caplog.records[i].name == logger_name for i in [-1, 0])
assert (
caplog.records[0]
.getMessage()
.startswith("Calling Bot API endpoint `getMe` with parameters `{}`")
)
assert (
caplog.records[-1]
.getMessage()
.startswith("Call to Bot API endpoint `getMe` finished with return value")
)
@bot_methods()
def test_camel_case_aliases(self, bot_class, bot_method_name, bot_method):
camel_case_name = to_camel_case(bot_method_name)
camel_case_function = getattr(bot_class, camel_case_name, False)
assert camel_case_function is not False, f"{camel_case_name} not found"
assert camel_case_function is bot_method, f"{camel_case_name} is not {bot_method}"
@bot_methods(include_do_api_request=True)
def test_coroutine_functions(self, bot_class, bot_method_name, bot_method):
"""Check that all offline_bot methods are defined as async def ..."""
meth = getattr(bot_method, "__wrapped__", bot_method) # to unwrap the @_log decorator
assert inspect.iscoroutinefunction(meth), f"{bot_method_name} must be a coroutine function"
@bot_methods(include_do_api_request=True)
def test_api_kwargs_and_timeouts_present(self, bot_class, bot_method_name, bot_method):
"""Check that all offline_bot methods have `api_kwargs` and timeout params."""
param_names = inspect.signature(bot_method).parameters.keys()
params = ("pool_timeout", "read_timeout", "connect_timeout", "write_timeout", "api_kwargs")
for param in params:
assert param in param_names, f"{bot_method_name} is missing the parameter `{param}`"
rate_arg = "rate_limit_args"
if bot_method_name.replace("_", "").lower() != "getupdates" and bot_class is ExtBot:
assert rate_arg in param_names, f"{bot_method} is missing the parameter `{rate_arg}`"
@bot_methods()
async def test_defaults_handling(
self,
bot_class,
bot_method_name: str,
bot_method,
offline_bot: PytestExtBot,
raw_bot: PytestBot,
):
"""
Here we check that the offline_bot methods handle tg.ext.Defaults correctly. This has two
parts:
1. Check that ExtBot actually inserts the defaults values correctly
2. Check that tg.Bot just replaces `DefaultValue(obj)` with `obj`, i.e. that it doesn't
pass any `DefaultValue` instances to Request. See the docstring of
tg.Bot._insert_defaults for details on why we need that
As for most defaults,
we can't really check the effect, we just check if we're passing the correct kwargs to
Request.post. As offline_bot method tests a scattered across the different test files, we
do this here in one place.
The same test is also run for all the shortcuts (Message.reply_text) etc in the
corresponding tests.
Finally, there are some tests for Defaults.{parse_mode, quote, allow_sending_without_reply}
at the appropriate places, as those are the only things we can actually check.
"""
# Check that ExtBot does the right thing
bot_method = getattr(offline_bot, bot_method_name)
raw_bot_method = getattr(raw_bot, bot_method_name)
assert await check_defaults_handling(bot_method, offline_bot)
assert await check_defaults_handling(raw_bot_method, raw_bot)
@pytest.mark.parametrize(
("name", "method"), inspect.getmembers(Bot, predicate=inspect.isfunction)
)
def test_ext_bot_signature(self, name, method):
"""
Here we make sure that all methods of ext.ExtBot have the same signature as the
corresponding methods of tg.Bot.
"""
# Some methods of ext.ExtBot
global_extra_args = {"rate_limit_args"}
extra_args_per_method = defaultdict(
set, {"__init__": {"arbitrary_callback_data", "defaults", "rate_limiter"}}
)
different_hints_per_method = defaultdict(set, {"__setattr__": {"ext_bot"}})
signature = inspect.signature(method)
ext_signature = inspect.signature(getattr(ExtBot, name))
assert (
ext_signature.return_annotation == signature.return_annotation
), f"Wrong return annotation for method {name}"
assert (
set(signature.parameters)
== set(ext_signature.parameters) - global_extra_args - extra_args_per_method[name]
), f"Wrong set of parameters for method {name}"
for param_name, param in signature.parameters.items():
if param_name in different_hints_per_method[name]:
continue
assert (
param.annotation == ext_signature.parameters[param_name].annotation
), f"Wrong annotation for parameter {param_name} of method {name}"
assert (
param.default == ext_signature.parameters[param_name].default
), f"Wrong default value for parameter {param_name} of method {name}"
assert (
param.kind == ext_signature.parameters[param_name].kind
), f"Wrong parameter kind for parameter {param_name} of method {name}"
async def test_unknown_kwargs(self, offline_bot, monkeypatch):
async def post(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters
if not all([data["unknown_kwarg_1"] == "7", data["unknown_kwarg_2"] == "5"]):
pytest.fail("got wrong parameters")
return True
monkeypatch.setattr(offline_bot.request, "post", post)
await offline_bot.send_message(
123, "text", api_kwargs={"unknown_kwarg_1": 7, "unknown_kwarg_2": 5}
)
async def test_get_updates_deserialization_error(self, offline_bot, monkeypatch, caplog):
async def faulty_do_request(*args, **kwargs):
return (
HTTPStatus.OK,
b'{"ok": true, "result": [{"update_id": "1", "message": "unknown_format"}]}',
)
monkeypatch.setattr(HTTPXRequest, "do_request", faulty_do_request)
offline_bot = PytestExtBot(get_updates_request=HTTPXRequest(), token=offline_bot.token)
with caplog.at_level(logging.CRITICAL), pytest.raises(AttributeError):
await offline_bot.get_updates()
assert len(caplog.records) == 1
assert caplog.records[0].name == "telegram.ext.ExtBot"
assert caplog.records[0].levelno == logging.CRITICAL
assert caplog.records[0].getMessage() == (
"Error while parsing updates! Received data was "
"[{'update_id': '1', 'message': 'unknown_format'}]"
)
assert caplog.records[0].exc_info[0] is AttributeError
async def test_answer_web_app_query(self, offline_bot, raw_bot, monkeypatch):
params = False
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
nonlocal params
params = request_data.parameters == {
"web_app_query_id": "12345",
"result": {
"title": "title",
"input_message_content": {
"message_text": "text",
},
"type": InlineQueryResultType.ARTICLE,
"id": "1",
},
}
return SentWebAppMessage("321").to_dict()
# We test different result types more thoroughly for answer_inline_query, so we just
# use the one type here
result = InlineQueryResultArticle("1", "title", InputTextMessageContent("text"))
copied_result = copy.copy(result)
ext_bot = offline_bot
for bot_type in (ext_bot, raw_bot):
# We need to test 1) below both the offline_bot and raw_bot and setting this up with
# pytest.parametrize appears to be difficult ...
monkeypatch.setattr(bot_type.request, "post", make_assertion)
web_app_msg = await bot_type.answer_web_app_query("12345", result)
assert params, "something went wrong with passing arguments to the request"
assert isinstance(web_app_msg, SentWebAppMessage)
assert web_app_msg.inline_message_id == "321"
# 1)
# make sure that the results were not edited in-place
assert result == copied_result
assert (
result.input_message_content.parse_mode
== copied_result.input_message_content.parse_mode
)
@pytest.mark.parametrize(
"default_bot",
[{"parse_mode": "Markdown", "link_preview_options": LinkPreviewOptions(is_disabled=True)}],
indirect=True,
)
@pytest.mark.parametrize(
("ilq_result", "expected_params"),
[
(
InlineQueryResultArticle("1", "title", InputTextMessageContent("text")),
{
"web_app_query_id": "12345",
"result": {
"title": "title",
"input_message_content": {
"message_text": "text",
"parse_mode": "Markdown",
"link_preview_options": {
"is_disabled": True,
},
},
"type": InlineQueryResultType.ARTICLE,
"id": "1",
},
},
),
(
InlineQueryResultArticle(
"1",
"title",
InputTextMessageContent(
"text", parse_mode="HTML", disable_web_page_preview=False
),
),
{
"web_app_query_id": "12345",
"result": {
"title": "title",
"input_message_content": {
"message_text": "text",
"parse_mode": "HTML",
"link_preview_options": {
"is_disabled": False,
},
},
"type": InlineQueryResultType.ARTICLE,
"id": "1",
},
},
),
(
InlineQueryResultArticle(
"1",
"title",
InputTextMessageContent(
"text", parse_mode=None, disable_web_page_preview="False"
),
),
{
"web_app_query_id": "12345",
"result": {
"title": "title",
"input_message_content": {
"message_text": "text",
"link_preview_options": {
"is_disabled": "False",
},
},
"type": InlineQueryResultType.ARTICLE,
"id": "1",
},
},
),
],
)
async def test_answer_web_app_query_defaults(
self, default_bot, ilq_result, expected_params, monkeypatch
):
offline_bot = default_bot
params = False
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
nonlocal params
params = request_data.parameters == expected_params
return SentWebAppMessage("321").to_dict()
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
# We test different result types more thoroughly for answer_inline_query, so we just
# use the one type here
copied_result = copy.copy(ilq_result)
web_app_msg = await offline_bot.answer_web_app_query("12345", ilq_result)
assert params, "something went wrong with passing arguments to the request"
assert isinstance(web_app_msg, SentWebAppMessage)
assert web_app_msg.inline_message_id == "321"
# make sure that the results were not edited in-place
assert ilq_result == copied_result
assert (
ilq_result.input_message_content.parse_mode
== copied_result.input_message_content.parse_mode
)
# TODO: Needs improvement. We need incoming inline query to test answer.
@pytest.mark.parametrize("button_type", ["start", "web_app"])
@pytest.mark.parametrize("cache_time", [74, dtm.timedelta(seconds=74)])
async def test_answer_inline_query(
self, monkeypatch, offline_bot, raw_bot, button_type, cache_time
):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
expected = {
"cache_time": 74,
"results": [
{
"title": "first",
"id": "11",
"type": "article",
"input_message_content": {"message_text": "first"},
},
{
"title": "second",
"id": "12",
"type": "article",
"input_message_content": {"message_text": "second"},
},
{
"title": "test_result",
"id": "123",
"type": "document",
"document_url": (
"https://raw.githubusercontent.com/python-telegram-bot"
"/logos/master/logo/png/ptb-logo_240.png"
),
"mime_type": "image/png",
"caption": "ptb_logo",
"input_message_content": {"message_text": "imc"},
},
],
"next_offset": "42",
"inline_query_id": 1234,
"is_personal": True,
}
if button_type == "start":
button_dict = {"text": "button_text", "start_parameter": "start_parameter"}
else:
button_dict = {
"text": "button_text",
"web_app": {"url": "https://python-telegram-bot.org"},
}
expected["button"] = button_dict
return request_data.parameters == expected
results = [
InlineQueryResultArticle("11", "first", InputTextMessageContent("first")),
InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")),
InlineQueryResultDocument(
id="123",
document_url=(
"https://raw.githubusercontent.com/python-telegram-bot/logos/master/"
"logo/png/ptb-logo_240.png"
),
title="test_result",
mime_type="image/png",
caption="ptb_logo",
input_message_content=InputMessageContentLPO("imc"),
),
]
if button_type == "start":
button = InlineQueryResultsButton(
text="button_text", start_parameter="start_parameter"
)
elif button_type == "web_app":
button = InlineQueryResultsButton(
text="button_text", web_app=WebAppInfo("https://python-telegram-bot.org")
)
else:
button = None
copied_results = copy.copy(results)
ext_bot = offline_bot
for bot_type in (ext_bot, raw_bot):
# We need to test 1) below both the offline_bot and raw_bot and setting this up with
# pytest.parametrize appears to be difficult ...
monkeypatch.setattr(bot_type.request, "post", make_assertion)
assert await bot_type.answer_inline_query(
1234,
results=results,
cache_time=cache_time,
is_personal=True,
next_offset="42",
button=button,
)
# 1)
# make sure that the results were not edited in-place
assert results == copied_results
for idx, result in enumerate(results):
if hasattr(result, "parse_mode"):
assert result.parse_mode == copied_results[idx].parse_mode
if hasattr(result, "input_message_content"):
assert getattr(result.input_message_content, "parse_mode", None) == getattr(
copied_results[idx].input_message_content, "parse_mode", None
)
assert getattr(
result.input_message_content, "disable_web_page_preview", None
) == getattr(
copied_results[idx].input_message_content, "disable_web_page_preview", None
)
monkeypatch.delattr(bot_type.request, "post")
async def test_answer_inline_query_no_default_parse_mode(self, monkeypatch, offline_bot):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters == {
"cache_time": 300,
"results": [
{
"title": "first",
"id": "11",
"type": "article",
"input_message_content": {"message_text": "first"},
},
{
"title": "second",
"id": "12",
"type": "article",
"input_message_content": {"message_text": "second"},
},
{
"title": "test_result",
"id": "123",
"type": "document",
"document_url": (
"https://raw.githubusercontent.com/"
"python-telegram-bot/logos/master/logo/png/"
"ptb-logo_240.png"
),
"mime_type": "image/png",
"caption": "ptb_logo",
"input_message_content": {"message_text": "imc"},
},
],
"next_offset": "42",
"inline_query_id": 1234,
"is_personal": True,
}
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
results = [
InlineQueryResultArticle("11", "first", InputTextMessageContent("first")),
InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")),
InlineQueryResultDocument(
id="123",
document_url=(
"https://raw.githubusercontent.com/python-telegram-bot/logos/master/"
"logo/png/ptb-logo_240.png"
),
title="test_result",
mime_type="image/png",
caption="ptb_logo",
input_message_content=InputMessageContentLPO("imc"),
),
]
copied_results = copy.copy(results)
assert await offline_bot.answer_inline_query(
1234,
results=results,
cache_time=300,
is_personal=True,
next_offset="42",
)
# make sure that the results were not edited in-place
assert results == copied_results
for idx, result in enumerate(results):
if hasattr(result, "parse_mode"):
assert result.parse_mode == copied_results[idx].parse_mode
if hasattr(result, "input_message_content"):
assert getattr(result.input_message_content, "parse_mode", None) == getattr(
copied_results[idx].input_message_content, "parse_mode", None
)
assert getattr(
result.input_message_content, "disable_web_page_preview", None
) == getattr(
copied_results[idx].input_message_content, "disable_web_page_preview", None
)
@pytest.mark.parametrize(
"default_bot",
[{"parse_mode": "Markdown", "link_preview_options": LinkPreviewOptions(is_disabled=True)}],
indirect=True,
)
async def test_answer_inline_query_default_parse_mode(self, monkeypatch, default_bot):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters == {
"cache_time": 300,
"results": [
{
"title": "first",
"id": "11",
"type": InlineQueryResultType.ARTICLE,
"input_message_content": {
"message_text": "first",
"parse_mode": "Markdown",
"link_preview_options": {
"is_disabled": True,
},
},
},
{
"title": "second",
"id": "12",
"type": InlineQueryResultType.ARTICLE,
"input_message_content": {
"message_text": "second",
"link_preview_options": {
"is_disabled": True,
},
},
},
{
"title": "test_result",
"id": "123",
"type": InlineQueryResultType.DOCUMENT,
"document_url": (
"https://raw.githubusercontent.com/"
"python-telegram-bot/logos/master/logo/png/"
"ptb-logo_240.png"
),
"mime_type": "image/png",
"caption": "ptb_logo",
"parse_mode": "Markdown",
"input_message_content": {
"message_text": "imc",
"link_preview_options": {
"is_disabled": True,
},
"parse_mode": "Markdown",
},
},
],
"next_offset": "42",
"inline_query_id": 1234,
"is_personal": True,
}
monkeypatch.setattr(default_bot.request, "post", make_assertion)
results = [
InlineQueryResultArticle("11", "first", InputTextMessageContent("first")),
InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")),
InlineQueryResultDocument(
id="123",
document_url=(
"https://raw.githubusercontent.com/python-telegram-bot/logos/master/"
"logo/png/ptb-logo_240.png"
),
title="test_result",
mime_type="image/png",
caption="ptb_logo",
input_message_content=InputTextMessageContent("imc"),
),
]
copied_results = copy.copy(results)
assert await default_bot.answer_inline_query(
1234,
results=results,
cache_time=300,
is_personal=True,
next_offset="42",
)
# make sure that the results were not edited in-place
assert results == copied_results
for idx, result in enumerate(results):
if hasattr(result, "parse_mode"):
assert result.parse_mode == copied_results[idx].parse_mode
if hasattr(result, "input_message_content"):
assert getattr(result.input_message_content, "parse_mode", None) == getattr(
copied_results[idx].input_message_content, "parse_mode", None
)
assert getattr(
result.input_message_content, "disable_web_page_preview", None
) == getattr(
copied_results[idx].input_message_content, "disable_web_page_preview", None
)
@pytest.mark.parametrize(
("current_offset", "num_results", "id_offset", "expected_next_offset"),
[
("", InlineQueryLimit.RESULTS, 1, 1),
(1, InlineQueryLimit.RESULTS, 51, 2),
(5, 3, 251, ""),
],
)
async def test_answer_inline_query_current_offset_1(
self,
monkeypatch,
offline_bot,
inline_results,
current_offset,
num_results,
id_offset,
expected_next_offset,
):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
results = data["results"]
length_matches = len(results) == num_results
ids_match = all(int(res["id"]) == id_offset + i for i, res in enumerate(results))
next_offset_matches = data["next_offset"] == str(expected_next_offset)
return length_matches and ids_match and next_offset_matches
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.answer_inline_query(
1234, results=inline_results, current_offset=current_offset
)
async def test_answer_inline_query_current_offset_2(
self, monkeypatch, offline_bot, inline_results
):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
results = data["results"]
length_matches = len(results) == InlineQueryLimit.RESULTS
ids_match = all(int(res["id"]) == 1 + i for i, res in enumerate(results))
next_offset_matches = data["next_offset"] == "1"
return length_matches and ids_match and next_offset_matches
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.answer_inline_query(
1234, results=inline_results, current_offset=0
)
inline_results = inline_results[:30]
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
results = data["results"]
length_matches = len(results) == 30
ids_match = all(int(res["id"]) == 1 + i for i, res in enumerate(results))
next_offset_matches = not data["next_offset"]
return length_matches and ids_match and next_offset_matches
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.answer_inline_query(
1234, results=inline_results, current_offset=0
)
async def test_answer_inline_query_current_offset_callback(self, monkeypatch, offline_bot):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
results = data["results"]
length = len(results) == 5
ids = all(int(res["id"]) == 6 + i for i, res in enumerate(results))
next_offset = data["next_offset"] == "2"
return length and ids and next_offset
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.answer_inline_query(
1234, results=inline_results_callback, current_offset=1
)
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
results = data["results"]
length = results == []
next_offset = not data["next_offset"]
return length and next_offset
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.answer_inline_query(
1234, results=inline_results_callback, current_offset=6
)
async def test_send_edit_message_mutually_exclusive_link_preview(self, offline_bot, chat_id):
"""Test that link_preview is mutually exclusive with disable_web_page_preview."""
with pytest.raises(ValueError, match="`link_preview_options` are mutually exclusive"):
await offline_bot.send_message(
chat_id, "text", disable_web_page_preview=True, link_preview_options="something"
)
with pytest.raises(ValueError, match="`link_preview_options` are mutually exclusive"):
await offline_bot.edit_message_text(
"text", chat_id, 1, disable_web_page_preview=True, link_preview_options="something"
)
async def test_rtm_aswr_mutually_exclusive_reply_parameters(self, offline_bot, chat_id):
"""Test that reply_to_message_id and allow_sending_without_reply are mutually exclusive
with reply_parameters."""
with pytest.raises(ValueError, match="`reply_to_message_id` and"):
await offline_bot.send_message(
chat_id, "text", reply_to_message_id=1, reply_parameters=True
)
with pytest.raises(ValueError, match="`allow_sending_without_reply` and"):
await offline_bot.send_message(
chat_id, "text", allow_sending_without_reply=True, reply_parameters=True
)
# Test with copy message
with pytest.raises(ValueError, match="`reply_to_message_id` and"):
await offline_bot.copy_message(
chat_id, chat_id, 1, reply_to_message_id=1, reply_parameters=True
)
with pytest.raises(ValueError, match="`allow_sending_without_reply` and"):
await offline_bot.copy_message(
chat_id, chat_id, 1, allow_sending_without_reply=True, reply_parameters=True
)
# Test with send media group
media = InputMediaPhoto("")
with pytest.raises(ValueError, match="`reply_to_message_id` and"):
await offline_bot.send_media_group(
chat_id, media, reply_to_message_id=1, reply_parameters=True
)
with pytest.raises(ValueError, match="`allow_sending_without_reply` and"):
await offline_bot.send_media_group(
chat_id, media, allow_sending_without_reply=True, reply_parameters=True
)
# get_file is tested multiple times in the test_*media* modules.
# Here we only test the behaviour for offline_bot apis in local mode
async def test_get_file_local_mode(self, offline_bot, monkeypatch):
path = str(data_file("game.gif"))
async def make_assertion(*args, **kwargs):
return {
"file_id": None,
"file_unique_id": None,
"file_size": None,
"file_path": path,
}
monkeypatch.setattr(offline_bot, "_post", make_assertion)
resulting_path = (await offline_bot.get_file("file_id")).file_path
assert offline_bot.token not in resulting_path
assert resulting_path == path
# TODO: Needs improvement. No feasible way to test until bots can add members.
async def test_ban_chat_member(self, monkeypatch, offline_bot):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters
chat_id = data["chat_id"] == "2"
user_id = data["user_id"] == "32"
until_date = data.get("until_date", "1577887200") == "1577887200"
revoke_msgs = data.get("revoke_messages", "true") == "true"
return chat_id and user_id and until_date and revoke_msgs
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
until = from_timestamp(1577887200)
assert await offline_bot.ban_chat_member(2, 32)
assert await offline_bot.ban_chat_member(2, 32, until_date=until)
assert await offline_bot.ban_chat_member(2, 32, until_date=1577887200)
assert await offline_bot.ban_chat_member(2, 32, revoke_messages=True)
async def test_ban_chat_member_default_tz(self, monkeypatch, tz_bot):
until = dtm.datetime(2020, 1, 11, 16, 13)
until_timestamp = to_timestamp(until, tzinfo=tz_bot.defaults.tzinfo)
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
chat_id = data["chat_id"] == 2
user_id = data["user_id"] == 32
until_date = data.get("until_date", until_timestamp) == until_timestamp
return chat_id and user_id and until_date
monkeypatch.setattr(tz_bot.request, "post", make_assertion)
assert await tz_bot.ban_chat_member(2, 32)
assert await tz_bot.ban_chat_member(2, 32, until_date=until)
assert await tz_bot.ban_chat_member(2, 32, until_date=until_timestamp)
async def test_ban_chat_sender_chat(self, monkeypatch, offline_bot):
# For now, we just test that we pass the correct data to TG
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
chat_id = data["chat_id"] == 2
sender_chat_id = data["sender_chat_id"] == 32
return chat_id and sender_chat_id
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.ban_chat_sender_chat(2, 32)
# TODO: Needs improvement.
@pytest.mark.parametrize("only_if_banned", [True, False, None])
async def test_unban_chat_member(self, monkeypatch, offline_bot, only_if_banned):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
chat_id = data["chat_id"] == 2
user_id = data["user_id"] == 32
o_i_b = data.get("only_if_banned", None) == only_if_banned
return chat_id and user_id and o_i_b
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.unban_chat_member(2, 32, only_if_banned=only_if_banned)
async def test_unban_chat_sender_chat(self, monkeypatch, offline_bot):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters
chat_id = data["chat_id"] == "2"
sender_chat_id = data["sender_chat_id"] == "32"
return chat_id and sender_chat_id
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.unban_chat_sender_chat(2, 32)
async def test_set_chat_permissions(self, monkeypatch, offline_bot, chat_permissions):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters
chat_id = data["chat_id"] == "2"
permissions = data["permissions"] == chat_permissions.to_json()
use_independent_chat_permissions = data["use_independent_chat_permissions"]
return chat_id and permissions and use_independent_chat_permissions
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.set_chat_permissions(2, chat_permissions, True)
async def test_set_chat_administrator_custom_title(self, monkeypatch, offline_bot):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
chat_id = data["chat_id"] == 2
user_id = data["user_id"] == 32
custom_title = data["custom_title"] == "custom_title"
return chat_id and user_id and custom_title
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.set_chat_administrator_custom_title(2, 32, "custom_title")
# TODO: Needs improvement. Need an incoming callbackquery to test
@pytest.mark.parametrize("cache_time", [74, dtm.timedelta(seconds=74)])
async def test_answer_callback_query(self, monkeypatch, offline_bot, cache_time):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters == {
"callback_query_id": 23,
"show_alert": True,
"url": "no_url",
"cache_time": 74,
"text": "answer",
}
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.answer_callback_query(
23, text="answer", show_alert=True, url="no_url", cache_time=cache_time
)
@pytest.mark.parametrize("drop_pending_updates", [True, False])
async def test_set_webhook_delete_webhook_drop_pending_updates(
self, offline_bot, drop_pending_updates, monkeypatch
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
return data.get("drop_pending_updates") == drop_pending_updates
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.set_webhook("", drop_pending_updates=drop_pending_updates)
assert await offline_bot.delete_webhook(drop_pending_updates=drop_pending_updates)
@pytest.mark.parametrize("local_file", ["str", "Path", False])
async def test_set_webhook_params(self, offline_bot, monkeypatch, local_file):
# actually making calls to TG is done in
# test_set_webhook_get_webhook_info_and_delete_webhook. Sadly secret_token can't be tested
# there so we have this function \o/
async def make_assertion(*args, **_):
kwargs = args[1]
if local_file is False:
cert_assertion = (
kwargs["certificate"].input_file_content
== data_file("sslcert.pem").read_bytes()
)
else:
cert_assertion = data_file("sslcert.pem").as_uri()
return (
kwargs["url"] == "example.com"
and cert_assertion
and kwargs["max_connections"] == 7
and kwargs["allowed_updates"] == ["messages"]
and kwargs["ip_address"] == "127.0.0.1"
and kwargs["drop_pending_updates"]
and kwargs["secret_token"] == "SoSecretToken"
)
monkeypatch.setattr(offline_bot, "_post", make_assertion)
cert_path = data_file("sslcert.pem")
if local_file == "str":
certificate = str(cert_path)
elif local_file == "Path":
certificate = cert_path
else:
certificate = cert_path.read_bytes()
assert await offline_bot.set_webhook(
"example.com",
certificate,
7,
["messages"],
"127.0.0.1",
True,
"SoSecretToken",
)
# TODO: Needs improvement. Need incoming shipping queries to test
async def test_answer_shipping_query_ok(self, monkeypatch, offline_bot):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters == {
"shipping_query_id": 1,
"ok": True,
"shipping_options": [
{"title": "option1", "prices": [{"label": "price", "amount": 100}], "id": 1}
],
}
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
shipping_options = ShippingOption(1, "option1", [LabeledPrice("price", 100)])
assert await offline_bot.answer_shipping_query(
1, True, shipping_options=[shipping_options]
)
async def test_answer_shipping_query_error_message(self, monkeypatch, offline_bot):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters == {
"shipping_query_id": 1,
"error_message": "Not enough fish",
"ok": False,
}
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.answer_shipping_query(1, False, error_message="Not enough fish")
# TODO: Needs improvement. Need incoming pre checkout queries to test
async def test_answer_pre_checkout_query_ok(self, monkeypatch, offline_bot):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters == {"pre_checkout_query_id": 1, "ok": True}
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.answer_pre_checkout_query(1, True)
async def test_answer_pre_checkout_query_error_message(self, monkeypatch, offline_bot):
# For now just test that our internals pass the correct data
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters == {
"pre_checkout_query_id": 1,
"error_message": "Not enough fish",
"ok": False,
}
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.answer_pre_checkout_query(
1, False, error_message="Not enough fish"
)
async def test_restrict_chat_member(self, offline_bot, chat_permissions, monkeypatch):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.json_parameters
chat_id = data["chat_id"] == "@chat"
user_id = data["user_id"] == "2"
permissions = data["permissions"] == chat_permissions.to_json()
until_date = data["until_date"] == "200"
use_independent_chat_permissions = data["use_independent_chat_permissions"]
return (
chat_id
and user_id
and permissions
and until_date
and use_independent_chat_permissions
)
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.restrict_chat_member("@chat", 2, chat_permissions, 200, True)
async def test_restrict_chat_member_default_tz(
self, monkeypatch, tz_bot, channel_id, chat_permissions
):
until = dtm.datetime(2020, 1, 11, 16, 13)
until_timestamp = to_timestamp(until, tzinfo=tz_bot.defaults.tzinfo)
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters.get("until_date", until_timestamp) == until_timestamp
monkeypatch.setattr(tz_bot.request, "post", make_assertion)
assert await tz_bot.restrict_chat_member(channel_id, 95205500, chat_permissions)
assert await tz_bot.restrict_chat_member(
channel_id, 95205500, chat_permissions, until_date=until
)
assert await tz_bot.restrict_chat_member(
channel_id, 95205500, chat_permissions, until_date=until_timestamp
)
@pytest.mark.parametrize("local_mode", [True, False])
async def test_set_chat_photo_local_files(
self, dummy_message_dict, monkeypatch, offline_bot, chat_id, local_mode
):
try:
offline_bot._local_mode = local_mode
# For just test that the correct paths are passed as we have no local Bot API set up
self.test_flag = False
file = data_file("telegram.jpg")
expected = file.as_uri()
async def make_assertion(_, data, *args, **kwargs):
if local_mode:
self.test_flag = data.get("photo") == expected
else:
self.test_flag = isinstance(data.get("photo"), InputFile)
monkeypatch.setattr(offline_bot, "_post", make_assertion)
await offline_bot.set_chat_photo(chat_id, file)
assert self.test_flag
finally:
offline_bot._local_mode = False
async def test_timeout_propagation_explicit(self, monkeypatch, offline_bot, chat_id):
# Use BaseException that's not a subclass of Exception such that
# OkException should not be caught anywhere
class OkException(BaseException):
pass
timeout = 42
async def do_request(*args, **kwargs):
obj = kwargs.get("read_timeout")
if obj == timeout:
raise OkException
return 200, b'{"ok": true, "result": []}'
monkeypatch.setattr(offline_bot.request, "do_request", do_request)
# Test file uploading
with pytest.raises(OkException):
await offline_bot.send_photo(
chat_id, data_file("telegram.jpg").open("rb"), read_timeout=timeout
)
# Test JSON submission
with pytest.raises(OkException):
await offline_bot.get_chat_administrators(chat_id, read_timeout=timeout)
async def test_timeout_propagation_implicit(self, monkeypatch, offline_bot, chat_id):
# Use BaseException that's not a subclass of Exception such that
# OkException should not be caught anywhere
class OkException(BaseException):
pass
async def request(*args, **kwargs):
timeout = kwargs.get("timeout")
if timeout.write == 20:
raise OkException
return 200, b'{"ok": true, "result": []}'
monkeypatch.setattr(httpx.AsyncClient, "request", request)
monkeypatch.setattr(offline_bot, "_request", (object(), HTTPXRequest()))
# Test file uploading
with pytest.raises(OkException):
await offline_bot.send_photo(chat_id, data_file("telegram.jpg").open("rb"))
async def test_log_out(self, monkeypatch, offline_bot):
# We don't actually make a request as to not break the test setup
async def assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters == {} and url.split("/")[-1] == "logOut"
monkeypatch.setattr(offline_bot.request, "post", assertion)
assert await offline_bot.log_out()
async def test_close(self, monkeypatch, offline_bot):
# We don't actually make a request as to not break the test setup
async def assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.json_parameters == {} and url.split("/")[-1] == "close"
monkeypatch.setattr(offline_bot.request, "post", assertion)
assert await offline_bot.close()
@pytest.mark.parametrize("json_keyboard", [True, False])
@pytest.mark.parametrize("caption", ["<b>Test</b>", "", None])
async def test_copy_message(
self, monkeypatch, offline_bot, chat_id, media_message, json_keyboard, caption
):
keyboard = InlineKeyboardMarkup(
[[InlineKeyboardButton(text="test", callback_data="test2")]]
)
async def post(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
if not all(
[
data["chat_id"] == chat_id,
data["from_chat_id"] == chat_id,
data["message_id"] == media_message.message_id,
data.get("caption") == caption,
data["parse_mode"] == ParseMode.HTML,
data["reply_parameters"]
== ReplyParameters(message_id=media_message.message_id).to_dict(),
(
data["reply_markup"] == keyboard.to_json()
if json_keyboard
else keyboard.to_dict()
),
data["disable_notification"] is True,
data["caption_entities"]
== [MessageEntity(MessageEntity.BOLD, 0, 4).to_dict()],
data["protect_content"] is True,
data["message_thread_id"] == 1,
data["video_start_timestamp"] == 999,
]
):
pytest.fail("I got wrong parameters in post")
return data
monkeypatch.setattr(offline_bot.request, "post", post)
await offline_bot.copy_message(
chat_id,
from_chat_id=chat_id,
message_id=media_message.message_id,
caption=caption,
video_start_timestamp=999,
caption_entities=[MessageEntity(MessageEntity.BOLD, 0, 4)],
parse_mode=ParseMode.HTML,
reply_to_message_id=media_message.message_id,
reply_markup=keyboard.to_json() if json_keyboard else keyboard,
disable_notification=True,
protect_content=True,
message_thread_id=1,
)
# In the following tests we check that get_updates inserts callback data correctly if necessary
# The same must be done in the webhook updater. This is tested over at test_updater.py, but
# here we test more extensively.
@pytest.mark.parametrize(
("acd_in", "maxsize"),
[(True, 1024), (False, 1024), (0, 0), (None, None)],
)
async def test_callback_data_maxsize(self, bot_info, acd_in, maxsize):
async with make_bot(bot_info, arbitrary_callback_data=acd_in, offline=True) as acd_bot:
if acd_in is not False:
assert acd_bot.callback_data_cache.maxsize == maxsize
else:
assert acd_bot.callback_data_cache is None
async def test_arbitrary_callback_data_no_insert(self, monkeypatch, cdc_bot):
"""Updates that don't need insertion shouldn't fail obviously"""
offline_bot = cdc_bot
async def post(*args, **kwargs):
update = Update(
17,
poll=Poll(
"42",
"question",
options=[PollOption("option", 0)],
total_voter_count=0,
is_closed=False,
is_anonymous=True,
type=Poll.REGULAR,
allows_multiple_answers=False,
),
)
return [update.to_dict()]
try:
monkeypatch.setattr(BaseRequest, "post", post)
updates = await offline_bot.get_updates(timeout=1)
assert len(updates) == 1
assert updates[0].update_id == 17
assert updates[0].poll.id == "42"
finally:
offline_bot.callback_data_cache.clear_callback_data()
offline_bot.callback_data_cache.clear_callback_queries()
@pytest.mark.parametrize(
"message_type", ["channel_post", "edited_channel_post", "message", "edited_message"]
)
async def test_arbitrary_callback_data_pinned_message_reply_to_message(
self, cdc_bot, monkeypatch, message_type
):
offline_bot = cdc_bot
reply_markup = InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="callback_data")
)
message = Message(
1,
dtm.datetime.utcnow(),
get_dummy_object(Chat),
reply_markup=offline_bot.callback_data_cache.process_keyboard(reply_markup),
)
message._unfreeze()
# We do to_dict -> de_json to make sure those aren't the same objects
message.pinned_message = Message.de_json(message.to_dict(), offline_bot)
async def post(*args, **kwargs):
update = Update(
17,
**{
message_type: Message(
1,
dtm.datetime.utcnow(),
get_dummy_object(Chat),
pinned_message=message,
reply_to_message=Message.de_json(message.to_dict(), offline_bot),
)
},
)
return [update.to_dict()]
try:
monkeypatch.setattr(BaseRequest, "post", post)
updates = await offline_bot.get_updates(timeout=1)
assert isinstance(updates, tuple)
assert len(updates) == 1
effective_message = updates[0][message_type]
assert (
effective_message.reply_to_message.reply_markup.inline_keyboard[0][0].callback_data
== "callback_data"
)
assert (
effective_message.pinned_message.reply_markup.inline_keyboard[0][0].callback_data
== "callback_data"
)
pinned_message = effective_message.reply_to_message.pinned_message
assert (
pinned_message.reply_markup.inline_keyboard[0][0].callback_data == "callback_data"
)
finally:
offline_bot.callback_data_cache.clear_callback_data()
offline_bot.callback_data_cache.clear_callback_queries()
async def test_get_updates_invalid_callback_data(self, cdc_bot, monkeypatch):
offline_bot = cdc_bot
async def post(*args, **kwargs):
return [
Update(
17,
callback_query=CallbackQuery(
id=1,
from_user=None,
chat_instance=123,
data="invalid data",
message=Message(
1,
from_user=User(1, "", False),
date=dtm.datetime.utcnow(),
chat=Chat(1, ""),
text="Webhook",
),
),
).to_dict()
]
try:
monkeypatch.setattr(BaseRequest, "post", post)
updates = await offline_bot.get_updates(timeout=1)
assert isinstance(updates, tuple)
assert len(updates) == 1
assert isinstance(updates[0].callback_query.data, InvalidCallbackData)
finally:
# Reset b/c bots scope is session
offline_bot.callback_data_cache.clear_callback_data()
offline_bot.callback_data_cache.clear_callback_queries()
# TODO: Needs improvement. We need incoming inline query to test answer.
async def test_replace_callback_data_answer_inline_query(self, monkeypatch, cdc_bot, chat_id):
offline_bot = cdc_bot
# For now just test that our internals pass the correct data
async def make_assertion(
endpoint,
data=None,
*args,
**kwargs,
):
inline_keyboard = data["results"][0]["reply_markup"].inline_keyboard
assertion_1 = inline_keyboard[0][1] == no_replace_button
assertion_2 = inline_keyboard[0][0] != replace_button
keyboard, button = (
inline_keyboard[0][0].callback_data[:32],
inline_keyboard[0][0].callback_data[32:],
)
assertion_3 = (
offline_bot.callback_data_cache._keyboard_data[keyboard].button_data[button]
== "replace_test"
)
assertion_4 = data["results"][1].reply_markup is None
return assertion_1 and assertion_2 and assertion_3 and assertion_4
try:
replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test")
no_replace_button = InlineKeyboardButton(
text="no_replace", url="http://python-telegram-bot.org/"
)
reply_markup = InlineKeyboardMarkup.from_row(
[
replace_button,
no_replace_button,
]
)
# call this here so `offline_bot.get_me()` won't be called after mocking
offline_bot.username
monkeypatch.setattr(offline_bot, "_post", make_assertion)
results = [
InlineQueryResultArticle(
"11", "first", InputTextMessageContent("first"), reply_markup=reply_markup
),
InlineQueryResultVoice(
"22",
"https://python-telegram-bot.org/static/testfiles/telegram.ogg",
title="second",
),
]
assert await offline_bot.answer_inline_query(chat_id, results=results)
finally:
offline_bot.callback_data_cache.clear_callback_data()
offline_bot.callback_data_cache.clear_callback_queries()
@pytest.mark.parametrize(
"message_type", ["channel_post", "edited_channel_post", "message", "edited_message"]
)
@pytest.mark.parametrize("self_sender", [True, False])
async def test_arbitrary_callback_data_via_bot(
self, cdc_bot, monkeypatch, self_sender, message_type
):
bot = cdc_bot
reply_markup = InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="callback_data")
)
reply_markup = bot.callback_data_cache.process_keyboard(reply_markup)
message = Message(
1,
dtm.datetime.utcnow(),
get_dummy_object(Chat),
reply_markup=reply_markup,
via_bot=bot.bot if self_sender else User(1, "first", False),
)
async def post(*args, **kwargs):
return [Update(17, **{message_type: message}).to_dict()]
try:
monkeypatch.setattr(BaseRequest, "post", post)
updates = await bot.get_updates(timeout=1)
assert isinstance(updates, tuple)
assert len(updates) == 1
message = updates[0][message_type]
if self_sender:
assert message.reply_markup.inline_keyboard[0][0].callback_data == "callback_data"
else:
assert (
message.reply_markup.inline_keyboard[0][0].callback_data
== reply_markup.inline_keyboard[0][0].callback_data
)
finally:
bot.callback_data_cache.clear_callback_data()
bot.callback_data_cache.clear_callback_queries()
@pytest.mark.parametrize("bot_class", [Bot, ExtBot])
async def test_http2_runtime_error(self, recwarn, bot_class):
bot_class("12345:ABCDE", base_url="http://", request=HTTPXRequest(http_version="2"))
bot_class(
"12345:ABCDE",
base_url="http://",
get_updates_request=HTTPXRequest(http_version="2"),
)
bot_class(
"12345:ABCDE",
base_url="http://",
request=HTTPXRequest(http_version="2"),
get_updates_request=HTTPXRequest(http_version="2"),
)
assert len(recwarn) == 3
assert "You set the HTTP version for the request HTTPXRequest instance" in str(
recwarn[0].message
)
assert "You set the HTTP version for the get_updates_request HTTPXRequest instance" in str(
recwarn[1].message
)
assert (
"You set the HTTP version for the get_updates_request and request HTTPXRequest "
"instance" in str(recwarn[2].message)
)
for warning in recwarn:
assert warning.filename == __file__, "wrong stacklevel!"
assert warning.category is PTBUserWarning
async def test_set_get_my_name(self, offline_bot, monkeypatch):
"""We only test that we pass the correct values to TG since this endpoint is heavily
rate limited which makes automated tests rather infeasible."""
default_name = "default_bot_name"
en_name = "en_bot_name"
de_name = "de_bot_name"
# We predefine the responses that we would TG expect to send us
set_stack = asyncio.Queue()
get_stack = asyncio.Queue()
await set_stack.put({"name": default_name})
await set_stack.put({"name": en_name, "language_code": "en"})
await set_stack.put({"name": de_name, "language_code": "de"})
await get_stack.put({"name": default_name, "language_code": None})
await get_stack.put({"name": en_name, "language_code": "en"})
await get_stack.put({"name": de_name, "language_code": "de"})
await set_stack.put({"name": default_name})
await set_stack.put({"language_code": "en"})
await set_stack.put({"language_code": "de"})
await get_stack.put({"name": default_name, "language_code": None})
await get_stack.put({"name": default_name, "language_code": "en"})
await get_stack.put({"name": default_name, "language_code": "de"})
async def post(url, request_data: RequestData, *args, **kwargs):
# The mock-post now just fetches the predefined responses from the queues
if "setMyName" in url:
expected = await set_stack.get()
assert request_data.json_parameters == expected
set_stack.task_done()
return True
bot_name = await get_stack.get()
if "language_code" in request_data.json_parameters:
assert request_data.json_parameters == {"language_code": bot_name["language_code"]}
else:
assert request_data.json_parameters == {}
get_stack.task_done()
return bot_name
monkeypatch.setattr(offline_bot.request, "post", post)
# Set the names
assert all(
await asyncio.gather(
offline_bot.set_my_name(default_name),
offline_bot.set_my_name(en_name, language_code="en"),
offline_bot.set_my_name(de_name, language_code="de"),
)
)
# Check that they were set correctly
assert await asyncio.gather(
offline_bot.get_my_name(), offline_bot.get_my_name("en"), offline_bot.get_my_name("de")
) == [
BotName(default_name),
BotName(en_name),
BotName(de_name),
]
# Delete the names
assert all(
await asyncio.gather(
offline_bot.set_my_name(default_name),
offline_bot.set_my_name(None, language_code="en"),
offline_bot.set_my_name(None, language_code="de"),
)
)
# Check that they were deleted correctly
assert await asyncio.gather(
offline_bot.get_my_name(), offline_bot.get_my_name("en"), offline_bot.get_my_name("de")
) == 3 * [BotName(default_name)]
async def test_set_message_reaction(self, offline_bot, monkeypatch):
"""This is here so we can test the convenient conversion we do in the function without
having to do multiple requests to Telegram"""
expected_param = [
[{"emoji": ReactionEmoji.THUMBS_UP, "type": "emoji"}],
[{"emoji": ReactionEmoji.RED_HEART, "type": "emoji"}],
[{"custom_emoji_id": "custom_emoji_1", "type": "custom_emoji"}],
[{"custom_emoji_id": "custom_emoji_2", "type": "custom_emoji"}],
[{"emoji": ReactionEmoji.THUMBS_DOWN, "type": "emoji"}],
[{"custom_emoji_id": "custom_emoji_3", "type": "custom_emoji"}],
[
{"emoji": ReactionEmoji.RED_HEART, "type": "emoji"},
{"custom_emoji_id": "custom_emoji_4", "type": "custom_emoji"},
{"emoji": ReactionEmoji.THUMBS_DOWN, "type": "emoji"},
{"custom_emoji_id": "custom_emoji_5", "type": "custom_emoji"},
],
[],
]
amount = 0
async def post(url, request_data: RequestData, *args, **kwargs):
# The mock-post now just fetches the predefined responses from the queues
assert request_data.json_parameters["chat_id"] == "1"
assert request_data.json_parameters["message_id"] == "2"
assert request_data.json_parameters["is_big"]
nonlocal amount
assert request_data.parameters["reaction"] == expected_param[amount]
amount += 1
monkeypatch.setattr(offline_bot.request, "post", post)
await offline_bot.set_message_reaction(
1, 2, [ReactionTypeEmoji(ReactionEmoji.THUMBS_UP)], True
)
await offline_bot.set_message_reaction(
1, 2, ReactionTypeEmoji(ReactionEmoji.RED_HEART), True
)
await offline_bot.set_message_reaction(
1, 2, [ReactionTypeCustomEmoji("custom_emoji_1")], True
)
await offline_bot.set_message_reaction(
1, 2, ReactionTypeCustomEmoji("custom_emoji_2"), True
)
await offline_bot.set_message_reaction(1, 2, ReactionEmoji.THUMBS_DOWN, True)
await offline_bot.set_message_reaction(1, 2, "custom_emoji_3", True)
await offline_bot.set_message_reaction(
1,
2,
[
ReactionTypeEmoji(ReactionEmoji.RED_HEART),
ReactionTypeCustomEmoji("custom_emoji_4"),
ReactionEmoji.THUMBS_DOWN,
ReactionTypeCustomEmoji("custom_emoji_5"),
],
True,
)
@pytest.mark.parametrize(
("default_bot", "custom"),
[
({"parse_mode": ParseMode.HTML}, None),
({"parse_mode": ParseMode.HTML}, ParseMode.MARKDOWN_V2),
({"parse_mode": None}, ParseMode.MARKDOWN_V2),
],
indirect=["default_bot"],
)
async def test_send_message_default_quote_parse_mode(
self, default_bot, chat_id, custom, monkeypatch
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters["reply_parameters"].get("quote_parse_mode") == (
custom or default_bot.defaults.quote_parse_mode
)
return make_message("dummy reply").to_dict()
kwargs = {"message_id": 1}
if custom is not None:
kwargs["quote_parse_mode"] = custom
monkeypatch.setattr(default_bot.request, "post", make_assertion)
await default_bot.send_message(chat_id, "test", reply_parameters=ReplyParameters(**kwargs))
@pytest.mark.parametrize(
("default_bot", "custom"),
[
({"parse_mode": ParseMode.HTML}, "NOTHING"),
({"parse_mode": ParseMode.HTML}, None),
({"parse_mode": ParseMode.HTML}, ParseMode.MARKDOWN_V2),
({"parse_mode": None}, ParseMode.MARKDOWN_V2),
],
indirect=["default_bot"],
)
async def test_send_poll_default_text_question_parse_mode(
self, default_bot, raw_bot, chat_id, custom, monkeypatch
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
expected = default_bot.defaults.text_parse_mode if custom == "NOTHING" else custom
option_1 = request_data.parameters["options"][0]
option_2 = request_data.parameters["options"][1]
assert option_1.get("text_parse_mode") == (default_bot.defaults.text_parse_mode)
assert option_2.get("text_parse_mode") == expected
assert request_data.parameters.get("question_parse_mode") == expected
return make_message("dummy reply").to_dict()
async def make_raw_assertion(url, request_data: RequestData, *args, **kwargs):
expected = None if custom == "NOTHING" else custom
option_1 = request_data.parameters["options"][0]
option_2 = request_data.parameters["options"][1]
assert option_1.get("text_parse_mode") is None
assert option_2.get("text_parse_mode") == expected
assert request_data.parameters.get("question_parse_mode") == expected
return make_message("dummy reply").to_dict()
if custom == "NOTHING":
option_2 = InputPollOption("option2")
kwargs = {}
else:
option_2 = InputPollOption("option2", text_parse_mode=custom)
kwargs = {"question_parse_mode": custom}
monkeypatch.setattr(default_bot.request, "post", make_assertion)
await default_bot.send_poll(
chat_id, question="question", options=["option1", option_2], **kwargs
)
monkeypatch.setattr(raw_bot.request, "post", make_raw_assertion)
await raw_bot.send_poll(
chat_id, question="question", options=["option1", option_2], **kwargs
)
@pytest.mark.parametrize(
("default_bot", "custom"),
[
({"parse_mode": ParseMode.HTML}, None),
({"parse_mode": ParseMode.HTML}, ParseMode.MARKDOWN_V2),
({"parse_mode": None}, ParseMode.MARKDOWN_V2),
],
indirect=["default_bot"],
)
async def test_send_poll_default_quote_parse_mode(
self, default_bot, chat_id, custom, monkeypatch
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters["reply_parameters"].get("quote_parse_mode") == (
custom or default_bot.defaults.quote_parse_mode
)
return make_message("dummy reply").to_dict()
kwargs = {"message_id": 1}
if custom is not None:
kwargs["quote_parse_mode"] = custom
monkeypatch.setattr(default_bot.request, "post", make_assertion)
await default_bot.send_poll(
chat_id,
question="question",
options=["option1", "option2"],
reply_parameters=ReplyParameters(**kwargs),
)
async def test_send_poll_question_parse_mode_entities(self, offline_bot, monkeypatch):
# Currently only custom emoji are supported as entities which we can't test
# We just test that the correct data is passed for now
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters["question_entities"] == [
{"type": "custom_emoji", "offset": 0, "length": 1},
{"type": "custom_emoji", "offset": 2, "length": 1},
]
assert request_data.parameters["question_parse_mode"] == ParseMode.MARKDOWN_V2
return make_message("dummy reply").to_dict()
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
await offline_bot.send_poll(
1,
question="😀😃",
options=["option1", "option2"],
question_entities=[
MessageEntity(MessageEntity.CUSTOM_EMOJI, 0, 1),
MessageEntity(MessageEntity.CUSTOM_EMOJI, 2, 1),
],
question_parse_mode=ParseMode.MARKDOWN_V2,
)
@pytest.mark.parametrize(
("default_bot", "custom"),
[
({"parse_mode": ParseMode.HTML}, None),
({"parse_mode": ParseMode.HTML}, ParseMode.MARKDOWN_V2),
({"parse_mode": None}, ParseMode.MARKDOWN_V2),
],
indirect=["default_bot"],
)
async def test_send_game_default_quote_parse_mode(
self, default_bot, chat_id, custom, monkeypatch
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters["reply_parameters"].get("quote_parse_mode") == (
custom or default_bot.defaults.quote_parse_mode
)
return make_message("dummy reply").to_dict()
kwargs = {"message_id": 1}
if custom is not None:
kwargs["quote_parse_mode"] = custom
monkeypatch.setattr(default_bot.request, "post", make_assertion)
await default_bot.send_game(
chat_id, "game_short_name", reply_parameters=ReplyParameters(**kwargs)
)
@pytest.mark.parametrize(
("default_bot", "custom"),
[
({"parse_mode": ParseMode.HTML}, None),
({"parse_mode": ParseMode.HTML}, ParseMode.MARKDOWN_V2),
({"parse_mode": None}, ParseMode.MARKDOWN_V2),
],
indirect=["default_bot"],
)
async def test_copy_message_default_quote_parse_mode(
self, default_bot, chat_id, custom, monkeypatch
):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters["reply_parameters"].get("quote_parse_mode") == (
custom or default_bot.defaults.quote_parse_mode
)
return make_message("dummy reply").to_dict()
kwargs = {"message_id": 1}
if custom is not None:
kwargs["quote_parse_mode"] = custom
monkeypatch.setattr(default_bot.request, "post", make_assertion)
await default_bot.copy_message(chat_id, 1, 1, reply_parameters=ReplyParameters(**kwargs))
async def test_do_api_request_camel_case_conversion(self, offline_bot, monkeypatch):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return url.endswith("camelCase")
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.do_api_request("camel_case")
@pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning")
async def test_do_api_request_media_write_timeout(self, offline_bot, chat_id, monkeypatch):
test_flag = None
class CustomRequest(BaseRequest):
async def initialize(self_) -> None:
pass
async def shutdown(self_) -> None:
pass
async def do_request(self_, *args, **kwargs) -> tuple[int, bytes]:
nonlocal test_flag
test_flag = (
kwargs.get("read_timeout"),
kwargs.get("connect_timeout"),
kwargs.get("write_timeout"),
kwargs.get("pool_timeout"),
)
return HTTPStatus.OK, b'{"ok": "True", "result": {}}'
@property
def read_timeout(self):
return 1
custom_request = CustomRequest()
offline_bot = Bot(offline_bot.token, request=custom_request)
await offline_bot.do_api_request(
"send_document",
api_kwargs={
"chat_id": chat_id,
"caption": "test_caption",
"document": InputFile(data_file("telegram.png").open("rb")),
},
)
assert test_flag == (
DEFAULT_NONE,
DEFAULT_NONE,
DEFAULT_NONE,
DEFAULT_NONE,
)
@pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning")
async def test_do_api_request_default_timezone(self, tz_bot, monkeypatch):
until = dtm.datetime(2020, 1, 11, 16, 13)
until_timestamp = to_timestamp(until, tzinfo=tz_bot.defaults.tzinfo)
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
data = request_data.parameters
chat_id = data["chat_id"] == 2
user_id = data["user_id"] == 32
until_date = data.get("until_date", until_timestamp) == until_timestamp
return chat_id and user_id and until_date
monkeypatch.setattr(tz_bot.request, "post", make_assertion)
assert await tz_bot.do_api_request(
"banChatMember", api_kwargs={"chat_id": 2, "user_id": 32}
)
assert await tz_bot.do_api_request(
"banChatMember", api_kwargs={"chat_id": 2, "user_id": 32, "until_date": until}
)
assert await tz_bot.do_api_request(
"banChatMember",
api_kwargs={"chat_id": 2, "user_id": 32, "until_date": until_timestamp},
)
async def test_business_connection_id_argument(
self, offline_bot, monkeypatch, dummy_message_dict
):
"""We can't connect to a business acc, so we just test that the correct data is passed.
We also can't test every single method easily, so we just test a few. Our linting will
catch any unused args with the others."""
return_values = asyncio.Queue()
await return_values.put(dummy_message_dict)
await return_values.put(
Poll(
id="42",
question="question",
options=[PollOption("option", 0)],
total_voter_count=5,
is_closed=True,
is_anonymous=True,
type="regular",
allows_multiple_answers=False,
).to_dict()
)
await return_values.put(True)
await return_values.put(True)
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters.get("business_connection_id") == 42
return await return_values.get()
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
await offline_bot.send_message(2, "text", business_connection_id=42)
await offline_bot.stop_poll(chat_id=1, message_id=2, business_connection_id=42)
await offline_bot.pin_chat_message(chat_id=1, message_id=2, business_connection_id=42)
await offline_bot.unpin_chat_message(chat_id=1, business_connection_id=42)
async def test_message_effect_id_argument(self, offline_bot, monkeypatch):
"""We can't test every single method easily, so we just test one. Our linting will catch
any unused args with the others."""
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters.get("message_effect_id") == 42
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.send_message(2, "text", message_effect_id=42)
async def test_allow_paid_broadcast_argument(self, offline_bot, monkeypatch):
"""We can't test every single method easily, so we just test one. Our linting will catch
any unused args with the others."""
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return request_data.parameters.get("allow_paid_broadcast") == 42
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.send_message(2, "text", allow_paid_broadcast=42)
async def test_send_chat_action_all_args(self, bot, chat_id, monkeypatch):
async def make_assertion(*args, **_):
kwargs = args[1]
return (
kwargs["chat_id"] == chat_id
and kwargs["action"] == "action"
and kwargs["message_thread_id"] == 1
and kwargs["business_connection_id"] == 3
)
monkeypatch.setattr(bot, "_post", make_assertion)
assert await bot.send_chat_action(chat_id, "action", 1, 3)
async def test_gift_premium_subscription_all_args(self, bot, monkeypatch):
# can't make actual request so we just test that the correct data is passed
async def make_assertion(*args, **_):
kwargs = args[1]
return (
kwargs.get("user_id") == 12
and kwargs.get("month_count") == 3
and kwargs.get("star_count") == 1000
and kwargs.get("text") == "test text"
and kwargs.get("text_parse_mode") == "Markdown"
and kwargs.get("text_entities")
== [
MessageEntity(MessageEntity.BOLD, 0, 3),
MessageEntity(MessageEntity.ITALIC, 5, 11),
]
)
monkeypatch.setattr(bot, "_post", make_assertion)
assert await bot.gift_premium_subscription(
user_id=12,
month_count=3,
star_count=1000,
text="test text",
text_parse_mode="Markdown",
text_entities=[
MessageEntity(MessageEntity.BOLD, 0, 3),
MessageEntity(MessageEntity.ITALIC, 5, 11),
],
)
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
@pytest.mark.parametrize(
("passed_value", "expected_value"),
[(DEFAULT_NONE, "Markdown"), ("HTML", "HTML"), (None, None)],
)
async def test_gift_premium_subscription_default_parse_mode(
self, default_bot, monkeypatch, passed_value, expected_value
):
# can't make actual request so we just test that the correct data is passed
async def make_assertion(url, request_data, *args, **kwargs):
assert request_data.parameters.get("text_parse_mode") == expected_value
return True
monkeypatch.setattr(default_bot.request, "post", make_assertion)
kwargs = {
"user_id": 123,
"month_count": 3,
"star_count": 1000,
"text": "text",
}
if passed_value is not DEFAULT_NONE:
kwargs["text_parse_mode"] = passed_value
assert await default_bot.gift_premium_subscription(**kwargs)
async def test_refund_star_payment(self, offline_bot, monkeypatch):
# can't make actual request so we just test that the correct data is passed
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return (
request_data.parameters.get("user_id") == 42
and request_data.parameters.get("telegram_payment_charge_id") == "37"
)
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.refund_star_payment(42, "37")
async def test_get_star_transactions(self, offline_bot, monkeypatch):
# we just want to test the offset parameter
st = StarTransactions([StarTransaction("1", 1, dtm.datetime.now())]).to_json()
async def do_request(url, request_data: RequestData, *args, **kwargs):
offset = request_data.parameters.get("offset") == 3
if offset:
return 200, f'{{"ok": true, "result": {st}}}'.encode()
return 400, b'{"ok": false, "result": []}'
monkeypatch.setattr(offline_bot.request, "do_request", do_request)
obj = await offline_bot.get_star_transactions(offset=3)
assert isinstance(obj, StarTransactions)
async def test_edit_user_star_subscription(self, offline_bot, monkeypatch):
"""Can't properly test, so we only check that the correct values are passed"""
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
return (
request_data.parameters.get("user_id") == 42
and request_data.parameters.get("telegram_payment_charge_id")
== "telegram_payment_charge_id"
and request_data.parameters.get("is_canceled") is False
)
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
assert await offline_bot.edit_user_star_subscription(
42, "telegram_payment_charge_id", False
)
async def test_create_chat_subscription_invite_link(
self,
monkeypatch,
offline_bot,
):
# Since the chat invite link object does not say if the sub args are passed we can
# only check here
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters.get("subscription_period") == 2592000
assert request_data.parameters.get("subscription_price") == 6
return ChatInviteLink(
"https://t.me/joinchat/invite_link", User(1, "first", False), False, False, False
).to_dict()
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
await offline_bot.create_chat_subscription_invite_link(1234, 2592000, 6)
@pytest.mark.parametrize(
"expiration_date", [dtm.datetime(2024, 1, 1), 1704067200], ids=["datetime", "timestamp"]
)
async def test_set_user_emoji_status_basic(self, offline_bot, monkeypatch, expiration_date):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters.get("user_id") == 4242
assert (
request_data.parameters.get("emoji_status_custom_emoji_id")
== "emoji_status_custom_emoji_id"
)
assert request_data.parameters.get("emoji_status_expiration_date") == 1704067200
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
await offline_bot.set_user_emoji_status(
4242, "emoji_status_custom_emoji_id", expiration_date
)
async def test_set_user_emoji_status_default_timezone(self, tz_bot, monkeypatch):
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters.get("user_id") == 4242
assert (
request_data.parameters.get("emoji_status_custom_emoji_id")
== "emoji_status_custom_emoji_id"
)
assert request_data.parameters.get("emoji_status_expiration_date") == to_timestamp(
dtm.datetime(2024, 1, 1), tzinfo=tz_bot.defaults.tzinfo
)
monkeypatch.setattr(tz_bot.request, "post", make_assertion)
await tz_bot.set_user_emoji_status(
4242, "emoji_status_custom_emoji_id", dtm.datetime(2024, 1, 1)
)
async def test_verify_user(self, offline_bot, monkeypatch):
"No way to test this without getting verified"
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters.get("user_id") == 1234
assert request_data.parameters.get("custom_description") == "this is so custom"
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
await offline_bot.verify_user(1234, "this is so custom")
async def test_verify_chat(self, offline_bot, monkeypatch):
"No way to test this without getting verified"
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters.get("chat_id") == 1234
assert request_data.parameters.get("custom_description") == "this is so custom"
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
await offline_bot.verify_chat(1234, "this is so custom")
async def test_unverify_user(self, offline_bot, monkeypatch):
"No way to test this without getting verified"
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters.get("user_id") == 1234
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
await offline_bot.remove_user_verification(1234)
async def test_unverify_chat(self, offline_bot, monkeypatch):
"No way to test this without getting verified"
async def make_assertion(url, request_data: RequestData, *args, **kwargs):
assert request_data.parameters.get("chat_id") == 1234
monkeypatch.setattr(offline_bot.request, "post", make_assertion)
await offline_bot.remove_chat_verification(1234)
async def test_get_my_star_balance(self, offline_bot, monkeypatch):
sa = StarAmount(1000).to_json()
async def do_request(url, request_data: RequestData, *args, **kwargs):
assert not request_data.parameters
return 200, f'{{"ok": true, "result": {sa}}}'.encode()
monkeypatch.setattr(offline_bot.request, "do_request", do_request)
obj = await offline_bot.get_my_star_balance()
assert isinstance(obj, StarAmount)
class TestBotWithRequest:
"""
Most are executed on tg.ext.ExtBot, as that class only extends the functionality of tg.bot
Behavior for init of ExtBot with missing optional dependency cachetools (for CallbackDataCache)
is tested in `test_callbackdatacache`
"""
# get_available_gifts, send_gift are tested in `test_gift`.
# No need to duplicate here.
async def test_invalid_token_server_response(self):
with pytest.raises(InvalidToken, match="The token `12` was rejected by the server."):
async with ExtBot(token="12"):
pass
async def test_multiple_init_cycles(self, bot):
# nothing really to assert - this should just not fail
test_bot = Bot(bot.token)
async with test_bot:
await test_bot.get_me()
async with test_bot:
await test_bot.get_me()
async def test_forward_message(self, bot, chat_id, static_message):
forward_message = await bot.forward_message(
chat_id, from_chat_id=chat_id, message_id=static_message.message_id
)
assert forward_message.text == static_message.text
assert forward_message.forward_origin.sender_user == static_message.from_user
assert isinstance(forward_message.forward_origin.date, dtm.datetime)
async def test_forward_protected_message(self, bot, chat_id):
tasks = asyncio.gather(
bot.send_message(chat_id, "cant forward me", protect_content=True),
bot.send_message(chat_id, "forward me", protect_content=False),
)
to_forward_protected, to_forward_unprotected = await tasks
assert to_forward_protected.has_protected_content
assert not to_forward_unprotected.has_protected_content
forwarded_but_now_protected = await to_forward_unprotected.forward(
chat_id, protect_content=True
)
assert forwarded_but_now_protected.has_protected_content
tasks = asyncio.gather(
to_forward_protected.forward(chat_id),
forwarded_but_now_protected.forward(chat_id),
return_exceptions=True,
)
result = await tasks
assert all("can't be forwarded" in str(exc) for exc in result)
async def test_forward_messages(self, bot, chat_id):
# not using gather here to have deteriminically ordered message_ids
msg1 = await bot.send_message(chat_id, text="will be forwarded")
msg2 = await bot.send_message(chat_id, text="will be forwarded")
forward_messages = await bot.forward_messages(
chat_id, from_chat_id=chat_id, message_ids=(msg1.message_id, msg2.message_id)
)
assert isinstance(forward_messages, tuple)
tasks = asyncio.gather(
bot.send_message(
chat_id, "temp 1", reply_to_message_id=forward_messages[0].message_id
),
bot.send_message(
chat_id, "temp 2", reply_to_message_id=forward_messages[1].message_id
),
)
temp_msg1, temp_msg2 = await tasks
forward_msg1 = temp_msg1.reply_to_message
forward_msg2 = temp_msg2.reply_to_message
assert forward_msg1.text == msg1.text
assert forward_msg1.forward_origin.sender_user == msg1.from_user
assert isinstance(forward_msg1.forward_origin.date, dtm.datetime)
assert forward_msg2.text == msg2.text
assert forward_msg2.forward_origin.sender_user == msg2.from_user
assert isinstance(forward_msg2.forward_origin.date, dtm.datetime)
async def test_delete_message(self, bot, chat_id):
message = await bot.send_message(chat_id, text="will be deleted")
assert await bot.delete_message(chat_id=chat_id, message_id=message.message_id) is True
async def test_delete_message_old_message(self, bot, chat_id):
with pytest.raises(BadRequest):
# Considering that the first message is old enough
await bot.delete_message(chat_id=chat_id, message_id=1)
# send_photo, send_audio, send_document, send_sticker, send_video, send_voice, send_video_note,
# send_media_group, send_animation, get_user_chat_boosts are tested in their respective
# test modules. No need to duplicate here.
async def test_delete_messages(self, bot, chat_id):
msg1, msg2 = await asyncio.gather(
bot.send_message(chat_id, text="will be deleted"),
bot.send_message(chat_id, text="will be deleted"),
)
assert (
await bot.delete_messages(chat_id=chat_id, message_ids=sorted((msg1.id, msg2.id)))
is True
)
async def test_send_venue(self, bot, chat_id):
longitude = -46.788279
latitude = -23.691288
title = "title"
address = "address"
foursquare_id = "foursquare id"
foursquare_type = "foursquare type"
google_place_id = "google_place id"
google_place_type = "google_place type"
tasks = asyncio.gather(
*(
bot.send_venue(
chat_id=chat_id,
title=title,
address=address,
latitude=latitude,
longitude=longitude,
protect_content=True,
**i,
)
for i in (
{"foursquare_id": foursquare_id, "foursquare_type": foursquare_type},
{"google_place_id": google_place_id, "google_place_type": google_place_type},
)
),
)
message, message2 = await tasks
assert message.venue
assert message.venue.title == title
assert message.venue.address == address
assert message.venue.location.latitude == latitude
assert message.venue.location.longitude == longitude
assert message.venue.foursquare_id == foursquare_id
assert message.venue.foursquare_type == foursquare_type
assert message.venue.google_place_id is None
assert message.venue.google_place_type is None
assert message.has_protected_content
assert message2.venue
assert message2.venue.title == title
assert message2.venue.address == address
assert message2.venue.location.latitude == latitude
assert message2.venue.location.longitude == longitude
assert message2.venue.google_place_id == google_place_id
assert message2.venue.google_place_type == google_place_type
assert message2.venue.foursquare_id is None
assert message2.venue.foursquare_type is None
assert message2.has_protected_content
async def test_send_contact(self, bot, chat_id):
phone_number = "+11234567890"
first_name = "Leandro"
last_name = "Toledo"
message = await bot.send_contact(
chat_id=chat_id,
phone_number=phone_number,
first_name=first_name,
last_name=last_name,
protect_content=True,
)
assert message.contact
assert message.contact.phone_number == phone_number
assert message.contact.first_name == first_name
assert message.contact.last_name == last_name
assert message.has_protected_content
# TODO: Add bot to group to test polls too
@pytest.mark.parametrize(
"reply_markup",
[
None,
InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="data")
),
InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="data")
).to_dict(),
],
)
async def test_send_and_stop_poll(self, bot, super_group_id, reply_markup):
question = "Is this a test?"
answers = ["Yes", InputPollOption("No"), "Maybe"]
explanation = "[Here is a link](https://google.com)"
explanation_entities = [
MessageEntity(MessageEntity.TEXT_LINK, 0, 14, url="https://google.com")
]
poll_task = asyncio.create_task(
bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
is_anonymous=False,
allows_multiple_answers=True,
read_timeout=60,
protect_content=True,
)
)
quiz_task = asyncio.create_task(
bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
type=Poll.QUIZ,
correct_option_id=2,
is_closed=True,
explanation=explanation,
explanation_parse_mode=ParseMode.MARKDOWN_V2,
)
)
message = await poll_task
assert message.poll
assert message.poll.question == question
assert message.poll.options[0].text == answers[0]
assert message.poll.options[1].text == answers[1].text
assert message.poll.options[2].text == answers[2]
assert not message.poll.is_anonymous
assert message.poll.allows_multiple_answers
assert not message.poll.is_closed
assert message.poll.type == Poll.REGULAR
assert message.has_protected_content
# Since only the poll and not the complete message is returned, we can't check that the
# reply_markup is correct. So we just test that sending doesn't give an error.
poll = await bot.stop_poll(
chat_id=super_group_id,
message_id=message.message_id,
reply_markup=reply_markup,
read_timeout=60,
)
assert isinstance(poll, Poll)
assert poll.is_closed
assert poll.options[0].text == answers[0]
assert poll.options[0].voter_count == 0
assert poll.options[1].text == answers[1].text
assert poll.options[1].voter_count == 0
assert poll.options[2].text == answers[2]
assert poll.options[2].voter_count == 0
assert poll.question == question
assert poll.total_voter_count == 0
message_quiz = await quiz_task
assert message_quiz.poll.correct_option_id == 2
assert message_quiz.poll.type == Poll.QUIZ
assert message_quiz.poll.is_closed
assert message_quiz.poll.explanation == "Here is a link"
assert message_quiz.poll.explanation_entities == tuple(explanation_entities)
assert poll_task.done()
assert quiz_task.done()
@pytest.mark.parametrize(
("open_period", "close_date"),
[(5, None), (dtm.timedelta(seconds=5), None), (None, True)],
ids=["open_period", "open_period-dtm", "close_date"],
)
async def test_send_open_period(self, bot, super_group_id, open_period, close_date):
question = "Is this a test?"
answers = ["Yes", "No", "Maybe"]
reply_markup = InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="data")
)
if close_date:
close_date = dtm.datetime.utcnow() + dtm.timedelta(seconds=5.05)
message = await bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
is_anonymous=False,
allows_multiple_answers=True,
read_timeout=60,
open_period=open_period,
close_date=close_date,
)
await asyncio.sleep(5.1)
new_message = await bot.edit_message_reply_markup(
chat_id=super_group_id,
message_id=message.message_id,
reply_markup=reply_markup,
read_timeout=60,
)
assert new_message.poll.id == message.poll.id
assert new_message.poll.is_closed
async def test_send_close_date_default_tz(self, tz_bot, super_group_id):
question = "Is this a test?"
answers = ["Yes", "No", "Maybe"]
reply_markup = InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="data")
)
aware_close_date = dtm.datetime.now(tz=tz_bot.defaults.tzinfo) + dtm.timedelta(seconds=5)
close_date = aware_close_date.replace(tzinfo=None)
msg = await tz_bot.send_poll( # The timezone returned from this is always converted to UTC
chat_id=super_group_id,
question=question,
options=answers,
close_date=close_date,
read_timeout=60,
)
msg.poll._unfreeze()
# Sometimes there can be a few seconds delay, so don't let the test fail due to that-
msg.poll.close_date = msg.poll.close_date.astimezone(aware_close_date.tzinfo)
assert abs(msg.poll.close_date - aware_close_date) <= dtm.timedelta(seconds=5)
await asyncio.sleep(5.1)
new_message = await tz_bot.edit_message_reply_markup(
chat_id=super_group_id,
message_id=msg.message_id,
reply_markup=reply_markup,
read_timeout=60,
)
assert new_message.poll.id == msg.poll.id
assert new_message.poll.is_closed
async def test_send_poll_explanation_entities(self, bot, chat_id):
test_string = "Italic Bold Code"
entities = [
MessageEntity(MessageEntity.ITALIC, 0, 6),
MessageEntity(MessageEntity.ITALIC, 7, 4),
MessageEntity(MessageEntity.ITALIC, 12, 4),
]
message = await bot.send_poll(
chat_id,
"question",
options=["a", "b"],
correct_option_id=0,
type=Poll.QUIZ,
explanation=test_string,
explanation_entities=entities,
)
assert message.poll.explanation == test_string
assert message.poll.explanation_entities == tuple(entities)
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
async def test_send_poll_default_parse_mode(self, default_bot, super_group_id):
explanation = "Italic Bold Code"
explanation_markdown = "_Italic_ *Bold* `Code`"
question = "Is this a test?"
answers = ["Yes", "No", "Maybe"]
tasks = asyncio.gather(
*(
default_bot.send_poll(
chat_id=super_group_id,
question=question,
options=answers,
type=Poll.QUIZ,
correct_option_id=2,
is_closed=True,
explanation=explanation_markdown,
**i,
)
for i in ({}, {"explanation_parse_mode": None}, {"explanation_parse_mode": "HTML"})
),
)
message1, message2, message3 = await tasks
assert message1.poll.explanation == explanation
assert message1.poll.explanation_entities == (
MessageEntity(MessageEntity.ITALIC, 0, 6),
MessageEntity(MessageEntity.BOLD, 7, 4),
MessageEntity(MessageEntity.CODE, 12, 4),
)
assert message2.poll.explanation == explanation_markdown
assert message2.poll.explanation_entities == ()
assert message3.poll.explanation == explanation_markdown
assert message3.poll.explanation_entities == ()
@pytest.mark.parametrize(
("default_bot", "custom"),
[
({"allow_sending_without_reply": True}, None),
({"allow_sending_without_reply": False}, None),
({"allow_sending_without_reply": False}, True),
],
indirect=["default_bot"],
)
async def test_send_poll_default_allow_sending_without_reply(
self, default_bot, chat_id, custom
):
question = "Is this a test?"
answers = ["Yes", "No", "Maybe"]
reply_to_message = await default_bot.send_message(chat_id, "test")
await reply_to_message.delete()
if custom is not None:
message = await default_bot.send_poll(
chat_id,
question=question,
options=answers,
allow_sending_without_reply=custom,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
elif default_bot.defaults.allow_sending_without_reply:
message = await default_bot.send_poll(
chat_id,
question=question,
options=answers,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
else:
with pytest.raises(BadRequest, match="Message to be replied not found"):
await default_bot.send_poll(
chat_id,
question=question,
options=answers,
reply_to_message_id=reply_to_message.message_id,
)
@pytest.mark.parametrize("default_bot", [{"protect_content": True}], indirect=True)
async def test_send_poll_default_protect_content(self, chat_id, default_bot):
tasks = asyncio.gather(
default_bot.send_poll(chat_id, "Test", ["1", "2"]),
default_bot.send_poll(chat_id, "test", ["1", "2"], protect_content=False),
)
protected_poll, unprotect_poll = await tasks
assert protected_poll.has_protected_content
assert not unprotect_poll.has_protected_content
@pytest.mark.parametrize("emoji", [*Dice.ALL_EMOJI, None])
async def test_send_dice(self, bot, chat_id, emoji):
message = await bot.send_dice(chat_id, emoji=emoji, protect_content=True)
assert message.dice
assert message.has_protected_content
if emoji is None:
assert message.dice.emoji == Dice.DICE
else:
assert message.dice.emoji == emoji
@pytest.mark.parametrize(
("default_bot", "custom"),
[
({"allow_sending_without_reply": True}, None),
({"allow_sending_without_reply": False}, None),
({"allow_sending_without_reply": False}, True),
],
indirect=["default_bot"],
)
async def test_send_dice_default_allow_sending_without_reply(
self, default_bot, chat_id, custom
):
reply_to_message = await default_bot.send_message(chat_id, "test")
await reply_to_message.delete()
if custom is not None:
message = await default_bot.send_dice(
chat_id,
allow_sending_without_reply=custom,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
elif default_bot.defaults.allow_sending_without_reply:
message = await default_bot.send_dice(
chat_id,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
else:
with pytest.raises(BadRequest, match="Message to be replied not found"):
await default_bot.send_dice(
chat_id, reply_to_message_id=reply_to_message.message_id
)
@pytest.mark.parametrize("default_bot", [{"protect_content": True}], indirect=True)
async def test_send_dice_default_protect_content(self, chat_id, default_bot):
tasks = asyncio.gather(
default_bot.send_dice(chat_id), default_bot.send_dice(chat_id, protect_content=False)
)
protected_dice, unprotected_dice = await tasks
assert protected_dice.has_protected_content
assert not unprotected_dice.has_protected_content
@pytest.mark.parametrize("chat_action", list(ChatAction))
async def test_send_chat_action(self, bot, chat_id, chat_action):
assert await bot.send_chat_action(chat_id, chat_action)
async def test_wrong_chat_action(self, bot, chat_id):
with pytest.raises(BadRequest, match="Wrong parameter action"):
await bot.send_chat_action(chat_id, "unknown action")
async def test_answer_inline_query_current_offset_error(self, bot, inline_results):
with pytest.raises(ValueError, match="`current_offset` and `next_offset`"):
await bot.answer_inline_query(
1234, results=inline_results, next_offset=42, current_offset=51
)
async def test_save_prepared_inline_message(self, bot, chat_id):
# We can't really check that the result is stored correctly, we just ensur ethat we get
# a proper return value
result = InlineQueryResultArticle(
id="some_id", title="title", input_message_content=InputTextMessageContent("text")
)
out = await bot.save_prepared_inline_message(chat_id, result, True, False, True, False)
assert isinstance(out, PreparedInlineMessage)
async def test_get_user_profile_photos(self, bot, chat_id):
user_profile_photos = await bot.get_user_profile_photos(chat_id)
assert user_profile_photos.photos[0][0].file_size == 5403
async def test_get_one_user_profile_photo(self, bot, chat_id):
user_profile_photos = await bot.get_user_profile_photos(chat_id, offset=0, limit=1)
assert user_profile_photos.total_count == 1
assert user_profile_photos.photos[0][0].file_size == 5403
async def test_edit_message_text(self, bot, one_time_message):
message = await bot.edit_message_text(
text="new_text",
chat_id=one_time_message.chat_id,
message_id=one_time_message.message_id,
parse_mode="HTML",
disable_web_page_preview=True,
)
assert message.text == "new_text"
async def test_edit_message_text_entities(self, bot, one_time_message):
test_string = "Italic Bold Code"
entities = [
MessageEntity(MessageEntity.ITALIC, 0, 6),
MessageEntity(MessageEntity.ITALIC, 7, 4),
MessageEntity(MessageEntity.ITALIC, 12, 4),
]
message = await bot.edit_message_text(
text=test_string,
chat_id=one_time_message.chat_id,
message_id=one_time_message.message_id,
entities=entities,
)
assert message.text == test_string
assert message.entities == tuple(entities)
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
async def test_edit_message_text_default_parse_mode(
self, default_bot, chat_id, one_time_message
):
test_string = "Italic Bold Code"
test_markdown_string = "_Italic_ *Bold* `Code`"
message = await default_bot.edit_message_text(
text=test_markdown_string,
chat_id=one_time_message.chat_id,
message_id=one_time_message.message_id,
disable_web_page_preview=True,
)
assert message.text_markdown == test_markdown_string
assert message.text == test_string
message = await default_bot.edit_message_text(
text=test_markdown_string,
chat_id=message.chat_id,
message_id=message.message_id,
parse_mode=None,
disable_web_page_preview=True,
)
assert message.text == test_markdown_string
assert message.text_markdown == escape_markdown(test_markdown_string)
suffix = " edited"
message = await default_bot.edit_message_text(
text=test_markdown_string + suffix,
chat_id=message.chat_id,
message_id=message.message_id,
parse_mode="HTML",
disable_web_page_preview=True,
)
assert message.text == test_markdown_string + suffix
assert message.text_markdown == escape_markdown(test_markdown_string) + suffix
@pytest.mark.skip(reason="need reference to an inline message")
async def test_edit_message_text_inline(self):
pass
async def test_edit_message_caption(self, bot, media_message):
message = await bot.edit_message_caption(
caption="new_caption",
chat_id=media_message.chat_id,
message_id=media_message.message_id,
show_caption_above_media=False,
)
assert message.caption == "new_caption"
assert not message.show_caption_above_media
async def test_edit_message_caption_entities(self, bot, media_message):
test_string = "Italic Bold Code"
entities = [
MessageEntity(MessageEntity.ITALIC, 0, 6),
MessageEntity(MessageEntity.ITALIC, 7, 4),
MessageEntity(MessageEntity.ITALIC, 12, 4),
]
message = await bot.edit_message_caption(
caption=test_string,
chat_id=media_message.chat_id,
message_id=media_message.message_id,
caption_entities=entities,
)
assert message.caption == test_string
assert message.caption_entities == tuple(entities)
# edit_message_media is tested in test_inputmedia
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
async def test_edit_message_caption_default_parse_mode(self, default_bot, media_message):
test_string = "Italic Bold Code"
test_markdown_string = "_Italic_ *Bold* `Code`"
message = await default_bot.edit_message_caption(
caption=test_markdown_string,
chat_id=media_message.chat_id,
message_id=media_message.message_id,
)
assert message.caption_markdown == test_markdown_string
assert message.caption == test_string
message = await default_bot.edit_message_caption(
caption=test_markdown_string,
chat_id=media_message.chat_id,
message_id=media_message.message_id,
parse_mode=None,
)
assert message.caption == test_markdown_string
assert message.caption_markdown == escape_markdown(test_markdown_string)
message = await default_bot.edit_message_caption(
caption=test_markdown_string,
chat_id=media_message.chat_id,
message_id=media_message.message_id,
)
message = await default_bot.edit_message_caption(
caption=test_markdown_string,
chat_id=media_message.chat_id,
message_id=media_message.message_id,
parse_mode="HTML",
)
assert message.caption == test_markdown_string
assert message.caption_markdown == escape_markdown(test_markdown_string)
async def test_edit_message_caption_with_parse_mode(self, bot, media_message):
message = await bot.edit_message_caption(
caption="new *caption*",
parse_mode="Markdown",
chat_id=media_message.chat_id,
message_id=media_message.message_id,
)
assert message.caption == "new caption"
@pytest.mark.skip(reason="need reference to an inline message")
async def test_edit_message_caption_inline(self):
pass
async def test_edit_reply_markup(self, bot, one_time_message):
new_markup = InlineKeyboardMarkup([[InlineKeyboardButton(text="test", callback_data="1")]])
message = await bot.edit_message_reply_markup(
chat_id=one_time_message.chat_id,
message_id=one_time_message.message_id,
reply_markup=new_markup,
)
assert message is not True
@pytest.mark.skip(reason="need reference to an inline message")
async def test_edit_reply_markup_inline(self):
pass
# TODO: Actually send updates to the test bot so this can be tested properly
@pytest.mark.parametrize("timeout", [1, dtm.timedelta(seconds=1)])
async def test_get_updates(self, bot, timeout):
await bot.delete_webhook() # make sure there is no webhook set if webhook tests failed
updates = await bot.get_updates(timeout=timeout)
assert isinstance(updates, tuple)
if updates:
assert isinstance(updates[0], Update)
@pytest.mark.parametrize(
("read_timeout", "timeout", "expected"),
[
(None, None, 0),
(1, None, 1),
(None, 1, 1),
(None, dtm.timedelta(seconds=1), 1),
(DEFAULT_NONE, None, 10),
(DEFAULT_NONE, 1, 11),
(DEFAULT_NONE, dtm.timedelta(seconds=1), 11),
(1, 2, 3),
(1, dtm.timedelta(seconds=2), 3),
],
)
async def test_get_updates_read_timeout_value_passing(
self, bot, read_timeout, timeout, expected, monkeypatch
):
caught_read_timeout = None
async def catch_timeouts(*args, **kwargs):
nonlocal caught_read_timeout
caught_read_timeout = kwargs.get("read_timeout")
return HTTPStatus.OK, b'{"ok": "True", "result": {}}'
monkeypatch.setattr(HTTPXRequest, "do_request", catch_timeouts)
bot = Bot(get_updates_request=HTTPXRequest(read_timeout=10), token=bot.token)
await bot.get_updates(read_timeout=read_timeout, timeout=timeout)
assert caught_read_timeout == expected
@pytest.mark.parametrize("use_ip", [True, False])
# local file path as file_input is tested below in test_set_webhook_params
@pytest.mark.parametrize("file_input", ["bytes", "file_handle"])
async def test_set_webhook_get_webhook_info_and_delete_webhook(self, bot, use_ip, file_input):
url = "https://python-telegram-bot.org/test/webhook"
# Get the ip address of the website - dynamically just in case it ever changes
ip = socket.gethostbyname("python-telegram-bot.org")
max_connections = 7
allowed_updates = ["message"]
file_input = (
data_file("sslcert.pem").read_bytes()
if file_input == "bytes"
else data_file("sslcert.pem").open("rb")
)
await bot.set_webhook(
url,
max_connections=max_connections,
allowed_updates=allowed_updates,
ip_address=ip if use_ip else None,
certificate=file_input if use_ip else None,
)
await asyncio.sleep(1)
live_info = await bot.get_webhook_info()
assert live_info.url == url
assert live_info.max_connections == max_connections
assert live_info.allowed_updates == tuple(allowed_updates)
assert live_info.ip_address == ip
assert live_info.has_custom_certificate == use_ip
await bot.delete_webhook()
await asyncio.sleep(1)
info = await bot.get_webhook_info()
assert not info.url
assert info.ip_address is None
assert info.has_custom_certificate is False
async def test_leave_chat(self, bot):
with pytest.raises(BadRequest, match="Chat not found"):
await bot.leave_chat(-123456)
async def test_get_chat(self, bot, super_group_id):
cfi = await bot.get_chat(super_group_id)
assert cfi.type == "supergroup"
assert cfi.title == f">>> telegram.Bot(test) @{bot.username}"
assert cfi.id == int(super_group_id)
async def test_get_chat_administrators(self, bot, channel_id):
admins = await bot.get_chat_administrators(channel_id)
assert isinstance(admins, tuple)
for a in admins:
assert a.status in ("administrator", "creator")
async def test_get_chat_member_count(self, bot, channel_id):
count = await bot.get_chat_member_count(channel_id)
assert isinstance(count, int)
assert count > 3
async def test_get_chat_member(self, bot, channel_id, chat_id):
chat_member = await bot.get_chat_member(channel_id, chat_id)
assert chat_member.status == "creator"
assert chat_member.user.first_name == "PTB"
assert chat_member.user.last_name == "Test user"
@pytest.mark.skip(reason="Not implemented since we need a supergroup with many members")
async def test_set_chat_sticker_set(self):
pass
@pytest.mark.skip(reason="Not implemented since we need a supergroup with many members")
async def test_delete_chat_sticker_set(self):
pass
async def test_send_game(self, bot, chat_id):
game_short_name = "test_game"
message = await bot.send_game(chat_id, game_short_name, protect_content=True)
assert message.game
assert (
message.game.description
== "A no-op test game, for python-telegram-bot bot framework testing."
)
assert message.game.animation.file_id
# We added some test bots later and for some reason the file size is not the same for them
# so we accept three different sizes here. Shouldn't be too much of
assert message.game.photo[0].file_size in [851, 4928, 850]
assert message.has_protected_content
@pytest.mark.parametrize(
("default_bot", "custom"),
[
({"allow_sending_without_reply": True}, None),
({"allow_sending_without_reply": False}, None),
({"allow_sending_without_reply": False}, True),
],
indirect=["default_bot"],
)
async def test_send_game_default_allow_sending_without_reply(
self, default_bot, chat_id, custom
):
game_short_name = "test_game"
reply_to_message = await default_bot.send_message(chat_id, "test")
await reply_to_message.delete()
if custom is not None:
message = await default_bot.send_game(
chat_id,
game_short_name,
allow_sending_without_reply=custom,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
elif default_bot.defaults.allow_sending_without_reply:
message = await default_bot.send_game(
chat_id,
game_short_name,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
else:
with pytest.raises(BadRequest, match="Message to be replied not found"):
await default_bot.send_game(
chat_id, game_short_name, reply_to_message_id=reply_to_message.message_id
)
@pytest.mark.parametrize(
("default_bot", "val"),
[({"protect_content": True}, True), ({"protect_content": False}, None)],
indirect=["default_bot"],
)
async def test_send_game_default_protect_content(self, default_bot, chat_id, val):
protected = await default_bot.send_game(chat_id, "test_game", protect_content=val)
assert protected.has_protected_content is val
@xfail
async def test_set_game_score_and_high_scores(self, bot, chat_id):
# First, test setting a score.
game_short_name = "test_game"
game = await bot.send_game(chat_id, game_short_name)
message = await bot.set_game_score(
user_id=chat_id,
score=BASE_GAME_SCORE, # Score value is relevant for other set_game_score_* tests!
chat_id=game.chat_id,
message_id=game.message_id,
)
assert message.game.description == game.game.description
assert message.game.photo[0].file_size == game.game.photo[0].file_size
assert message.game.animation.file_unique_id == game.game.animation.file_unique_id
assert message.game.text != game.game.text
# Test setting a score higher than previous
game_short_name = "test_game"
game = await bot.send_game(chat_id, game_short_name)
score = BASE_GAME_SCORE + 1
message = await bot.set_game_score(
user_id=chat_id,
score=score,
chat_id=game.chat_id,
message_id=game.message_id,
disable_edit_message=True,
)
assert message.game.description == game.game.description
assert message.game.photo[0].file_size == game.game.photo[0].file_size
assert message.game.animation.file_unique_id == game.game.animation.file_unique_id
assert message.game.text == game.game.text
# Test setting a score lower than previous (should raise error)
game_short_name = "test_game"
game = await bot.send_game(chat_id, game_short_name)
score = BASE_GAME_SCORE # Even a score equal to previous raises an error.
with pytest.raises(BadRequest, match="Bot_score_not_modified"):
await bot.set_game_score(
user_id=chat_id, score=score, chat_id=game.chat_id, message_id=game.message_id
)
# Test force setting a lower score
game_short_name = "test_game"
game = await bot.send_game(chat_id, game_short_name)
await asyncio.sleep(1.5)
score = BASE_GAME_SCORE - 10
message = await bot.set_game_score(
user_id=chat_id,
score=score,
chat_id=game.chat_id,
message_id=game.message_id,
force=True,
)
assert message.game.description == game.game.description
assert message.game.photo[0].file_size == game.game.photo[0].file_size
assert message.game.animation.file_unique_id == game.game.animation.file_unique_id
# For some reason the returned message doesn't contain the updated score. need to fetch
# the game again... (the service message is also absent when running the test suite)
game2 = await bot.send_game(chat_id, game_short_name)
assert str(score) in game2.game.text
# We need a game to get the scores for
game_short_name = "test_game"
game = await bot.send_game(chat_id, game_short_name)
high_scores = await bot.get_game_high_scores(chat_id, game.chat_id, game.message_id)
# We assume that the other game score tests ran within 20 sec
assert high_scores[0].score == BASE_GAME_SCORE - 10
# send_invoice and create_invoice_link is tested in test_invoice
async def test_promote_chat_member(self, bot, channel_id, monkeypatch):
# TODO: Add bot to supergroup so this can be tested properly / give bot perms
with pytest.raises(BadRequest, match="Not enough rights"):
assert await bot.promote_chat_member(
channel_id,
1325859552,
is_anonymous=True,
can_change_info=True,
can_post_messages=True,
can_edit_messages=True,
can_delete_messages=True,
can_invite_users=True,
can_restrict_members=True,
can_pin_messages=True,
can_promote_members=True,
can_manage_chat=True,
can_manage_video_chats=True,
can_manage_topics=True,
can_post_stories=True,
can_edit_stories=True,
can_delete_stories=True,
)
# Test that we pass the correct params to TG
async def make_assertion(*args, **_):
data = args[1]
return (
data.get("chat_id") == channel_id
and data.get("user_id") == 1325859552
and data.get("is_anonymous") == 1
and data.get("can_change_info") == 2
and data.get("can_post_messages") == 3
and data.get("can_edit_messages") == 4
and data.get("can_delete_messages") == 5
and data.get("can_invite_users") == 6
and data.get("can_restrict_members") == 7
and data.get("can_pin_messages") == 8
and data.get("can_promote_members") == 9
and data.get("can_manage_chat") == 10
and data.get("can_manage_video_chats") == 11
and data.get("can_manage_topics") == 12
and data.get("can_post_stories") == 13
and data.get("can_edit_stories") == 14
and data.get("can_delete_stories") == 15
)
monkeypatch.setattr(bot, "_post", make_assertion)
assert await bot.promote_chat_member(
channel_id,
1325859552,
is_anonymous=1,
can_change_info=2,
can_post_messages=3,
can_edit_messages=4,
can_delete_messages=5,
can_invite_users=6,
can_restrict_members=7,
can_pin_messages=8,
can_promote_members=9,
can_manage_chat=10,
can_manage_video_chats=11,
can_manage_topics=12,
can_post_stories=13,
can_edit_stories=14,
can_delete_stories=15,
)
async def test_export_chat_invite_link(self, bot, channel_id):
# Each link is unique apparently
invite_link = await bot.export_chat_invite_link(channel_id)
assert isinstance(invite_link, str)
assert invite_link
async def test_edit_revoke_chat_invite_link_passing_link_objects(self, bot, channel_id):
invite_link = await bot.create_chat_invite_link(chat_id=channel_id)
assert invite_link.name is None
edited_link = await bot.edit_chat_invite_link(
chat_id=channel_id, invite_link=invite_link, name="some_name"
)
assert edited_link == invite_link
assert edited_link.name == "some_name"
revoked_link = await bot.revoke_chat_invite_link(
chat_id=channel_id, invite_link=edited_link
)
assert revoked_link.invite_link == edited_link.invite_link
assert revoked_link.is_revoked is True
assert revoked_link.name == "some_name"
@pytest.mark.parametrize("creates_join_request", [True, False])
@pytest.mark.parametrize("name", [None, "name"])
async def test_create_chat_invite_link_basics(
self, bot, creates_join_request, name, channel_id
):
data = {}
if creates_join_request:
data["creates_join_request"] = True
if name:
data["name"] = name
invite_link = await bot.create_chat_invite_link(chat_id=channel_id, **data)
assert invite_link.member_limit is None
assert invite_link.expire_date is None
assert invite_link.creates_join_request == creates_join_request
assert invite_link.name == name
revoked_link = await bot.revoke_chat_invite_link(
chat_id=channel_id, invite_link=invite_link.invite_link
)
assert revoked_link.is_revoked
@pytest.mark.parametrize("datetime", argvalues=[True, False], ids=["datetime", "integer"])
async def test_advanced_chat_invite_links(self, bot, channel_id, datetime):
# we are testing this all in one function in order to save api calls
timestamp = dtm.datetime.utcnow()
add_seconds = dtm.timedelta(0, 70)
time_in_future = timestamp + add_seconds
expire_time = time_in_future if datetime else to_timestamp(time_in_future)
aware_time_in_future = localize(time_in_future, UTC)
invite_link = await bot.create_chat_invite_link(
channel_id, expire_date=expire_time, member_limit=10
)
assert invite_link.invite_link
assert not invite_link.invite_link.endswith("...")
assert abs(invite_link.expire_date - aware_time_in_future) < dtm.timedelta(seconds=1)
assert invite_link.member_limit == 10
add_seconds = dtm.timedelta(0, 80)
time_in_future = timestamp + add_seconds
expire_time = time_in_future if datetime else to_timestamp(time_in_future)
aware_time_in_future = localize(time_in_future, UTC)
edited_invite_link = await bot.edit_chat_invite_link(
channel_id,
invite_link.invite_link,
expire_date=expire_time,
member_limit=20,
name="NewName",
)
assert edited_invite_link.invite_link == invite_link.invite_link
assert abs(edited_invite_link.expire_date - aware_time_in_future) < dtm.timedelta(
seconds=1
)
assert edited_invite_link.name == "NewName"
assert edited_invite_link.member_limit == 20
edited_invite_link = await bot.edit_chat_invite_link(
channel_id,
invite_link.invite_link,
name="EvenNewerName",
creates_join_request=True,
)
assert edited_invite_link.invite_link == invite_link.invite_link
assert not edited_invite_link.expire_date
assert edited_invite_link.name == "EvenNewerName"
assert edited_invite_link.creates_join_request
assert edited_invite_link.member_limit is None
revoked_invite_link = await bot.revoke_chat_invite_link(
channel_id, invite_link.invite_link
)
assert revoked_invite_link.invite_link == invite_link.invite_link
assert revoked_invite_link.is_revoked
async def test_advanced_chat_invite_links_default_tzinfo(self, tz_bot, channel_id):
# we are testing this all in one function in order to save api calls
add_seconds = dtm.timedelta(0, 70)
aware_expire_date = dtm.datetime.now(tz=tz_bot.defaults.tzinfo) + add_seconds
time_in_future = aware_expire_date.replace(tzinfo=None)
invite_link = await tz_bot.create_chat_invite_link(
channel_id, expire_date=time_in_future, member_limit=10
)
assert invite_link.invite_link
assert not invite_link.invite_link.endswith("...")
assert abs(invite_link.expire_date - aware_expire_date) < dtm.timedelta(seconds=1)
assert invite_link.member_limit == 10
add_seconds = dtm.timedelta(0, 80)
aware_expire_date += add_seconds
time_in_future = aware_expire_date.replace(tzinfo=None)
edited_invite_link = await tz_bot.edit_chat_invite_link(
channel_id,
invite_link.invite_link,
expire_date=time_in_future,
member_limit=20,
name="NewName",
)
assert edited_invite_link.invite_link == invite_link.invite_link
assert abs(edited_invite_link.expire_date - aware_expire_date) < dtm.timedelta(seconds=1)
assert edited_invite_link.name == "NewName"
assert edited_invite_link.member_limit == 20
edited_invite_link = await tz_bot.edit_chat_invite_link(
channel_id,
invite_link.invite_link,
name="EvenNewerName",
creates_join_request=True,
)
assert edited_invite_link.invite_link == invite_link.invite_link
assert not edited_invite_link.expire_date
assert edited_invite_link.name == "EvenNewerName"
assert edited_invite_link.creates_join_request
assert edited_invite_link.member_limit is None
revoked_invite_link = await tz_bot.revoke_chat_invite_link(
channel_id, invite_link.invite_link
)
assert revoked_invite_link.invite_link == invite_link.invite_link
assert revoked_invite_link.is_revoked
async def test_approve_chat_join_request(self, bot, chat_id, channel_id):
# TODO: Need incoming join request to properly test
# Since we can't create join requests on the fly, we just tests the call to TG
# by checking that it complains about approving a user who is already in the chat
with pytest.raises(BadRequest, match="User_already_participant"):
await bot.approve_chat_join_request(chat_id=channel_id, user_id=chat_id)
async def test_decline_chat_join_request(self, bot, chat_id, channel_id):
# TODO: Need incoming join request to properly test
# Since we can't create join requests on the fly, we just tests the call to TG
# by checking that it complains about declining a user who is already in the chat
#
# The error message Hide_requester_missing started showing up instead of
# User_already_participant. Don't know why …
with pytest.raises(BadRequest, match="User_already_participant|Hide_requester_missing"):
await bot.decline_chat_join_request(chat_id=channel_id, user_id=chat_id)
async def test_set_chat_photo(self, bot, channel_id):
async def func():
assert await bot.set_chat_photo(channel_id, f)
with data_file("telegram_test_channel.jpg").open("rb") as f:
await expect_bad_request(
func, "Type of file mismatch", "Telegram did not accept the file."
)
async def test_delete_chat_photo(self, bot, channel_id):
async def func():
assert await bot.delete_chat_photo(channel_id)
await expect_bad_request(func, "Chat_not_modified", "Chat photo was not set.")
async def test_set_chat_title(self, bot, channel_id):
assert await bot.set_chat_title(channel_id, ">>> telegram.Bot() - Tests")
async def test_set_chat_description(self, bot, channel_id):
assert await bot.set_chat_description(channel_id, "Time: " + str(time.time()))
async def test_pin_and_unpin_message(self, bot, super_group_id):
messages = [] # contains the Messages we sent
pinned_messages_tasks = set() # contains the asyncio.Tasks that pin the messages
# Let's send 3 messages so we can pin them
awaitables = {bot.send_message(super_group_id, f"test_pin_message_{i}") for i in range(3)}
# We will pin the messages immediately after sending them
for sending_msg in asyncio.as_completed(awaitables): # as_completed sends the messages
msg = await sending_msg
coro = bot.pin_chat_message(super_group_id, msg.message_id, True, read_timeout=10)
pinned_messages_tasks.add(asyncio.create_task(coro)) # start pinning the message
messages.append(msg)
assert len(messages) == 3 # Check if we sent 3 messages
# Check if we pinned 3 messages
assert all([await i for i in pinned_messages_tasks])
assert all(i.done() for i in pinned_messages_tasks) # Check if all tasks are done
chat = await bot.get_chat(super_group_id) # get the chat to check the pinned message
assert chat.pinned_message in messages
# Determine which message is not the most recently pinned
for old_pin_msg in messages:
if chat.pinned_message != old_pin_msg:
break
# Test unpinning our messages
tasks = asyncio.gather(
bot.unpin_chat_message( # unpins any message except the most recent
chat_id=super_group_id, # because we don't want to accidentally unpin the same msg
message_id=old_pin_msg.message_id, # twice
read_timeout=10,
),
bot.unpin_chat_message(chat_id=super_group_id, read_timeout=10), # unpins most recent
)
assert all(await tasks)
assert all(i.done() for i in tasks)
assert await bot.unpin_all_chat_messages(super_group_id, read_timeout=10)
# get_sticker_set, upload_sticker_file, create_new_sticker_set, add_sticker_to_set,
# set_sticker_position_in_set, delete_sticker_from_set and get_custom_emoji_stickers,
# replace_sticker_in_set are tested in the test_sticker module.
# get_forum_topic_icon_stickers, edit_forum_topic, general_forum etc...
# are tested in the test_forum module.
async def test_send_message_disable_web_page_preview(self, bot, chat_id):
"""Test that disable_web_page_preview is substituted for link_preview_options and that
it still works as expected for backward compatability."""
msg = await bot.send_message(
chat_id,
"https://github.com/python-telegram-bot/python-telegram-bot",
disable_web_page_preview=True,
)
assert msg.link_preview_options
assert msg.link_preview_options.is_disabled
async def test_send_message_link_preview_options(self, bot, chat_id):
"""Test whether link_preview_options is correctly passed to the API."""
# btw it is possible to have no url in the text, but set a url for the preview.
msg = await bot.send_message(
chat_id,
"https://github.com/python-telegram-bot/python-telegram-bot",
link_preview_options=LinkPreviewOptions(prefer_small_media=True, show_above_text=True),
)
assert msg.link_preview_options
assert not msg.link_preview_options.is_disabled
# The prefer_* options aren't very consistent on the client side (big pic shown) +
# they are not returned by the API.
# assert msg.link_preview_options.prefer_small_media
assert msg.link_preview_options.show_above_text
@pytest.mark.parametrize(
"default_bot",
[{"link_preview_options": LinkPreviewOptions(show_above_text=True)}],
indirect=True,
)
async def test_send_message_default_link_preview_options(self, default_bot, chat_id):
"""Test whether Defaults.link_preview_options is correctly fused with the passed LPO."""
github_url = "https://github.com/python-telegram-bot/python-telegram-bot"
website = "https://python-telegram-bot.org/"
# First test just the default passing:
coro1 = default_bot.send_message(chat_id, github_url)
# Next test fusion of both LPOs:
coro2 = default_bot.send_message(
chat_id,
github_url,
link_preview_options=LinkPreviewOptions(url=website, prefer_large_media=True),
)
# Now test fusion + overriding of passed LPO:
coro3 = default_bot.send_message(
chat_id,
github_url,
link_preview_options=LinkPreviewOptions(show_above_text=False, url=website),
)
# finally test explicitly setting to None
coro4 = default_bot.send_message(chat_id, github_url, link_preview_options=None)
msgs = asyncio.gather(coro1, coro2, coro3, coro4)
msg1, msg2, msg3, msg4 = await msgs
assert msg1.link_preview_options
assert msg1.link_preview_options.show_above_text
assert msg2.link_preview_options
assert msg2.link_preview_options.show_above_text
assert msg2.link_preview_options.url == website
assert msg2.link_preview_options.prefer_large_media # Now works correctly using new url..
assert msg3.link_preview_options
assert not msg3.link_preview_options.show_above_text
assert msg3.link_preview_options.url == website
assert msg4.link_preview_options == LinkPreviewOptions(url=github_url)
@pytest.mark.parametrize(
"default_bot",
[{"link_preview_options": LinkPreviewOptions(show_above_text=True)}],
indirect=True,
)
async def test_edit_message_text_default_link_preview_options(self, default_bot, chat_id):
"""Test whether Defaults.link_preview_options is correctly fused with the passed LPO."""
github_url = "https://github.com/python-telegram-bot/python-telegram-bot"
website = "https://python-telegram-bot.org/"
telegram_url = "https://telegram.org"
base_1, base_2, base_3, base_4 = await asyncio.gather(
*(default_bot.send_message(chat_id, telegram_url) for _ in range(4))
)
# First test just the default passing:
coro1 = base_1.edit_text(github_url)
# Next test fusion of both LPOs:
coro2 = base_2.edit_text(
github_url,
link_preview_options=LinkPreviewOptions(url=website, prefer_large_media=True),
)
# Now test fusion + overriding of passed LPO:
coro3 = base_3.edit_text(
github_url,
link_preview_options=LinkPreviewOptions(show_above_text=False, url=website),
)
# finally test explicitly setting to None
coro4 = base_4.edit_text(github_url, link_preview_options=None)
msgs = asyncio.gather(coro1, coro2, coro3, coro4)
msg1, msg2, msg3, msg4 = await msgs
assert msg1.link_preview_options
assert msg1.link_preview_options.show_above_text
assert msg2.link_preview_options
assert msg2.link_preview_options.show_above_text
assert msg2.link_preview_options.url == website
assert msg2.link_preview_options.prefer_large_media # Now works correctly using new url..
assert msg3.link_preview_options
assert not msg3.link_preview_options.show_above_text
assert msg3.link_preview_options.url == website
assert msg4.link_preview_options == LinkPreviewOptions(url=github_url)
async def test_send_message_entities(self, bot, chat_id):
test_string = "Italic Bold Code Spoiler"
entities = [
MessageEntity(MessageEntity.ITALIC, 0, 6),
MessageEntity(MessageEntity.ITALIC, 7, 4),
MessageEntity(MessageEntity.ITALIC, 12, 4),
MessageEntity(MessageEntity.SPOILER, 17, 7),
]
message = await bot.send_message(chat_id=chat_id, text=test_string, entities=entities)
assert message.text == test_string
assert message.entities == tuple(entities)
@pytest.mark.parametrize("default_bot", [{"parse_mode": "Markdown"}], indirect=True)
async def test_send_message_default_parse_mode(self, default_bot, chat_id):
test_string = "Italic Bold Code"
test_markdown_string = "_Italic_ *Bold* `Code`"
tasks = asyncio.gather(
*(
default_bot.send_message(chat_id, test_markdown_string, **i)
for i in ({}, {"parse_mode": None}, {"parse_mode": "HTML"})
)
)
msg1, msg2, msg3 = await tasks
assert msg1.text_markdown == test_markdown_string
assert msg1.text == test_string
assert msg2.text == test_markdown_string
assert msg2.text_markdown == escape_markdown(test_markdown_string)
assert msg3.text == test_markdown_string
assert msg3.text_markdown == escape_markdown(test_markdown_string)
@pytest.mark.parametrize("default_bot", [{"protect_content": True}], indirect=True)
async def test_send_message_default_protect_content(self, default_bot, chat_id):
tasks = asyncio.gather(
default_bot.send_message(chat_id, "test"),
default_bot.send_message(chat_id, "test", protect_content=False),
)
to_check, no_protect = await tasks
assert to_check.has_protected_content
assert not no_protect.has_protected_content
@pytest.mark.parametrize(
("default_bot", "custom"),
[
({"allow_sending_without_reply": True}, None),
({"allow_sending_without_reply": False}, None),
({"allow_sending_without_reply": False}, True),
],
indirect=["default_bot"],
)
async def test_send_message_default_allow_sending_without_reply(
self, default_bot, chat_id, custom
):
reply_to_message = await default_bot.send_message(chat_id, "test")
await reply_to_message.delete()
if custom is not None:
message = await default_bot.send_message(
chat_id,
"test",
allow_sending_without_reply=custom,
reply_to_message_id=reply_to_message.message_id,
)
assert message.reply_to_message is None
elif default_bot.defaults.allow_sending_without_reply:
message = await default_bot.send_message(
chat_id, "test", reply_to_message_id=reply_to_message.message_id
)
assert message.reply_to_message is None
else:
with pytest.raises(BadRequest, match="Message to be replied not found"):
await default_bot.send_message(
chat_id, "test", reply_to_message_id=reply_to_message.message_id
)
async def test_get_set_my_default_administrator_rights(self, bot):
# Test that my default administrator rights for group are as all False
assert await bot.set_my_default_administrator_rights() # clear any set rights
my_admin_rights_grp = await bot.get_my_default_administrator_rights()
assert isinstance(my_admin_rights_grp, ChatAdministratorRights)
assert all(not getattr(my_admin_rights_grp, at) for at in my_admin_rights_grp.__slots__)
# Test setting my default admin rights for channel
my_rights = ChatAdministratorRights.all_rights()
assert await bot.set_my_default_administrator_rights(my_rights, for_channels=True)
my_admin_rights_ch = await bot.get_my_default_administrator_rights(for_channels=True)
assert my_admin_rights_ch.can_invite_users is my_rights.can_invite_users
# tg bug? is_anonymous is False despite setting it True for channels:
assert my_admin_rights_ch.is_anonymous is not my_rights.is_anonymous
assert my_admin_rights_ch.can_manage_chat is my_rights.can_manage_chat
assert my_admin_rights_ch.can_delete_messages is my_rights.can_delete_messages
assert my_admin_rights_ch.can_edit_messages is my_rights.can_edit_messages
assert my_admin_rights_ch.can_post_messages is my_rights.can_post_messages
assert my_admin_rights_ch.can_change_info is my_rights.can_change_info
assert my_admin_rights_ch.can_promote_members is my_rights.can_promote_members
assert my_admin_rights_ch.can_restrict_members is my_rights.can_restrict_members
assert my_admin_rights_ch.can_pin_messages is None # Not returned for channels
assert my_admin_rights_ch.can_manage_topics is None # Not returned for channels
async def test_get_set_chat_menu_button(self, bot, chat_id):
# Test our chat menu button is commands-
menu_button = await bot.get_chat_menu_button()
assert isinstance(menu_button, MenuButton)
assert isinstance(menu_button, MenuButtonCommands)
assert menu_button.type == MenuButtonType.COMMANDS
# Test setting our chat menu button to Webapp.
my_menu = MenuButtonWebApp("click me!", WebAppInfo("https://telegram.org/"))
assert await bot.set_chat_menu_button(chat_id=chat_id, menu_button=my_menu)
menu_button = await bot.get_chat_menu_button(chat_id)
assert isinstance(menu_button, MenuButtonWebApp)
assert menu_button.type == MenuButtonType.WEB_APP
assert menu_button.text == my_menu.text
assert menu_button.web_app.url == my_menu.web_app.url
assert await bot.set_chat_menu_button(chat_id=chat_id, menu_button=MenuButtonDefault())
menu_button = await bot.get_chat_menu_button(chat_id=chat_id)
assert isinstance(menu_button, MenuButtonDefault)
async def test_set_and_get_my_commands(self, bot):
commands = [BotCommand("cmd1", "descr1"), ["cmd2", "descr2"]]
assert await bot.set_my_commands([])
assert await bot.get_my_commands() == ()
assert await bot.set_my_commands(commands)
for i, bc in enumerate(await bot.get_my_commands()):
assert bc.command == f"cmd{i + 1}"
assert bc.description == f"descr{i + 1}"
async def test_get_set_delete_my_commands_with_scope(self, bot, super_group_id, chat_id):
group_cmds = [BotCommand("group_cmd", "visible to this supergroup only")]
private_cmds = [BotCommand("private_cmd", "visible to this private chat only")]
group_scope = BotCommandScopeChat(super_group_id)
private_scope = BotCommandScopeChat(chat_id)
# Set supergroup command list with lang code and check if the same can be returned from api
assert await bot.set_my_commands(group_cmds, scope=group_scope, language_code="en")
gotten_group_cmds = await bot.get_my_commands(scope=group_scope, language_code="en")
assert len(gotten_group_cmds) == len(group_cmds)
assert gotten_group_cmds[0].command == group_cmds[0].command
# Set private command list and check if same can be returned from the api
assert await bot.set_my_commands(private_cmds, scope=private_scope)
gotten_private_cmd = await bot.get_my_commands(scope=private_scope)
assert len(gotten_private_cmd) == len(private_cmds)
assert gotten_private_cmd[0].command == private_cmds[0].command
# Delete command list from that supergroup and private chat-
tasks = asyncio.gather(
bot.delete_my_commands(private_scope),
bot.delete_my_commands(group_scope, "en"),
)
assert all(await tasks)
# Check if its been deleted-
tasks = asyncio.gather(
bot.get_my_commands(private_scope),
bot.get_my_commands(group_scope, "en"),
)
deleted_priv_cmds, deleted_grp_cmds = await tasks
assert len(deleted_grp_cmds) == 0 == len(group_cmds) - 1
assert len(deleted_priv_cmds) == 0 == len(private_cmds) - 1
await bot.delete_my_commands() # Delete commands from default scope
assert len(await bot.get_my_commands()) == 0
async def test_copy_message_without_reply(self, bot, chat_id, media_message):
keyboard = InlineKeyboardMarkup(
[[InlineKeyboardButton(text="test", callback_data="test2")]]
)
returned = await bot.copy_message(
chat_id,
from_chat_id=chat_id,
message_id=media_message.message_id,
caption="<b>Test</b>",
parse_mode=ParseMode.HTML,
reply_to_message_id=media_message.message_id,
reply_markup=keyboard,
show_caption_above_media=False,
)
# we send a temp message which replies to the returned message id in order to get a
# message object
temp_message = await bot.send_message(
chat_id, "test", reply_to_message_id=returned.message_id
)
message = temp_message.reply_to_message
assert message.chat_id == int(chat_id)
assert message.caption == "Test"
assert len(message.caption_entities) == 1
assert message.reply_markup == keyboard
@pytest.mark.parametrize(
"default_bot",
[
({"parse_mode": ParseMode.HTML, "allow_sending_without_reply": True}),
({"parse_mode": None, "allow_sending_without_reply": True}),
({"parse_mode": None, "allow_sending_without_reply": False}),
],
indirect=["default_bot"],
)
async def test_copy_message_with_default(self, default_bot, chat_id, media_message):
reply_to_message = await default_bot.send_message(chat_id, "test")
await reply_to_message.delete()
if not default_bot.defaults.allow_sending_without_reply:
with pytest.raises(BadRequest, match="not found"):
await default_bot.copy_message(
chat_id,
from_chat_id=chat_id,
message_id=media_message.message_id,
caption="<b>Test</b>",
reply_to_message_id=reply_to_message.message_id,
)
return
returned = await default_bot.copy_message(
chat_id,
from_chat_id=chat_id,
message_id=media_message.message_id,
caption="<b>Test</b>",
reply_to_message_id=reply_to_message.message_id,
)
# we send a temp message which replies to the returned message id in order to get a
# message object
temp_message = await default_bot.send_message(
chat_id, "test", reply_to_message_id=returned.message_id
)
message = temp_message.reply_to_message
if default_bot.defaults.parse_mode:
assert len(message.caption_entities) == 1
else:
assert len(message.caption_entities) == 0
async def test_copy_messages(self, bot, chat_id):
# not using gather here to have deterministically ordered message_ids
msg1 = await bot.send_message(chat_id, text="will be copied 1")
msg2 = await bot.send_message(chat_id, text="will be copied 2")
copy_messages = await bot.copy_messages(
chat_id, from_chat_id=chat_id, message_ids=(msg1.message_id, msg2.message_id)
)
assert isinstance(copy_messages, tuple)
tasks = asyncio.gather(
bot.send_message(chat_id, "temp 1", reply_to_message_id=copy_messages[0].message_id),
bot.send_message(chat_id, "temp 2", reply_to_message_id=copy_messages[1].message_id),
)
temp_msg1, temp_msg2 = await tasks
forward_msg1 = temp_msg1.reply_to_message
forward_msg2 = temp_msg2.reply_to_message
assert forward_msg1.text == msg1.text
assert forward_msg2.text == msg2.text
# Continue testing arbitrary callback data here with actual requests:
async def test_replace_callback_data_send_message(self, cdc_bot, chat_id):
bot = cdc_bot
try:
replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test")
no_replace_button = InlineKeyboardButton(
text="no_replace", url="http://python-telegram-bot.org/"
)
reply_markup = InlineKeyboardMarkup.from_row(
[
replace_button,
no_replace_button,
]
)
message = await bot.send_message(
chat_id=chat_id, text="test", reply_markup=reply_markup
)
inline_keyboard = message.reply_markup.inline_keyboard
assert inline_keyboard[0][1] == no_replace_button
assert inline_keyboard[0][0] == replace_button
keyboard = next(iter(bot.callback_data_cache._keyboard_data))
data = next(
iter(bot.callback_data_cache._keyboard_data[keyboard].button_data.values())
)
assert data == "replace_test"
finally:
bot.callback_data_cache.clear_callback_data()
bot.callback_data_cache.clear_callback_queries()
async def test_replace_callback_data_stop_poll_and_repl_to_message(self, cdc_bot, chat_id):
bot = cdc_bot
poll_message = await bot.send_poll(chat_id=chat_id, question="test", options=["1", "2"])
try:
replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test")
no_replace_button = InlineKeyboardButton(
text="no_replace", url="http://python-telegram-bot.org/"
)
reply_markup = InlineKeyboardMarkup.from_row(
[
replace_button,
no_replace_button,
]
)
await poll_message.stop_poll(reply_markup=reply_markup)
helper_message = await poll_message.reply_text("temp", do_quote=True)
message = helper_message.reply_to_message
inline_keyboard = message.reply_markup.inline_keyboard
assert inline_keyboard[0][1] == no_replace_button
assert inline_keyboard[0][0] == replace_button
keyboard = next(iter(bot.callback_data_cache._keyboard_data))
data = next(
iter(bot.callback_data_cache._keyboard_data[keyboard].button_data.values())
)
assert data == "replace_test"
finally:
bot.callback_data_cache.clear_callback_data()
bot.callback_data_cache.clear_callback_queries()
async def test_replace_callback_data_copy_message(self, cdc_bot, chat_id):
"""This also tests that data is inserted into the buttons of message.reply_to_message
where message is the return value of a bot method"""
bot = cdc_bot
original_message = await bot.send_message(chat_id=chat_id, text="original")
try:
replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test")
no_replace_button = InlineKeyboardButton(
text="no_replace", url="http://python-telegram-bot.org/"
)
reply_markup = InlineKeyboardMarkup.from_row(
[
replace_button,
no_replace_button,
]
)
message_id = await original_message.copy(chat_id=chat_id, reply_markup=reply_markup)
helper_message = await bot.send_message(
chat_id=chat_id, reply_to_message_id=message_id.message_id, text="temp"
)
message = helper_message.reply_to_message
inline_keyboard = message.reply_markup.inline_keyboard
assert inline_keyboard[0][1] == no_replace_button
assert inline_keyboard[0][0] == replace_button
keyboard = next(iter(bot.callback_data_cache._keyboard_data))
data = next(
iter(bot.callback_data_cache._keyboard_data[keyboard].button_data.values())
)
assert data == "replace_test"
finally:
bot.callback_data_cache.clear_callback_data()
bot.callback_data_cache.clear_callback_queries()
async def test_get_chat_arbitrary_callback_data(self, chat_id, cdc_bot):
bot = cdc_bot
try:
reply_markup = InlineKeyboardMarkup.from_button(
InlineKeyboardButton(text="text", callback_data="callback_data")
)
message = await bot.send_message(
chat_id, text="get_chat_arbitrary_callback_data", reply_markup=reply_markup
)
await message.pin()
keyboard = next(iter(bot.callback_data_cache._keyboard_data))
data = next(
iter(bot.callback_data_cache._keyboard_data[keyboard].button_data.values())
)
assert data == "callback_data"
cfi = await bot.get_chat(chat_id)
if not cfi.pinned_message:
pytest.xfail("Pinning messages is not always reliable on TG")
assert cfi.pinned_message == message
assert cfi.pinned_message.reply_markup == reply_markup
assert await message.unpin() # (not placed in finally block since msg can be unbound)
finally:
bot.callback_data_cache.clear_callback_data()
bot.callback_data_cache.clear_callback_queries()
async def test_arbitrary_callback_data_get_chat_no_pinned_message(
self, super_group_id, cdc_bot
):
bot = cdc_bot
await bot.unpin_all_chat_messages(super_group_id)
try:
cfi = await bot.get_chat(super_group_id)
assert isinstance(cfi, ChatFullInfo)
assert int(cfi.id) == int(super_group_id)
assert cfi.pinned_message is None
finally:
bot.callback_data_cache.clear_callback_data()
bot.callback_data_cache.clear_callback_queries()
async def test_set_get_my_description(self, bot):
default_description = f"{bot.username} - default - {dtm.datetime.utcnow().isoformat()}"
en_description = f"{bot.username} - en - {dtm.datetime.utcnow().isoformat()}"
de_description = f"{bot.username} - de - {dtm.datetime.utcnow().isoformat()}"
# Set the descriptions
assert all(
await asyncio.gather(
bot.set_my_description(default_description),
bot.set_my_description(en_description, language_code="en"),
bot.set_my_description(de_description, language_code="de"),
)
)
# Check that they were set correctly
assert await asyncio.gather(
bot.get_my_description(), bot.get_my_description("en"), bot.get_my_description("de")
) == [
BotDescription(default_description),
BotDescription(en_description),
BotDescription(de_description),
]
# Delete the descriptions
assert all(
await asyncio.gather(
bot.set_my_description(None),
bot.set_my_description(None, language_code="en"),
bot.set_my_description(None, language_code="de"),
)
)
# Check that they were deleted correctly
assert await asyncio.gather(
bot.get_my_description(), bot.get_my_description("en"), bot.get_my_description("de")
) == 3 * [BotDescription("")]
async def test_set_get_my_short_description(self, bot):
default_short_description = (
f"{bot.username} - default - {dtm.datetime.utcnow().isoformat()}"
)
en_short_description = f"{bot.username} - en - {dtm.datetime.utcnow().isoformat()}"
de_short_description = f"{bot.username} - de - {dtm.datetime.utcnow().isoformat()}"
# Set the short_descriptions
assert all(
await asyncio.gather(
bot.set_my_short_description(default_short_description),
bot.set_my_short_description(en_short_description, language_code="en"),
bot.set_my_short_description(de_short_description, language_code="de"),
)
)
# Check that they were set correctly
assert await asyncio.gather(
bot.get_my_short_description(),
bot.get_my_short_description("en"),
bot.get_my_short_description("de"),
) == [
BotShortDescription(default_short_description),
BotShortDescription(en_short_description),
BotShortDescription(de_short_description),
]
# Delete the short_descriptions
assert all(
await asyncio.gather(
bot.set_my_short_description(None),
bot.set_my_short_description(None, language_code="en"),
bot.set_my_short_description(None, language_code="de"),
)
)
# Check that they were deleted correctly
assert await asyncio.gather(
bot.get_my_short_description(),
bot.get_my_short_description("en"),
bot.get_my_short_description("de"),
) == 3 * [BotShortDescription("")]
async def test_set_message_reaction(self, bot, chat_id, static_message):
assert await bot.set_message_reaction(
chat_id, static_message.message_id, ReactionEmoji.THUMBS_DOWN, True
)
@pytest.mark.parametrize("bot_class", [Bot, ExtBot])
async def test_do_api_request_warning_known_method(self, bot, bot_class):
with pytest.warns(PTBUserWarning, match="Please use 'Bot.get_me'") as record:
await bot_class(bot.token).do_api_request("get_me")
assert record[0].filename == __file__, "Wrong stack level!"
async def test_do_api_request_unknown_method(self, bot):
with pytest.raises(EndPointNotFound, match="'unknownEndpoint' not found"):
await bot.do_api_request("unknown_endpoint")
@pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning")
async def test_do_api_request_invalid_token(self, bot):
# we do not initialize the bot here on purpose b/c that's the case were we actually
# do not know for sure if the token is invalid or the method was not found
with pytest.raises(
InvalidToken, match="token was rejected by Telegram or the endpoint 'getMe'"
):
await Bot("invalid_token").do_api_request("get_me")
# same test, but with a valid token bot and unknown endpoint
with pytest.raises(
InvalidToken, match="token was rejected by Telegram or the endpoint 'unknownEndpoint'"
):
await Bot(bot.token).do_api_request("unknown_endpoint")
@pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning")
@pytest.mark.parametrize("return_type", [Message, None])
async def test_do_api_request_basic_and_files(self, bot, chat_id, return_type):
result = await bot.do_api_request(
"send_document",
api_kwargs={
"chat_id": chat_id,
"caption": "test_caption",
"document": InputFile(data_file("telegram.png").open("rb")),
},
return_type=return_type,
)
if return_type is None:
assert isinstance(result, dict)
result = Message.de_json(result, bot)
assert isinstance(result, Message)
assert result.chat_id == int(chat_id)
assert result.caption == "test_caption"
out = BytesIO()
await (await result.document.get_file()).download_to_memory(out)
out.seek(0)
assert out.read() == data_file("telegram.png").open("rb").read()
assert result.document.file_name == "telegram.png"
@pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning")
@pytest.mark.parametrize("return_type", [Message, None])
async def test_do_api_request_list_return_type(self, bot, chat_id, return_type):
result = await bot.do_api_request(
"send_media_group",
api_kwargs={
"chat_id": chat_id,
"media": [
InputMediaDocument(
InputFile(
data_file("text_file.txt").open("rb"),
attach=True,
)
),
InputMediaDocument(
InputFile(
data_file("local_file.txt").open("rb"),
attach=True,
)
),
],
},
return_type=return_type,
)
if return_type is None:
assert isinstance(result, list)
for entry in result:
assert isinstance(entry, dict)
result = Message.de_list(result, bot)
for message, file_name in zip(result, ("text_file.txt", "local_file.txt")):
assert isinstance(message, Message)
assert message.chat_id == int(chat_id)
out = BytesIO()
await (await message.document.get_file()).download_to_memory(out)
out.seek(0)
assert out.read() == data_file(file_name).open("rb").read()
assert message.document.file_name == file_name
@pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning")
@pytest.mark.parametrize("return_type", [Message, None])
async def test_do_api_request_bool_return_type(self, bot, chat_id, return_type):
assert await bot.do_api_request("delete_my_commands", return_type=return_type) is True
async def test_get_star_transactions(self, bot):
transactions = await bot.get_star_transactions(limit=1)
assert isinstance(transactions, StarTransactions)
assert len(transactions.transactions) == 0
@pytest.mark.parametrize("subscription_period", [2592000, dtm.timedelta(days=30)])
async def test_create_edit_chat_subscription_link(
self, bot, subscription_channel_id, channel_id, subscription_period
):
sub_link = await bot.create_chat_subscription_invite_link(
subscription_channel_id,
name="sub_name",
subscription_period=subscription_period,
subscription_price=13,
)
assert sub_link.name == "sub_name"
assert sub_link.subscription_period == 2592000
assert sub_link.subscription_price == 13
edited_link = await bot.edit_chat_subscription_invite_link(
chat_id=subscription_channel_id, invite_link=sub_link, name="sub_name_2"
)
assert edited_link.name == "sub_name_2"
assert sub_link.subscription_period == 2592000
assert sub_link.subscription_price == 13
async def test_get_my_star_balance(self, bot):
balance = await bot.get_my_star_balance()
assert isinstance(balance, StarAmount)
assert balance.amount == 0
|