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
|
#!/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/].
"""Persistence of conversations is tested in test_basepersistence.py"""
import asyncio
import functools
import logging
from copy import copy
from pathlib import Path
from warnings import filterwarnings
import pytest
from telegram import (
CallbackQuery,
Chat,
ChosenInlineResult,
InlineQuery,
Message,
MessageEntity,
PreCheckoutQuery,
ShippingQuery,
Update,
User,
)
from telegram.ext import (
ApplicationBuilder,
ApplicationHandlerStop,
CallbackContext,
CallbackQueryHandler,
ChosenInlineResultHandler,
CommandHandler,
ConversationHandler,
Defaults,
InlineQueryHandler,
JobQueue,
MessageHandler,
PollAnswerHandler,
PollHandler,
PreCheckoutQueryHandler,
ShippingQueryHandler,
StringCommandHandler,
StringRegexHandler,
TypeHandler,
filters,
)
from telegram.warnings import PTBUserWarning
from tests.auxil.build_messages import make_command_message
from tests.auxil.files import SOURCE_ROOT_PATH
from tests.auxil.pytest_classes import PytestBot, make_bot
from tests.auxil.slots import mro_slots
@pytest.fixture(scope="class")
def user1():
return User(first_name="Misses Test", id=123, is_bot=False)
@pytest.fixture(scope="class")
def user2():
return User(first_name="Mister Test", id=124, is_bot=False)
def raise_ahs(func):
@functools.wraps(func) # for checking __repr__
async def decorator(self, *args, **kwargs):
result = await func(self, *args, **kwargs)
if self.raise_app_handler_stop:
raise ApplicationHandlerStop(result)
return result
return decorator
class TestConversationHandler:
"""Persistence of conversations is tested in test_basepersistence.py"""
# State definitions
# At first we're thirsty. Then we brew coffee, we drink it
# and then we can start coding!
END, THIRSTY, BREWING, DRINKING, CODING = range(-1, 4)
# Drinking state definitions (nested)
# At first we're holding the cup. Then we sip coffee, and last we swallow it
HOLDING, SIPPING, SWALLOWING, REPLENISHING, STOPPING = map(chr, range(ord("a"), ord("f")))
current_state, entry_points, states, fallbacks = None, None, None, None
group = Chat(0, Chat.GROUP)
second_group = Chat(1, Chat.GROUP)
raise_app_handler_stop = False
test_flag = False
# Test related
@pytest.fixture(autouse=True)
def _reset(self):
self.raise_app_handler_stop = False
self.test_flag = False
self.current_state = {}
self.entry_points = [CommandHandler("start", self.start)]
self.states = {
self.THIRSTY: [CommandHandler("brew", self.brew), CommandHandler("wait", self.start)],
self.BREWING: [CommandHandler("pourCoffee", self.drink)],
self.DRINKING: [
CommandHandler("startCoding", self.code),
CommandHandler("drinkMore", self.drink),
CommandHandler("end", self.end),
],
self.CODING: [
CommandHandler("keepCoding", self.code),
CommandHandler("gettingThirsty", self.start),
CommandHandler("drinkMore", self.drink),
],
}
self.fallbacks = [CommandHandler("eat", self.start)]
self.is_timeout = False
# for nesting tests
self.nested_states = {
self.THIRSTY: [CommandHandler("brew", self.brew), CommandHandler("wait", self.start)],
self.BREWING: [CommandHandler("pourCoffee", self.drink)],
self.CODING: [
CommandHandler("keepCoding", self.code),
CommandHandler("gettingThirsty", self.start),
CommandHandler("drinkMore", self.drink),
],
}
self.drinking_entry_points = [CommandHandler("hold", self.hold)]
self.drinking_states = {
self.HOLDING: [CommandHandler("sip", self.sip)],
self.SIPPING: [CommandHandler("swallow", self.swallow)],
self.SWALLOWING: [CommandHandler("hold", self.hold)],
}
self.drinking_fallbacks = [
CommandHandler("replenish", self.replenish),
CommandHandler("stop", self.stop),
CommandHandler("end", self.end),
CommandHandler("startCoding", self.code),
CommandHandler("drinkMore", self.drink),
]
self.drinking_entry_points.extend(self.drinking_fallbacks)
# Map nested states to parent states:
self.drinking_map_to_parent = {
# Option 1 - Map a fictional internal state to an external parent state
self.REPLENISHING: self.BREWING,
# Option 2 - Map a fictional internal state to the END state on the parent
self.STOPPING: self.END,
# Option 3 - Map the internal END state to an external parent state
self.END: self.CODING,
# Option 4 - Map an external state to the same external parent state
self.CODING: self.CODING,
# Option 5 - Map an external state to the internal entry point
self.DRINKING: self.DRINKING,
}
# State handlers
def _set_state(self, update, state):
self.current_state[update.message.from_user.id] = state
return state
# Actions
@raise_ahs
async def start(self, update, context):
if isinstance(update, Update):
return self._set_state(update, self.THIRSTY)
return self._set_state(context.bot, self.THIRSTY)
@raise_ahs
async def end(self, update, context):
return self._set_state(update, self.END)
@raise_ahs
async def start_end(self, update, context):
return self._set_state(update, self.END)
@raise_ahs
async def start_none(self, update, context):
return self._set_state(update, None)
@raise_ahs
async def brew(self, update, context):
if isinstance(update, Update):
return self._set_state(update, self.BREWING)
return self._set_state(context.bot, self.BREWING)
@raise_ahs
async def drink(self, update, context):
return self._set_state(update, self.DRINKING)
@raise_ahs
async def code(self, update, context):
return self._set_state(update, self.CODING)
@raise_ahs
async def passout(self, update, context):
assert update.message.text == "/brew"
assert isinstance(update, Update)
self.is_timeout = True
@raise_ahs
async def passout2(self, update, context):
assert isinstance(update, Update)
self.is_timeout = True
@raise_ahs
async def passout_context(self, update, context):
assert update.message.text == "/brew"
assert isinstance(context, CallbackContext)
self.is_timeout = True
@raise_ahs
async def passout2_context(self, update, context):
assert isinstance(context, CallbackContext)
self.is_timeout = True
# Drinking actions (nested)
@raise_ahs
async def hold(self, update, context):
return self._set_state(update, self.HOLDING)
@raise_ahs
async def sip(self, update, context):
return self._set_state(update, self.SIPPING)
@raise_ahs
async def swallow(self, update, context):
return self._set_state(update, self.SWALLOWING)
@raise_ahs
async def replenish(self, update, context):
return self._set_state(update, self.REPLENISHING)
@raise_ahs
async def stop(self, update, context):
return self._set_state(update, self.STOPPING)
def test_slot_behaviour(self):
handler = ConversationHandler(entry_points=[], states={}, fallbacks=[])
for attr in handler.__slots__:
assert getattr(handler, attr, "err") != "err", f"got extra slot '{attr}'"
assert len(mro_slots(handler)) == len(set(mro_slots(handler))), "duplicate slot"
def test_init(self):
entry_points = []
states = {}
fallbacks = []
map_to_parent = {}
ch = ConversationHandler(
entry_points=entry_points,
states=states,
fallbacks=fallbacks,
per_chat="per_chat",
per_user="per_user",
per_message="per_message",
persistent="persistent",
name="name",
allow_reentry="allow_reentry",
conversation_timeout=42,
map_to_parent=map_to_parent,
)
assert ch.entry_points is entry_points
assert ch.states is states
assert ch.fallbacks is fallbacks
assert ch.map_to_parent is map_to_parent
assert ch.per_chat == "per_chat"
assert ch.per_user == "per_user"
assert ch.per_message == "per_message"
assert ch.persistent == "persistent"
assert ch.name == "name"
assert ch.allow_reentry == "allow_reentry"
def test_init_persistent_no_name(self):
with pytest.raises(ValueError, match="can't be persistent when handler is unnamed"):
ConversationHandler(
self.entry_points, states=self.states, fallbacks=[], persistent=True
)
def test_repr_no_truncation(self):
# ConversationHandler's __repr__ is not inherited from BaseHandler.
ch = ConversationHandler(
name="test_handler",
entry_points=[],
states=self.drinking_states,
fallbacks=[],
)
assert repr(ch) == (
"ConversationHandler[name=test_handler, "
"states={'a': [CommandHandler[callback=TestConversationHandler.sip]], "
"'b': [CommandHandler[callback=TestConversationHandler.swallow]], "
"'c': [CommandHandler[callback=TestConversationHandler.hold]]}]"
)
def test_repr_with_truncation(self):
states = copy(self.drinking_states)
# there are exactly 3 drinking states. adding one more to make sure it's truncated
states["extra_to_be_truncated"] = [CommandHandler("foo", self.start)]
ch = ConversationHandler(
name="test_handler",
entry_points=[],
states=states,
fallbacks=[],
)
assert repr(ch) == (
"ConversationHandler[name=test_handler, "
"states={'a': [CommandHandler[callback=TestConversationHandler.sip]], "
"'b': [CommandHandler[callback=TestConversationHandler.swallow]], "
"'c': [CommandHandler[callback=TestConversationHandler.hold]], ...}]"
)
async def test_check_update_returns_non(self, app, user1):
"""checks some cases where updates should not be handled"""
conv_handler = ConversationHandler([], {}, [], per_message=True, per_chat=True)
assert not conv_handler.check_update("not an Update")
assert not conv_handler.check_update(Update(0))
assert not conv_handler.check_update(
Update(0, callback_query=CallbackQuery("1", from_user=user1, chat_instance="1"))
)
async def test_handlers_generate_warning(self, recwarn):
"""this function tests all handler + per_* setting combinations."""
# the warning message action needs to be set to always,
# otherwise only the first occurrence will be issued
filterwarnings(action="always", category=PTBUserWarning)
# this class doesn't do anything, its just not the Update class
class NotUpdate:
pass
recwarn.clear()
# this conversation handler has the string, string_regex, Pollhandler and TypeHandler
# which should all generate a warning no matter the per_* setting. TypeHandler should
# not when the class is Update
ConversationHandler(
entry_points=[StringCommandHandler("code", self.code)],
states={
self.BREWING: [
StringRegexHandler("code", self.code),
PollHandler(self.code),
TypeHandler(NotUpdate, self.code),
],
},
fallbacks=[TypeHandler(Update, self.code)],
)
# these handlers should all raise a warning when per_chat is True
ConversationHandler(
entry_points=[ShippingQueryHandler(self.code)],
states={
self.BREWING: [
InlineQueryHandler(self.code),
PreCheckoutQueryHandler(self.code),
PollAnswerHandler(self.code),
],
},
fallbacks=[ChosenInlineResultHandler(self.code)],
per_chat=True,
)
# the CallbackQueryHandler should *not* raise when per_message is True,
# but any other one should
ConversationHandler(
entry_points=[CallbackQueryHandler(self.code)],
states={
self.BREWING: [CommandHandler("code", self.code)],
},
fallbacks=[CallbackQueryHandler(self.code)],
per_message=True,
)
# the CallbackQueryHandler should raise when per_message is False
ConversationHandler(
entry_points=[CommandHandler("code", self.code)],
states={
self.BREWING: [CommandHandler("code", self.code)],
},
fallbacks=[CallbackQueryHandler(self.code)],
per_message=False,
)
# adding a nested conv to a conversation with timeout should warn
child = ConversationHandler(
entry_points=[CommandHandler("code", self.code)],
states={
self.BREWING: [CommandHandler("code", self.code)],
},
fallbacks=[CommandHandler("code", self.code)],
)
ConversationHandler(
entry_points=[CommandHandler("code", self.code)],
states={
self.BREWING: [child],
},
fallbacks=[CommandHandler("code", self.code)],
conversation_timeout=42,
)
# If per_message is True, per_chat should also be True, since msg ids are not unique
ConversationHandler(
entry_points=[CallbackQueryHandler(self.code, "code")],
states={
self.BREWING: [CallbackQueryHandler(self.code, "code")],
},
fallbacks=[CallbackQueryHandler(self.code, "code")],
per_message=True,
per_chat=False,
)
# the overall number of handlers throwing a warning is 13
assert len(recwarn) == 13
# now we test the messages, they are raised in the order they are inserted
# into the conversation handler
assert (
str(recwarn[0].message)
== "The `ConversationHandler` only handles updates of type `telegram.Update`. "
"StringCommandHandler handles updates of type `str`."
)
assert (
str(recwarn[1].message)
== "The `ConversationHandler` only handles updates of type `telegram.Update`. "
"StringRegexHandler handles updates of type `str`."
)
assert (
str(recwarn[2].message)
== "PollHandler will never trigger in a conversation since it has no information "
"about the chat or the user who voted in it. Do you mean the "
"`PollAnswerHandler`?"
)
assert (
str(recwarn[3].message)
== "The `ConversationHandler` only handles updates of type `telegram.Update`. "
"The TypeHandler is set to handle NotUpdate."
)
per_faq_link = (
" Read this FAQ entry to learn more about the per_* settings: "
"https://github.com/python-telegram-bot/python-telegram-bot/wiki"
"/Frequently-Asked-Questions#what-do-the-per_-settings-in-conversationhandler-do."
)
assert str(recwarn[4].message) == (
"Updates handled by ShippingQueryHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[5].message) == (
"Updates handled by ChosenInlineResultHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[6].message) == (
"Updates handled by InlineQueryHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[7].message) == (
"Updates handled by PreCheckoutQueryHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[8].message) == (
"Updates handled by PollAnswerHandler only have information about the user,"
" so this handler won't ever be triggered if `per_chat=True`." + per_faq_link
)
assert str(recwarn[9].message) == (
"If 'per_message=True', all entry points, state handlers, and fallbacks must be "
"'CallbackQueryHandler', since no other handlers have a message context."
+ per_faq_link
)
assert str(recwarn[10].message) == (
"If 'per_message=False', 'CallbackQueryHandler' will not be tracked for every message."
+ per_faq_link
)
assert (
str(recwarn[11].message)
== "Using `conversation_timeout` with nested conversations is currently not "
"supported. You can still try to use it, but it will likely behave differently"
" from what you expect."
)
assert (
str(recwarn[12].message)
== "If 'per_message=True' is used, 'per_chat=True' should also be used, "
"since message IDs are not globally unique."
)
# this for loop checks if the correct stacklevel is used when generating the warning
for warning in recwarn:
assert warning.category is PTBUserWarning
assert warning.filename == __file__, "incorrect stacklevel!"
@pytest.mark.parametrize(
"attr",
[
"entry_points",
"states",
"fallbacks",
"per_chat",
"per_user",
"per_message",
"name",
"persistent",
"allow_reentry",
"conversation_timeout",
"map_to_parent",
],
indirect=False,
)
def test_immutable(self, attr):
ch = ConversationHandler(entry_points=[], states={}, fallbacks=[])
with pytest.raises(AttributeError, match=f"You can not assign a new value to {attr}"):
setattr(ch, attr, True)
def test_per_all_false(self):
with pytest.raises(ValueError, match="can't all be 'False'"):
ConversationHandler(
entry_points=[],
states={},
fallbacks=[],
per_chat=False,
per_user=False,
per_message=False,
)
@pytest.mark.parametrize("raise_ahs", [True, False])
async def test_basic_and_app_handler_stop(self, app, bot, user1, user2, raise_ahs):
handler = ConversationHandler(
entry_points=self.entry_points, states=self.states, fallbacks=self.fallbacks
)
app.add_handler(handler)
async def callback(_, __):
self.test_flag = True
app.add_handler(TypeHandler(object, callback), group=100)
self.raise_app_handler_stop = raise_ahs
# User one, starts the state machine.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
assert self.test_flag == (not raise_ahs)
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.BREWING
assert self.test_flag == (not raise_ahs)
# Lets see if an invalid command makes sure, no state is changed.
message.text = "/nothing"
message.entities[0].length = len("/nothing")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.BREWING
assert self.test_flag is True
self.test_flag = False
# Lets see if the state machine still works by pouring coffee.
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
assert self.test_flag == (not raise_ahs)
# Let's now verify that for another user, who did not start yet,
# the state has not been changed.
message.from_user = user2
await app.process_update(Update(update_id=0, message=message))
with pytest.raises(KeyError):
self.current_state[user2.id]
async def test_conversation_handler_end(self, caplog, app, bot, user1):
handler = ConversationHandler(
entry_points=self.entry_points, states=self.states, fallbacks=self.fallbacks
)
app.add_handler(handler)
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
message.text = "/end"
message.entities[0].length = len("/end")
caplog.clear()
with caplog.at_level(logging.ERROR):
await app.process_update(Update(update_id=0, message=message))
assert len(caplog.records) == 0
assert self.current_state[user1.id] == self.END
# make sure that the conversation has ended by checking that the start command is
# accepted again
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(update_id=0, message=message))
async def test_conversation_handler_fallback(self, app, bot, user1, user2):
handler = ConversationHandler(
entry_points=self.entry_points, states=self.states, fallbacks=self.fallbacks
)
app.add_handler(handler)
# first check if fallback will not trigger start when not started
message = Message(
0,
None,
self.group,
from_user=user1,
text="/eat",
entities=[MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/eat"))],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
with pytest.raises(KeyError):
self.current_state[user1.id]
# User starts the state machine.
message.text = "/start"
message.entities[0].length = len("/start")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.BREWING
# Now a fallback command is issued
message.text = "/eat"
message.entities[0].length = len("/eat")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
async def test_unknown_state_warning(self, app, bot, user1, recwarn):
def build_callback(state):
async def callback(_, __):
return state
return callback
handler = ConversationHandler(
entry_points=[CommandHandler("start", build_callback(1))],
states={
1: [TypeHandler(Update, build_callback(69))],
2: [TypeHandler(Update, build_callback(42))],
},
fallbacks=self.fallbacks,
name="xyz",
)
app.add_handler(handler)
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
try:
await app.process_update(Update(update_id=1, message=message))
except Exception as exc:
print(exc)
raise exc
assert len(recwarn) == 1
assert recwarn[0].category is PTBUserWarning
assert (
Path(recwarn[0].filename)
== SOURCE_ROOT_PATH / "ext" / "_handlers" / "conversationhandler.py"
), "wrong stacklevel!"
assert (
str(recwarn[0].message)
== "'callback' returned state 69 which is unknown to the ConversationHandler xyz."
)
async def test_conversation_handler_per_chat(self, app, bot, user1, user2):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
per_user=False,
)
app.add_handler(handler)
# User one, starts the state machine.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
# Let's now verify that for another user, who did not start yet,
# the state will be changed because they are in the same group.
message.from_user = user2
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
# Check that we're in the DRINKING state by checking that the corresponding command
# is accepted
message.from_user = user1
message.text = "/startCoding"
message.entities[0].length = len("/startCoding")
assert handler.check_update(Update(update_id=0, message=message))
message.from_user = user2
assert handler.check_update(Update(update_id=0, message=message))
async def test_conversation_handler_per_user(self, app, bot, user1):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
per_chat=False,
)
app.add_handler(handler)
# User one, starts the state machine.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
# First check that updates without user won't be handled
message.from_user = None
assert not handler.check_update(Update(update_id=0, message=message))
message.from_user = user1
async with app:
await app.process_update(Update(update_id=0, message=message))
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
# Let's now verify that for the same user in a different group, the state will still be
# updated
message.chat = self.second_group
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
# Check that we're in the DRINKING state by checking that the corresponding command
# is accepted
message.chat = self.group
message.text = "/startCoding"
message.entities[0].length = len("/startCoding")
assert handler.check_update(Update(update_id=0, message=message))
message.chat = self.second_group
assert handler.check_update(Update(update_id=0, message=message))
@pytest.mark.parametrize("inline", [True, False])
@pytest.mark.filterwarnings("ignore: If 'per_message=True' is used, 'per_chat=True'")
async def test_conversation_handler_per_message(self, app, bot, user1, user2, inline):
async def entry(update, context):
return 1
async def one(update, context):
return 2
async def two(update, context):
return ConversationHandler.END
handler = ConversationHandler(
entry_points=[CallbackQueryHandler(entry)],
states={
1: [CallbackQueryHandler(one, pattern="^1$")],
2: [CallbackQueryHandler(two, pattern="^2$")],
},
fallbacks=[],
per_message=True,
per_chat=not inline,
)
app.add_handler(handler)
# User one, starts the state machine.
message = (
Message(0, None, self.group, from_user=user1, text="msg w/ inlinekeyboard")
if not inline
else None
)
if message:
message.set_bot(bot)
message._unfreeze()
inline_message_id = "42" if inline else None
async with app:
cbq_1 = CallbackQuery(
0,
user1,
None,
message=message,
data="1",
inline_message_id=inline_message_id,
)
cbq_1.set_bot(bot)
cbq_2 = CallbackQuery(
0,
user1,
None,
message=message,
data="2",
inline_message_id=inline_message_id,
)
cbq_2.set_bot(bot)
cbq_2._unfreeze()
await app.process_update(Update(update_id=0, callback_query=cbq_1))
# Make sure that we're in the correct state
assert handler.check_update(Update(0, callback_query=cbq_1))
assert not handler.check_update(Update(0, callback_query=cbq_2))
await app.process_update(Update(update_id=0, callback_query=cbq_1))
# Make sure that we're in the correct state
assert not handler.check_update(Update(0, callback_query=cbq_1))
assert handler.check_update(Update(0, callback_query=cbq_2))
# Let's now verify that for a different user in the same group, the state will not be
# updated
cbq_2.from_user = user2
await app.process_update(Update(update_id=0, callback_query=cbq_2))
cbq_2.from_user = user1
assert not handler.check_update(Update(0, callback_query=cbq_1))
assert handler.check_update(Update(0, callback_query=cbq_2))
async def test_end_on_first_message(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", self.start_end)], states={}, fallbacks=[]
)
app.add_handler(handler)
# User starts the state machine and immediately ends it.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
assert handler.check_update(Update(update_id=0, message=message))
async def test_end_on_first_message_non_blocking_handler(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", callback=self.start_end, block=False)],
states={},
fallbacks=[],
)
app.add_handler(handler)
# User starts the state machine with a non-blocking function that immediately ends the
# conversation. non-blocking results are resolved when the users state is queried next
# time.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
# give the task a chance to finish
await asyncio.sleep(0.1)
# Let's check that processing the same update again is accepted. this confirms that
# a) the pending state is correctly resolved
# b) the conversation has ended
assert handler.check_update(Update(0, message=message))
async def test_none_on_first_message(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[MessageHandler(filters.ALL, self.start_none)], states={}, fallbacks=[]
)
app.add_handler(handler)
# User starts the state machine and a callback function returns None
message = Message(0, None, self.group, from_user=user1, text="/start")
message.set_bot(bot)
message._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
# Check that the same message is accepted again, i.e. the conversation immediately
# ended
assert handler.check_update(Update(0, message=message))
async def test_none_on_first_message_non_blocking_handler(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", self.start_none, block=False)],
states={},
fallbacks=[],
)
app.add_handler(handler)
# User starts the state machine with a non-blocking handler that returns None
# non-blocking results are resolved when the users state is queried next time.
message = Message(
0,
None,
self.group,
text="/start",
from_user=user1,
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
# Give the task a chance to finish
await asyncio.sleep(0.1)
# Let's check that processing the same update again is accepted. this confirms that
# a) the pending state is correctly resolved
# b) the conversation has ended
assert handler.check_update(Update(0, message=message))
async def test_per_chat_message_without_chat(self, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", self.start_end)], states={}, fallbacks=[]
)
cbq = CallbackQuery(0, user1, None, None)
cbq.set_bot(bot)
update = Update(0, callback_query=cbq)
assert not handler.check_update(update)
async def test_channel_message_without_chat(self, bot):
handler = ConversationHandler(
entry_points=[MessageHandler(filters.ALL, self.start_end)], states={}, fallbacks=[]
)
message = Message(0, date=None, chat=Chat(0, Chat.CHANNEL, "Misses Test"))
message.set_bot(bot)
message._unfreeze()
update = Update(0, channel_post=message)
assert not handler.check_update(update)
update = Update(0, edited_channel_post=message)
assert not handler.check_update(update)
async def test_all_update_types(self, app, bot, user1):
handler = ConversationHandler(
entry_points=[CommandHandler("start", self.start_end)], states={}, fallbacks=[]
)
message = Message(0, None, self.group, from_user=user1, text="ignore")
message.set_bot(bot)
message._unfreeze()
callback_query = CallbackQuery(0, user1, None, message=message, data="data")
callback_query.set_bot(bot)
chosen_inline_result = ChosenInlineResult(0, user1, "query")
chosen_inline_result.set_bot(bot)
inline_query = InlineQuery(0, user1, "query", offset="")
inline_query.set_bot(bot)
pre_checkout_query = PreCheckoutQuery(0, user1, "USD", 100, [])
pre_checkout_query.set_bot(bot)
shipping_query = ShippingQuery(0, user1, [], None)
shipping_query.set_bot(bot)
assert not handler.check_update(Update(0, callback_query=callback_query))
assert not handler.check_update(Update(0, chosen_inline_result=chosen_inline_result))
assert not handler.check_update(Update(0, inline_query=inline_query))
assert not handler.check_update(Update(0, message=message))
assert not handler.check_update(Update(0, pre_checkout_query=pre_checkout_query))
assert not handler.check_update(Update(0, shipping_query=shipping_query))
@pytest.mark.parametrize("jq", [True, False])
async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
if not jq:
app = ApplicationBuilder().token(bot.token).job_queue(None).build()
app.add_handler(handler)
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.5)
if jq:
assert len(recwarn) == 1
else:
assert len(recwarn) == 2
assert str(recwarn[0].message if jq else recwarn[1].message).startswith(
"Ignoring `conversation_timeout`"
)
assert ("is not running" if jq else "No `JobQueue` set up.") in str(recwarn[0].message)
for warning in recwarn:
assert warning.category is PTBUserWarning
assert (
Path(warning.filename)
== SOURCE_ROOT_PATH / "ext" / "_handlers" / "conversationhandler.py"
), "wrong stacklevel!"
# now set app.job_queue back to it's original value
async def test_schedule_job_exception(self, app, bot, user1, monkeypatch, caplog):
def mocked_run_once(*a, **kw):
raise Exception("job error")
class DictJB(JobQueue):
pass
app = ApplicationBuilder().token(bot.token).job_queue(DictJB()).build()
monkeypatch.setattr(app.job_queue, "run_once", mocked_run_once)
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
conversation_timeout=100,
)
app.add_handler(handler)
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.start()
with caplog.at_level(logging.ERROR):
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.5)
assert len(caplog.records) == 1
assert caplog.records[0].message == "Failed to schedule timeout."
assert caplog.records[0].name == "telegram.ext.ConversationHandler"
assert str(caplog.records[0].exc_info[1]) == "job error"
await app.stop()
@pytest.mark.parametrize(argnames="test_type", argvalues=["none", "exception"])
async def test_non_blocking_exception_or_none(self, app, bot, user1, caplog, test_type):
"""Here we make sure that when a non-blocking handler raises an
exception or returns None, the state isn't changed.
"""
error = Exception("task exception")
async def conv_entry(*a, **kw):
return 1
async def raise_error(*a, **kw):
if test_type == "none":
return
raise error
handler = ConversationHandler(
entry_points=[CommandHandler("start", conv_entry)],
states={1: [MessageHandler(filters.Text(["error"]), raise_error)]},
fallbacks=self.fallbacks,
block=False,
)
app.add_handler(handler)
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
# start the conversation
async with app:
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.1)
message.text = "error"
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.1)
caplog.clear()
with caplog.at_level(logging.ERROR):
# This also makes sure that we're still in the same state
assert handler.check_update(Update(0, message=message))
if test_type == "exception":
assert len(caplog.records) == 1
assert caplog.records[0].name == "telegram.ext.ConversationHandler"
assert (
caplog.records[0].message
== "Task function raised exception. Falling back to old state 1"
)
assert caplog.records[0].exc_info[1] is None
else:
assert len(caplog.records) == 0
async def test_non_blocking_entry_point_exception(self, app, bot, user1, caplog):
"""Here we make sure that when a non-blocking entry point raises an
exception, the state isn't changed.
"""
error = Exception("task exception")
async def raise_error(*a, **kw):
raise error
handler = ConversationHandler(
entry_points=[CommandHandler("start", raise_error, block=False)],
states={},
fallbacks=self.fallbacks,
)
app.add_handler(handler)
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
# start the conversation
async with app:
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.1)
caplog.clear()
with caplog.at_level(logging.ERROR):
# This also makes sure that we're still in the same state
assert handler.check_update(Update(0, message=message))
assert len(caplog.records) == 1
assert caplog.records[0].name == "telegram.ext.ConversationHandler"
assert (
caplog.records[0].message
== "Task function raised exception. Falling back to old state None"
)
assert caplog.records[0].exc_info[1] is None
async def test_conversation_timeout(self, app, bot, user1):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
app.add_handler(handler)
# Start state machine, then reach timeout
start_message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
start_message.set_bot(bot)
brew_message = Message(
0,
None,
self.group,
from_user=user1,
text="/brew",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/brew"))
],
)
brew_message.set_bot(bot)
pour_coffee_message = Message(
0,
None,
self.group,
from_user=user1,
text="/pourCoffee",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/pourCoffee"))
],
)
pour_coffee_message.set_bot(bot)
async with app:
await app.start()
await app.process_update(Update(update_id=0, message=start_message))
assert handler.check_update(Update(0, message=brew_message))
await asyncio.sleep(0.75)
assert handler.check_update(Update(0, message=start_message))
# Start state machine, do something, then reach timeout
await app.process_update(Update(update_id=1, message=start_message))
assert handler.check_update(Update(0, message=brew_message))
# assert handler.conversations.get((self.group.id, user1.id)) == self.THIRSTY
# start_message.text = '/brew'
# start_message.entities[0].length = len('/brew')
await app.process_update(Update(update_id=2, message=brew_message))
assert handler.check_update(Update(0, message=pour_coffee_message))
# assert handler.conversations.get((self.group.id, user1.id)) == self.BREWING
await asyncio.sleep(0.75)
assert handler.check_update(Update(0, message=start_message))
# assert handler.conversations.get((self.group.id, user1.id)) is None
await app.stop()
async def test_timeout_not_triggered_on_conv_end_non_blocking(self, bot, app, user1):
def timeout(*a, **kw):
self.test_flag = True
self.states.update({ConversationHandler.TIMEOUT: [TypeHandler(Update, timeout)]})
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
block=False,
)
app.add_handler(handler)
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
# start the conversation
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.1)
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=1, message=message))
await asyncio.sleep(0.1)
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=2, message=message))
await asyncio.sleep(0.1)
message.text = "/end"
message.entities[0].length = len("/end")
await app.process_update(Update(update_id=3, message=message))
await asyncio.sleep(1)
# assert timeout handler didn't get called
assert self.test_flag is False
async def test_conversation_timeout_application_handler_stop(self, app, bot, user1, recwarn):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
def timeout(*args, **kwargs):
raise ApplicationHandlerStop
self.states.update({ConversationHandler.TIMEOUT: [TypeHandler(Update, timeout)]})
app.add_handler(handler)
# Start state machine, then reach timeout
message = Message(
0,
None,
self.group,
text="/start",
from_user=user1,
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
brew_message = Message(
0,
None,
self.group,
from_user=user1,
text="/brew",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/brew"))
],
)
brew_message.set_bot(bot)
async with app:
await app.start()
await app.process_update(Update(update_id=0, message=message))
# Make sure that we're in the next state
assert handler.check_update(Update(0, message=brew_message))
await app.process_update(Update(0, message=brew_message))
await asyncio.sleep(0.9)
# Check that conversation has ended by checking that the start messages is accepted
# again
assert handler.check_update(Update(0, message=message))
assert len(recwarn) == 1
assert str(recwarn[0].message).startswith("ApplicationHandlerStop in TIMEOUT")
assert recwarn[0].category is PTBUserWarning
assert (
Path(recwarn[0].filename) == SOURCE_ROOT_PATH / "ext" / "_jobqueue.py"
), "wrong stacklevel!"
await app.stop()
async def test_conversation_handler_timeout_update_and_context(self, app, bot, user1):
context = None
async def start_callback(u, c):
nonlocal context
context = c
return await self.start(u, c)
# Start state machine, then reach timeout
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
update = Update(update_id=0, message=message)
async def timeout_callback(u, c):
assert u is update
assert c is context
self.is_timeout = (u is update) and (c is context)
states = self.states
timeout_handler = CommandHandler("start", timeout_callback)
states.update({ConversationHandler.TIMEOUT: [timeout_handler]})
handler = ConversationHandler(
entry_points=[CommandHandler("start", start_callback)],
states=states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
app.add_handler(handler)
async with app:
await app.start()
await app.process_update(update)
await asyncio.sleep(0.9)
# check that the conversation has ended by checking that the start message is accepted
assert handler.check_update(Update(0, message=message))
assert self.is_timeout
await app.stop()
@pytest.mark.flaky(3, 1)
async def test_conversation_timeout_keeps_extending(self, app, bot, user1):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
app.add_handler(handler)
# Start state machine, wait, do something, verify the timeout is extended.
# t=0 /start (timeout=.5)
# t=.35 /brew (timeout=.85)
# t=.5 original timeout
# t=.6 /pourCoffee (timeout=1.1)
# t=.85 second timeout
# t=1.1 actual timeout
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.start()
await app.process_update(Update(update_id=0, message=message))
message.text = "/brew"
message.entities[0].length = len("/brew")
assert handler.check_update(Update(0, message=message))
await asyncio.sleep(0.35) # t=.35
assert handler.check_update(Update(0, message=message))
await app.process_update(Update(update_id=0, message=message))
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
assert handler.check_update(Update(0, message=message))
await asyncio.sleep(0.25) # t=.6
assert handler.check_update(Update(0, message=message))
await app.process_update(Update(update_id=0, message=message))
message.text = "/startCoding"
message.entities[0].length = len("/startCoding")
assert handler.check_update(Update(0, message=message))
await asyncio.sleep(0.4) # t=1.0
assert handler.check_update(Update(0, message=message))
await asyncio.sleep(0.3) # t=1.3
assert not handler.check_update(Update(0, message=message))
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(0, message=message))
await app.stop()
async def test_conversation_timeout_two_users(self, app, bot, user1, user2):
handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
app.add_handler(handler)
# Start state machine, do something as second user, then reach timeout
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.start()
await app.process_update(Update(update_id=0, message=message))
message.text = "/brew"
message.entities[0].length = len("/brew")
assert handler.check_update(Update(0, message=message))
message.from_user = user2
await app.process_update(Update(update_id=0, message=message))
message.text = "/start"
message.entities[0].length = len("/start")
# Make sure that user2s conversation has not yet started
assert handler.check_update(Update(0, message=message))
await app.process_update(Update(update_id=0, message=message))
message.text = "/brew"
message.entities[0].length = len("/brew")
assert handler.check_update(Update(0, message=message))
await asyncio.sleep(0.7)
# check that both conversations have ended by checking that the start message is
# accepted again
message.text = "/start"
message.entities[0].length = len("/start")
message.from_user = user1
assert handler.check_update(Update(0, message=message))
message.from_user = user2
assert handler.check_update(Update(0, message=message))
await app.stop()
async def test_conversation_handler_timeout_state(self, app, bot, user1):
states = self.states
states.update(
{
ConversationHandler.TIMEOUT: [
CommandHandler("brew", self.passout),
MessageHandler(~filters.Regex("oding"), self.passout2),
]
}
)
handler = ConversationHandler(
entry_points=self.entry_points,
states=states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
app.add_handler(handler)
# CommandHandler timeout
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.start()
await app.process_update(Update(update_id=0, message=message))
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.7)
# check that conversation has ended by checking that start cmd is accepted again
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(0, message=message))
assert self.is_timeout
# MessageHandler timeout
self.is_timeout = False
message.text = "/start"
message.entities[0].length = len("/start")
await app.process_update(Update(update_id=1, message=message))
await asyncio.sleep(0.7)
# check that conversation has ended by checking that start cmd is accepted again
assert handler.check_update(Update(0, message=message))
assert self.is_timeout
# Timeout but no valid handler
self.is_timeout = False
await app.process_update(Update(update_id=0, message=message))
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
message.text = "/startCoding"
message.entities[0].length = len("/startCoding")
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.7)
# check that conversation has ended by checking that start cmd is accepted again
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(0, message=message))
assert not self.is_timeout
await app.stop()
async def test_conversation_handler_timeout_state_context(self, app, bot, user1):
states = self.states
states.update(
{
ConversationHandler.TIMEOUT: [
CommandHandler("brew", self.passout_context),
MessageHandler(~filters.Regex("oding"), self.passout2_context),
]
}
)
handler = ConversationHandler(
entry_points=self.entry_points,
states=states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
app.add_handler(handler)
# CommandHandler timeout
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.start()
await app.process_update(Update(update_id=0, message=message))
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.7)
# check that conversation has ended by checking that start cmd is accepted again
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(0, message=message))
assert self.is_timeout
# MessageHandler timeout
self.is_timeout = False
message.text = "/start"
message.entities[0].length = len("/start")
await app.process_update(Update(update_id=1, message=message))
await asyncio.sleep(0.7)
# check that conversation has ended by checking that start cmd is accepted again
assert handler.check_update(Update(0, message=message))
assert self.is_timeout
# Timeout but no valid handler
self.is_timeout = False
await app.process_update(Update(update_id=0, message=message))
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
message.text = "/startCoding"
message.entities[0].length = len("/startCoding")
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.7)
# check that conversation has ended by checking that start cmd is accepted again
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(0, message=message))
assert not self.is_timeout
await app.stop()
async def test_conversation_timeout_cancel_conflict(self, app, bot, user1):
# Start state machine, wait half the timeout,
# then call a callback that takes more than the timeout
# t=0 /start (timeout=.5)
# t=.25 /slowbrew (sleep .5)
# | t=.5 original timeout (should not execute)
# | t=.75 /slowbrew returns (timeout=1.25)
# t=1.25 timeout
async def slowbrew(_update, context):
await asyncio.sleep(0.25)
# Let's give to the original timeout a chance to execute
await asyncio.sleep(0.25)
# By returning None we do not override the conversation state so
# we can see if the timeout has been executed
states = self.states
states[self.THIRSTY].append(CommandHandler("slowbrew", slowbrew))
states.update({ConversationHandler.TIMEOUT: [MessageHandler(None, self.passout2)]})
handler = ConversationHandler(
entry_points=self.entry_points,
states=states,
fallbacks=self.fallbacks,
conversation_timeout=0.5,
)
app.add_handler(handler)
# CommandHandler timeout
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.start()
await app.process_update(Update(update_id=0, message=message))
await asyncio.sleep(0.25)
message.text = "/slowbrew"
message.entities[0].length = len("/slowbrew")
await app.process_update(Update(update_id=0, message=message))
# Check that conversation has not ended by checking that start cmd is not accepted
message.text = "/start"
message.entities[0].length = len("/start")
assert not handler.check_update(Update(0, message=message))
assert not self.is_timeout
await asyncio.sleep(0.7)
# Check that conversation has ended by checking that start cmd is accepted again
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(0, message=message))
assert self.is_timeout
await app.stop()
async def test_nested_conversation_handler(self, app, bot, user1, user2):
self.nested_states[self.DRINKING] = [
ConversationHandler(
entry_points=self.drinking_entry_points,
states=self.drinking_states,
fallbacks=self.drinking_fallbacks,
map_to_parent=self.drinking_map_to_parent,
)
]
handler = ConversationHandler(
entry_points=self.entry_points, states=self.nested_states, fallbacks=self.fallbacks
)
app.add_handler(handler)
# User one, starts the state machine.
message = Message(
0,
None,
self.group,
from_user=user1,
text="/start",
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.BREWING
# Lets pour some coffee.
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
# The user is holding the cup
message.text = "/hold"
message.entities[0].length = len("/hold")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.HOLDING
# The user is sipping coffee
message.text = "/sip"
message.entities[0].length = len("/sip")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.SIPPING
# The user is swallowing
message.text = "/swallow"
message.entities[0].length = len("/swallow")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.SWALLOWING
# The user is holding the cup again
message.text = "/hold"
message.entities[0].length = len("/hold")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.HOLDING
# The user wants to replenish the coffee supply
message.text = "/replenish"
message.entities[0].length = len("/replenish")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.REPLENISHING
# check that we're in the right state now by checking that the update is accepted
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
assert handler.check_update(Update(0, message=message))
# The user wants to drink their coffee again)
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
# The user is now ready to start coding
message.text = "/startCoding"
message.entities[0].length = len("/startCoding")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.CODING
# The user decides it's time to drink again
message.text = "/drinkMore"
message.entities[0].length = len("/drinkMore")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
# The user is holding their cup
message.text = "/hold"
message.entities[0].length = len("/hold")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.HOLDING
# The user wants to end with the drinking and go back to coding
message.text = "/end"
message.entities[0].length = len("/end")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.END
# check that we're in the right state now by checking that the update is accepted
message.text = "/drinkMore"
message.entities[0].length = len("/drinkMore")
assert handler.check_update(Update(0, message=message))
# The user wants to drink once more
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
# The user wants to stop altogether
message.text = "/stop"
message.entities[0].length = len("/stop")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.STOPPING
# check that the conversation has ended by checking that the start cmd is accepted
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(0, message=message))
async def test_nested_conversation_application_handler_stop(self, app, bot, user1, user2):
self.nested_states[self.DRINKING] = [
ConversationHandler(
entry_points=self.drinking_entry_points,
states=self.drinking_states,
fallbacks=self.drinking_fallbacks,
map_to_parent=self.drinking_map_to_parent,
)
]
handler = ConversationHandler(
entry_points=self.entry_points, states=self.nested_states, fallbacks=self.fallbacks
)
def test_callback(u, c):
self.test_flag = True
app.add_handler(handler)
app.add_handler(TypeHandler(Update, test_callback), group=1)
self.raise_app_handler_stop = True
# User one, starts the state machine.
message = Message(
0,
None,
self.group,
text="/start",
from_user=user1,
entities=[
MessageEntity(type=MessageEntity.BOT_COMMAND, offset=0, length=len("/start"))
],
)
message.set_bot(bot)
message._unfreeze()
message.entities[0]._unfreeze()
async with app:
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.THIRSTY
assert not self.test_flag
# The user is thirsty and wants to brew coffee.
message.text = "/brew"
message.entities[0].length = len("/brew")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.BREWING
assert not self.test_flag
# Lets pour some coffee.
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
assert not self.test_flag
# The user is holding the cup
message.text = "/hold"
message.entities[0].length = len("/hold")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.HOLDING
assert not self.test_flag
# The user is sipping coffee
message.text = "/sip"
message.entities[0].length = len("/sip")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.SIPPING
assert not self.test_flag
# The user is swallowing
message.text = "/swallow"
message.entities[0].length = len("/swallow")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.SWALLOWING
assert not self.test_flag
# The user is holding the cup again
message.text = "/hold"
message.entities[0].length = len("/hold")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.HOLDING
assert not self.test_flag
# The user wants to replenish the coffee supply
message.text = "/replenish"
message.entities[0].length = len("/replenish")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.REPLENISHING
# check that we're in the right state now by checking that the update is accepted
message.text = "/pourCoffee"
message.entities[0].length = len("/pourCoffee")
assert handler.check_update(Update(0, message=message))
assert not self.test_flag
# The user wants to drink their coffee again
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
assert not self.test_flag
# The user is now ready to start coding
message.text = "/startCoding"
message.entities[0].length = len("/startCoding")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.CODING
assert not self.test_flag
# The user decides it's time to drink again
message.text = "/drinkMore"
message.entities[0].length = len("/drinkMore")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
assert not self.test_flag
# The user is holding their cup
message.text = "/hold"
message.entities[0].length = len("/hold")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.HOLDING
assert not self.test_flag
# The user wants to end with the drinking and go back to coding
message.text = "/end"
message.entities[0].length = len("/end")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.END
# check that we're in the right state now by checking that the update is accepted
message.text = "/drinkMore"
message.entities[0].length = len("/drinkMore")
assert handler.check_update(Update(0, message=message))
assert not self.test_flag
# The user wants to drink once more
message.text = "/drinkMore"
message.entities[0].length = len("/drinkMore")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.DRINKING
assert not self.test_flag
# The user wants to stop altogether
message.text = "/stop"
message.entities[0].length = len("/stop")
await app.process_update(Update(update_id=0, message=message))
assert self.current_state[user1.id] == self.STOPPING
# check that the conv has ended by checking that the start cmd is accepted
message.text = "/start"
message.entities[0].length = len("/start")
assert handler.check_update(Update(0, message=message))
assert not self.test_flag
@pytest.mark.parametrize("callback_raises", [True, False])
async def test_timeout_non_block(self, app, user1, callback_raises):
event = asyncio.Event()
async def callback(_, __):
await event.wait()
if callback_raises:
raise RuntimeError
return 1
conv_handler = ConversationHandler(
entry_points=[MessageHandler(filters.ALL, callback=callback, block=False)],
states={ConversationHandler.TIMEOUT: [TypeHandler(Update, self.passout2)]},
fallbacks=[],
conversation_timeout=0.5,
)
app.add_handler(conv_handler)
async with app:
await app.start()
message = Message(
0,
None,
self.group,
text="/start",
from_user=user1,
)
assert conv_handler.check_update(Update(0, message=message))
await app.process_update(Update(0, message=message))
await asyncio.sleep(0.7)
tasks = asyncio.all_tasks()
assert any(":handle_update:non_blocking_cb" in t.get_name() for t in tasks)
assert any(":handle_update:timeout_job" in t.get_name() for t in tasks)
assert not self.is_timeout
event.set()
await asyncio.sleep(0.7)
assert self.is_timeout == (not callback_raises)
await app.stop()
async def test_no_timeout_on_end(self, app, user1):
conv_handler = ConversationHandler(
entry_points=[MessageHandler(filters.ALL, callback=self.start_end)],
states={ConversationHandler.TIMEOUT: [TypeHandler(Update, self.passout2)]},
fallbacks=[],
conversation_timeout=0.5,
)
app.add_handler(conv_handler)
async with app:
await app.start()
message = Message(
0,
None,
self.group,
text="/start",
from_user=user1,
)
assert conv_handler.check_update(Update(0, message=message))
await app.process_update(Update(0, message=message))
await asyncio.sleep(0.7)
assert not self.is_timeout
await app.stop()
async def test_conversation_handler_block_dont_override(self, app):
"""This just makes sure that we don't change any attributes of the handlers of the conv"""
conv_handler = ConversationHandler(
entry_points=self.entry_points,
states=self.states,
fallbacks=self.fallbacks,
block=False,
)
all_handlers = conv_handler.entry_points + conv_handler.fallbacks
for state_handlers in conv_handler.states.values():
all_handlers += state_handlers
for handler in all_handlers:
assert handler.block
conv_handler = ConversationHandler(
entry_points=[CommandHandler("start", self.start_end, block=False)],
states={1: [CommandHandler("start", self.start_end, block=False)]},
fallbacks=[CommandHandler("start", self.start_end, block=False)],
block=True,
)
all_handlers = conv_handler.entry_points + conv_handler.fallbacks
for state_handlers in conv_handler.states.values():
all_handlers += state_handlers
for handler in all_handlers:
assert handler.block is False
@pytest.mark.parametrize("default_block", [True, False, None])
@pytest.mark.parametrize("ch_block", [True, False, None])
@pytest.mark.parametrize("handler_block", [True, False, None])
@pytest.mark.parametrize("ext_bot", [True, False], ids=["ExtBot", "Bot"])
async def test_blocking_resolution_order(
self, bot_info, default_block, ch_block, handler_block, ext_bot
):
event = asyncio.Event()
async def callback(_, __):
await event.wait()
event.clear()
self.test_flag = True
return 1
if handler_block is not None:
handler = CommandHandler("start", callback=callback, block=handler_block)
fallback = MessageHandler(filters.ALL, callback, block=handler_block)
else:
handler = CommandHandler("start", callback=callback)
fallback = MessageHandler(filters.ALL, callback, block=handler_block)
defaults = Defaults(block=default_block) if default_block is not None else None
if ch_block is not None:
conv_handler = ConversationHandler(
entry_points=[handler],
states={1: [handler]},
fallbacks=[fallback],
block=ch_block,
)
else:
conv_handler = ConversationHandler(
entry_points=[handler],
states={1: [handler]},
fallbacks=[fallback],
)
bot = make_bot(bot_info, defaults=defaults) if ext_bot else PytestBot(bot_info["token"])
app = ApplicationBuilder().bot(bot).build()
app.add_handler(conv_handler)
async with app:
start_message = make_command_message("/start")
start_message.set_bot(bot)
fallback_message = make_command_message("/fallback")
fallback_message.set_bot(bot)
# This loop makes sure that we test all of entry points, states handler & fallbacks
for message in [start_message, fallback_message]:
process_update_task = asyncio.create_task(
app.process_update(Update(0, message=message))
)
if (
# resolution order is handler_block -> ch_block -> default_block
# setting block=True/False on a lower priority setting may only have an effect
# if it wasn't set for the higher priority settings
(handler_block is False)
or ((handler_block is None) and (ch_block is False))
or (
(handler_block is None)
and (ch_block is None)
and ext_bot
and (default_block is False)
)
):
# check that the handler was called non-blocking by checking that
# `process_update` has finished
await asyncio.sleep(0.01)
assert process_update_task.done()
else:
# the opposite
assert not process_update_task.done()
# In any case, the callback must not have finished
assert not self.test_flag
# After setting the event, the callback must have finished and in the blocking
# case this leads to `process_update` finishing.
event.set()
await asyncio.sleep(0.01)
assert process_update_task.done()
assert self.test_flag
self.test_flag = False
async def test_waiting_state(self, app, user1):
event = asyncio.Event()
async def callback_1(_, __):
self.test_flag = 1
async def callback_2(_, __):
self.test_flag = 2
async def callback_3(_, __):
self.test_flag = 3
async def blocking(_, __):
await event.wait()
return 1
conv_handler = ConversationHandler(
entry_points=[MessageHandler(filters.ALL, callback=blocking, block=False)],
states={
ConversationHandler.WAITING: [
MessageHandler(filters.Regex("1"), callback_1),
MessageHandler(filters.Regex("2"), callback_2),
],
1: [MessageHandler(filters.Regex("2"), callback_3)],
},
fallbacks=[],
)
app.add_handler(conv_handler)
message = Message(
0,
None,
self.group,
text="/start",
from_user=user1,
)
message._unfreeze()
async with app:
await app.process_update(Update(0, message=message))
assert not self.test_flag
message.text = "1"
await app.process_update(Update(0, message=message))
assert self.test_flag == 1
message.text = "2"
await app.process_update(Update(0, message=message))
assert self.test_flag == 2
event.set()
await asyncio.sleep(0.05)
self.test_flag = None
await app.process_update(Update(0, message=message))
assert self.test_flag == 3
|