From bda08c4aa7bbb8de0f8a27652b67d871bd22f98d Mon Sep 17 00:00:00 2001 From: Aditya Yadav Date: Fri, 25 Nov 2022 22:37:22 +0530 Subject: [PATCH 01/11] warning to install optional dependencies --- docs/source/examples.rst | 3 +++ examples/arbitrarycallbackdatabot.py | 3 +++ examples/passportbot.py | 2 ++ examples/timerbot.py | 3 +++ telegram/ext/_callbackcontext.py | 6 ++++++ 5 files changed, 17 insertions(+) diff --git a/docs/source/examples.rst b/docs/source/examples.rst index c39a4785dd8..43e23dd5292 100644 --- a/docs/source/examples.rst +++ b/docs/source/examples.rst @@ -40,6 +40,7 @@ up a job to send a message to that user after 30 seconds. The user can also cancel the timer by sending ``/unset``. To learn more about the ``JobQueue``, read `this wiki article `__. +Note: To use JobQueue, you must install ptb via ``pip install python-telegram-bot[job-queue]`` :any:`examples.conversationbot` ------------------------------- @@ -115,6 +116,7 @@ Don’t forget to enable and configure payments with `@BotFather `_. Check out this `guide `__ on Telegram passports in PTB. +Note: To use telegram passport, you must install ptb via ``pip install python-telegram-bot[passport]`` :any:`examples.paymentbot` -------------------------- @@ -162,6 +164,7 @@ combination with ``telegram.ext.Application``. This example showcases how PTBs “arbitrary callback data” feature can be used. +Note: To use arbitrary callback data, you must install ptb via ``pip install python-telegram-bot[callback-data]`` Pure API -------- diff --git a/examples/arbitrarycallbackdatabot.py b/examples/arbitrarycallbackdatabot.py index 0b0ffa1d71a..dbee3c72dd7 100644 --- a/examples/arbitrarycallbackdatabot.py +++ b/examples/arbitrarycallbackdatabot.py @@ -6,6 +6,9 @@ For detailed info on arbitrary callback data, see the wiki page at https://github.com/python-telegram-bot/python-telegram-bot/wiki/Arbitrary-callback_data + +Note: +To use arbitrary callback data, you must install ptb via `pip install python-telegram-bot[callback-data]` """ import logging from typing import List, Tuple, cast diff --git a/examples/passportbot.py b/examples/passportbot.py index 3cb03ef2384..59c49ef23a0 100644 --- a/examples/passportbot.py +++ b/examples/passportbot.py @@ -10,6 +10,8 @@ See https://github.com/python-telegram-bot/python-telegram-bot/wiki/Telegram-Passport for how to use Telegram Passport properly with python-telegram-bot. +Note: +To use telegram passport, you must install PTB via `pip install python-telegram-bot[passport]` """ import logging from pathlib import Path diff --git a/examples/timerbot.py b/examples/timerbot.py index 02d2af7fe76..fd5fc2f5f4c 100644 --- a/examples/timerbot.py +++ b/examples/timerbot.py @@ -16,6 +16,9 @@ Basic Alarm Bot example, sends a message after a set time. Press Ctrl-C on the command line or send a signal to the process to stop the bot. + +Note: +To use arbitrary callback data you must install ptb via `pip install python-telegram-bot[callback-data]` """ import logging diff --git a/telegram/ext/_callbackcontext.py b/telegram/ext/_callbackcontext.py index e7b99b4c173..6ad42c8701b 100644 --- a/telegram/ext/_callbackcontext.py +++ b/telegram/ext/_callbackcontext.py @@ -22,6 +22,7 @@ from telegram._callbackquery import CallbackQuery from telegram._update import Update from telegram.ext._extbot import ExtBot +from telegram._utils.warnings import warn from telegram.ext._utils.types import BD, BT, CD, UD if TYPE_CHECKING: @@ -389,6 +390,11 @@ def job_queue(self) -> Optional["JobQueue"]: .. seealso:: `Job Queue `_ """ + if self._application.job_queue is None: + warn( + "No `JobQueue` Set up. To use `JobQueue`, you must install PTB via" + "`pip install python-telegram-bot[job_queue]`." + ) return self._application.job_queue @property From 76e45db5a4e95b507eab78cb647d376b72cfd7f9 Mon Sep 17 00:00:00 2001 From: Aditya Yadav Date: Sun, 27 Nov 2022 20:18:53 +0530 Subject: [PATCH 02/11] requested changes --- docs/source/examples.rst | 6 +++--- examples/arbitrarycallbackdatabot.py | 3 ++- examples/passportbot.py | 3 ++- examples/timerbot.py | 3 ++- telegram/ext/_application.py | 30 +++++++++++++++++++++------- telegram/ext/_callbackcontext.py | 4 ++-- telegram/ext/_conversationhandler.py | 15 ++++++++------ 7 files changed, 43 insertions(+), 21 deletions(-) diff --git a/docs/source/examples.rst b/docs/source/examples.rst index 43e23dd5292..3c949eb88a4 100644 --- a/docs/source/examples.rst +++ b/docs/source/examples.rst @@ -40,7 +40,7 @@ up a job to send a message to that user after 30 seconds. The user can also cancel the timer by sending ``/unset``. To learn more about the ``JobQueue``, read `this wiki article `__. -Note: To use JobQueue, you must install ptb via ``pip install python-telegram-bot[job-queue]`` +Note: To use ``JobQueue``, you must install PTB via ``pip install python-telegram-bot[job-queue]`` :any:`examples.conversationbot` ------------------------------- @@ -116,7 +116,7 @@ Don’t forget to enable and configure payments with `@BotFather `_. Check out this `guide `__ on Telegram passports in PTB. -Note: To use telegram passport, you must install ptb via ``pip install python-telegram-bot[passport]`` +Note: To use Telegram Passport, you must install PTB via ``pip install python-telegram-bot[passport]`` :any:`examples.paymentbot` -------------------------- @@ -164,7 +164,7 @@ combination with ``telegram.ext.Application``. This example showcases how PTBs “arbitrary callback data” feature can be used. -Note: To use arbitrary callback data, you must install ptb via ``pip install python-telegram-bot[callback-data]`` +Note: To use arbitrary callback data, you must install PTB via ``pip install python-telegram-bot[callback-data]`` Pure API -------- diff --git a/examples/arbitrarycallbackdatabot.py b/examples/arbitrarycallbackdatabot.py index dbee3c72dd7..3fca2c5fee7 100644 --- a/examples/arbitrarycallbackdatabot.py +++ b/examples/arbitrarycallbackdatabot.py @@ -8,7 +8,8 @@ https://github.com/python-telegram-bot/python-telegram-bot/wiki/Arbitrary-callback_data Note: -To use arbitrary callback data, you must install ptb via `pip install python-telegram-bot[callback-data]` +To use arbitrary callback data, you must install PTB via +`pip install python-telegram-bot[callback-data]` """ import logging from typing import List, Tuple, cast diff --git a/examples/passportbot.py b/examples/passportbot.py index 59c49ef23a0..77281e85e22 100644 --- a/examples/passportbot.py +++ b/examples/passportbot.py @@ -11,7 +11,8 @@ for how to use Telegram Passport properly with python-telegram-bot. Note: -To use telegram passport, you must install PTB via `pip install python-telegram-bot[passport]` +To use Telegram Passport, you must install PTB via +`pip install python-telegram-bot[passport]` """ import logging from pathlib import Path diff --git a/examples/timerbot.py b/examples/timerbot.py index fd5fc2f5f4c..29f45caaf5c 100644 --- a/examples/timerbot.py +++ b/examples/timerbot.py @@ -18,7 +18,8 @@ bot. Note: -To use arbitrary callback data you must install ptb via `pip install python-telegram-bot[callback-data]` +To use arbitrary callback data, you must install ptb via +`pip install python-telegram-bot[callback-data]` """ import logging diff --git a/telegram/ext/_application.py b/telegram/ext/_application.py index 5543fafc5c7..9d6b5069cf6 100644 --- a/telegram/ext/_application.py +++ b/telegram/ext/_application.py @@ -64,7 +64,7 @@ if TYPE_CHECKING: from telegram import Message - from telegram.ext import ConversationHandler + from telegram.ext import ConversationHandler, JobQueue from telegram.ext._applicationbuilder import InitApplicationBuilder from telegram.ext._jobqueue import Job @@ -218,6 +218,7 @@ class Application(Generic[BT, CCT, UD, CD, BD, JQ], AbstractAsyncContextManager) "_concurrent_updates_sem", "_conversation_handler_conversations", "_initialized", + "_job_queue", "_running", "_user_data", "_user_ids_to_be_deleted_in_persistence", @@ -228,7 +229,6 @@ class Application(Generic[BT, CCT, UD, CD, BD, JQ], AbstractAsyncContextManager) "context_types", "error_handlers", "handlers", - "job_queue", "persistence", "post_init", "post_shutdown", @@ -264,7 +264,6 @@ def __init__( self.bot = bot self.update_queue = update_queue - self.job_queue = job_queue self.context_types = context_types self.updater = updater self.handlers: Dict[int, List[BaseHandler]] = {} @@ -306,6 +305,7 @@ def __init__( # A number of low-level helpers for the internal logic self._initialized = False self._running = False + self._job_queue = job_queue self.__update_fetcher_task: Optional[asyncio.Task] = None self.__update_persistence_task: Optional[asyncio.Task] = None self.__update_persistence_event = asyncio.Event() @@ -337,6 +337,22 @@ def concurrent_updates(self) -> int: """ return self._concurrent_updates + @property + def job_queue(self) -> Optional["JobQueue"]: + """ + :class:`telegram.ext.JobQueue`: The :class:`JobQueue` used by the + :class:`telegram.ext.Application`. + + .. seealso:: `Job Queue `_ + """ + if self._job_queue is None: + warn( + "No `JobQueue` set up. To use `JobQueue`, you must install PTB via " + "`pip install python-telegram-bot[job_queue]`." + ) + return self._job_queue + async def initialize(self) -> None: """Initializes the Application by initializing: @@ -511,8 +527,8 @@ async def start(self) -> None: ) _logger.debug("Loop for updating persistence started") - if self.job_queue: - await self.job_queue.start() # type: ignore[union-attr] + if self._job_queue: + await self._job_queue.start() # type: ignore[union-attr] _logger.debug("JobQueue started") self.__update_fetcher_task = asyncio.create_task( @@ -561,9 +577,9 @@ async def stop(self) -> None: await self.__update_fetcher_task _logger.debug("Application stopped fetching of updates.") - if self.job_queue: + if self._job_queue: _logger.debug("Waiting for running jobs to finish") - await self.job_queue.stop(wait=True) # type: ignore[union-attr] + await self._job_queue.stop(wait=True) # type: ignore[union-attr] _logger.debug("JobQueue stopped") _logger.debug("Waiting for `create_task` calls to be processed") diff --git a/telegram/ext/_callbackcontext.py b/telegram/ext/_callbackcontext.py index 6ad42c8701b..feca3a1042b 100644 --- a/telegram/ext/_callbackcontext.py +++ b/telegram/ext/_callbackcontext.py @@ -21,8 +21,8 @@ from telegram._callbackquery import CallbackQuery from telegram._update import Update -from telegram.ext._extbot import ExtBot from telegram._utils.warnings import warn +from telegram.ext._extbot import ExtBot from telegram.ext._utils.types import BD, BT, CD, UD if TYPE_CHECKING: @@ -392,7 +392,7 @@ def job_queue(self) -> Optional["JobQueue"]: """ if self._application.job_queue is None: warn( - "No `JobQueue` Set up. To use `JobQueue`, you must install PTB via" + "No `JobQueue` set up. To use `JobQueue`, you must install PTB via " "`pip install python-telegram-bot[job_queue]`." ) return self._application.job_queue diff --git a/telegram/ext/_conversationhandler.py b/telegram/ext/_conversationhandler.py index 0402f740a7c..9c5375e6eee 100644 --- a/telegram/ext/_conversationhandler.py +++ b/telegram/ext/_conversationhandler.py @@ -675,12 +675,15 @@ def _schedule_job( try: # both job_queue & conversation_timeout are checked before calling _schedule_job - j_queue = application.job_queue - self.timeout_jobs[conversation_key] = j_queue.run_once( - self._trigger_timeout, - self.conversation_timeout, # type: ignore[arg-type] - data=_ConversationTimeoutContext(conversation_key, update, application, context), - ) + if application.job_queue: + j_queue = application.job_queue + self.timeout_jobs[conversation_key] = j_queue.run_once( + self._trigger_timeout, + self.conversation_timeout, # type: ignore[arg-type] + data=_ConversationTimeoutContext( + conversation_key, update, application, context + ), + ) except Exception as exc: _logger.exception("Failed to schedule timeout.", exc_info=exc) From 8b72dc552cf1b597032ae088fb71b545f2d97964 Mon Sep 17 00:00:00 2001 From: Aditya Yadav Date: Tue, 29 Nov 2022 13:35:43 +0530 Subject: [PATCH 03/11] add tests --- telegram/ext/_application.py | 2 -- telegram/ext/_conversationhandler.py | 4 ++-- tests/test_application.py | 35 ++++++++++++++-------------- tests/test_callbackcontext.py | 16 ++++++++++++- 4 files changed, 34 insertions(+), 23 deletions(-) diff --git a/telegram/ext/_application.py b/telegram/ext/_application.py index 9d6b5069cf6..5864e2f615e 100644 --- a/telegram/ext/_application.py +++ b/telegram/ext/_application.py @@ -151,8 +151,6 @@ class Application(Generic[BT, CCT, UD, CD, BD, JQ], AbstractAsyncContextManager) update_queue (:class:`asyncio.Queue`): The synchronized queue that will contain the updates. updater (:class:`telegram.ext.Updater`): Optional. The updater used by this application. - job_queue (:class:`telegram.ext.JobQueue`): Optional. The :class:`telegram.ext.JobQueue` - instance to pass onto handler callbacks. chat_data (:obj:`types.MappingProxyType`): A dictionary handlers can use to store data for the chat. For each integer chat id, the corresponding value of this mapping is available as :attr:`telegram.ext.CallbackContext.chat_data` in handler callbacks for diff --git a/telegram/ext/_conversationhandler.py b/telegram/ext/_conversationhandler.py index 9c5375e6eee..4069f80b257 100644 --- a/telegram/ext/_conversationhandler.py +++ b/telegram/ext/_conversationhandler.py @@ -675,8 +675,8 @@ def _schedule_job( try: # both job_queue & conversation_timeout are checked before calling _schedule_job - if application.job_queue: - j_queue = application.job_queue + j_queue = application.job_queue + if j_queue: self.timeout_jobs[conversation_key] = j_queue.run_once( self._trigger_timeout, self.conversation_timeout, # type: ignore[arg-type] diff --git a/tests/test_application.py b/tests/test_application.py index eb5b741b116..5df4d4480cc 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -201,6 +201,16 @@ async def post_shutdown(application: Application) -> None: post_shutdown=None, ) + def test_job_queue(self, bot, recwarn): + expected_warning = ( + "No `JobQueue` set up. To use `JobQueue`, you must install PTB via " + "`pip install python-telegram-bot[job_queue]`." + ) + application = ApplicationBuilder().token(bot.token).job_queue(None).build() + assert application.job_queue is None + assert len(recwarn) == 1 + assert str(recwarn[0].message) == expected_warning + def test_custom_context_init(self, bot): cc = ContextTypes( context=CustomContext, @@ -384,23 +394,18 @@ def test_builder(self, app): builder_1.token(app.bot.token) builder_2.token(app.bot.token) - @pytest.mark.parametrize("job_queue", (True, False)) - async def test_start_stop_processing_updates(self, bot, job_queue): + # @pytest.mark.parametrize("job_queue", (True, False)) + async def test_start_stop_processing_updates(self, bot): # TODO: repeat a similar test for create_task, persistence processing and job queue - if job_queue: - app = ApplicationBuilder().token(bot.token).build() - else: - app = ApplicationBuilder().token(bot.token).job_queue(None).build() + app = ApplicationBuilder().token(bot.token).build() async def callback(u, c): self.received = u assert not app.running assert not app.updater.running - if job_queue: - assert not app.job_queue.scheduler.running - else: - assert app.job_queue is None + assert not app.job_queue.scheduler.running + app.add_handler(TypeHandler(object, callback)) await app.update_queue.put(1) @@ -411,10 +416,7 @@ async def callback(u, c): async with app: await app.start() assert app.running - if job_queue: - assert app.job_queue.scheduler.running - else: - assert app.job_queue is None + assert app.job_queue.scheduler.running # app.start() should not start the updater! assert not app.updater.running await asyncio.sleep(0.05) @@ -426,10 +428,7 @@ async def callback(u, c): assert not app.running # app.stop() should not stop the updater! assert app.updater.running - if job_queue: - assert not app.job_queue.scheduler.running - else: - assert app.job_queue is None + assert not app.job_queue.scheduler.running await app.update_queue.put(2) await asyncio.sleep(0.05) assert not app.update_queue.empty() diff --git a/tests/test_callbackcontext.py b/tests/test_callbackcontext.py index 3f98aa65544..c83de64b71e 100644 --- a/tests/test_callbackcontext.py +++ b/tests/test_callbackcontext.py @@ -38,7 +38,7 @@ class TestCallbackContext: - def test_slot_behaviour(self, app, mro_slots, recwarn): + def test_slot_behaviour(self, app, mro_slots): c = CallbackContext(app) for attr in c.__slots__: assert getattr(c, attr, "err") != "err", f"got extra slot '{attr}'" @@ -58,6 +58,20 @@ def test_from_job(self, app): assert callback_context.job_queue is app.job_queue assert callback_context.update_queue is app.update_queue + def test_job_queue(self, bot, app, recwarn): + expected_warning = ( + "No `JobQueue` set up. To use `JobQueue`, you must install PTB via " + "`pip install python-telegram-bot[job_queue]`." + ) + + callback_context = CallbackContext(app) + assert callback_context.job_queue is app.job_queue + app = ApplicationBuilder().job_queue(None).token(bot.token).build() + callback_context = CallbackContext(app) + assert callback_context.job_queue is None + assert len(recwarn) == 1 + assert str(recwarn[0].message) == expected_warning + def test_from_update(self, app): update = Update( 0, message=Message(0, None, Chat(1, "chat"), from_user=User(1, "user", False)) From ce3895629738fe748d204a5fa716c0fbcc131249 Mon Sep 17 00:00:00 2001 From: Aditya Yadav Date: Wed, 30 Nov 2022 07:54:30 +0530 Subject: [PATCH 04/11] fix tests --- telegram/ext/_conversationhandler.py | 13 +++++------ tests/test_application.py | 32 ++++++++++++++++++++-------- tests/test_applicationbuilder.py | 3 ++- tests/test_callbackcontext.py | 1 + tests/test_conversationhandler.py | 4 ++-- 5 files changed, 33 insertions(+), 20 deletions(-) diff --git a/telegram/ext/_conversationhandler.py b/telegram/ext/_conversationhandler.py index 4069f80b257..0402f740a7c 100644 --- a/telegram/ext/_conversationhandler.py +++ b/telegram/ext/_conversationhandler.py @@ -676,14 +676,11 @@ def _schedule_job( try: # both job_queue & conversation_timeout are checked before calling _schedule_job j_queue = application.job_queue - if j_queue: - self.timeout_jobs[conversation_key] = j_queue.run_once( - self._trigger_timeout, - self.conversation_timeout, # type: ignore[arg-type] - data=_ConversationTimeoutContext( - conversation_key, update, application, context - ), - ) + self.timeout_jobs[conversation_key] = j_queue.run_once( + self._trigger_timeout, + self.conversation_timeout, # type: ignore[arg-type] + data=_ConversationTimeoutContext(conversation_key, update, application, context), + ) except Exception as exc: _logger.exception("Failed to schedule timeout.", exc_info=exc) diff --git a/tests/test_application.py b/tests/test_application.py index 5df4d4480cc..2f8fa266f7f 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -201,15 +201,17 @@ async def post_shutdown(application: Application) -> None: post_shutdown=None, ) - def test_job_queue(self, bot, recwarn): + def test_job_queue(self, bot, app, recwarn): expected_warning = ( "No `JobQueue` set up. To use `JobQueue`, you must install PTB via " "`pip install python-telegram-bot[job_queue]`." ) + assert app.job_queue is app._job_queue application = ApplicationBuilder().token(bot.token).job_queue(None).build() assert application.job_queue is None assert len(recwarn) == 1 assert str(recwarn[0].message) == expected_warning + assert recwarn[0].filename == __file__, "wrong stacklevel" def test_custom_context_init(self, bot): cc = ContextTypes( @@ -394,18 +396,24 @@ def test_builder(self, app): builder_1.token(app.bot.token) builder_2.token(app.bot.token) - # @pytest.mark.parametrize("job_queue", (True, False)) - async def test_start_stop_processing_updates(self, bot): + @pytest.mark.parametrize("job_queue", (True, False)) + @pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning") + async def test_start_stop_processing_updates(self, bot, job_queue): # TODO: repeat a similar test for create_task, persistence processing and job queue - app = ApplicationBuilder().token(bot.token).build() + if job_queue: + app = ApplicationBuilder().token(bot.token).build() + else: + app = ApplicationBuilder().token(bot.token).job_queue(None).build() async def callback(u, c): self.received = u assert not app.running assert not app.updater.running - assert not app.job_queue.scheduler.running - + if job_queue: + assert not app.job_queue.scheduler.running + else: + assert app.job_queue is None app.add_handler(TypeHandler(object, callback)) await app.update_queue.put(1) @@ -416,7 +424,10 @@ async def callback(u, c): async with app: await app.start() assert app.running - assert app.job_queue.scheduler.running + if job_queue: + assert app.job_queue.scheduler.running + else: + assert app.job_queue is None # app.start() should not start the updater! assert not app.updater.running await asyncio.sleep(0.05) @@ -428,7 +439,10 @@ async def callback(u, c): assert not app.running # app.stop() should not stop the updater! assert app.updater.running - assert not app.job_queue.scheduler.running + if job_queue: + assert not app.job_queue.scheduler.running + else: + assert app.job_queue is None await app.update_queue.put(2) await asyncio.sleep(0.05) assert not app.update_queue.empty() @@ -1944,4 +1958,4 @@ async def abort_app(): if platform.system() == "Windows": assert received_signals == [] else: - assert received_signals == [signal.SIGINT, signal.SIGTERM, signal.SIGABRT] + assert received_signals == [signal.SIGINT, signal.SIGTERM, signal.SIGABRT] \ No newline at end of file diff --git a/tests/test_applicationbuilder.py b/tests/test_applicationbuilder.py index 6f196f2f3dc..3c07225476c 100644 --- a/tests/test_applicationbuilder.py +++ b/tests/test_applicationbuilder.py @@ -416,9 +416,10 @@ def test_no_updater(self, bot, builder): assert isinstance(app.job_queue, JobQueue) assert app.job_queue.application is app + @pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning") def test_no_job_queue(self, bot, builder): app = builder.token(bot.token).job_queue(None).build() assert app.bot.token == bot.token assert app.job_queue is None assert isinstance(app.update_queue, asyncio.Queue) - assert isinstance(app.updater, Updater) + assert isinstance(app.updater, Updater) \ No newline at end of file diff --git a/tests/test_callbackcontext.py b/tests/test_callbackcontext.py index c83de64b71e..007cf143896 100644 --- a/tests/test_callbackcontext.py +++ b/tests/test_callbackcontext.py @@ -71,6 +71,7 @@ def test_job_queue(self, bot, app, recwarn): assert callback_context.job_queue is None assert len(recwarn) == 1 assert str(recwarn[0].message) == expected_warning + assert recwarn[0].filename == __file__, "wrong stacklevel" def test_from_update(self, app): update = Update( diff --git a/tests/test_conversationhandler.py b/tests/test_conversationhandler.py index 8fa461df651..c1d10ae6362 100644 --- a/tests/test_conversationhandler.py +++ b/tests/test_conversationhandler.py @@ -1000,7 +1000,7 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): # and then set app.job_queue to None. jqueue = app.job_queue if not jq: - app.job_queue = None + app = ApplicationBuilder().token(bot.token).job_queue(None) app.add_handler(handler) message = Message( @@ -1031,7 +1031,7 @@ def mocked_run_once(*a, **kw): class DictJB(JobQueue): pass - app.job_queue = DictJB() + app = ApplicationBuilder().token(bot.token).job_queue(DictJB()) monkeypatch.setattr(app.job_queue, "run_once", mocked_run_once) handler = ConversationHandler( entry_points=self.entry_points, From 42bd6e4c9e357c5107e03c691ace138042d654f1 Mon Sep 17 00:00:00 2001 From: Aditya Yadav Date: Wed, 30 Nov 2022 09:43:37 +0530 Subject: [PATCH 05/11] fix another test --- tests/test_applicationbuilder.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_applicationbuilder.py b/tests/test_applicationbuilder.py index 3c07225476c..ea95d6f17ca 100644 --- a/tests/test_applicationbuilder.py +++ b/tests/test_applicationbuilder.py @@ -51,7 +51,7 @@ def builder(): @pytest.mark.skipif(TEST_WITH_OPT_DEPS, reason="Optional dependencies are installed") class TestApplicationBuilderNoOptDeps: def test_init(self, builder): - builder.token("token") + builder.token("token").job_queue(None) app = builder.build() assert app.job_queue is None From 5d2cc801fb57b8ab073458a1d87addabf4c042b9 Mon Sep 17 00:00:00 2001 From: Aditya Yadav Date: Wed, 30 Nov 2022 13:47:34 +0530 Subject: [PATCH 06/11] try fixing test --- tests/test_applicationbuilder.py | 4 ++-- tests/test_conversationhandler.py | 10 +++++----- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/tests/test_applicationbuilder.py b/tests/test_applicationbuilder.py index ea95d6f17ca..f290e9dfa87 100644 --- a/tests/test_applicationbuilder.py +++ b/tests/test_applicationbuilder.py @@ -51,7 +51,7 @@ def builder(): @pytest.mark.skipif(TEST_WITH_OPT_DEPS, reason="Optional dependencies are installed") class TestApplicationBuilderNoOptDeps: def test_init(self, builder): - builder.token("token").job_queue(None) + builder.token("token") app = builder.build() assert app.job_queue is None @@ -422,4 +422,4 @@ def test_no_job_queue(self, bot, builder): assert app.bot.token == bot.token assert app.job_queue is None assert isinstance(app.update_queue, asyncio.Queue) - assert isinstance(app.updater, Updater) \ No newline at end of file + assert isinstance(app.updater, Updater) diff --git a/tests/test_conversationhandler.py b/tests/test_conversationhandler.py index c1d10ae6362..2c5faddbd63 100644 --- a/tests/test_conversationhandler.py +++ b/tests/test_conversationhandler.py @@ -998,9 +998,9 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): ) # save app.job_queue in temp variable jqueue # and then set app.job_queue to None. - jqueue = app.job_queue + jqueue = app._job_queue if not jq: - app = ApplicationBuilder().token(bot.token).job_queue(None) + app = ApplicationBuilder().token(bot.token).job_queue(None).build() app.add_handler(handler) message = Message( @@ -1022,7 +1022,7 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): assert str(recwarn[0].message).startswith("Ignoring `conversation_timeout`") assert ("is not running" if jq else "has no JobQueue.") in str(recwarn[0].message) # now set app.job_queue back to it's original value - app.job_queue = jqueue + app._job_queue = jqueue async def test_schedule_job_exception(self, app, bot, user1, monkeypatch, caplog): def mocked_run_once(*a, **kw): @@ -1031,8 +1031,8 @@ def mocked_run_once(*a, **kw): class DictJB(JobQueue): pass - app = ApplicationBuilder().token(bot.token).job_queue(DictJB()) - monkeypatch.setattr(app.job_queue, "run_once", mocked_run_once) + 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, From 60e50ca11ba6122269b718aa0d4ae7203d9f7521 Mon Sep 17 00:00:00 2001 From: Aditya Yadav Date: Wed, 30 Nov 2022 14:51:37 +0530 Subject: [PATCH 07/11] replace app.job_queue with app._job_queue --- tests/test_application.py | 14 +++++++------- tests/test_applicationbuilder.py | 16 ++++++++-------- tests/test_callbackcontext.py | 16 ++++++++-------- tests/test_conversationhandler.py | 6 +++--- tests/test_jobqueue.py | 12 ++++++------ 5 files changed, 32 insertions(+), 32 deletions(-) diff --git a/tests/test_application.py b/tests/test_application.py index 2f8fa266f7f..f581b148168 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -169,7 +169,7 @@ async def post_shutdown(application: Application) -> None: ) assert app.bot is bot assert app.update_queue is update_queue - assert app.job_queue is job_queue + assert app._job_queue is job_queue assert app.persistence is persistence assert app.context_types is context_types assert app.updater is updater @@ -440,9 +440,9 @@ async def callback(u, c): # app.stop() should not stop the updater! assert app.updater.running if job_queue: - assert not app.job_queue.scheduler.running + assert not app._job_queue.scheduler.running else: - assert app.job_queue is None + assert app._job_queue is None await app.update_queue.put(2) await asyncio.sleep(0.05) assert not app.update_queue.empty() @@ -1378,7 +1378,7 @@ def thread_target(): # Check that everything's running assertions["app_running"] = app.running assertions["updater_running"] = app.updater.running - assertions["job_queue_running"] = app.job_queue.scheduler.running + assertions["job_queue_running"] = app._job_queue.scheduler.running # Check that we're getting updates update_event.wait() @@ -1396,7 +1396,7 @@ def thread_target(): # # Assert that everything has stopped running assertions["app_not_running"] = not app.running assertions["updater_not_running"] = not app.updater.running - assertions["job_queue_not_running"] = not app.job_queue.scheduler.running + assertions["job_queue_not_running"] = not app._job_queue.scheduler.running monkeypatch.setattr(app.bot, "get_updates", get_updates) app.add_error_handler(self.error_handler_context) @@ -1585,7 +1585,7 @@ def thread_target(): # Check that everything's running assertions["app_running"] = app.running assertions["updater_running"] = app.updater.running - assertions["job_queue_running"] = app.job_queue.scheduler.running + assertions["job_queue_running"] = app._job_queue.scheduler.running # Check that we're getting updates loop = asyncio.new_event_loop() @@ -1602,7 +1602,7 @@ def thread_target(): # # Assert that everything has stopped running assertions["app_not_running"] = not app.running assertions["updater_not_running"] = not app.updater.running - assertions["job_queue_not_running"] = not app.job_queue.scheduler.running + assertions["job_queue_not_running"] = not app._job_queue.scheduler.running monkeypatch.setattr(app.bot, "set_webhook", set_webhook) monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) diff --git a/tests/test_applicationbuilder.py b/tests/test_applicationbuilder.py index f290e9dfa87..dc630878dc6 100644 --- a/tests/test_applicationbuilder.py +++ b/tests/test_applicationbuilder.py @@ -53,7 +53,7 @@ class TestApplicationBuilderNoOptDeps: def test_init(self, builder): builder.token("token") app = builder.build() - assert app.job_queue is None + assert app._job_queue is None @pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="Optional dependencies not installed") @@ -127,8 +127,8 @@ class Client: assert app.updater.bot is app.bot assert app.updater.update_queue is app.update_queue - assert isinstance(app.job_queue, JobQueue) - assert app.job_queue.application is app + assert isinstance(app._job_queue, JobQueue) + assert app._job_queue.application is app assert app.persistence is None assert app.post_init is None @@ -370,8 +370,8 @@ async def post_shutdown(app: Application) -> None: .post_shutdown(post_shutdown) .arbitrary_callback_data(True) ).build() - assert app.job_queue is job_queue - assert app.job_queue.application is app + assert app._job_queue is job_queue + assert app._job_queue.application is app assert app.persistence is persistence assert app.persistence.bot is app.bot assert app.update_queue is update_queue @@ -413,13 +413,13 @@ def test_no_updater(self, bot, builder): assert app.bot.token == bot.token assert app.updater is None assert isinstance(app.update_queue, asyncio.Queue) - assert isinstance(app.job_queue, JobQueue) - assert app.job_queue.application is app + assert isinstance(app._job_queue, JobQueue) + assert app._job_queue.application is app @pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning") def test_no_job_queue(self, bot, builder): app = builder.token(bot.token).job_queue(None).build() assert app.bot.token == bot.token - assert app.job_queue is None + assert app._job_queue is None assert isinstance(app.update_queue, asyncio.Queue) assert isinstance(app.updater, Updater) diff --git a/tests/test_callbackcontext.py b/tests/test_callbackcontext.py index 007cf143896..8351a26ac4e 100644 --- a/tests/test_callbackcontext.py +++ b/tests/test_callbackcontext.py @@ -46,7 +46,7 @@ def test_slot_behaviour(self, app, mro_slots): assert len(mro_slots(c)) == len(set(mro_slots(c))), "duplicate slot" def test_from_job(self, app): - job = app.job_queue.run_once(lambda x: x, 10) + job = app._job_queue.run_once(lambda x: x, 10) callback_context = CallbackContext.from_job(job, app) @@ -55,7 +55,7 @@ def test_from_job(self, app): assert callback_context.user_data is None assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app.job_queue + assert callback_context.job_queue is app._job_queue assert callback_context.update_queue is app.update_queue def test_job_queue(self, bot, app, recwarn): @@ -65,7 +65,7 @@ def test_job_queue(self, bot, app, recwarn): ) callback_context = CallbackContext(app) - assert callback_context.job_queue is app.job_queue + assert callback_context.job_queue is app._job_queue app = ApplicationBuilder().job_queue(None).token(bot.token).build() callback_context = CallbackContext(app) assert callback_context.job_queue is None @@ -84,7 +84,7 @@ def test_from_update(self, app): assert callback_context.user_data == {} assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app.job_queue + assert callback_context.job_queue is app._job_queue assert callback_context.update_queue is app.update_queue callback_context_same_user_chat = CallbackContext.from_update(update, app) @@ -114,7 +114,7 @@ def test_from_update_not_update(self, app): assert callback_context.user_data is None assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app.job_queue + assert callback_context.job_queue is app._job_queue assert callback_context.update_queue is app.update_queue callback_context = CallbackContext.from_update("", app) @@ -123,7 +123,7 @@ def test_from_update_not_update(self, app): assert callback_context.user_data is None assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app.job_queue + assert callback_context.job_queue is app._job_queue assert callback_context.update_queue is app.update_queue def test_from_error(self, app): @@ -142,7 +142,7 @@ def test_from_error(self, app): assert callback_context.user_data == {} assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app.job_queue + assert callback_context.job_queue is app._job_queue assert callback_context.update_queue is app.update_queue assert callback_context.coroutine is coroutine @@ -159,7 +159,7 @@ def test_from_error_job_user_chat_data(self, app): assert callback_context.user_data == {} assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app.job_queue + assert callback_context.job_queue is app._job_queue assert callback_context.update_queue is app.update_queue assert callback_context.job is job diff --git a/tests/test_conversationhandler.py b/tests/test_conversationhandler.py index 2c5faddbd63..517ea9dd564 100644 --- a/tests/test_conversationhandler.py +++ b/tests/test_conversationhandler.py @@ -996,8 +996,8 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): fallbacks=self.fallbacks, conversation_timeout=0.5, ) - # save app.job_queue in temp variable jqueue - # and then set app.job_queue to None. + # save app._job_queue in temp variable jqueue + # and then set app._job_queue to None. jqueue = app._job_queue if not jq: app = ApplicationBuilder().token(bot.token).job_queue(None).build() @@ -1021,7 +1021,7 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): assert len(recwarn) == 1 assert str(recwarn[0].message).startswith("Ignoring `conversation_timeout`") assert ("is not running" if jq else "has no JobQueue.") in str(recwarn[0].message) - # now set app.job_queue back to it's original value + # now set app._job_queue back to it's original value app._job_queue = jqueue async def test_schedule_job_exception(self, app, bot, user1, monkeypatch, caplog): diff --git a/tests/test_jobqueue.py b/tests/test_jobqueue.py index be691fc1a25..857da9e36c9 100644 --- a/tests/test_jobqueue.py +++ b/tests/test_jobqueue.py @@ -271,15 +271,15 @@ async def test_error(self, job_queue): async def test_in_application(self, bot): app = ApplicationBuilder().token(bot.token).build() async with app: - assert not app.job_queue.scheduler.running + assert not app._job_queue.scheduler.running await app.start() - assert app.job_queue.scheduler.running + assert app._job_queue.scheduler.running - app.job_queue.run_repeating(self.job_run_once, 0.2) + app._job_queue.run_repeating(self.job_run_once, 0.2) await asyncio.sleep(0.3) assert self.result == 1 await app.stop() - assert not app.job_queue.scheduler.running + assert not app._job_queue.scheduler.running await asyncio.sleep(1) assert self.result == 1 @@ -425,7 +425,7 @@ async def test_default_tzinfo(self, tz_bot): # we're parametrizing this with two different UTC offsets to exclude the possibility # of an xpass when the test is run in a timezone with the same UTC offset app = ApplicationBuilder().bot(tz_bot).build() - jq = app.job_queue + jq = app._job_queue await jq.start() when = dtm.datetime.now(tz_bot.defaults.tzinfo) + dtm.timedelta(seconds=0.1) @@ -447,7 +447,7 @@ async def test_get_jobs(self, job_queue): assert job_queue.get_jobs_by_name("name2") == (job3,) async def test_job_run(self, app): - job = app.job_queue.run_repeating(self.job_run_once, 0.02) + job = app._job_queue.run_repeating(self.job_run_once, 0.02) await asyncio.sleep(0.05) assert self.result == 0 await job.run(app) From b256f9e1c6515bb0c4df69a5187142862345a5f7 Mon Sep 17 00:00:00 2001 From: Aditya Yadav Date: Wed, 30 Nov 2022 22:06:56 +0530 Subject: [PATCH 08/11] update to higher stacklevel --- telegram/ext/_application.py | 3 ++- telegram/ext/_callbackcontext.py | 7 ++++--- tests/test_application.py | 16 ++++++++-------- tests/test_applicationbuilder.py | 14 +++++++------- tests/test_callbackcontext.py | 16 ++++++++-------- tests/test_conversationhandler.py | 12 ++++++------ tests/test_jobqueue.py | 12 ++++++------ 7 files changed, 41 insertions(+), 39 deletions(-) diff --git a/telegram/ext/_application.py b/telegram/ext/_application.py index 5864e2f615e..0311787b07b 100644 --- a/telegram/ext/_application.py +++ b/telegram/ext/_application.py @@ -347,7 +347,8 @@ def job_queue(self) -> Optional["JobQueue"]: if self._job_queue is None: warn( "No `JobQueue` set up. To use `JobQueue`, you must install PTB via " - "`pip install python-telegram-bot[job_queue]`." + "`pip install python-telegram-bot[job_queue]`.", + stacklevel=2, ) return self._job_queue diff --git a/telegram/ext/_callbackcontext.py b/telegram/ext/_callbackcontext.py index feca3a1042b..769573f8b7e 100644 --- a/telegram/ext/_callbackcontext.py +++ b/telegram/ext/_callbackcontext.py @@ -390,12 +390,13 @@ def job_queue(self) -> Optional["JobQueue"]: .. seealso:: `Job Queue `_ """ - if self._application.job_queue is None: + if self._application._job_queue is None: warn( "No `JobQueue` set up. To use `JobQueue`, you must install PTB via " - "`pip install python-telegram-bot[job_queue]`." + "`pip install python-telegram-bot[job_queue]`.", + stacklevel=2, ) - return self._application.job_queue + return self._application._job_queue @property def update_queue(self) -> "Queue[object]": diff --git a/tests/test_application.py b/tests/test_application.py index f581b148168..35dedb7fbec 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -169,7 +169,7 @@ async def post_shutdown(application: Application) -> None: ) assert app.bot is bot assert app.update_queue is update_queue - assert app._job_queue is job_queue + assert app.job_queue is job_queue assert app.persistence is persistence assert app.context_types is context_types assert app.updater is updater @@ -440,9 +440,9 @@ async def callback(u, c): # app.stop() should not stop the updater! assert app.updater.running if job_queue: - assert not app._job_queue.scheduler.running + assert not app.job_queue.scheduler.running else: - assert app._job_queue is None + assert app.job_queue is None await app.update_queue.put(2) await asyncio.sleep(0.05) assert not app.update_queue.empty() @@ -1378,7 +1378,7 @@ def thread_target(): # Check that everything's running assertions["app_running"] = app.running assertions["updater_running"] = app.updater.running - assertions["job_queue_running"] = app._job_queue.scheduler.running + assertions["job_queue_running"] = app.job_queue.scheduler.running # Check that we're getting updates update_event.wait() @@ -1396,7 +1396,7 @@ def thread_target(): # # Assert that everything has stopped running assertions["app_not_running"] = not app.running assertions["updater_not_running"] = not app.updater.running - assertions["job_queue_not_running"] = not app._job_queue.scheduler.running + assertions["job_queue_not_running"] = not app.job_queue.scheduler.running monkeypatch.setattr(app.bot, "get_updates", get_updates) app.add_error_handler(self.error_handler_context) @@ -1585,7 +1585,7 @@ def thread_target(): # Check that everything's running assertions["app_running"] = app.running assertions["updater_running"] = app.updater.running - assertions["job_queue_running"] = app._job_queue.scheduler.running + assertions["job_queue_running"] = app.job_queue.scheduler.running # Check that we're getting updates loop = asyncio.new_event_loop() @@ -1602,7 +1602,7 @@ def thread_target(): # # Assert that everything has stopped running assertions["app_not_running"] = not app.running assertions["updater_not_running"] = not app.updater.running - assertions["job_queue_not_running"] = not app._job_queue.scheduler.running + assertions["job_queue_not_running"] = not app.job_queue.scheduler.running monkeypatch.setattr(app.bot, "set_webhook", set_webhook) monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) @@ -1958,4 +1958,4 @@ async def abort_app(): if platform.system() == "Windows": assert received_signals == [] else: - assert received_signals == [signal.SIGINT, signal.SIGTERM, signal.SIGABRT] \ No newline at end of file + assert received_signals == [signal.SIGINT, signal.SIGTERM, signal.SIGABRT] diff --git a/tests/test_applicationbuilder.py b/tests/test_applicationbuilder.py index dc630878dc6..022d8ef0c51 100644 --- a/tests/test_applicationbuilder.py +++ b/tests/test_applicationbuilder.py @@ -127,8 +127,8 @@ class Client: assert app.updater.bot is app.bot assert app.updater.update_queue is app.update_queue - assert isinstance(app._job_queue, JobQueue) - assert app._job_queue.application is app + assert isinstance(app.job_queue, JobQueue) + assert app.job_queue.application is app assert app.persistence is None assert app.post_init is None @@ -370,8 +370,8 @@ async def post_shutdown(app: Application) -> None: .post_shutdown(post_shutdown) .arbitrary_callback_data(True) ).build() - assert app._job_queue is job_queue - assert app._job_queue.application is app + assert app.job_queue is job_queue + assert app.job_queue.application is app assert app.persistence is persistence assert app.persistence.bot is app.bot assert app.update_queue is update_queue @@ -413,13 +413,13 @@ def test_no_updater(self, bot, builder): assert app.bot.token == bot.token assert app.updater is None assert isinstance(app.update_queue, asyncio.Queue) - assert isinstance(app._job_queue, JobQueue) - assert app._job_queue.application is app + assert isinstance(app.job_queue, JobQueue) + assert app.job_queue.application is app @pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning") def test_no_job_queue(self, bot, builder): app = builder.token(bot.token).job_queue(None).build() assert app.bot.token == bot.token - assert app._job_queue is None + assert app.job_queue is None assert isinstance(app.update_queue, asyncio.Queue) assert isinstance(app.updater, Updater) diff --git a/tests/test_callbackcontext.py b/tests/test_callbackcontext.py index 8351a26ac4e..007cf143896 100644 --- a/tests/test_callbackcontext.py +++ b/tests/test_callbackcontext.py @@ -46,7 +46,7 @@ def test_slot_behaviour(self, app, mro_slots): assert len(mro_slots(c)) == len(set(mro_slots(c))), "duplicate slot" def test_from_job(self, app): - job = app._job_queue.run_once(lambda x: x, 10) + job = app.job_queue.run_once(lambda x: x, 10) callback_context = CallbackContext.from_job(job, app) @@ -55,7 +55,7 @@ def test_from_job(self, app): assert callback_context.user_data is None assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app._job_queue + assert callback_context.job_queue is app.job_queue assert callback_context.update_queue is app.update_queue def test_job_queue(self, bot, app, recwarn): @@ -65,7 +65,7 @@ def test_job_queue(self, bot, app, recwarn): ) callback_context = CallbackContext(app) - assert callback_context.job_queue is app._job_queue + assert callback_context.job_queue is app.job_queue app = ApplicationBuilder().job_queue(None).token(bot.token).build() callback_context = CallbackContext(app) assert callback_context.job_queue is None @@ -84,7 +84,7 @@ def test_from_update(self, app): assert callback_context.user_data == {} assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app._job_queue + assert callback_context.job_queue is app.job_queue assert callback_context.update_queue is app.update_queue callback_context_same_user_chat = CallbackContext.from_update(update, app) @@ -114,7 +114,7 @@ def test_from_update_not_update(self, app): assert callback_context.user_data is None assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app._job_queue + assert callback_context.job_queue is app.job_queue assert callback_context.update_queue is app.update_queue callback_context = CallbackContext.from_update("", app) @@ -123,7 +123,7 @@ def test_from_update_not_update(self, app): assert callback_context.user_data is None assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app._job_queue + assert callback_context.job_queue is app.job_queue assert callback_context.update_queue is app.update_queue def test_from_error(self, app): @@ -142,7 +142,7 @@ def test_from_error(self, app): assert callback_context.user_data == {} assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app._job_queue + assert callback_context.job_queue is app.job_queue assert callback_context.update_queue is app.update_queue assert callback_context.coroutine is coroutine @@ -159,7 +159,7 @@ def test_from_error_job_user_chat_data(self, app): assert callback_context.user_data == {} assert callback_context.bot_data is app.bot_data assert callback_context.bot is app.bot - assert callback_context.job_queue is app._job_queue + assert callback_context.job_queue is app.job_queue assert callback_context.update_queue is app.update_queue assert callback_context.job is job diff --git a/tests/test_conversationhandler.py b/tests/test_conversationhandler.py index 517ea9dd564..519e3662b13 100644 --- a/tests/test_conversationhandler.py +++ b/tests/test_conversationhandler.py @@ -996,9 +996,9 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): fallbacks=self.fallbacks, conversation_timeout=0.5, ) - # save app._job_queue in temp variable jqueue - # and then set app._job_queue to None. - jqueue = app._job_queue + # save app.job_queue in temp variable jqueue + # and then set app.job_queue to None. + jqueue = app.job_queue if not jq: app = ApplicationBuilder().token(bot.token).job_queue(None).build() app.add_handler(handler) @@ -1021,8 +1021,8 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): assert len(recwarn) == 1 assert str(recwarn[0].message).startswith("Ignoring `conversation_timeout`") assert ("is not running" if jq else "has no JobQueue.") in str(recwarn[0].message) - # now set app._job_queue back to it's original value - app._job_queue = jqueue + # now set app.job_queue back to it's original value + app.job_queue = jqueue async def test_schedule_job_exception(self, app, bot, user1, monkeypatch, caplog): def mocked_run_once(*a, **kw): @@ -1032,7 +1032,7 @@ class DictJB(JobQueue): pass app = ApplicationBuilder().token(bot.token).job_queue(DictJB()).build() - monkeypatch.setattr(app._job_queue, "run_once", mocked_run_once) + monkeypatch.setattr(app.job_queue, "run_once", mocked_run_once) handler = ConversationHandler( entry_points=self.entry_points, states=self.states, diff --git a/tests/test_jobqueue.py b/tests/test_jobqueue.py index 857da9e36c9..be691fc1a25 100644 --- a/tests/test_jobqueue.py +++ b/tests/test_jobqueue.py @@ -271,15 +271,15 @@ async def test_error(self, job_queue): async def test_in_application(self, bot): app = ApplicationBuilder().token(bot.token).build() async with app: - assert not app._job_queue.scheduler.running + assert not app.job_queue.scheduler.running await app.start() - assert app._job_queue.scheduler.running + assert app.job_queue.scheduler.running - app._job_queue.run_repeating(self.job_run_once, 0.2) + app.job_queue.run_repeating(self.job_run_once, 0.2) await asyncio.sleep(0.3) assert self.result == 1 await app.stop() - assert not app._job_queue.scheduler.running + assert not app.job_queue.scheduler.running await asyncio.sleep(1) assert self.result == 1 @@ -425,7 +425,7 @@ async def test_default_tzinfo(self, tz_bot): # we're parametrizing this with two different UTC offsets to exclude the possibility # of an xpass when the test is run in a timezone with the same UTC offset app = ApplicationBuilder().bot(tz_bot).build() - jq = app._job_queue + jq = app.job_queue await jq.start() when = dtm.datetime.now(tz_bot.defaults.tzinfo) + dtm.timedelta(seconds=0.1) @@ -447,7 +447,7 @@ async def test_get_jobs(self, job_queue): assert job_queue.get_jobs_by_name("name2") == (job3,) async def test_job_run(self, app): - job = app._job_queue.run_repeating(self.job_run_once, 0.02) + job = app.job_queue.run_repeating(self.job_run_once, 0.02) await asyncio.sleep(0.05) assert self.result == 0 await job.run(app) From ad3050c7fecaf63ccd50311b271af29aad8d8cad Mon Sep 17 00:00:00 2001 From: Aditya Yadav Date: Thu, 1 Dec 2022 18:14:52 +0530 Subject: [PATCH 09/11] fix tests(probably) --- tests/test_conversationhandler.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/tests/test_conversationhandler.py b/tests/test_conversationhandler.py index 519e3662b13..657d32d0531 100644 --- a/tests/test_conversationhandler.py +++ b/tests/test_conversationhandler.py @@ -1018,11 +1018,16 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): async with app: await app.process_update(Update(update_id=0, message=message)) await asyncio.sleep(0.5) - assert len(recwarn) == 1 - assert str(recwarn[0].message).startswith("Ignoring `conversation_timeout`") - assert ("is not running" if jq else "has no JobQueue.") in str(recwarn[0].message) + 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) # now set app.job_queue back to it's original value - app.job_queue = jqueue + app._job_queue = jqueue async def test_schedule_job_exception(self, app, bot, user1, monkeypatch, caplog): def mocked_run_once(*a, **kw): From f80ebd06516055189374599a005fbf5fc3e29eb0 Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Thu, 1 Dec 2022 19:30:33 +0100 Subject: [PATCH 10/11] make pylint happy --- telegram/ext/_callbackcontext.py | 4 ++-- telegram/ext/_conversationhandler.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/telegram/ext/_callbackcontext.py b/telegram/ext/_callbackcontext.py index 769573f8b7e..eaa99f03197 100644 --- a/telegram/ext/_callbackcontext.py +++ b/telegram/ext/_callbackcontext.py @@ -390,13 +390,13 @@ def job_queue(self) -> Optional["JobQueue"]: .. seealso:: `Job Queue `_ """ - if self._application._job_queue is None: + if self._application._job_queue is None: # pylint: disable=protected-access warn( "No `JobQueue` set up. To use `JobQueue`, you must install PTB via " "`pip install python-telegram-bot[job_queue]`.", stacklevel=2, ) - return self._application._job_queue + return self._application._job_queue # pylint: disable=protected-access @property def update_queue(self) -> "Queue[object]": diff --git a/telegram/ext/_conversationhandler.py b/telegram/ext/_conversationhandler.py index 0402f740a7c..277bbf8a254 100644 --- a/telegram/ext/_conversationhandler.py +++ b/telegram/ext/_conversationhandler.py @@ -676,7 +676,7 @@ def _schedule_job( try: # both job_queue & conversation_timeout are checked before calling _schedule_job j_queue = application.job_queue - self.timeout_jobs[conversation_key] = j_queue.run_once( + self.timeout_jobs[conversation_key] = j_queue.run_once( # type: ignore[union-attr] self._trigger_timeout, self.conversation_timeout, # type: ignore[arg-type] data=_ConversationTimeoutContext(conversation_key, update, application, context), From 9c9be3f31b2e2dabae1a4fa0d18b88bb9278b935 Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Thu, 1 Dec 2022 19:35:34 +0100 Subject: [PATCH 11/11] cosmetics --- tests/test_applicationbuilder.py | 3 ++- tests/test_conversationhandler.py | 4 ---- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/tests/test_applicationbuilder.py b/tests/test_applicationbuilder.py index 022d8ef0c51..da6be21a98b 100644 --- a/tests/test_applicationbuilder.py +++ b/tests/test_applicationbuilder.py @@ -50,10 +50,11 @@ def builder(): @pytest.mark.skipif(TEST_WITH_OPT_DEPS, reason="Optional dependencies are installed") class TestApplicationBuilderNoOptDeps: + @pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning") def test_init(self, builder): builder.token("token") app = builder.build() - assert app._job_queue is None + assert app.job_queue is None @pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="Optional dependencies not installed") diff --git a/tests/test_conversationhandler.py b/tests/test_conversationhandler.py index 657d32d0531..fcb00889129 100644 --- a/tests/test_conversationhandler.py +++ b/tests/test_conversationhandler.py @@ -996,9 +996,6 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): fallbacks=self.fallbacks, conversation_timeout=0.5, ) - # save app.job_queue in temp variable jqueue - # and then set app.job_queue to None. - jqueue = app.job_queue if not jq: app = ApplicationBuilder().token(bot.token).job_queue(None).build() app.add_handler(handler) @@ -1027,7 +1024,6 @@ async def test_no_running_job_queue_warning(self, app, bot, user1, recwarn, jq): ) assert ("is not running" if jq else "No `JobQueue` set up.") in str(recwarn[0].message) # now set app.job_queue back to it's original value - app._job_queue = jqueue async def test_schedule_job_exception(self, app, bot, user1, monkeypatch, caplog): def mocked_run_once(*a, **kw):