From 778cc0c9a6044251c4f9ac2697aab480a4ca5b5b Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Tue, 3 Sep 2024 05:18:22 +0200 Subject: [PATCH 1/9] Make Tests for `telegram.ext` Independent of Networking By cutting of the internet connection in the fixtures --- tests/auxil/networking.py | 22 ++++++- tests/auxil/pytest_classes.py | 11 ++-- tests/conftest.py | 53 ++++------------- tests/ext/conftest.py | 97 +++++++++++++++++++++++++++++++ tests/ext/test_callbackcontext.py | 6 +- tests/ext/test_updater.py | 26 +++++---- 6 files changed, 153 insertions(+), 62 deletions(-) create mode 100644 tests/ext/conftest.py diff --git a/tests/auxil/networking.py b/tests/auxil/networking.py index 7c20da7ac94..50beb4ab959 100644 --- a/tests/auxil/networking.py +++ b/tests/auxil/networking.py @@ -17,7 +17,7 @@ # You should have received a copy of the GNU Lesser Public License # along with this program. If not, see [http://www.gnu.org/licenses/]. from pathlib import Path -from typing import Optional +from typing import Optional, Tuple import pytest from httpx import AsyncClient, AsyncHTTPTransport, Response @@ -26,7 +26,7 @@ from telegram._utils.strings import TextEncoding from telegram._utils.types import ODVInput from telegram.error import BadRequest, RetryAfter, TimedOut -from telegram.request import HTTPXRequest, RequestData +from telegram.request import BaseRequest, HTTPXRequest, RequestData class NonchalantHttpxRequest(HTTPXRequest): @@ -60,6 +60,24 @@ async def _request_wrapper( pytest.xfail(f"Ignoring TimedOut error: {e}") +class OfflineHTTPXRequest(HTTPXRequest): + """This Request class disallows making requests to Telegram's servers. + Use this in tests that should not depend on the network. + """ + + async def do_request( + self, + url: str, + method: str, + request_data: Optional[RequestData] = None, + read_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE, + write_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE, + connect_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE, + pool_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE, + ) -> Tuple[int, bytes]: + raise RuntimeError("OfflineHTTPXRequest: Network access disallowed") + + async def expect_bad_request(func, message, reason): """ Wrapper for testing bot functions expected to result in an :class:`telegram.error.BadRequest`. diff --git a/tests/auxil/pytest_classes.py b/tests/auxil/pytest_classes.py index 1b976b02e6c..6e16939178f 100644 --- a/tests/auxil/pytest_classes.py +++ b/tests/auxil/pytest_classes.py @@ -25,7 +25,7 @@ from tests.auxil.ci_bots import BOT_INFO_PROVIDER from tests.auxil.constants import PRIVATE_KEY from tests.auxil.envvars import TEST_WITH_OPT_DEPS -from tests.auxil.networking import NonchalantHttpxRequest +from tests.auxil.networking import NonchalantHttpxRequest, OfflineHTTPXRequest def _get_bot_user(token: str) -> User: @@ -93,17 +93,20 @@ class PytestUpdater(Updater): pass -def make_bot(bot_info=None, **kwargs): +def make_bot(bot_info=None, offline: bool = False, **kwargs): """ Tests are executed on tg.ext.ExtBot, as that class only extends the functionality of tg.bot """ token = kwargs.pop("token", (bot_info or {}).get("token")) private_key = kwargs.pop("private_key", PRIVATE_KEY) kwargs.pop("token", None) + + request_class = OfflineHTTPXRequest if offline else NonchalantHttpxRequest + return PytestExtBot( token=token, private_key=private_key if TEST_WITH_OPT_DEPS else None, - request=NonchalantHttpxRequest(8), - get_updates_request=NonchalantHttpxRequest(1), + request=request_class(8), + get_updates_request=request_class(1), **kwargs, ) diff --git a/tests/conftest.py b/tests/conftest.py index c721605bdb5..e8ef01cabac 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -37,15 +37,14 @@ Update, User, ) -from telegram.ext import ApplicationBuilder, Defaults, Updater -from telegram.ext.filters import MessageFilter, UpdateFilter +from telegram.ext import Defaults from tests.auxil.build_messages import DATE from tests.auxil.ci_bots import BOT_INFO_PROVIDER from tests.auxil.constants import PRIVATE_KEY from tests.auxil.envvars import RUN_TEST_OFFICIAL, TEST_WITH_OPT_DEPS from tests.auxil.files import data_file from tests.auxil.networking import NonchalantHttpxRequest -from tests.auxil.pytest_classes import PytestApplication, PytestBot, make_bot +from tests.auxil.pytest_classes import PytestBot, make_bot from tests.auxil.timezones import BasicTimezone if TEST_WITH_OPT_DEPS: @@ -124,6 +123,15 @@ async def bot(bot_info): yield _bot +@pytest.fixture(scope="session") +async def offline_bot(bot_info): + """Makes an offline Bot instance with the given bot_info + Note that in tests/ext we also override the `bot` fixture to return the offline bot instead. + """ + async with make_bot(bot_info, offline=True) as _bot: + yield _bot + + @pytest.fixture def one_time_bot(bot_info): """A function scoped bot since the session bot would shutdown when `async with app` finishes""" @@ -211,28 +219,6 @@ def subscription_channel_id(bot_info): return bot_info["subscription_channel_id"] -@pytest.fixture -async def app(bot_info): - # We build a new bot each time so that we use `app` in a context manager without problems - application = ( - ApplicationBuilder().bot(make_bot(bot_info)).application_class(PytestApplication).build() - ) - yield application - if application.running: - await application.stop() - await application.shutdown() - - -@pytest.fixture -async def updater(bot_info): - # We build a new bot each time so that we use `updater` in a context manager without problems - up = Updater(bot=make_bot(bot_info), update_queue=asyncio.Queue()) - yield up - if up.running: - await up.stop() - await up.shutdown() - - @pytest.fixture def thumb_file(): with data_file("thumb.jpg").open("rb") as f: @@ -245,23 +231,6 @@ def class_thumb_file(): yield f -@pytest.fixture( - scope="class", - params=[{"class": MessageFilter}, {"class": UpdateFilter}], - ids=["MessageFilter", "UpdateFilter"], -) -def mock_filter(request): - class MockFilter(request.param["class"]): - def __init__(self): - super().__init__() - self.tested = False - - def filter(self, _): - self.tested = True - - return MockFilter() - - def _get_false_update_fixture_decorator_params(): message = Message(1, DATE, Chat(1, ""), from_user=User(1, "", False), text="test") params = [ diff --git a/tests/ext/conftest.py b/tests/ext/conftest.py new file mode 100644 index 00000000000..da1a372be55 --- /dev/null +++ b/tests/ext/conftest.py @@ -0,0 +1,97 @@ +import asyncio + +import pytest + +from telegram.ext import ApplicationBuilder, Updater +from telegram.ext.filters import MessageFilter, UpdateFilter +from tests.auxil.constants import PRIVATE_KEY +from tests.auxil.envvars import TEST_WITH_OPT_DEPS +from tests.auxil.networking import OfflineHTTPXRequest +from tests.auxil.pytest_classes import PytestApplication, PytestBot, make_bot + +# This module overrides the bot fixtures defined in the global conftest.py to use the offline bot. +# We don't want the tests on telegram.ext to depend on the network, so we use the offline bot +# instead. + + +@pytest.fixture(scope="session") +async def bot(bot_info, offline_bot): + return offline_bot + + +@pytest.fixture +async def app(bot_info): + # We build a new bot each time so that we use `app` in a context manager without problems + application = ( + ApplicationBuilder() + .bot(make_bot(bot_info, offline=True)) + .application_class(PytestApplication) + .build() + ) + yield application + if application.running: + await application.stop() + await application.shutdown() + + +@pytest.fixture +async def updater(bot_info): + # We build a new bot each time so that we use `updater` in a context manager without problems + up = Updater(bot=make_bot(bot_info, offline=True), update_queue=asyncio.Queue()) + yield up + if up.running: + await up.stop() + await up.shutdown() + + +@pytest.fixture +def one_time_bot(bot_info): + """A function scoped bot since the session bot would shutdown when `async with app` finishes""" + return make_bot(bot_info, offline=True) + + +@pytest.fixture(scope="session") +async def cdc_bot(bot_info): + """Makes an ExtBot instance with the given bot_info that uses arbitrary callback_data""" + async with make_bot(bot_info, arbitrary_callback_data=True, offline=True) as _bot: + yield _bot + + +@pytest.fixture(scope="session") +async def raw_bot(bot_info): + """Makes an regular Bot instance with the given bot_info""" + async with PytestBot( + bot_info["token"], + private_key=PRIVATE_KEY if TEST_WITH_OPT_DEPS else None, + request=OfflineHTTPXRequest(8), + get_updates_request=OfflineHTTPXRequest(1), + ) as _bot: + yield _bot + + +@pytest.fixture +async def on_time_raw_bot(bot_info): + """Makes an regular Bot instance with the given bot_info""" + return PytestBot( + bot_info["token"], + private_key=PRIVATE_KEY if TEST_WITH_OPT_DEPS else None, + request=OfflineHTTPXRequest(8), + get_updates_request=OfflineHTTPXRequest(1), + ) + + +@pytest.fixture( + scope="class", + params=[{"class": MessageFilter}, {"class": UpdateFilter}], + ids=["MessageFilter", "UpdateFilter"], +) +def mock_filter(request): + class MockFilter(request.param["class"]): + def __init__(self): + super().__init__() + self.tested = False + + def filter(self, _): + self.tested = True + + return MockFilter() diff --git a/tests/ext/test_callbackcontext.py b/tests/ext/test_callbackcontext.py index 0a099f64f15..9a5f64e6f21 100644 --- a/tests/ext/test_callbackcontext.py +++ b/tests/ext/test_callbackcontext.py @@ -20,7 +20,6 @@ import pytest from telegram import ( - Bot, CallbackQuery, Chat, InlineKeyboardButton, @@ -194,8 +193,7 @@ def test_application_attribute(self, app): callback_context = CallbackContext(app) assert callback_context.application is app - def test_drop_callback_data_exception(self, bot, app): - non_ext_bot = Bot(bot.token) + def test_drop_callback_data_exception(self, bot, app, raw_bot): update = Update( 0, message=Message(0, None, Chat(1, "chat"), from_user=User(1, "user", False)) ) @@ -206,7 +204,7 @@ def test_drop_callback_data_exception(self, bot, app): callback_context.drop_callback_data(None) try: - app.bot = non_ext_bot + app.bot = raw_bot with pytest.raises(RuntimeError, match="telegram.Bot does not allow for"): callback_context.drop_callback_data(None) finally: diff --git a/tests/ext/test_updater.py b/tests/ext/test_updater.py index 84a86c988da..98b5a77cb17 100644 --- a/tests/ext/test_updater.py +++ b/tests/ext/test_updater.py @@ -35,7 +35,7 @@ from tests.auxil.envvars import TEST_WITH_OPT_DEPS from tests.auxil.files import TEST_DATA_PATH, data_file from tests.auxil.networking import send_webhook_message -from tests.auxil.pytest_classes import PytestBot, make_bot +from tests.auxil.pytest_classes import make_bot from tests.auxil.slots import mro_slots UNIX_AVAILABLE = False @@ -246,13 +246,12 @@ async def get_updates(*args, **kwargs): await asyncio.sleep(0.1) return [] - orig_del_webhook = updater.bot.delete_webhook - async def delete_webhook(*args, **kwargs): # Dropping pending updates is done by passing the parameter to delete_webhook if kwargs.get("drop_pending_updates"): self.message_count += 1 - return await orig_del_webhook(*args, **kwargs) + await asyncio.sleep(0) + return True monkeypatch.setattr(updater.bot, "get_updates", get_updates) monkeypatch.setattr(updater.bot, "delete_webhook", delete_webhook) @@ -264,7 +263,6 @@ async def delete_webhook(*args, **kwargs): await updates.join() await updater.stop() assert not updater.running - assert not (await updater.bot.get_webhook_info()).url if drop_pending_updates: assert self.message_count == 1 else: @@ -281,7 +279,6 @@ async def delete_webhook(*args, **kwargs): await updates.join() await updater.stop() assert not updater.running - assert not (await updater.bot.get_webhook_info()).url self.received = [] self.message_count = 0 @@ -505,7 +502,7 @@ async def do_request(*args, **kwargs): async with updater: # Patch within the context so that updater.bot.initialize can still be called # by the context manager - monkeypatch.setattr(HTTPXRequest, "do_request", do_request) + monkeypatch.setattr(updater.bot.request, "do_request", do_request) if exception_class == InvalidToken: with pytest.raises(InvalidToken, match="1"): @@ -705,14 +702,23 @@ async def delete_webhook(*args, **kwargs): "unix", [None, "file_path", "socket_object"] if UNIX_AVAILABLE else [None] ) async def test_webhook_basic( - self, monkeypatch, updater, drop_pending_updates, ext_bot, secret_token, unix, file_path + self, + monkeypatch, + updater, + drop_pending_updates, + ext_bot, + secret_token, + unix, + file_path, + one_time_bot, + on_time_raw_bot, ): # Testing with both ExtBot and Bot to make sure any logic in WebhookHandler # that depends on this distinction works if ext_bot and not isinstance(updater.bot, ExtBot): - updater.bot = ExtBot(updater.bot.token) + updater.bot = one_time_bot if not ext_bot and type(updater.bot) is not Bot: - updater.bot = PytestBot(updater.bot.token) + updater.bot = on_time_raw_bot async def delete_webhook(*args, **kwargs): # Dropping pending updates is done by passing the parameter to delete_webhook From 63256eb2faa9144a83fb707f420b9b47abe97332 Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Wed, 4 Sep 2024 22:20:36 +0200 Subject: [PATCH 2/9] Fix Tests and try speeding up a bit --- tests/auxil/networking.py | 13 +++++++++++-- tests/auxil/pytest_classes.py | 4 ++-- tests/ext/conftest.py | 10 +++++----- tests/ext/test_application.py | 28 +++++++++++++++++++++++++++- 4 files changed, 45 insertions(+), 10 deletions(-) diff --git a/tests/auxil/networking.py b/tests/auxil/networking.py index 50beb4ab959..8c4b5a3288b 100644 --- a/tests/auxil/networking.py +++ b/tests/auxil/networking.py @@ -60,11 +60,20 @@ async def _request_wrapper( pytest.xfail(f"Ignoring TimedOut error: {e}") -class OfflineHTTPXRequest(HTTPXRequest): +class OfflineRequest(BaseRequest): """This Request class disallows making requests to Telegram's servers. Use this in tests that should not depend on the network. """ + async def initialize(self) -> None: + pass + + async def shutdown(self) -> None: + pass + + def __init__(self, *args, **kwargs): + pass + async def do_request( self, url: str, @@ -75,7 +84,7 @@ async def do_request( connect_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE, pool_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE, ) -> Tuple[int, bytes]: - raise RuntimeError("OfflineHTTPXRequest: Network access disallowed") + raise RuntimeError("OfflineRequest: Network access disallowed") async def expect_bad_request(func, message, reason): diff --git a/tests/auxil/pytest_classes.py b/tests/auxil/pytest_classes.py index 6e16939178f..b80945b6704 100644 --- a/tests/auxil/pytest_classes.py +++ b/tests/auxil/pytest_classes.py @@ -25,7 +25,7 @@ from tests.auxil.ci_bots import BOT_INFO_PROVIDER from tests.auxil.constants import PRIVATE_KEY from tests.auxil.envvars import TEST_WITH_OPT_DEPS -from tests.auxil.networking import NonchalantHttpxRequest, OfflineHTTPXRequest +from tests.auxil.networking import NonchalantHttpxRequest, OfflineRequest def _get_bot_user(token: str) -> User: @@ -101,7 +101,7 @@ def make_bot(bot_info=None, offline: bool = False, **kwargs): private_key = kwargs.pop("private_key", PRIVATE_KEY) kwargs.pop("token", None) - request_class = OfflineHTTPXRequest if offline else NonchalantHttpxRequest + request_class = OfflineRequest if offline else NonchalantHttpxRequest return PytestExtBot( token=token, diff --git a/tests/ext/conftest.py b/tests/ext/conftest.py index da1a372be55..6c1c81ab144 100644 --- a/tests/ext/conftest.py +++ b/tests/ext/conftest.py @@ -6,7 +6,7 @@ from telegram.ext.filters import MessageFilter, UpdateFilter from tests.auxil.constants import PRIVATE_KEY from tests.auxil.envvars import TEST_WITH_OPT_DEPS -from tests.auxil.networking import OfflineHTTPXRequest +from tests.auxil.networking import OfflineRequest from tests.auxil.pytest_classes import PytestApplication, PytestBot, make_bot # This module overrides the bot fixtures defined in the global conftest.py to use the offline bot. @@ -63,8 +63,8 @@ async def raw_bot(bot_info): async with PytestBot( bot_info["token"], private_key=PRIVATE_KEY if TEST_WITH_OPT_DEPS else None, - request=OfflineHTTPXRequest(8), - get_updates_request=OfflineHTTPXRequest(1), + request=OfflineRequest(), + get_updates_request=OfflineRequest(), ) as _bot: yield _bot @@ -75,8 +75,8 @@ async def on_time_raw_bot(bot_info): return PytestBot( bot_info["token"], private_key=PRIVATE_KEY if TEST_WITH_OPT_DEPS else None, - request=OfflineHTTPXRequest(8), - get_updates_request=OfflineHTTPXRequest(1), + request=OfflineRequest(), + get_updates_request=OfflineRequest(), ) diff --git a/tests/ext/test_application.py b/tests/ext/test_application.py index c423c5d5fbf..baf168f0fe4 100644 --- a/tests/ext/test_application.py +++ b/tests/ext/test_application.py @@ -432,7 +432,7 @@ def test_builder(self, app): @pytest.mark.parametrize("job_queue", [True, False]) @pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning") - async def test_start_stop_processing_updates(self, one_time_bot, job_queue): + async def test_start_stop_processing_updates(self, one_time_bot, job_queue, monkeypatch): # TODO: repeat a similar test for create_task, persistence processing and job queue if job_queue: app = ApplicationBuilder().bot(one_time_bot).build() @@ -442,6 +442,16 @@ async def test_start_stop_processing_updates(self, one_time_bot, job_queue): async def callback(u, c): self.received = u + async def get_updates(*args, **kwargs): + await asyncio.sleep(0) + return [] + + async def delete_webhook(*args, **kwargs): + return True + + monkeypatch.setattr(app.bot, "get_updates", get_updates) + monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + assert not app.running assert not app.updater.running if job_queue: @@ -473,6 +483,8 @@ async def callback(u, c): await app.updater.start_polling() except TelegramError: pytest.xfail("start_polling timed out") + except BaseException as e: + pytest.fail(f"Unexpected exception: {e}") else: await app.stop() assert not app.running @@ -2161,6 +2173,11 @@ def after(_, name): .build() ) + async def delete_webhook(*args, **kwargs): + return True + + monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + app.run_polling(close_loop=False) # This checks two things: @@ -2221,6 +2238,9 @@ async def get_updates(*args, **kwargs): await asyncio.sleep(0) return [] + async def delete_webhook(*args, **kwargs): + return True + for cls, method, entry in [ (Application, "initialize", "app_initialize"), (Application, "start", "app_start"), @@ -2250,6 +2270,7 @@ def after(_, name): .build() ) monkeypatch.setattr(app.bot, "get_updates", get_updates) + monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) app.add_handler(TypeHandler(object, update_logger_callback), group=-10) app.add_handler(TypeHandler(object, handler_callback)) @@ -2312,6 +2333,9 @@ def _after_shutdown(*args, **kwargs): return _after_shutdown + async def delete_webhook(*args, **kwargs): + return True + monkeypatch.setattr(Application, method, raise_method) monkeypatch.setattr( Application, @@ -2322,6 +2346,8 @@ def _after_shutdown(*args, **kwargs): Updater, "shutdown", call_after(Updater.shutdown, after_shutdown("updater")) ) app = ApplicationBuilder().bot(one_time_bot).build() + + monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) with pytest.raises(RuntimeError, match="Test Exception"): app.run_polling(close_loop=False) From 321b2d4e84022847debc2228843ae6232504ba07 Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Wed, 4 Sep 2024 22:21:25 +0200 Subject: [PATCH 3/9] Review --- tests/ext/conftest.py | 2 +- tests/ext/test_updater.py | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/ext/conftest.py b/tests/ext/conftest.py index 6c1c81ab144..7573afb3a38 100644 --- a/tests/ext/conftest.py +++ b/tests/ext/conftest.py @@ -70,7 +70,7 @@ async def raw_bot(bot_info): @pytest.fixture -async def on_time_raw_bot(bot_info): +async def one_time_raw_bot(bot_info): """Makes an regular Bot instance with the given bot_info""" return PytestBot( bot_info["token"], diff --git a/tests/ext/test_updater.py b/tests/ext/test_updater.py index 98b5a77cb17..362c55e9695 100644 --- a/tests/ext/test_updater.py +++ b/tests/ext/test_updater.py @@ -711,14 +711,14 @@ async def test_webhook_basic( unix, file_path, one_time_bot, - on_time_raw_bot, + one_time_raw_bot, ): # Testing with both ExtBot and Bot to make sure any logic in WebhookHandler # that depends on this distinction works if ext_bot and not isinstance(updater.bot, ExtBot): updater.bot = one_time_bot if not ext_bot and type(updater.bot) is not Bot: - updater.bot = on_time_raw_bot + updater.bot = one_time_raw_bot async def delete_webhook(*args, **kwargs): # Dropping pending updates is done by passing the parameter to delete_webhook From 017925a6b2bfbe7591023bbfaa6e14e434a8797b Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Sun, 8 Sep 2024 14:36:31 +0200 Subject: [PATCH 4/9] =?UTF-8?q?Way=20more=20test=20fixing=20=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/auxil/networking.py | 2 +- tests/ext/conftest.py | 12 ++- tests/ext/test_application.py | 83 +++++-------------- .../test_inlinequeryhandler.py | 0 tests/{ => ext}/test_pollhandler.py | 0 tests/ext/test_updater.py | 71 +++++----------- 6 files changed, 54 insertions(+), 114 deletions(-) rename tests/{_inline => ext}/test_inlinequeryhandler.py (100%) rename tests/{ => ext}/test_pollhandler.py (100%) diff --git a/tests/auxil/networking.py b/tests/auxil/networking.py index 8c4b5a3288b..a695eb232f7 100644 --- a/tests/auxil/networking.py +++ b/tests/auxil/networking.py @@ -84,7 +84,7 @@ async def do_request( connect_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE, pool_timeout: ODVInput[float] = BaseRequest.DEFAULT_NONE, ) -> Tuple[int, bytes]: - raise RuntimeError("OfflineRequest: Network access disallowed") + pytest.fail("OfflineRequest: Network access disallowed in this test") async def expect_bad_request(func, message, reason): diff --git a/tests/ext/conftest.py b/tests/ext/conftest.py index 7573afb3a38..39d34390a15 100644 --- a/tests/ext/conftest.py +++ b/tests/ext/conftest.py @@ -19,8 +19,12 @@ async def bot(bot_info, offline_bot): return offline_bot +async def return_true(*args, **kwargs): + return True + + @pytest.fixture -async def app(bot_info): +async def app(bot_info, monkeypatch): # We build a new bot each time so that we use `app` in a context manager without problems application = ( ApplicationBuilder() @@ -28,6 +32,8 @@ async def app(bot_info): .application_class(PytestApplication) .build() ) + monkeypatch.setattr(application.bot, "delete_webhook", return_true) + monkeypatch.setattr(application.bot, "set_webhook", return_true) yield application if application.running: await application.stop() @@ -35,9 +41,11 @@ async def app(bot_info): @pytest.fixture -async def updater(bot_info): +async def updater(bot_info, monkeypatch): # We build a new bot each time so that we use `updater` in a context manager without problems up = Updater(bot=make_bot(bot_info, offline=True), update_queue=asyncio.Queue()) + monkeypatch.setattr(up.bot, "delete_webhook", return_true) + monkeypatch.setattr(up.bot, "set_webhook", return_true) yield up if up.running: await up.stop() diff --git a/tests/ext/test_application.py b/tests/ext/test_application.py index baf168f0fe4..80cebc2c176 100644 --- a/tests/ext/test_application.py +++ b/tests/ext/test_application.py @@ -483,8 +483,6 @@ async def delete_webhook(*args, **kwargs): await app.updater.start_polling() except TelegramError: pytest.xfail("start_polling timed out") - except BaseException as e: - pytest.fail(f"Unexpected exception: {e}") else: await app.stop() assert not app.running @@ -1796,12 +1794,6 @@ def thread_target(): def test_run_webhook_basic(self, app, monkeypatch, caplog): assertions = {} - async def delete_webhook(*args, **kwargs): - return True - - async def set_webhook(*args, **kwargs): - return True - def thread_target(): waited = 0 while not app.running: @@ -1832,8 +1824,6 @@ def thread_target(): assertions["updater_not_running"] = not app.updater.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) app.add_handler(TypeHandler(object, self.callback_set_count(42))) thread = Thread(target=thread_target) @@ -1869,17 +1859,6 @@ def thread_target(): def test_run_webhook_post_init(self, one_time_bot, monkeypatch): events = [] - async def delete_webhook(*args, **kwargs): - return True - - async def set_webhook(*args, **kwargs): - return True - - async def get_updates(*args, **kwargs): - # This makes sure that other coroutines have a chance of running as well - await asyncio.sleep(0) - return [] - def thread_target(): waited = 0 while not app.running: @@ -1901,8 +1880,7 @@ async def post_init(app: Application) -> None: .build() ) app.bot._unfreeze() - monkeypatch.setattr(app.bot, "set_webhook", set_webhook) - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + monkeypatch.setattr( app, "initialize", call_after(app.initialize, lambda _: events.append("init")) ) @@ -1935,17 +1913,6 @@ async def post_init(app: Application) -> None: def test_run_webhook_post_shutdown(self, one_time_bot, monkeypatch): events = [] - async def delete_webhook(*args, **kwargs): - return True - - async def set_webhook(*args, **kwargs): - return True - - async def get_updates(*args, **kwargs): - # This makes sure that other coroutines have a chance of running as well - await asyncio.sleep(0) - return [] - def thread_target(): waited = 0 while not app.running: @@ -1967,8 +1934,7 @@ async def post_shutdown(app: Application) -> None: .build() ) app.bot._unfreeze() - monkeypatch.setattr(app.bot, "set_webhook", set_webhook) - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + monkeypatch.setattr( app, "shutdown", call_after(app.shutdown, lambda _: events.append("shutdown")) ) @@ -2005,17 +1971,6 @@ async def post_shutdown(app: Application) -> None: def test_run_webhook_post_stop(self, one_time_bot, monkeypatch): events = [] - async def delete_webhook(*args, **kwargs): - return True - - async def set_webhook(*args, **kwargs): - return True - - async def get_updates(*args, **kwargs): - # This makes sure that other coroutines have a chance of running as well - await asyncio.sleep(0) - return [] - def thread_target(): waited = 0 while not app.running: @@ -2037,8 +1992,7 @@ async def post_stop(app: Application) -> None: .build() ) app.bot._unfreeze() - monkeypatch.setattr(app.bot, "set_webhook", set_webhook) - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + monkeypatch.setattr(app, "stop", call_after(app.stop, lambda _: events.append("stop"))) monkeypatch.setattr( app.updater, @@ -2173,11 +2127,6 @@ def after(_, name): .build() ) - async def delete_webhook(*args, **kwargs): - return True - - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) - app.run_polling(close_loop=False) # This checks two things: @@ -2336,6 +2285,10 @@ def _after_shutdown(*args, **kwargs): async def delete_webhook(*args, **kwargs): return True + async def get_updates(*args, **kwargs): + await asyncio.sleep(0) + return [] + monkeypatch.setattr(Application, method, raise_method) monkeypatch.setattr( Application, @@ -2346,8 +2299,9 @@ async def delete_webhook(*args, **kwargs): Updater, "shutdown", call_after(Updater.shutdown, after_shutdown("updater")) ) app = ApplicationBuilder().bot(one_time_bot).build() - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + monkeypatch.setattr(app.bot, "get_updates", get_updates) + with pytest.raises(RuntimeError, match="Test Exception"): app.run_polling(close_loop=False) @@ -2444,7 +2398,13 @@ def signal_handler_test(*args, **kwargs): received_signals.append(args[0]) loop = asyncio.get_event_loop() + + async def get_updates(*args, **kwargs): + await asyncio.sleep(0) + return [] + monkeypatch.setattr(loop, "add_signal_handler", signal_handler_test) + monkeypatch.setattr(app.bot, "get_updates", get_updates) def abort_app(): raise SystemExit @@ -2526,12 +2486,6 @@ async def get_updates(*args, **kwargs): await asyncio.sleep(0) return [] - async def delete_webhook(*args, **kwargs): - return True - - async def set_webhook(*args, **kwargs): - return True - async def post_init(app): # Simply calling app.update_queue.put_nowait(method) in the thread_target doesn't work # for some reason (probably threading magic), so we use an event from the thread_target @@ -2542,6 +2496,9 @@ async def task(app): app.create_task(task(app)) + async def return_true(*args, **kwargs): + return True + app = ( ApplicationBuilder() .application_class(PytestApplication) @@ -2550,8 +2507,6 @@ async def task(app): .build() ) monkeypatch.setattr(app.bot, "get_updates", get_updates) - monkeypatch.setattr(app.bot, "set_webhook", set_webhook) - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) events = [] monkeypatch.setattr( @@ -2569,6 +2524,8 @@ async def task(app): "shutdown", call_after(app.shutdown, lambda _: events.append("app.shutdown")), ) + monkeypatch.setattr(app.bot, "set_webhook", return_true) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) def thread_target(): waited = 0 diff --git a/tests/_inline/test_inlinequeryhandler.py b/tests/ext/test_inlinequeryhandler.py similarity index 100% rename from tests/_inline/test_inlinequeryhandler.py rename to tests/ext/test_inlinequeryhandler.py diff --git a/tests/test_pollhandler.py b/tests/ext/test_pollhandler.py similarity index 100% rename from tests/test_pollhandler.py rename to tests/ext/test_pollhandler.py diff --git a/tests/ext/test_updater.py b/tests/ext/test_updater.py index 362c55e9695..5ca6effdc14 100644 --- a/tests/ext/test_updater.py +++ b/tests/ext/test_updater.py @@ -30,7 +30,6 @@ from telegram._utils.defaultvalue import DEFAULT_NONE from telegram.error import InvalidToken, RetryAfter, TelegramError, TimedOut from telegram.ext import ExtBot, InvalidCallbackData, Updater -from telegram.request import HTTPXRequest from tests.auxil.build_messages import make_message, make_message_update from tests.auxil.envvars import TEST_WITH_OPT_DEPS from tests.auxil.files import TEST_DATA_PATH, data_file @@ -179,14 +178,15 @@ async def test_start_without_initialize(self, updater, method): @pytest.mark.parametrize("method", ["start_polling", "start_webhook"]) async def test_shutdown_while_running(self, updater, method, monkeypatch): - async def set_webhook(*args, **kwargs): - return True - - monkeypatch.setattr(updater.bot, "set_webhook", set_webhook) - ip = "127.0.0.1" port = randrange(1024, 49152) # Select random port + async def get_updates(*args, **kwargs): + await asyncio.sleep(0) + return [] + + monkeypatch.setattr(updater.bot, "get_updates", get_updates) + async with updater: if "webhook" in method: await getattr(updater, method)( @@ -408,7 +408,13 @@ async def get_updates(*args, **kwargs): assert log_found - async def test_start_polling_already_running(self, updater): + async def test_start_polling_already_running(self, updater, monkeypatch): + async def get_updates(*args, **kwargs): + await asyncio.sleep(0) + return [] + + monkeypatch.setattr(updater.bot, "get_updates", get_updates) + async with updater: await updater.start_polling() task = asyncio.create_task(updater.start_polling()) @@ -495,15 +501,13 @@ async def get_updates(*args, **kwargs): async def test_start_polling_bootstrap_retries( self, updater, monkeypatch, exception_class, retries ): - async def do_request(*args, **kwargs): + async def delete_webhook(*args, **kwargs): self.message_count += 1 raise exception_class(str(self.message_count)) - async with updater: - # Patch within the context so that updater.bot.initialize can still be called - # by the context manager - monkeypatch.setattr(updater.bot.request, "do_request", do_request) + monkeypatch.setattr(updater.bot, "delete_webhook", delete_webhook) + async with updater: if exception_class == InvalidToken: with pytest.raises(InvalidToken, match="1"): await updater.start_polling(bootstrap_retries=retries) @@ -879,12 +883,6 @@ async def test_no_unix(self, updater): await updater.start_webhook(unix="DoesntMatter", webhook_url="TOKEN") async def test_start_webhook_already_running(self, updater, monkeypatch): - async def return_true(*args, **kwargs): - return True - - monkeypatch.setattr(updater.bot, "set_webhook", return_true) - monkeypatch.setattr(updater.bot, "delete_webhook", return_true) - ip = "127.0.0.1" port = randrange(1024, 49152) # Select random port async with updater: @@ -983,12 +981,12 @@ async def test_webhook_arbitrary_callback_data( extensively in test_bot.py in conjunction with get_updates.""" updater = Updater(bot=cdc_bot, update_queue=asyncio.Queue()) - async def return_true(*args, **kwargs): + async def set_webhook(*args, **kwargs): return True + monkeypatch.setattr(updater.bot, "set_webhook", set_webhook) + try: - monkeypatch.setattr(updater.bot, "set_webhook", return_true) - monkeypatch.setattr(updater.bot, "delete_webhook", return_true) ip = "127.0.0.1" port = randrange(1024, 49152) # Select random port @@ -1031,11 +1029,6 @@ async def return_true(*args, **kwargs): updater.bot.callback_data_cache.clear_callback_queries() async def test_webhook_invalid_ssl(self, monkeypatch, updater): - async def return_true(*args, **kwargs): - return True - - monkeypatch.setattr(updater.bot, "set_webhook", return_true) - monkeypatch.setattr(updater.bot, "delete_webhook", return_true) ip = "127.0.0.1" port = randrange(1024, 49152) # Select random port @@ -1062,9 +1055,6 @@ async def set_webhook(**kwargs): self.test_flag.append(bool(kwargs.get("certificate"))) return True - async def return_true(*args, **kwargs): - return True - orig_wh_server_init = WebhookServer.__init__ def webhook_server_init(*args, **kwargs): @@ -1072,7 +1062,7 @@ def webhook_server_init(*args, **kwargs): orig_wh_server_init(*args, **kwargs) monkeypatch.setattr(updater.bot, "set_webhook", set_webhook) - monkeypatch.setattr(updater.bot, "delete_webhook", return_true) + monkeypatch.setattr( "telegram.ext._utils.webhookhandler.WebhookServer.__init__", webhook_server_init ) @@ -1094,15 +1084,13 @@ def webhook_server_init(*args, **kwargs): async def test_start_webhook_bootstrap_retries( self, updater, monkeypatch, exception_class, retries ): - async def do_request(*args, **kwargs): + async def set_webhook(*args, **kwargs): self.message_count += 1 raise exception_class(str(self.message_count)) - async with updater: - # Patch within the context so that updater.bot.initialize can still be called - # by the context manager - monkeypatch.setattr(HTTPXRequest, "do_request", do_request) + monkeypatch.setattr(updater.bot, "set_webhook", set_webhook) + async with updater: if exception_class == InvalidToken: with pytest.raises(InvalidToken, match="1"): await updater.start_webhook(bootstrap_retries=retries) @@ -1113,11 +1101,6 @@ async def do_request(*args, **kwargs): ) async def test_webhook_invalid_posts(self, updater, monkeypatch): - async def return_true(*args, **kwargs): - return True - - monkeypatch.setattr(updater.bot, "set_webhook", return_true) - monkeypatch.setattr(updater.bot, "delete_webhook", return_true) ip = "127.0.0.1" port = randrange(1024, 49152) @@ -1152,17 +1135,9 @@ async def return_true(*args, **kwargs): await updater.stop() async def test_webhook_update_de_json_fails(self, monkeypatch, updater, caplog): - async def delete_webhook(*args, **kwargs): - return True - - async def set_webhook(*args, **kwargs): - return True - def de_json_fails(*args, **kwargs): raise TypeError("Invalid input") - monkeypatch.setattr(updater.bot, "set_webhook", set_webhook) - monkeypatch.setattr(updater.bot, "delete_webhook", delete_webhook) orig_de_json = Update.de_json monkeypatch.setattr(Update, "de_json", de_json_fails) From 98d0890bb9a90c31c540714b6ea8b6922dd8840d Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Sun, 8 Sep 2024 15:33:23 +0200 Subject: [PATCH 5/9] fix unix-only tests --- tests/ext/test_application.py | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/tests/ext/test_application.py b/tests/ext/test_application.py index 80cebc2c176..9de105bcc7f 100644 --- a/tests/ext/test_application.py +++ b/tests/ext/test_application.py @@ -1591,6 +1591,9 @@ def thread_target(): async def post_init(app: Application) -> None: events.append("post_init") + async def delete_webhook(*args, **kwargs): + return True + app = ( Application.builder() .application_class(PytestApplication) @@ -1608,6 +1611,7 @@ async def post_init(app: Application) -> None: "start_polling", call_after(app.updater.start_polling, lambda _: events.append("start_polling")), ) + monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) thread = Thread(target=thread_target) thread.start() @@ -1637,6 +1641,9 @@ def thread_target(): os.kill(os.getpid(), signal.SIGINT) + async def delete_webhook(*args, **kwargs): + return True + async def post_shutdown(app: Application) -> None: events.append("post_shutdown") @@ -1657,6 +1664,7 @@ async def post_shutdown(app: Application) -> None: "shutdown", call_after(app.updater.shutdown, lambda _: events.append("updater.shutdown")), ) + monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) thread = Thread(target=thread_target) thread.start() @@ -1690,6 +1698,9 @@ def thread_target(): os.kill(os.getpid(), signal.SIGINT) + async def delete_webhook(*args, **kwargs): + return True + async def post_stop(app: Application) -> None: events.append("post_stop") @@ -1713,6 +1724,7 @@ async def post_stop(app: Application) -> None: "shutdown", call_after(app.updater.shutdown, lambda _: events.append("updater.shutdown")), ) + monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) thread = Thread(target=thread_target) thread.start() @@ -1872,6 +1884,9 @@ def thread_target(): async def post_init(app: Application) -> None: events.append("post_init") + async def return_true(*args, **kwargs): + return True + app = ( Application.builder() .post_init(post_init) @@ -1889,6 +1904,8 @@ async def post_init(app: Application) -> None: "start_webhook", call_after(app.updater.start_webhook, lambda _: events.append("start_webhook")), ) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) + monkeypatch.setattr(app.bot, "set_webhook", return_true) thread = Thread(target=thread_target) thread.start() @@ -1926,6 +1943,9 @@ def thread_target(): async def post_shutdown(app: Application) -> None: events.append("post_shutdown") + async def return_true(*args, **kwargs): + return True + app = ( Application.builder() .application_class(PytestApplication) @@ -1943,6 +1963,8 @@ async def post_shutdown(app: Application) -> None: "shutdown", call_after(app.updater.shutdown, lambda _: events.append("updater.shutdown")), ) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) + monkeypatch.setattr(app.bot, "set_webhook", return_true) thread = Thread(target=thread_target) thread.start() @@ -1984,6 +2006,9 @@ def thread_target(): async def post_stop(app: Application) -> None: events.append("post_stop") + async def return_true(*args, **kwargs): + return True + app = ( Application.builder() .application_class(PytestApplication) @@ -2004,6 +2029,8 @@ async def post_stop(app: Application) -> None: "shutdown", call_after(app.updater.shutdown, lambda _: events.append("updater.shutdown")), ) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) + monkeypatch.setattr(app.bot, "set_webhook", return_true) thread = Thread(target=thread_target) thread.start() From c25ee5e9372207963dc789bf959c4c99cef30d1d Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Sun, 8 Sep 2024 16:58:16 +0200 Subject: [PATCH 6/9] Reduce code duplication --- tests/auxil/monkeypatch.py | 29 ++++++++++ tests/ext/conftest.py | 5 +- tests/ext/test_application.py | 101 ++++++---------------------------- tests/ext/test_updater.py | 27 ++------- 4 files changed, 52 insertions(+), 110 deletions(-) create mode 100644 tests/auxil/monkeypatch.py diff --git a/tests/auxil/monkeypatch.py b/tests/auxil/monkeypatch.py new file mode 100644 index 00000000000..087ea80232d --- /dev/null +++ b/tests/auxil/monkeypatch.py @@ -0,0 +1,29 @@ +#!/usr/bin/env python +# +# A library that provides a Python interface to the Telegram Bot API +# Copyright (C) 2015-2024 +# Leandro Toledo de Souza +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Lesser Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser Public License for more details. +# +# You should have received a copy of the GNU Lesser Public License +# along with this program. If not, see [http://www.gnu.org/licenses/]. +import asyncio + + +async def return_true(*args, **kwargs): + return True + + +async def empty_get_updates(*args, **kwargs): + # The `await` gives the event loop a chance to run other tasks + await asyncio.sleep(0) + return [] diff --git a/tests/ext/conftest.py b/tests/ext/conftest.py index 39d34390a15..f1a877b6e27 100644 --- a/tests/ext/conftest.py +++ b/tests/ext/conftest.py @@ -6,6 +6,7 @@ from telegram.ext.filters import MessageFilter, UpdateFilter from tests.auxil.constants import PRIVATE_KEY from tests.auxil.envvars import TEST_WITH_OPT_DEPS +from tests.auxil.monkeypatch import return_true from tests.auxil.networking import OfflineRequest from tests.auxil.pytest_classes import PytestApplication, PytestBot, make_bot @@ -19,10 +20,6 @@ async def bot(bot_info, offline_bot): return offline_bot -async def return_true(*args, **kwargs): - return True - - @pytest.fixture async def app(bot_info, monkeypatch): # We build a new bot each time so that we use `app` in a context manager without problems diff --git a/tests/ext/test_application.py b/tests/ext/test_application.py index 9de105bcc7f..2826f4cad99 100644 --- a/tests/ext/test_application.py +++ b/tests/ext/test_application.py @@ -60,6 +60,7 @@ from tests.auxil.asyncio_helpers import call_after from tests.auxil.build_messages import make_message_update from tests.auxil.files import PROJECT_ROOT_PATH +from tests.auxil.monkeypatch import empty_get_updates, return_true from tests.auxil.networking import send_webhook_message from tests.auxil.pytest_classes import PytestApplication, PytestUpdater, make_bot from tests.auxil.slots import mro_slots @@ -442,15 +443,8 @@ async def test_start_stop_processing_updates(self, one_time_bot, job_queue, monk async def callback(u, c): self.received = u - async def get_updates(*args, **kwargs): - await asyncio.sleep(0) - return [] - - async def delete_webhook(*args, **kwargs): - return True - - monkeypatch.setattr(app.bot, "get_updates", get_updates) - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + monkeypatch.setattr(app.bot, "get_updates", empty_get_updates) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) assert not app.running assert not app.updater.running @@ -1529,11 +1523,6 @@ def thread_target(): def test_run_polling_timeout_deprecation_warnings( self, timeout_name, monkeypatch, recwarn, app ): - async def get_updates(*args, **kwargs): - # This makes sure that other coroutines have a chance of running as well - await asyncio.sleep(0) - return [] - def thread_target(): waited = 0 while not app.running: @@ -1546,7 +1535,7 @@ def thread_target(): os.kill(os.getpid(), signal.SIGINT) - monkeypatch.setattr(app.bot, "get_updates", get_updates) + monkeypatch.setattr(app.bot, "get_updates", empty_get_updates) thread = Thread(target=thread_target) thread.start() @@ -1573,11 +1562,6 @@ def thread_target(): def test_run_polling_post_init(self, one_time_bot, monkeypatch): events = [] - async def get_updates(*args, **kwargs): - # This makes sure that other coroutines have a chance of running as well - await asyncio.sleep(0) - return [] - def thread_target(): waited = 0 while not app.running: @@ -1591,9 +1575,6 @@ def thread_target(): async def post_init(app: Application) -> None: events.append("post_init") - async def delete_webhook(*args, **kwargs): - return True - app = ( Application.builder() .application_class(PytestApplication) @@ -1602,7 +1583,7 @@ async def delete_webhook(*args, **kwargs): .build() ) app.bot._unfreeze() - monkeypatch.setattr(app.bot, "get_updates", get_updates) + monkeypatch.setattr(app.bot, "get_updates", empty_get_updates) monkeypatch.setattr( app, "initialize", call_after(app.initialize, lambda _: events.append("init")) ) @@ -1611,7 +1592,7 @@ async def delete_webhook(*args, **kwargs): "start_polling", call_after(app.updater.start_polling, lambda _: events.append("start_polling")), ) - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) thread = Thread(target=thread_target) thread.start() @@ -1626,11 +1607,6 @@ async def delete_webhook(*args, **kwargs): def test_run_polling_post_shutdown(self, one_time_bot, monkeypatch): events = [] - async def get_updates(*args, **kwargs): - # This makes sure that other coroutines have a chance of running as well - await asyncio.sleep(0) - return [] - def thread_target(): waited = 0 while not app.running: @@ -1641,9 +1617,6 @@ def thread_target(): os.kill(os.getpid(), signal.SIGINT) - async def delete_webhook(*args, **kwargs): - return True - async def post_shutdown(app: Application) -> None: events.append("post_shutdown") @@ -1655,7 +1628,7 @@ async def post_shutdown(app: Application) -> None: .build() ) app.bot._unfreeze() - monkeypatch.setattr(app.bot, "get_updates", get_updates) + monkeypatch.setattr(app.bot, "get_updates", empty_get_updates) monkeypatch.setattr( app, "shutdown", call_after(app.shutdown, lambda _: events.append("shutdown")) ) @@ -1664,7 +1637,7 @@ async def post_shutdown(app: Application) -> None: "shutdown", call_after(app.updater.shutdown, lambda _: events.append("updater.shutdown")), ) - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) thread = Thread(target=thread_target) thread.start() @@ -1683,11 +1656,6 @@ async def post_shutdown(app: Application) -> None: def test_run_polling_post_stop(self, one_time_bot, monkeypatch): events = [] - async def get_updates(*args, **kwargs): - # This makes sure that other coroutines have a chance of running as well - await asyncio.sleep(0) - return [] - def thread_target(): waited = 0 while not app.running: @@ -1698,9 +1666,6 @@ def thread_target(): os.kill(os.getpid(), signal.SIGINT) - async def delete_webhook(*args, **kwargs): - return True - async def post_stop(app: Application) -> None: events.append("post_stop") @@ -1712,7 +1677,7 @@ async def post_stop(app: Application) -> None: .build() ) app.bot._unfreeze() - monkeypatch.setattr(app.bot, "get_updates", get_updates) + monkeypatch.setattr(app.bot, "get_updates", empty_get_updates) monkeypatch.setattr(app, "stop", call_after(app.stop, lambda _: events.append("stop"))) monkeypatch.setattr( app.updater, @@ -1724,7 +1689,7 @@ async def post_stop(app: Application) -> None: "shutdown", call_after(app.updater.shutdown, lambda _: events.append("updater.shutdown")), ) - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) thread = Thread(target=thread_target) thread.start() @@ -1884,9 +1849,6 @@ def thread_target(): async def post_init(app: Application) -> None: events.append("post_init") - async def return_true(*args, **kwargs): - return True - app = ( Application.builder() .post_init(post_init) @@ -1943,9 +1905,6 @@ def thread_target(): async def post_shutdown(app: Application) -> None: events.append("post_shutdown") - async def return_true(*args, **kwargs): - return True - app = ( Application.builder() .application_class(PytestApplication) @@ -2006,9 +1965,6 @@ def thread_target(): async def post_stop(app: Application) -> None: events.append("post_stop") - async def return_true(*args, **kwargs): - return True - app = ( Application.builder() .application_class(PytestApplication) @@ -2210,13 +2166,6 @@ async def update_logger_callback(update, context): async def callback(*args, **kwargs): called_callbacks.add(kwargs["name"]) - async def get_updates(*args, **kwargs): - await asyncio.sleep(0) - return [] - - async def delete_webhook(*args, **kwargs): - return True - for cls, method, entry in [ (Application, "initialize", "app_initialize"), (Application, "start", "app_start"), @@ -2245,8 +2194,8 @@ def after(_, name): .post_shutdown(functools.partial(callback, name="post_shutdown")) .build() ) - monkeypatch.setattr(app.bot, "get_updates", get_updates) - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) + monkeypatch.setattr(app.bot, "get_updates", empty_get_updates) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) app.add_handler(TypeHandler(object, update_logger_callback), group=-10) app.add_handler(TypeHandler(object, handler_callback)) @@ -2309,13 +2258,6 @@ def _after_shutdown(*args, **kwargs): return _after_shutdown - async def delete_webhook(*args, **kwargs): - return True - - async def get_updates(*args, **kwargs): - await asyncio.sleep(0) - return [] - monkeypatch.setattr(Application, method, raise_method) monkeypatch.setattr( Application, @@ -2326,8 +2268,8 @@ async def get_updates(*args, **kwargs): Updater, "shutdown", call_after(Updater.shutdown, after_shutdown("updater")) ) app = ApplicationBuilder().bot(one_time_bot).build() - monkeypatch.setattr(app.bot, "delete_webhook", delete_webhook) - monkeypatch.setattr(app.bot, "get_updates", get_updates) + monkeypatch.setattr(app.bot, "delete_webhook", return_true) + monkeypatch.setattr(app.bot, "get_updates", empty_get_updates) with pytest.raises(RuntimeError, match="Test Exception"): app.run_polling(close_loop=False) @@ -2426,12 +2368,8 @@ def signal_handler_test(*args, **kwargs): loop = asyncio.get_event_loop() - async def get_updates(*args, **kwargs): - await asyncio.sleep(0) - return [] - monkeypatch.setattr(loop, "add_signal_handler", signal_handler_test) - monkeypatch.setattr(app.bot, "get_updates", get_updates) + monkeypatch.setattr(app.bot, "get_updates", empty_get_updates) def abort_app(): raise SystemExit @@ -2509,10 +2447,6 @@ def test_stop_running(self, one_time_bot, monkeypatch, method): called_stop_running = threading.Event() assertions = {} - async def get_updates(*args, **kwargs): - await asyncio.sleep(0) - return [] - async def post_init(app): # Simply calling app.update_queue.put_nowait(method) in the thread_target doesn't work # for some reason (probably threading magic), so we use an event from the thread_target @@ -2523,9 +2457,6 @@ async def task(app): app.create_task(task(app)) - async def return_true(*args, **kwargs): - return True - app = ( ApplicationBuilder() .application_class(PytestApplication) @@ -2533,7 +2464,7 @@ async def return_true(*args, **kwargs): .post_init(post_init) .build() ) - monkeypatch.setattr(app.bot, "get_updates", get_updates) + monkeypatch.setattr(app.bot, "get_updates", empty_get_updates) events = [] monkeypatch.setattr( diff --git a/tests/ext/test_updater.py b/tests/ext/test_updater.py index 5ca6effdc14..b2b218cc137 100644 --- a/tests/ext/test_updater.py +++ b/tests/ext/test_updater.py @@ -33,6 +33,7 @@ from tests.auxil.build_messages import make_message, make_message_update from tests.auxil.envvars import TEST_WITH_OPT_DEPS from tests.auxil.files import TEST_DATA_PATH, data_file +from tests.auxil.monkeypatch import empty_get_updates, return_true from tests.auxil.networking import send_webhook_message from tests.auxil.pytest_classes import make_bot from tests.auxil.slots import mro_slots @@ -181,11 +182,7 @@ async def test_shutdown_while_running(self, updater, method, monkeypatch): ip = "127.0.0.1" port = randrange(1024, 49152) # Select random port - async def get_updates(*args, **kwargs): - await asyncio.sleep(0) - return [] - - monkeypatch.setattr(updater.bot, "get_updates", get_updates) + monkeypatch.setattr(updater.bot, "get_updates", empty_get_updates) async with updater: if "webhook" in method: @@ -381,11 +378,8 @@ async def get_updates(*args, **kwargs): assert log_found async def test_polling_mark_updates_as_read_failure(self, monkeypatch, updater, caplog): - async def get_updates(*args, **kwargs): - await asyncio.sleep(0) - return [] - monkeypatch.setattr(updater.bot, "get_updates", get_updates) + monkeypatch.setattr(updater.bot, "get_updates", empty_get_updates) async with updater: await updater.start_polling() @@ -409,11 +403,8 @@ async def get_updates(*args, **kwargs): assert log_found async def test_start_polling_already_running(self, updater, monkeypatch): - async def get_updates(*args, **kwargs): - await asyncio.sleep(0) - return [] - monkeypatch.setattr(updater.bot, "get_updates", get_updates) + monkeypatch.setattr(updater.bot, "get_updates", empty_get_updates) async with updater: await updater.start_polling() @@ -730,10 +721,7 @@ async def delete_webhook(*args, **kwargs): self.message_count += 1 return True - async def set_webhook(*args, **kwargs): - return True - - monkeypatch.setattr(updater.bot, "set_webhook", set_webhook) + monkeypatch.setattr(updater.bot, "set_webhook", return_true) monkeypatch.setattr(updater.bot, "delete_webhook", delete_webhook) ip = "127.0.0.1" @@ -981,10 +969,7 @@ async def test_webhook_arbitrary_callback_data( extensively in test_bot.py in conjunction with get_updates.""" updater = Updater(bot=cdc_bot, update_queue=asyncio.Queue()) - async def set_webhook(*args, **kwargs): - return True - - monkeypatch.setattr(updater.bot, "set_webhook", set_webhook) + monkeypatch.setattr(updater.bot, "set_webhook", return_true) try: From 7a8184bdb311665dfe6fb88f0ec646bb74c76428 Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Sun, 8 Sep 2024 18:04:49 +0200 Subject: [PATCH 7/9] Enforce the `offline_bot` fixture in `Test*WithoutRequest` --- tests/_files/test_animation.py | 32 +- tests/_files/test_audio.py | 28 +- tests/_files/test_chatphoto.py | 12 +- tests/_files/test_contact.py | 22 +- tests/_files/test_document.py | 26 +- tests/_files/test_file.py | 14 +- tests/_files/test_inputmedia.py | 24 +- tests/_files/test_location.py | 46 +- tests/_files/test_photo.py | 32 +- tests/_files/test_sticker.py | 92 +-- tests/_files/test_venue.py | 18 +- tests/_files/test_video.py | 32 +- tests/_files/test_videonote.py | 36 +- tests/_files/test_voice.py | 32 +- tests/_games/test_game.py | 8 +- tests/_games/test_gamehighscore.py | 6 +- tests/_inline/test_inlinekeyboardbutton.py | 4 +- tests/_inline/test_inlinekeyboardmarkup.py | 8 +- tests/_inline/test_inlinequery.py | 4 +- .../test_inputinvoicemessagecontent.py | 8 +- tests/_passport/test_no_passport.py | 4 +- tests/_passport/test_passport.py | 42 +- tests/_payment/test_invoice.py | 24 +- tests/_payment/test_orderinfo.py | 4 +- tests/_payment/test_precheckoutquery.py | 6 +- tests/_payment/test_refundedpayment.py | 4 +- tests/_payment/test_shippingaddress.py | 4 +- tests/_payment/test_shippingquery.py | 6 +- tests/_payment/test_successfulpayment.py | 4 +- tests/conftest.py | 32 +- tests/request/test_request.py | 42 +- tests/test_birthdate.py | 4 +- tests/test_bot.py | 525 +++++++++--------- tests/test_botcommand.py | 6 +- tests/test_botcommandscope.py | 20 +- tests/test_business.py | 4 +- tests/test_callbackquery.py | 4 +- tests/test_chat.py | 4 +- tests/test_chatadministratorrights.py | 4 +- tests/test_chatbackground.py | 40 +- tests/test_chatboost.py | 52 +- tests/test_chatfullinfo.py | 8 +- tests/test_chatinvitelink.py | 12 +- tests/test_chatjoinrequest.py | 10 +- tests/test_chatlocation.py | 4 +- tests/test_chatmember.py | 26 +- tests/test_chatmemberupdated.py | 23 +- tests/test_chatpermissions.py | 4 +- tests/test_choseninlineresult.py | 8 +- tests/test_dice.py | 6 +- tests/test_forum.py | 12 +- tests/test_giveaway.py | 26 +- tests/test_inlinequeryresultsbutton.py | 8 +- tests/test_keyboardbutton.py | 2 +- tests/test_keyboardbuttonrequest.py | 10 +- tests/test_maybeinaccessiblemessage.py | 12 +- tests/test_menubutton.py | 22 +- tests/test_message.py | 16 +- tests/test_messageentity.py | 4 +- tests/test_messageorigin.py | 26 +- tests/test_paidmedia.py | 28 +- tests/test_poll.py | 8 +- tests/test_proximityalerttriggered.py | 4 +- tests/test_reaction.py | 28 +- tests/test_reply.py | 18 +- tests/test_sentwebappmessage.py | 2 +- tests/test_shared.py | 20 +- tests/test_stars.py | 58 +- tests/test_story.py | 6 +- tests/test_update.py | 8 +- tests/test_user.py | 4 +- tests/test_userprofilephotos.py | 4 +- tests/test_videochat.py | 14 +- tests/test_webappdata.py | 4 +- tests/test_webappinfo.py | 4 +- tests/test_webhookinfo.py | 10 +- 76 files changed, 937 insertions(+), 841 deletions(-) diff --git a/tests/_files/test_animation.py b/tests/_files/test_animation.py index 493d9bfae03..55c2076e23f 100644 --- a/tests/_files/test_animation.py +++ b/tests/_files/test_animation.py @@ -84,7 +84,7 @@ def test_expected_values(self, animation): assert animation.file_name.startswith("game.gif") == self.file_name.startswith("game.gif") assert isinstance(animation.thumbnail, PhotoSize) - def test_de_json(self, bot, animation): + def test_de_json(self, offline_bot, animation): json_dict = { "file_id": self.animation_file_id, "file_unique_id": self.animation_file_unique_id, @@ -96,7 +96,7 @@ def test_de_json(self, bot, animation): "mime_type": self.mime_type, "file_size": self.file_size, } - animation = Animation.de_json(json_dict, bot) + animation = Animation.de_json(json_dict, offline_bot) assert animation.api_kwargs == {} assert animation.file_id == self.animation_file_id assert animation.file_unique_id == self.animation_file_unique_id @@ -140,18 +140,22 @@ def test_equality(self): assert a != e assert hash(a) != hash(e) - async def test_send_animation_custom_filename(self, bot, chat_id, animation_file, monkeypatch): + async def test_send_animation_custom_filename( + self, offline_bot, chat_id, animation_file, monkeypatch + ): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_animation(chat_id, animation_file, filename="custom_filename") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_animation( + chat_id, animation_file, filename="custom_filename" + ) @pytest.mark.parametrize("local_mode", [True, False]) - async def test_send_animation_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_send_animation_local_files(self, monkeypatch, offline_bot, chat_id, local_mode): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -167,18 +171,18 @@ async def make_assertion(_, data, *args, **kwargs): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_animation(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_animation(chat_id, file, thumbnail=file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False - async def test_send_with_animation(self, monkeypatch, bot, chat_id, animation): + async def test_send_with_animation(self, monkeypatch, offline_bot, chat_id, animation): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters["animation"] == animation.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_animation(animation=animation, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_animation(animation=animation, chat_id=chat_id) async def test_get_file_instance_method(self, monkeypatch, animation): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_audio.py b/tests/_files/test_audio.py index f6b76c1f0c9..ed0d74d4d72 100644 --- a/tests/_files/test_audio.py +++ b/tests/_files/test_audio.py @@ -91,7 +91,7 @@ def test_expected_values(self, audio): assert audio.thumbnail.width == self.thumb_width assert audio.thumbnail.height == self.thumb_height - def test_de_json(self, bot, audio): + def test_de_json(self, offline_bot, audio): json_dict = { "file_id": self.audio_file_id, "file_unique_id": self.audio_file_unique_id, @@ -103,7 +103,7 @@ def test_de_json(self, bot, audio): "file_size": self.file_size, "thumbnail": audio.thumbnail.to_dict(), } - json_audio = Audio.de_json(json_dict, bot) + json_audio = Audio.de_json(json_dict, offline_bot) assert json_audio.api_kwargs == {} assert json_audio.file_id == self.audio_file_id @@ -147,25 +147,25 @@ def test_equality(self, audio): assert a != e assert hash(a) != hash(e) - async def test_send_with_audio(self, monkeypatch, bot, chat_id, audio): + async def test_send_with_audio(self, monkeypatch, offline_bot, chat_id, audio): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters["audio"] == audio.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_audio(audio=audio, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_audio(audio=audio, chat_id=chat_id) - async def test_send_audio_custom_filename(self, bot, chat_id, audio_file, monkeypatch): + async def test_send_audio_custom_filename(self, offline_bot, chat_id, audio_file, monkeypatch): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_audio(chat_id, audio_file, filename="custom_filename") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_audio(chat_id, audio_file, filename="custom_filename") @pytest.mark.parametrize("local_mode", [True, False]) - async def test_send_audio_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_send_audio_local_files(self, monkeypatch, offline_bot, chat_id, local_mode): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -179,11 +179,11 @@ async def make_assertion(_, data, *args, **kwargs): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_audio(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_audio(chat_id, file, thumbnail=file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, audio): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_chatphoto.py b/tests/_files/test_chatphoto.py index 5deaae38fb4..5bbb6a8f71e 100644 --- a/tests/_files/test_chatphoto.py +++ b/tests/_files/test_chatphoto.py @@ -66,14 +66,14 @@ def test_slot_behaviour(self, chat_photo): assert getattr(chat_photo, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(chat_photo)) == len(set(mro_slots(chat_photo))), "duplicate slot" - def test_de_json(self, bot, chat_photo): + def test_de_json(self, offline_bot, chat_photo): json_dict = { "small_file_id": self.chatphoto_small_file_id, "big_file_id": self.chatphoto_big_file_id, "small_file_unique_id": self.chatphoto_small_file_unique_id, "big_file_unique_id": self.chatphoto_big_file_unique_id, } - chat_photo = ChatPhoto.de_json(json_dict, bot) + chat_photo = ChatPhoto.de_json(json_dict, offline_bot) assert chat_photo.api_kwargs == {} assert chat_photo.small_file_id == self.chatphoto_small_file_id assert chat_photo.big_file_id == self.chatphoto_big_file_id @@ -121,12 +121,14 @@ def test_equality(self): assert a != e assert hash(a) != hash(e) - async def test_send_with_chat_photo(self, monkeypatch, bot, super_group_id, chat_photo): + async def test_send_with_chat_photo( + self, monkeypatch, offline_bot, super_group_id, chat_photo + ): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters["photo"] == chat_photo.to_dict() - monkeypatch.setattr(bot.request, "post", make_assertion) - message = await bot.set_chat_photo(photo=chat_photo, chat_id=super_group_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + message = await offline_bot.set_chat_photo(photo=chat_photo, chat_id=super_group_id) assert message async def test_get_small_file_instance_method(self, monkeypatch, chat_photo): diff --git a/tests/_files/test_contact.py b/tests/_files/test_contact.py index cb5777eb4dd..0869d7ff33e 100644 --- a/tests/_files/test_contact.py +++ b/tests/_files/test_contact.py @@ -52,22 +52,22 @@ def test_slot_behaviour(self, contact): assert getattr(contact, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(contact)) == len(set(mro_slots(contact))), "duplicate slot" - def test_de_json_required(self, bot): + def test_de_json_required(self, offline_bot): json_dict = {"phone_number": self.phone_number, "first_name": self.first_name} - contact = Contact.de_json(json_dict, bot) + contact = Contact.de_json(json_dict, offline_bot) assert contact.api_kwargs == {} assert contact.phone_number == self.phone_number assert contact.first_name == self.first_name - def test_de_json_all(self, bot): + def test_de_json_all(self, offline_bot): json_dict = { "phone_number": self.phone_number, "first_name": self.first_name, "last_name": self.last_name, "user_id": self.user_id, } - contact = Contact.de_json(json_dict, bot) + contact = Contact.de_json(json_dict, offline_bot) assert contact.api_kwargs == {} assert contact.phone_number == self.phone_number @@ -104,20 +104,20 @@ def test_equality(self): assert a != e assert hash(a) != hash(e) - async def test_send_contact_without_required(self, bot, chat_id): + async def test_send_contact_without_required(self, offline_bot, chat_id): with pytest.raises(ValueError, match="Either contact or phone_number and first_name"): - await bot.send_contact(chat_id=chat_id) + await offline_bot.send_contact(chat_id=chat_id) - async def test_send_mutually_exclusive(self, bot, chat_id, contact): + async def test_send_mutually_exclusive(self, offline_bot, chat_id, contact): with pytest.raises(ValueError, match="Not both"): - await bot.send_contact( + await offline_bot.send_contact( chat_id=chat_id, contact=contact, phone_number=contact.phone_number, first_name=contact.first_name, ) - async def test_send_with_contact(self, monkeypatch, bot, chat_id, contact): + async def test_send_with_contact(self, monkeypatch, offline_bot, chat_id, contact): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters phone = data["phone_number"] == contact.phone_number @@ -125,8 +125,8 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): last = data["last_name"] == contact.last_name return phone and first and last - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_contact(contact=contact, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_contact(contact=contact, chat_id=chat_id) @pytest.mark.parametrize( ("default_bot", "custom"), diff --git a/tests/_files/test_document.py b/tests/_files/test_document.py index 02f60ac464a..90b6bdf1121 100644 --- a/tests/_files/test_document.py +++ b/tests/_files/test_document.py @@ -83,7 +83,7 @@ def test_expected_values(self, document): assert document.thumbnail.width == self.thumb_width assert document.thumbnail.height == self.thumb_height - def test_de_json(self, bot, document): + def test_de_json(self, offline_bot, document): json_dict = { "file_id": self.document_file_id, "file_unique_id": self.document_file_unique_id, @@ -92,7 +92,7 @@ def test_de_json(self, bot, document): "mime_type": self.mime_type, "file_size": self.file_size, } - test_document = Document.de_json(json_dict, bot) + test_document = Document.de_json(json_dict, offline_bot) assert test_document.api_kwargs == {} assert test_document.file_id == self.document_file_id @@ -128,13 +128,13 @@ def test_equality(self, document): assert a != e assert hash(a) != hash(e) - async def test_error_send_without_required_args(self, bot, chat_id): + async def test_error_send_without_required_args(self, offline_bot, chat_id): with pytest.raises(TypeError): - await bot.send_document(chat_id=chat_id) + await offline_bot.send_document(chat_id=chat_id) @pytest.mark.parametrize("disable_content_type_detection", [True, False, None]) async def test_send_with_document( - self, monkeypatch, bot, chat_id, document, disable_content_type_detection + self, monkeypatch, offline_bot, chat_id, document, disable_content_type_detection ): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters @@ -143,9 +143,9 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): ) return data["document"] == document.file_id and type_detection - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - message = await bot.send_document( + message = await offline_bot.send_document( document=document, chat_id=chat_id, disable_content_type_detection=disable_content_type_detection, @@ -181,10 +181,10 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): ) @pytest.mark.parametrize("local_mode", [True, False]) - async def test_send_document_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_send_document_local_files(self, monkeypatch, offline_bot, chat_id, local_mode): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -200,11 +200,11 @@ async def make_assertion(_, data, *args, **kwargs): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_document(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_document(chat_id, file, thumbnail=file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, document): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_file.py b/tests/_files/test_file.py index ae9d92c0425..70874d5feb8 100644 --- a/tests/_files/test_file.py +++ b/tests/_files/test_file.py @@ -107,14 +107,14 @@ def test_slot_behaviour(self, file): assert getattr(file, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(file)) == len(set(mro_slots(file))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "file_id": self.file_id, "file_unique_id": self.file_unique_id, "file_path": self.file_path, "file_size": self.file_size, } - new_file = File.de_json(json_dict, bot) + new_file = File.de_json(json_dict, offline_bot) assert new_file.api_kwargs == {} assert new_file.file_id == self.file_id @@ -131,11 +131,11 @@ def test_to_dict(self, file): assert file_dict["file_path"] == file.file_path assert file_dict["file_size"] == file.file_size - def test_equality(self, bot): - a = File(self.file_id, self.file_unique_id, bot) - b = File("", self.file_unique_id, bot) + def test_equality(self, offline_bot): + a = File(self.file_id, self.file_unique_id, offline_bot) + b = File("", self.file_unique_id, offline_bot) c = File(self.file_id, self.file_unique_id, None) - d = File("", "", bot) + d = File("", "", offline_bot) e = Voice(self.file_id, self.file_unique_id, 0) assert a == b @@ -223,7 +223,7 @@ async def test(*args, **kwargs): assert buf2[len(buf) :] == buf assert buf2[: len(buf)] == buf - async def test_download_encrypted(self, monkeypatch, bot, encrypted_file): + async def test_download_encrypted(self, monkeypatch, offline_bot, encrypted_file): async def test(*args, **kwargs): return data_file("image_encrypted.jpg").read_bytes() diff --git a/tests/_files/test_inputmedia.py b/tests/_files/test_inputmedia.py index ff398113a48..6b54e4d196a 100644 --- a/tests/_files/test_inputmedia.py +++ b/tests/_files/test_inputmedia.py @@ -655,7 +655,7 @@ def media_group_no_caption_only_parse_mode(photo, thumb): # noqa: F811 class TestSendMediaGroupWithoutRequest: async def test_send_media_group_throws_error_with_group_caption_and_individual_captions( self, - bot, + offline_bot, chat_id, media_group, media_group_no_caption_only_caption_entities, @@ -670,11 +670,11 @@ async def test_send_media_group_throws_error_with_group_caption_and_individual_c ValueError, match="You can only supply either group caption or media with captions.", ): - await bot.send_media_group(chat_id, group, caption="foo") + await offline_bot.send_media_group(chat_id, group, caption="foo") async def test_send_media_group_custom_filename( self, - bot, + offline_bot, chat_id, photo_file, # noqa: F811 animation_file, # noqa: F811 @@ -690,7 +690,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): if result is True: raise Exception("Test was successful") - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) media = [ InputMediaAnimation(animation_file, filename="custom_filename"), @@ -700,10 +700,10 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): ] with pytest.raises(Exception, match="Test was successful"): - await bot.send_media_group(chat_id, media) + await offline_bot.send_media_group(chat_id, media) async def test_send_media_group_with_thumbs( - self, bot, chat_id, video_file, photo_file, monkeypatch # noqa: F811 + self, offline_bot, chat_id, video_file, photo_file, monkeypatch # noqa: F811 ): async def make_assertion(method, url, request_data: RequestData, *args, **kwargs): nonlocal input_video @@ -715,13 +715,13 @@ async def make_assertion(method, url, request_data: RequestData, *args, **kwargs result = video_check and thumb_check raise Exception(f"Test was {'successful' if result else 'failing'}") - monkeypatch.setattr(bot.request, "_request_wrapper", make_assertion) + monkeypatch.setattr(offline_bot.request, "_request_wrapper", make_assertion) input_video = InputMediaVideo(video_file, thumbnail=photo_file) with pytest.raises(Exception, match="Test was successful"): - await bot.send_media_group(chat_id, [input_video, input_video]) + await offline_bot.send_media_group(chat_id, [input_video, input_video]) async def test_edit_message_media_with_thumb( - self, bot, chat_id, video_file, photo_file, monkeypatch # noqa: F811 + self, offline_bot, chat_id, video_file, photo_file, monkeypatch # noqa: F811 ): async def make_assertion( method: str, url: str, request_data: Optional[RequestData] = None, *args, **kwargs @@ -734,10 +734,12 @@ async def make_assertion( result = video_check and thumb_check raise Exception(f"Test was {'successful' if result else 'failing'}") - monkeypatch.setattr(bot.request, "_request_wrapper", make_assertion) + monkeypatch.setattr(offline_bot.request, "_request_wrapper", make_assertion) input_video = InputMediaVideo(video_file, thumbnail=photo_file) with pytest.raises(Exception, match="Test was successful"): - await bot.edit_message_media(chat_id=chat_id, message_id=123, media=input_video) + await offline_bot.edit_message_media( + chat_id=chat_id, message_id=123, media=input_video + ) @pytest.mark.parametrize( ("default_bot", "custom"), diff --git a/tests/_files/test_location.py b/tests/_files/test_location.py index 72c6f720066..402f0ba7b11 100644 --- a/tests/_files/test_location.py +++ b/tests/_files/test_location.py @@ -55,7 +55,7 @@ def test_slot_behaviour(self, location): assert getattr(location, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(location)) == len(set(mro_slots(location))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "latitude": self.latitude, "longitude": self.longitude, @@ -64,7 +64,7 @@ def test_de_json(self, bot): "heading": self.heading, "proximity_alert_radius": self.proximity_alert_radius, } - location = Location.de_json(json_dict, bot) + location = Location.de_json(json_dict, offline_bot) assert location.api_kwargs == {} assert location.latitude == self.latitude @@ -96,26 +96,28 @@ def test_equality(self): assert a != d assert hash(a) != hash(d) - async def test_send_location_without_required(self, bot, chat_id): + async def test_send_location_without_required(self, offline_bot, chat_id): with pytest.raises(ValueError, match="Either location or latitude and longitude"): - await bot.send_location(chat_id=chat_id) + await offline_bot.send_location(chat_id=chat_id) - async def test_edit_location_without_required(self, bot): + async def test_edit_location_without_required(self, offline_bot): with pytest.raises(ValueError, match="Either location or latitude and longitude"): - await bot.edit_message_live_location(chat_id=2, message_id=3) + await offline_bot.edit_message_live_location(chat_id=2, message_id=3) - async def test_send_location_with_all_args(self, bot, location): + async def test_send_location_with_all_args(self, offline_bot, location): with pytest.raises(ValueError, match="Not both"): - await bot.send_location(chat_id=1, latitude=2.5, longitude=4.6, location=location) + await offline_bot.send_location( + chat_id=1, latitude=2.5, longitude=4.6, location=location + ) - async def test_edit_location_with_all_args(self, bot, location): + async def test_edit_location_with_all_args(self, offline_bot, location): with pytest.raises(ValueError, match="Not both"): - await bot.edit_message_live_location( + await offline_bot.edit_message_live_location( chat_id=1, message_id=7, latitude=2.5, longitude=4.6, location=location ) # TODO: Needs improvement with in inline sent live location. - async def test_edit_live_inline_message(self, monkeypatch, bot, location): + async def test_edit_live_inline_message(self, monkeypatch, offline_bot, location): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters lat = data["latitude"] == str(location.latitude) @@ -127,8 +129,8 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): live = data["live_period"] == "900" return lat and lon and id_ and ha and heading and prox_alert and live - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.edit_message_live_location( + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.edit_message_live_location( inline_message_id=1234, location=location, horizontal_accuracy=50, @@ -138,30 +140,30 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): ) # TODO: Needs improvement with in inline sent live location. - async def test_stop_live_inline_message(self, monkeypatch, bot): + async def test_stop_live_inline_message(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters["inline_message_id"] == "1234" - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.stop_message_live_location(inline_message_id=1234) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.stop_message_live_location(inline_message_id=1234) - async def test_send_with_location(self, monkeypatch, bot, chat_id, location): + async def test_send_with_location(self, monkeypatch, offline_bot, chat_id, location): async def make_assertion(url, request_data: RequestData, *args, **kwargs): lat = request_data.json_parameters["latitude"] == str(location.latitude) lon = request_data.json_parameters["longitude"] == str(location.longitude) return lat and lon - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_location(location=location, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_location(location=location, chat_id=chat_id) - async def test_edit_live_location_with_location(self, monkeypatch, bot, location): + async def test_edit_live_location_with_location(self, monkeypatch, offline_bot, location): async def make_assertion(url, request_data: RequestData, *args, **kwargs): lat = request_data.json_parameters["latitude"] == str(location.latitude) lon = request_data.json_parameters["longitude"] == str(location.longitude) return lat and lon - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.edit_message_live_location(None, None, location=location) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.edit_message_live_location(None, None, location=location) @pytest.mark.parametrize( ("default_bot", "custom"), diff --git a/tests/_files/test_photo.py b/tests/_files/test_photo.py index 6ba9e46acc4..919c3155bcb 100644 --- a/tests/_files/test_photo.py +++ b/tests/_files/test_photo.py @@ -105,7 +105,7 @@ def test_expected_values(self, photo, thumb): # so far assert thumb.file_size in [1475, 1477] - def test_de_json(self, bot, photo): + def test_de_json(self, offline_bot, photo): json_dict = { "file_id": photo.file_id, "file_unique_id": photo.file_unique_id, @@ -113,7 +113,7 @@ def test_de_json(self, bot, photo): "height": self.height, "file_size": self.file_size, } - json_photo = PhotoSize.de_json(json_dict, bot) + json_photo = PhotoSize.de_json(json_dict, offline_bot) assert json_photo.api_kwargs == {} assert json_photo.file_id == photo.file_id @@ -160,22 +160,22 @@ def test_equality(self, photo): assert a != e assert hash(a) != hash(e) - async def test_error_without_required_args(self, bot, chat_id): + async def test_error_without_required_args(self, offline_bot, chat_id): with pytest.raises(TypeError): - await bot.send_photo(chat_id=chat_id) + await offline_bot.send_photo(chat_id=chat_id) - async def test_send_photo_custom_filename(self, bot, chat_id, photo_file, monkeypatch): + async def test_send_photo_custom_filename(self, offline_bot, chat_id, photo_file, monkeypatch): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_photo(chat_id, photo_file, filename="custom_filename") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_photo(chat_id, photo_file, filename="custom_filename") @pytest.mark.parametrize("local_mode", [True, False]) - async def test_send_photo_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_send_photo_local_files(self, monkeypatch, offline_bot, chat_id, local_mode): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -187,18 +187,18 @@ async def make_assertion(_, data, *args, **kwargs): else: test_flag = isinstance(data.get("photo"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_photo(chat_id, file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_photo(chat_id, file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False - async def test_send_with_photosize(self, monkeypatch, bot, chat_id, photo): + async def test_send_with_photosize(self, monkeypatch, offline_bot, chat_id, photo): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters["photo"] == photo.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_photo(photo=photo, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_photo(photo=photo, chat_id=chat_id) async def test_get_file_instance_method(self, monkeypatch, photo): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_sticker.py b/tests/_files/test_sticker.py index 3f374cc2ea0..3fa608e3a4d 100644 --- a/tests/_files/test_sticker.py +++ b/tests/_files/test_sticker.py @@ -165,7 +165,7 @@ def test_to_dict(self, sticker): assert sticker_dict["type"] == sticker.type assert sticker_dict["needs_repainting"] == sticker.needs_repainting - def test_de_json(self, bot, sticker): + def test_de_json(self, offline_bot, sticker): json_dict = { "file_id": self.sticker_file_id, "file_unique_id": self.sticker_file_unique_id, @@ -181,7 +181,7 @@ def test_de_json(self, bot, sticker): "custom_emoji_id": self.custom_emoji_id, "needs_repainting": self.needs_repainting, } - json_sticker = Sticker.de_json(json_dict, bot) + json_sticker = Sticker.de_json(json_dict, offline_bot) assert json_sticker.api_kwargs == {} assert json_sticker.file_id == self.sticker_file_id @@ -284,22 +284,22 @@ def test_equality(self, sticker): assert a != e assert hash(a) != hash(e) - async def test_error_without_required_args(self, bot, chat_id): + async def test_error_without_required_args(self, offline_bot, chat_id): with pytest.raises(TypeError): - await bot.send_sticker(chat_id) + await offline_bot.send_sticker(chat_id) - async def test_send_with_sticker(self, monkeypatch, bot, chat_id, sticker): + async def test_send_with_sticker(self, monkeypatch, offline_bot, chat_id, sticker): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters["sticker"] == sticker.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_sticker(sticker=sticker, chat_id=chat_id) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_sticker(sticker=sticker, chat_id=chat_id) @pytest.mark.parametrize("local_mode", [True, False]) - async def test_send_sticker_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_send_sticker_local_files(self, monkeypatch, offline_bot, chat_id, local_mode): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -311,11 +311,11 @@ async def make_assertion(_, data, *args, **kwargs): else: test_flag = isinstance(data.get("sticker"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_sticker(chat_id, file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_sticker(chat_id, file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False @pytest.mark.parametrize( ("default_bot", "custom"), @@ -587,8 +587,8 @@ def test_slot_behaviour(self): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, sticker): - name = f"test_by_{bot.username}" + def test_de_json(self, offline_bot, sticker): + name = f"test_by_{offline_bot.username}" json_dict = { "name": name, "title": self.title, @@ -597,7 +597,7 @@ def test_de_json(self, bot, sticker): "sticker_type": self.sticker_type, "contains_masks": self.contains_masks, } - sticker_set = StickerSet.de_json(json_dict, bot) + sticker_set = StickerSet.de_json(json_dict, offline_bot) assert sticker_set.name == name assert sticker_set.title == self.title @@ -653,11 +653,11 @@ def test_equality(self): @pytest.mark.parametrize("local_mode", [True, False]) async def test_upload_sticker_file_local_files( - self, monkeypatch, bot, chat_id, local_mode, recwarn + self, monkeypatch, offline_bot, chat_id, local_mode, recwarn ): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -670,24 +670,24 @@ async def make_assertion(_, data, *args, **kwargs): else isinstance(data.get("sticker"), InputFile) ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.upload_sticker_file( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.upload_sticker_file( chat_id, sticker=file, sticker_format=StickerFormat.STATIC ) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False @pytest.mark.parametrize("local_mode", [True, False]) async def test_create_new_sticker_set_local_files( self, monkeypatch, - bot, + offline_bot, chat_id, local_mode, ): - monkeypatch.setattr(bot, "_local_mode", local_mode) - # For just test that the correct paths are passed as we have no local bot API set up + monkeypatch.setattr(offline_bot, "_local_mode", local_mode) + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") # always assumed to be local mode because we don't have access to local_mode setting @@ -698,8 +698,8 @@ async def make_assertion(_, data, *args, **kwargs): nonlocal test_flag test_flag = data.get("stickers")[0].sticker == expected - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.create_new_sticker_set( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.create_new_sticker_set( chat_id, "name", "title", @@ -707,7 +707,9 @@ async def make_assertion(_, data, *args, **kwargs): ) assert test_flag - async def test_create_new_sticker_all_params(self, monkeypatch, bot, chat_id, mask_position): + async def test_create_new_sticker_all_params( + self, monkeypatch, offline_bot, chat_id, mask_position + ): async def make_assertion(_, data, *args, **kwargs): assert data["user_id"] == chat_id assert data["name"] == "name" @@ -715,8 +717,8 @@ async def make_assertion(_, data, *args, **kwargs): assert data["stickers"] == ["wow.png", "wow.tgs", "wow.webp"] assert data["needs_repainting"] is True - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.create_new_sticker_set( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.create_new_sticker_set( chat_id, "name", "title", @@ -725,9 +727,11 @@ async def make_assertion(_, data, *args, **kwargs): ) @pytest.mark.parametrize("local_mode", [True, False]) - async def test_add_sticker_to_set_local_files(self, monkeypatch, bot, chat_id, local_mode): - monkeypatch.setattr(bot, "_local_mode", local_mode) - # For just test that the correct paths are passed as we have no local bot API set up + async def test_add_sticker_to_set_local_files( + self, monkeypatch, offline_bot, chat_id, local_mode + ): + monkeypatch.setattr(offline_bot, "_local_mode", local_mode) + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") # always assumed to be local mode because we don't have access to local_mode setting @@ -738,8 +742,8 @@ async def make_assertion(_, data, *args, **kwargs): nonlocal test_flag test_flag = data.get("sticker").sticker == expected - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.add_sticker_to_set( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.add_sticker_to_set( chat_id, "name", sticker=InputSticker(sticker=file, emoji_list=["this"], format="static"), @@ -748,11 +752,11 @@ async def make_assertion(_, data, *args, **kwargs): @pytest.mark.parametrize("local_mode", [True, False]) async def test_set_sticker_set_thumbnail_local_files( - self, monkeypatch, bot, chat_id, local_mode + self, monkeypatch, offline_bot, chat_id, local_mode ): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -764,11 +768,13 @@ async def make_assertion(_, data, *args, **kwargs): else: test_flag = isinstance(data.get("thumbnail"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.set_sticker_set_thumbnail("name", chat_id, thumbnail=file, format="static") + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.set_sticker_set_thumbnail( + "name", chat_id, thumbnail=file, format="static" + ) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, sticker): async def make_assertion(*_, **kwargs): @@ -1085,14 +1091,14 @@ def test_slot_behaviour(self, mask_position): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_mask_position_de_json(self, bot): + def test_mask_position_de_json(self, offline_bot): json_dict = { "point": self.point, "x_shift": self.x_shift, "y_shift": self.y_shift, "scale": self.scale, } - mask_position = MaskPosition.de_json(json_dict, bot) + mask_position = MaskPosition.de_json(json_dict, offline_bot) assert mask_position.api_kwargs == {} assert mask_position.point == self.point diff --git a/tests/_files/test_venue.py b/tests/_files/test_venue.py index b78223bbf5d..31883591e2a 100644 --- a/tests/_files/test_venue.py +++ b/tests/_files/test_venue.py @@ -57,7 +57,7 @@ def test_slot_behaviour(self, venue): assert getattr(venue, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(venue)) == len(set(mro_slots(venue))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "location": self.location.to_dict(), "title": self.title, @@ -67,7 +67,7 @@ def test_de_json(self, bot): "google_place_id": self.google_place_id, "google_place_type": self.google_place_type, } - venue = Venue.de_json(json_dict, bot) + venue = Venue.de_json(json_dict, offline_bot) assert venue.api_kwargs == {} assert venue.location == self.location @@ -110,13 +110,13 @@ def test_equality(self): assert a != d2 assert hash(a) != hash(d2) - async def test_send_venue_without_required(self, bot, chat_id): + async def test_send_venue_without_required(self, offline_bot, chat_id): with pytest.raises(ValueError, match="Either venue or latitude, longitude, address and"): - await bot.send_venue(chat_id=chat_id) + await offline_bot.send_venue(chat_id=chat_id) - async def test_send_venue_mutually_exclusive(self, bot, chat_id, venue): + async def test_send_venue_mutually_exclusive(self, offline_bot, chat_id, venue): with pytest.raises(ValueError, match="Not both"): - await bot.send_venue( + await offline_bot.send_venue( chat_id=chat_id, latitude=1, longitude=1, @@ -125,7 +125,7 @@ async def test_send_venue_mutually_exclusive(self, bot, chat_id, venue): venue=venue, ) - async def test_send_with_venue(self, monkeypatch, bot, chat_id, venue): + async def test_send_with_venue(self, monkeypatch, offline_bot, chat_id, venue): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters return ( @@ -139,8 +139,8 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): and data["google_place_type"] == self.google_place_type ) - monkeypatch.setattr(bot.request, "post", make_assertion) - message = await bot.send_venue(chat_id, venue=venue) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + message = await offline_bot.send_venue(chat_id, venue=venue) assert message @pytest.mark.parametrize( diff --git a/tests/_files/test_video.py b/tests/_files/test_video.py index 06666ea16b6..d4ace54e3e5 100644 --- a/tests/_files/test_video.py +++ b/tests/_files/test_video.py @@ -93,7 +93,7 @@ def test_expected_values(self, video): assert video.file_size == self.file_size assert video.mime_type == self.mime_type - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "file_id": self.video_file_id, "file_unique_id": self.video_file_unique_id, @@ -104,7 +104,7 @@ def test_de_json(self, bot): "file_size": self.file_size, "file_name": self.file_name, } - json_video = Video.de_json(json_dict, bot) + json_video = Video.de_json(json_dict, offline_bot) assert json_video.api_kwargs == {} assert json_video.file_id == self.video_file_id @@ -149,30 +149,30 @@ def test_equality(self, video): assert a != e assert hash(a) != hash(e) - async def test_error_without_required_args(self, bot, chat_id): + async def test_error_without_required_args(self, offline_bot, chat_id): with pytest.raises(TypeError): - await bot.send_video(chat_id=chat_id) + await offline_bot.send_video(chat_id=chat_id) - async def test_send_with_video(self, monkeypatch, bot, chat_id, video): + async def test_send_with_video(self, monkeypatch, offline_bot, chat_id, video): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters["video"] == video.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_video(chat_id, video=video) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_video(chat_id, video=video) - async def test_send_video_custom_filename(self, bot, chat_id, video_file, monkeypatch): + async def test_send_video_custom_filename(self, offline_bot, chat_id, video_file, monkeypatch): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.send_video(chat_id, video_file, filename="custom_filename") + assert await offline_bot.send_video(chat_id, video_file, filename="custom_filename") @pytest.mark.parametrize("local_mode", [True, False]) - async def test_send_video_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_send_video_local_files(self, monkeypatch, offline_bot, chat_id, local_mode): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -186,11 +186,11 @@ async def make_assertion(_, data, *args, **kwargs): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_video(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_video(chat_id, file, thumbnail=file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, video): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_videonote.py b/tests/_files/test_videonote.py index b86355e446d..d85de9fb4b0 100644 --- a/tests/_files/test_videonote.py +++ b/tests/_files/test_videonote.py @@ -85,7 +85,7 @@ def test_expected_values(self, video_note): assert video_note.duration == self.duration assert video_note.file_size == self.file_size - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "file_id": self.videonote_file_id, "file_unique_id": self.videonote_file_unique_id, @@ -93,7 +93,7 @@ def test_de_json(self, bot): "duration": self.duration, "file_size": self.file_size, } - json_video_note = VideoNote.de_json(json_dict, bot) + json_video_note = VideoNote.de_json(json_dict, offline_bot) assert json_video_note.api_kwargs == {} assert json_video_note.file_id == self.videonote_file_id @@ -132,32 +132,36 @@ def test_equality(self, video_note): assert a != e assert hash(a) != hash(e) - async def test_error_without_required_args(self, bot, chat_id): + async def test_error_without_required_args(self, offline_bot, chat_id): with pytest.raises(TypeError): - await bot.send_video_note(chat_id=chat_id) + await offline_bot.send_video_note(chat_id=chat_id) - async def test_send_with_video_note(self, monkeypatch, bot, chat_id, video_note): + async def test_send_with_video_note(self, monkeypatch, offline_bot, chat_id, video_note): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters["video_note"] == video_note.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_video_note(chat_id, video_note=video_note) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_video_note(chat_id, video_note=video_note) async def test_send_video_note_custom_filename( - self, bot, chat_id, video_note_file, monkeypatch + self, offline_bot, chat_id, video_note_file, monkeypatch ): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.send_video_note(chat_id, video_note_file, filename="custom_filename") + assert await offline_bot.send_video_note( + chat_id, video_note_file, filename="custom_filename" + ) @pytest.mark.parametrize("local_mode", [True, False]) - async def test_send_video_note_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_send_video_note_local_files( + self, monkeypatch, offline_bot, chat_id, local_mode + ): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -173,11 +177,11 @@ async def make_assertion(_, data, *args, **kwargs): data.get("thumbnail"), InputFile ) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_video_note(chat_id, file, thumbnail=file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_video_note(chat_id, file, thumbnail=file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, video_note): async def make_assertion(*_, **kwargs): diff --git a/tests/_files/test_voice.py b/tests/_files/test_voice.py index 454db0aaef4..e32bb195c8e 100644 --- a/tests/_files/test_voice.py +++ b/tests/_files/test_voice.py @@ -78,7 +78,7 @@ def test_expected_values(self, voice): assert voice.mime_type == self.mime_type assert voice.file_size == self.file_size - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "file_id": self.voice_file_id, "file_unique_id": self.voice_file_unique_id, @@ -86,7 +86,7 @@ def test_de_json(self, bot): "mime_type": self.mime_type, "file_size": self.file_size, } - json_voice = Voice.de_json(json_dict, bot) + json_voice = Voice.de_json(json_dict, offline_bot) assert json_voice.api_kwargs == {} assert json_voice.file_id == self.voice_file_id @@ -125,30 +125,30 @@ def test_equality(self, voice): assert a != e assert hash(a) != hash(e) - async def test_error_without_required_args(self, bot, chat_id): + async def test_error_without_required_args(self, offline_bot, chat_id): with pytest.raises(TypeError): - await bot.sendVoice(chat_id) + await offline_bot.sendVoice(chat_id) - async def test_send_voice_custom_filename(self, bot, chat_id, voice_file, monkeypatch): + async def test_send_voice_custom_filename(self, offline_bot, chat_id, voice_file, monkeypatch): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return next(iter(request_data.multipart_data.values()))[0] == "custom_filename" - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.send_voice(chat_id, voice_file, filename="custom_filename") + assert await offline_bot.send_voice(chat_id, voice_file, filename="custom_filename") - async def test_send_with_voice(self, monkeypatch, bot, chat_id, voice): + async def test_send_with_voice(self, monkeypatch, offline_bot, chat_id, voice): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters["voice"] == voice.file_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_voice(chat_id, voice=voice) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_voice(chat_id, voice=voice) @pytest.mark.parametrize("local_mode", [True, False]) - async def test_send_voice_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_send_voice_local_files(self, monkeypatch, offline_bot, chat_id, local_mode): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -160,11 +160,11 @@ async def make_assertion(_, data, *args, **kwargs): else: test_flag = isinstance(data.get("voice"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.send_voice(chat_id, file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.send_voice(chat_id, file) assert test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False async def test_get_file_instance_method(self, monkeypatch, voice): async def make_assertion(*_, **kwargs): diff --git a/tests/_games/test_game.py b/tests/_games/test_game.py index 23e0d5e9cea..89a6013211d 100644 --- a/tests/_games/test_game.py +++ b/tests/_games/test_game.py @@ -55,20 +55,20 @@ def test_slot_behaviour(self, game): assert getattr(game, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(game)) == len(set(mro_slots(game))), "duplicate slot" - def test_de_json_required(self, bot): + def test_de_json_required(self, offline_bot): json_dict = { "title": self.title, "description": self.description, "photo": [self.photo[0].to_dict()], } - game = Game.de_json(json_dict, bot) + game = Game.de_json(json_dict, offline_bot) assert game.api_kwargs == {} assert game.title == self.title assert game.description == self.description assert game.photo == tuple(self.photo) - def test_de_json_all(self, bot): + def test_de_json_all(self, offline_bot): json_dict = { "title": self.title, "description": self.description, @@ -77,7 +77,7 @@ def test_de_json_all(self, bot): "text_entities": [self.text_entities[0].to_dict()], "animation": self.animation.to_dict(), } - game = Game.de_json(json_dict, bot) + game = Game.de_json(json_dict, offline_bot) assert game.api_kwargs == {} assert game.title == self.title diff --git a/tests/_games/test_gamehighscore.py b/tests/_games/test_gamehighscore.py index fc76867b499..c07488c80fc 100644 --- a/tests/_games/test_gamehighscore.py +++ b/tests/_games/test_gamehighscore.py @@ -42,20 +42,20 @@ def test_slot_behaviour(self, game_highscore): assert getattr(game_highscore, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(game_highscore)) == len(set(mro_slots(game_highscore))), "same slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "position": self.position, "user": self.user.to_dict(), "score": self.score, } - highscore = GameHighScore.de_json(json_dict, bot) + highscore = GameHighScore.de_json(json_dict, offline_bot) assert highscore.api_kwargs == {} assert highscore.position == self.position assert highscore.user == self.user assert highscore.score == self.score - assert GameHighScore.de_json(None, bot) is None + assert GameHighScore.de_json(None, offline_bot) is None def test_to_dict(self, game_highscore): game_highscore_dict = game_highscore.to_dict() diff --git a/tests/_inline/test_inlinekeyboardbutton.py b/tests/_inline/test_inlinekeyboardbutton.py index 2569a8902ea..6e406f3ecc3 100644 --- a/tests/_inline/test_inlinekeyboardbutton.py +++ b/tests/_inline/test_inlinekeyboardbutton.py @@ -116,7 +116,7 @@ def test_to_dict(self, inline_keyboard_button): == inline_keyboard_button.switch_inline_query_chosen_chat.to_dict() ) - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "text": self.text, "url": self.url, @@ -150,7 +150,7 @@ def test_de_json(self, bot): == self.switch_inline_query_chosen_chat ) - none = InlineKeyboardButton.de_json({}, bot) + none = InlineKeyboardButton.de_json({}, offline_bot) assert none is None def test_equality(self): diff --git a/tests/_inline/test_inlinekeyboardmarkup.py b/tests/_inline/test_inlinekeyboardmarkup.py index 2f5bd2a5adf..461379436b9 100644 --- a/tests/_inline/test_inlinekeyboardmarkup.py +++ b/tests/_inline/test_inlinekeyboardmarkup.py @@ -192,7 +192,9 @@ def test_wrong_keyboard_inputs(self): with pytest.raises(ValueError, match="should be a sequence of sequences"): InlineKeyboardMarkup([[[InlineKeyboardButton("only_2d_array_is_allowed", "1")]]]) - async def test_expected_values_empty_switch(self, inline_keyboard_markup, bot, monkeypatch): + async def test_expected_values_empty_switch( + self, inline_keyboard_markup, offline_bot, monkeypatch + ): async def make_assertion( url, data, @@ -224,8 +226,8 @@ async def make_assertion( inline_keyboard_markup.inline_keyboard[0][1].callback_data = None inline_keyboard_markup.inline_keyboard[0][1].switch_inline_query_current_chat = "" - monkeypatch.setattr(bot, "_send_message", make_assertion) - await bot.send_message(123, "test", reply_markup=inline_keyboard_markup) + monkeypatch.setattr(offline_bot, "_send_message", make_assertion) + await offline_bot.send_message(123, "test", reply_markup=inline_keyboard_markup) class TestInlineKeyborardMarkupWithRequest(InlineKeyboardMarkupTestBase): diff --git a/tests/_inline/test_inlinequery.py b/tests/_inline/test_inlinequery.py index 4d2e73ffb87..7ff22c445c5 100644 --- a/tests/_inline/test_inlinequery.py +++ b/tests/_inline/test_inlinequery.py @@ -55,7 +55,7 @@ def test_slot_behaviour(self, inline_query): assert getattr(inline_query, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inline_query)) == len(set(mro_slots(inline_query))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "from": self.from_user.to_dict(), @@ -63,7 +63,7 @@ def test_de_json(self, bot): "offset": self.offset, "location": self.location.to_dict(), } - inline_query_json = InlineQuery.de_json(json_dict, bot) + inline_query_json = InlineQuery.de_json(json_dict, offline_bot) assert inline_query_json.api_kwargs == {} assert inline_query_json.id == self.id_ diff --git a/tests/_inline/test_inputinvoicemessagecontent.py b/tests/_inline/test_inputinvoicemessagecontent.py index 17bfad01359..4e35e9f6f43 100644 --- a/tests/_inline/test_inputinvoicemessagecontent.py +++ b/tests/_inline/test_inputinvoicemessagecontent.py @@ -203,8 +203,8 @@ def test_to_dict(self, input_invoice_message_content): == input_invoice_message_content.is_flexible ) - def test_de_json(self, bot): - assert InputInvoiceMessageContent.de_json({}, bot=bot) is None + def test_de_json(self, offline_bot): + assert InputInvoiceMessageContent.de_json({}, bot=offline_bot) is None json_dict = { "title": self.title, @@ -229,7 +229,9 @@ def test_de_json(self, bot): "is_flexible": self.is_flexible, } - input_invoice_message_content = InputInvoiceMessageContent.de_json(json_dict, bot=bot) + input_invoice_message_content = InputInvoiceMessageContent.de_json( + json_dict, bot=offline_bot + ) assert input_invoice_message_content.api_kwargs == {} assert input_invoice_message_content.title == self.title diff --git a/tests/_passport/test_no_passport.py b/tests/_passport/test_no_passport.py index 8b1af252cb3..ff3ce0a439c 100644 --- a/tests/_passport/test_no_passport.py +++ b/tests/_passport/test_no_passport.py @@ -28,7 +28,7 @@ """ import pytest -from telegram import _bot as bot +import telegram from telegram._passport import credentials from tests.auxil.envvars import TEST_WITH_OPT_DEPS @@ -39,7 +39,7 @@ class TestNoPassportWithoutRequest: def test_bot_init(self, bot_info): with pytest.raises(RuntimeError, match="passport"): - bot.Bot(bot_info["token"], private_key=1, private_key_password=2) + telegram.Bot(bot_info["token"], private_key=1, private_key_password=2) def test_credentials_decrypt(self): with pytest.raises(RuntimeError, match="passport"): diff --git a/tests/_passport/test_passport.py b/tests/_passport/test_passport.py index 9303ae7eb13..b094f808f81 100644 --- a/tests/_passport/test_passport.py +++ b/tests/_passport/test_passport.py @@ -390,8 +390,8 @@ def test_expected_decrypted_values(self, passport_data): assert email.type == "email" assert email.email == "fb3e3i47zt@dispostable.com" - def test_de_json_and_to_dict(self, bot): - passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot) + def test_de_json_and_to_dict(self, offline_bot): + passport_data = PassportData.de_json(RAW_PASSPORT_DATA, offline_bot) assert passport_data.api_kwargs == {} assert passport_data.to_dict() == RAW_PASSPORT_DATA @@ -414,14 +414,14 @@ def test_equality(self, passport_data): assert a != c assert hash(a) != hash(c) - def test_bot_init_invalid_key(self, bot): + def test_bot_init_invalid_key(self, offline_bot): with pytest.raises(TypeError): - Bot(bot.token, private_key="Invalid key!") + Bot(offline_bot.token, private_key="Invalid key!") with pytest.raises(ValueError, match="Could not deserialize key data"): - Bot(bot.token, private_key=b"Invalid key!") + Bot(offline_bot.token, private_key=b"Invalid key!") - def test_all_types(self, passport_data, bot, all_passport_data): + def test_all_types(self, passport_data, offline_bot, all_passport_data): credentials = passport_data.decrypted_credentials.to_dict() # Copy credentials from other types to all types so we can decrypt everything @@ -446,46 +446,46 @@ def test_all_types(self, passport_data, bot, all_passport_data): # Replaced below "credentials": {"data": "data", "hash": "hash", "secret": "secret"}, }, - bot=bot, + bot=offline_bot, ) assert new.api_kwargs == {} - new.credentials._decrypted_data = Credentials.de_json(credentials, bot) + new.credentials._decrypted_data = Credentials.de_json(credentials, offline_bot) assert new.credentials.api_kwargs == {} assert isinstance(new, PassportData) assert new.decrypted_data - async def test_passport_data_okay_with_non_crypto_bot(self, bot): - async with make_bot(token=bot.token) as b: + async def test_passport_data_okay_with_non_crypto_bot(self, offline_bot): + async with make_bot(token=offline_bot.token) as b: assert PassportData.de_json(RAW_PASSPORT_DATA, bot=b) - def test_wrong_hash(self, bot): + def test_wrong_hash(self, offline_bot): data = deepcopy(RAW_PASSPORT_DATA) data["credentials"]["hash"] = "bm90Y29ycmVjdGhhc2g=" # Not correct hash - passport_data = PassportData.de_json(data, bot=bot) + passport_data = PassportData.de_json(data, bot=offline_bot) with pytest.raises(PassportDecryptionError): assert passport_data.decrypted_data - async def test_wrong_key(self, bot): + async def test_wrong_key(self, offline_bot): short_key = ( b"-----BEGIN RSA PRIVATE" b" KEY-----\r\nMIIBOQIBAAJBAKU+OZ2jJm7sCA/ec4gngNZhXYPu+DZ/TAwSMl0W7vAPXAsLplBk\r\nO8l6IBHx8N0ZC4Bc65mO3b2G8YAzqndyqH8CAwEAAQJAWOx3jQFzeVXDsOaBPdAk\r\nYTncXVeIc6tlfUl9mOLyinSbRNCy1XicOiOZFgH1rRKOGIC1235QmqxFvdecySoY\r\nwQIhAOFeGgeX9CrEPuSsd9+kqUcA2avCwqdQgSdy2qggRFyJAiEAu7QHT8JQSkHU\r\nDELfzrzc24AhjyG0z1DpGZArM8COascCIDK42SboXj3Z2UXiQ0CEcMzYNiVgOisq\r\nBUd5pBi+2mPxAiAM5Z7G/Sv1HjbKrOGh29o0/sXPhtpckEuj5QMC6E0gywIgFY6S\r\nNjwrAA+cMmsgY0O2fAzEKkDc5YiFsiXaGaSS4eA=\r\n-----END" b" RSA PRIVATE KEY-----" ) - async with make_bot(token=bot.token, private_key=short_key) as b: + async with make_bot(token=offline_bot.token, private_key=short_key) as b: passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot=b) with pytest.raises(PassportDecryptionError): assert passport_data.decrypted_data - async with make_bot(token=bot.token, private_key=short_key) as b: + async with make_bot(token=offline_bot.token, private_key=short_key) as b: passport_data = PassportData.de_json(RAW_PASSPORT_DATA, bot=b) with pytest.raises(PassportDecryptionError): assert passport_data.decrypted_data async def test_mocked_download_passport_file(self, passport_data, monkeypatch): - # The files are not coming from our test bot, therefore the file id is invalid/wrong - # when coming from this bot, so we monkeypatch the call, to make sure that Bot.get_file + # The files are not coming from our test offline_bot, therefore the file id is invalid/wrong + # when coming from this offline_bot, so we monkeypatch the call, to make sure that Bot.get_file # at least gets called # TODO: Actually download a passport file in a test selfie = passport_data.decrypted_data[1].selfie @@ -501,7 +501,9 @@ async def get_file(*_, **kwargs): assert file._credentials.file_hash == self.driver_license_selfie_credentials_file_hash assert file._credentials.secret == self.driver_license_selfie_credentials_secret - async def test_mocked_set_passport_data_errors(self, monkeypatch, bot, chat_id, passport_data): + async def test_mocked_set_passport_data_errors( + self, monkeypatch, offline_bot, chat_id, passport_data + ): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters return ( @@ -514,8 +516,8 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): == passport_data.decrypted_credentials.secure_data.driver_license.data.data_hash ) - monkeypatch.setattr(bot.request, "post", make_assertion) - message = await bot.set_passport_data_errors( + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + message = await offline_bot.set_passport_data_errors( chat_id, [ PassportElementErrorSelfie( diff --git a/tests/_payment/test_invoice.py b/tests/_payment/test_invoice.py index 2293fe58745..585f4fd3e62 100644 --- a/tests/_payment/test_invoice.py +++ b/tests/_payment/test_invoice.py @@ -58,7 +58,7 @@ def test_slot_behaviour(self, invoice): assert getattr(invoice, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(invoice)) == len(set(mro_slots(invoice))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): invoice_json = Invoice.de_json( { "title": self.title, @@ -67,7 +67,7 @@ def test_de_json(self, bot): "currency": self.currency, "total_amount": self.total_amount, }, - bot, + offline_bot, ) assert invoice_json.api_kwargs == {} @@ -87,15 +87,15 @@ def test_to_dict(self, invoice): assert invoice_dict["currency"] == invoice.currency assert invoice_dict["total_amount"] == invoice.total_amount - async def test_send_invoice_all_args_mock(self, bot, monkeypatch): + async def test_send_invoice_all_args_mock(self, offline_bot, monkeypatch): # We do this one as safety guard to make sure that we pass all of the optional # parameters correctly because #2526 went unnoticed for 3 years … async def make_assertion(*args, **_): kwargs = args[1] return all(kwargs[key] == key for key in kwargs) - monkeypatch.setattr(bot, "_send_message", make_assertion) - assert await bot.send_invoice( + monkeypatch.setattr(offline_bot, "_send_message", make_assertion) + assert await offline_bot.send_invoice( chat_id="chat_id", title="title", description="description", @@ -122,13 +122,13 @@ async def make_assertion(*args, **_): protect_content=True, ) - async def test_send_all_args_create_invoice_link(self, bot, monkeypatch): + async def test_send_all_args_create_invoice_link(self, offline_bot, monkeypatch): async def make_assertion(*args, **_): kwargs = args[1] return all(kwargs[i] == i for i in kwargs) - monkeypatch.setattr(bot, "_post", make_assertion) - assert await bot.create_invoice_link( + monkeypatch.setattr(offline_bot, "_post", make_assertion) + assert await offline_bot.create_invoice_link( title="title", description="description", payload="payload", @@ -151,13 +151,15 @@ async def make_assertion(*args, **_): is_flexible="is_flexible", ) - async def test_send_object_as_provider_data(self, monkeypatch, bot, chat_id, provider_token): + async def test_send_object_as_provider_data( + self, monkeypatch, offline_bot, chat_id, provider_token + ): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters["provider_data"] == '{"test_data": 123456789}' - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.send_invoice( + assert await offline_bot.send_invoice( chat_id, self.title, self.description, diff --git a/tests/_payment/test_orderinfo.py b/tests/_payment/test_orderinfo.py index 8e27ed34390..4f6317222da 100644 --- a/tests/_payment/test_orderinfo.py +++ b/tests/_payment/test_orderinfo.py @@ -45,14 +45,14 @@ def test_slot_behaviour(self, order_info): assert getattr(order_info, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(order_info)) == len(set(mro_slots(order_info))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "name": self.name, "phone_number": self.phone_number, "email": self.email, "shipping_address": self.shipping_address.to_dict(), } - order_info = OrderInfo.de_json(json_dict, bot) + order_info = OrderInfo.de_json(json_dict, offline_bot) assert order_info.api_kwargs == {} assert order_info.name == self.name diff --git a/tests/_payment/test_precheckoutquery.py b/tests/_payment/test_precheckoutquery.py index aaca70407a4..e61adbcf9c3 100644 --- a/tests/_payment/test_precheckoutquery.py +++ b/tests/_payment/test_precheckoutquery.py @@ -60,7 +60,7 @@ def test_slot_behaviour(self, pre_checkout_query): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "invoice_payload": self.invoice_payload, @@ -70,10 +70,10 @@ def test_de_json(self, bot): "from": self.from_user.to_dict(), "order_info": self.order_info.to_dict(), } - pre_checkout_query = PreCheckoutQuery.de_json(json_dict, bot) + pre_checkout_query = PreCheckoutQuery.de_json(json_dict, offline_bot) assert pre_checkout_query.api_kwargs == {} - assert pre_checkout_query.get_bot() is bot + assert pre_checkout_query.get_bot() is offline_bot assert pre_checkout_query.id == self.id_ assert pre_checkout_query.invoice_payload == self.invoice_payload assert pre_checkout_query.shipping_option_id == self.shipping_option_id diff --git a/tests/_payment/test_refundedpayment.py b/tests/_payment/test_refundedpayment.py index 8ea4d1a5001..32581f785f8 100644 --- a/tests/_payment/test_refundedpayment.py +++ b/tests/_payment/test_refundedpayment.py @@ -48,7 +48,7 @@ def test_slot_behaviour(self, refunded_payment): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "invoice_payload": self.invoice_payload, "currency": self.currency, @@ -56,7 +56,7 @@ def test_de_json(self, bot): "telegram_payment_charge_id": self.telegram_payment_charge_id, "provider_payment_charge_id": self.provider_payment_charge_id, } - refunded_payment = RefundedPayment.de_json(json_dict, bot) + refunded_payment = RefundedPayment.de_json(json_dict, offline_bot) assert refunded_payment.api_kwargs == {} assert refunded_payment.invoice_payload == self.invoice_payload diff --git a/tests/_payment/test_shippingaddress.py b/tests/_payment/test_shippingaddress.py index 41fbeba5a16..371c8d2fc0c 100644 --- a/tests/_payment/test_shippingaddress.py +++ b/tests/_payment/test_shippingaddress.py @@ -50,7 +50,7 @@ def test_slot_behaviour(self, shipping_address): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "country_code": self.country_code, "state": self.state, @@ -59,7 +59,7 @@ def test_de_json(self, bot): "street_line2": self.street_line2, "post_code": self.post_code, } - shipping_address = ShippingAddress.de_json(json_dict, bot) + shipping_address = ShippingAddress.de_json(json_dict, offline_bot) assert shipping_address.api_kwargs == {} assert shipping_address.country_code == self.country_code diff --git a/tests/_payment/test_shippingquery.py b/tests/_payment/test_shippingquery.py index 4821cbae9c9..da99c1fd177 100644 --- a/tests/_payment/test_shippingquery.py +++ b/tests/_payment/test_shippingquery.py @@ -54,21 +54,21 @@ def test_slot_behaviour(self, shipping_query): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "invoice_payload": self.invoice_payload, "from": self.from_user.to_dict(), "shipping_address": self.shipping_address.to_dict(), } - shipping_query = ShippingQuery.de_json(json_dict, bot) + shipping_query = ShippingQuery.de_json(json_dict, offline_bot) assert shipping_query.api_kwargs == {} assert shipping_query.id == self.id_ assert shipping_query.invoice_payload == self.invoice_payload assert shipping_query.from_user == self.from_user assert shipping_query.shipping_address == self.shipping_address - assert shipping_query.get_bot() is bot + assert shipping_query.get_bot() is offline_bot def test_to_dict(self, shipping_query): shipping_query_dict = shipping_query.to_dict() diff --git a/tests/_payment/test_successfulpayment.py b/tests/_payment/test_successfulpayment.py index c4562d0a87d..2b4cf091850 100644 --- a/tests/_payment/test_successfulpayment.py +++ b/tests/_payment/test_successfulpayment.py @@ -52,7 +52,7 @@ def test_slot_behaviour(self, successful_payment): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "invoice_payload": self.invoice_payload, "shipping_option_id": self.shipping_option_id, @@ -62,7 +62,7 @@ def test_de_json(self, bot): "telegram_payment_charge_id": self.telegram_payment_charge_id, "provider_payment_charge_id": self.provider_payment_charge_id, } - successful_payment = SuccessfulPayment.de_json(json_dict, bot) + successful_payment = SuccessfulPayment.de_json(json_dict, offline_bot) assert successful_payment.api_kwargs == {} assert successful_payment.invoice_payload == self.invoice_payload diff --git a/tests/conftest.py b/tests/conftest.py index e8ef01cabac..b677bbe5964 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -39,9 +39,9 @@ ) from telegram.ext import Defaults from tests.auxil.build_messages import DATE -from tests.auxil.ci_bots import BOT_INFO_PROVIDER +from tests.auxil.ci_bots import BOT_INFO_PROVIDER, JOB_INDEX from tests.auxil.constants import PRIVATE_KEY -from tests.auxil.envvars import RUN_TEST_OFFICIAL, TEST_WITH_OPT_DEPS +from tests.auxil.envvars import GITHUB_ACTION, RUN_TEST_OFFICIAL, TEST_WITH_OPT_DEPS from tests.auxil.files import data_file from tests.auxil.networking import NonchalantHttpxRequest from tests.auxil.pytest_classes import PytestBot, make_bot @@ -98,6 +98,34 @@ def pytest_collection_modifyitems(items: List[pytest.Item]): parent.add_marker(pytest.mark.no_req) +if GITHUB_ACTION and JOB_INDEX == 0: + # let's not slow down the tests too much with these additional checks + # that's why we run them only in GitHub actions and only on *one* of the several test + # matrix entries + @pytest.fixture(autouse=True) + def _disallow_requests_in_without_request_tests(request): + """This fixture prevents tests that don't require requests from using the online-bot.""" + + if type(request).__name__ == "SubRequest": + # We want to allow *WithoutRequest test classes to use fixtures that do use requests, + # e.g. `animation` and so on. Unfortunately the `SubRequest` class is not public, so + # we check only the name for less dependency on pytests internal structure. + return + + if not request.cls: + return + name = request.cls.__name__ + if not name.endswith("WithoutRequest") or not request.fixturenames: + return + + if "bot" in request.fixturenames: + print(request.fixturenames) + pytest.fail( + f"Test function {request.function} in test class {name} should not have a `bot` " + f"fixture. Use `offline_bot` instead." + ) + + # Redefine the event_loop fixture to have a session scope. Otherwise `bot` fixture can't be # session. See https://github.com/pytest-dev/pytest-asyncio/issues/68 for more details. @pytest.fixture(scope="session") diff --git a/tests/request/test_request.py b/tests/request/test_request.py index 6adcdf7c068..34fd8d2c5d6 100644 --- a/tests/request/test_request.py +++ b/tests/request/test_request.py @@ -84,10 +84,10 @@ async def httpx_request(): TEST_WITH_OPT_DEPS, reason="Only relevant if the optional dependency is not installed" ) class TestNoSocksHTTP2WithoutRequest: - async def test_init(self, bot): - with pytest.raises(RuntimeError, match=r"python-telegram-bot\[socks\]"): + async def test_init(self, offline_bot): + with pytest.raises(RuntimeError, match=r"python-telegram-offline_bot\[socks\]"): HTTPXRequest(proxy="socks5://foo") - with pytest.raises(RuntimeError, match=r"python-telegram-bot\[http2\]"): + with pytest.raises(RuntimeError, match=r"python-telegram-offline_bot\[http2\]"): HTTPXRequest(http_version="2") @@ -515,28 +515,10 @@ async def aclose(*args, **kwargs): assert self.test_flag["init"] == 1 assert self.test_flag["shutdown"] == 1 - async def test_multiple_init_cycles(self): - # nothing really to assert - this should just not fail - httpx_request = HTTPXRequest() - async with httpx_request: - await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET") - async with httpx_request: - await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET") - async def test_http_version_error(self): with pytest.raises(ValueError, match="`http_version` must be either"): HTTPXRequest(http_version="1.0") - async def test_http_1_response(self): - httpx_request = HTTPXRequest(http_version="1.1") - async with httpx_request: - resp = await httpx_request._client.request( - url="https://python-telegram-bot.org", - method="GET", - headers={"User-Agent": httpx_request.USER_AGENT}, - ) - assert resp.http_version == "HTTP/1.1" - async def test_do_request_after_shutdown(self, httpx_request): await httpx_request.shutdown() with pytest.raises(RuntimeError, match="not initialized"): @@ -800,6 +782,24 @@ async def test_read_timeout_property(self, read_timeout): @pytest.mark.skipif(not TEST_WITH_OPT_DEPS, reason="No need to run this twice") class TestHTTPXRequestWithRequest: + async def test_multiple_init_cycles(self): + # nothing really to assert - this should just not fail + httpx_request = HTTPXRequest() + async with httpx_request: + await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET") + async with httpx_request: + await httpx_request.do_request(url="https://python-telegram-bot.org", method="GET") + + async def test_http_1_response(self): + httpx_request = HTTPXRequest(http_version="1.1") + async with httpx_request: + resp = await httpx_request._client.request( + url="https://python-telegram-bot.org", + method="GET", + headers={"User-Agent": httpx_request.USER_AGENT}, + ) + assert resp.http_version == "HTTP/1.1" + async def test_do_request_wait_for_pool(self, httpx_request): """The pool logic is buried rather deeply in httpxcore, so we make actual requests here instead of mocking""" diff --git a/tests/test_birthdate.py b/tests/test_birthdate.py index c22ebd9affd..11cb96a182e 100644 --- a/tests/test_birthdate.py +++ b/tests/test_birthdate.py @@ -48,9 +48,9 @@ def test_to_dict(self, birthdate): assert bd_dict["month"] == self.month assert bd_dict["year"] == self.year - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = {"day": self.day, "month": self.month, "year": self.year} - bd = Birthdate.de_json(json_dict, bot) + bd = Birthdate.de_json(json_dict, offline_bot) assert isinstance(bd, Birthdate) assert bd.day == self.day assert bd.month == self.month diff --git a/tests/test_bot.py b/tests/test_bot.py index 705b14c6d4d..df7cc1d9b70 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -224,8 +224,8 @@ def _reset(self): self.test_flag = None @pytest.mark.parametrize("bot_class", [Bot, ExtBot]) - def test_slot_behaviour(self, bot_class, bot): - inst = bot_class(bot.token) + def test_slot_behaviour(self, bot_class, offline_bot): + inst = bot_class(offline_bot.token) for attr in inst.__slots__: assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" @@ -235,27 +235,27 @@ async def test_no_token_passed(self): Bot("") async def test_repr(self): - bot = Bot(token="some_token", base_file_url="") - assert repr(bot) == "Bot[token=some_token]" + offline_bot = Bot(token="some_token", base_file_url="") + assert repr(offline_bot) == "Bot[token=some_token]" - async def test_to_dict(self, bot): - to_dict_bot = bot.to_dict() + async def test_to_dict(self, offline_bot): + to_dict_bot = offline_bot.to_dict() assert isinstance(to_dict_bot, dict) - assert to_dict_bot["id"] == bot.id - assert to_dict_bot["username"] == bot.username - assert to_dict_bot["first_name"] == bot.first_name - if bot.last_name: - assert to_dict_bot["last_name"] == bot.last_name + assert to_dict_bot["id"] == offline_bot.id + assert to_dict_bot["username"] == offline_bot.username + assert to_dict_bot["first_name"] == offline_bot.first_name + if offline_bot.last_name: + assert to_dict_bot["last_name"] == offline_bot.last_name - async def test_initialize_and_shutdown(self, bot: PytestExtBot, monkeypatch): + async def test_initialize_and_shutdown(self, offline_bot: PytestExtBot, monkeypatch): async def initialize(*args, **kwargs): self.test_flag = ["initialize"] async def stop(*args, **kwargs): self.test_flag.append("stop") - temp_bot = PytestBot(token=bot.token, request=NonchalantHttpxRequest()) + temp_bot = PytestBot(token=offline_bot.token, request=NonchalantHttpxRequest()) orig_stop = temp_bot.request.shutdown try: @@ -263,14 +263,14 @@ async def stop(*args, **kwargs): monkeypatch.setattr(temp_bot.request, "shutdown", stop) await temp_bot.initialize() assert self.test_flag == ["initialize"] - assert temp_bot.bot == bot.bot + assert temp_bot.bot == offline_bot.bot await temp_bot.shutdown() assert self.test_flag == ["initialize", "stop"] finally: await orig_stop() - async def test_multiple_inits_and_shutdowns(self, bot, monkeypatch): + async def test_multiple_inits_and_shutdowns(self, offline_bot, monkeypatch): self.received = defaultdict(int) async def initialize(*args, **kwargs): @@ -282,7 +282,7 @@ async def shutdown(*args, **kwargs): monkeypatch.setattr(HTTPXRequest, "initialize", initialize) monkeypatch.setattr(HTTPXRequest, "shutdown", shutdown) - test_bot = PytestBot(bot.token) + test_bot = PytestBot(offline_bot.token) await test_bot.initialize() await test_bot.initialize() await test_bot.initialize() @@ -290,37 +290,37 @@ async def shutdown(*args, **kwargs): await test_bot.shutdown() await test_bot.shutdown() - # 2 instead of 1 since we have to request objects for each bot + # 2 instead of 1 since we have to request objects for each offline_bot assert self.received["init"] == 2 assert self.received["shutdown"] == 2 - async def test_context_manager(self, monkeypatch, bot): + async def test_context_manager(self, monkeypatch, offline_bot): async def initialize(): self.test_flag = ["initialize"] async def shutdown(*args): self.test_flag.append("stop") - monkeypatch.setattr(bot, "initialize", initialize) - monkeypatch.setattr(bot, "shutdown", shutdown) + monkeypatch.setattr(offline_bot, "initialize", initialize) + monkeypatch.setattr(offline_bot, "shutdown", shutdown) - async with bot: + async with offline_bot: pass assert self.test_flag == ["initialize", "stop"] - async def test_context_manager_exception_on_init(self, monkeypatch, bot): + async def test_context_manager_exception_on_init(self, monkeypatch, offline_bot): async def initialize(): raise RuntimeError("initialize") async def shutdown(): self.test_flag = "stop" - monkeypatch.setattr(bot, "initialize", initialize) - monkeypatch.setattr(bot, "shutdown", shutdown) + monkeypatch.setattr(offline_bot, "initialize", initialize) + monkeypatch.setattr(offline_bot, "shutdown", shutdown) with pytest.raises(RuntimeError, match="initialize"): - async with bot: + async with offline_bot: pass assert self.test_flag == "stop" @@ -362,43 +362,43 @@ async def test_equality(self): "link", ], ) - async def test_get_me_and_properties_not_initialized(self, bot: Bot, attribute): - bot = Bot(token=bot.token) + async def test_get_me_and_properties_not_initialized(self, offline_bot: Bot, attribute): + offline_bot = Bot(token=offline_bot.token) try: with pytest.raises(RuntimeError, match="not properly initialized"): - bot[attribute] + offline_bot[attribute] finally: - await bot.shutdown() + await offline_bot.shutdown() - async def test_get_me_and_properties(self, bot): - get_me_bot = await ExtBot(bot.token).get_me() + async def test_get_me_and_properties(self, offline_bot): + get_me_bot = await ExtBot(offline_bot.token).get_me() assert isinstance(get_me_bot, User) - assert get_me_bot.id == bot.id - assert get_me_bot.username == bot.username - assert get_me_bot.first_name == bot.first_name - assert get_me_bot.last_name == bot.last_name - assert get_me_bot.name == bot.name - assert get_me_bot.can_join_groups == bot.can_join_groups - assert get_me_bot.can_read_all_group_messages == bot.can_read_all_group_messages - assert get_me_bot.supports_inline_queries == bot.supports_inline_queries - assert f"https://t.me/{get_me_bot.username}" == bot.link - - def test_bot_pickling_error(self, bot): + assert get_me_bot.id == offline_bot.id + assert get_me_bot.username == offline_bot.username + assert get_me_bot.first_name == offline_bot.first_name + assert get_me_bot.last_name == offline_bot.last_name + assert get_me_bot.name == offline_bot.name + assert get_me_bot.can_join_groups == offline_bot.can_join_groups + assert get_me_bot.can_read_all_group_messages == offline_bot.can_read_all_group_messages + assert get_me_bot.supports_inline_queries == offline_bot.supports_inline_queries + assert f"https://t.me/{get_me_bot.username}" == offline_bot.link + + def test_bot_pickling_error(self, offline_bot): with pytest.raises(pickle.PicklingError, match="Bot objects cannot be pickled"): - pickle.dumps(bot) + pickle.dumps(offline_bot) - def test_bot_deepcopy_error(self, bot): + def test_bot_deepcopy_error(self, offline_bot): with pytest.raises(TypeError, match="Bot objects cannot be deepcopied"): - copy.deepcopy(bot) + copy.deepcopy(offline_bot) @pytest.mark.parametrize( ("cls", "logger_name"), [(Bot, "telegram.Bot"), (ExtBot, "telegram.ext.ExtBot")] ) - async def test_bot_method_logging(self, bot: PytestExtBot, cls, logger_name, caplog): + async def test_bot_method_logging(self, offline_bot: PytestExtBot, cls, logger_name, caplog): # Second argument makes sure that we ignore logs from e.g. httpx with caplog.at_level(logging.DEBUG, logger="telegram"): - await cls(bot.token).get_me() + await cls(offline_bot.token).get_me() # Only for stabilizing this test- if len(caplog.records) == 4: for idx, record in enumerate(caplog.records): @@ -430,13 +430,13 @@ def test_camel_case_aliases(self, bot_class, bot_method_name, bot_method): @bot_methods(include_do_api_request=True) def test_coroutine_functions(self, bot_class, bot_method_name, bot_method): - """Check that all bot methods are defined as async def ...""" + """Check that all offline_bot methods are defined as async def ...""" meth = getattr(bot_method, "__wrapped__", bot_method) # to unwrap the @_log decorator assert inspect.iscoroutinefunction(meth), f"{bot_method_name} must be a coroutine function" @bot_methods(include_do_api_request=True) def test_api_kwargs_and_timeouts_present(self, bot_class, bot_method_name, bot_method): - """Check that all bot methods have `api_kwargs` and timeout params.""" + """Check that all offline_bot methods have `api_kwargs` and timeout params.""" param_names = inspect.signature(bot_method).parameters.keys() params = ("pool_timeout", "read_timeout", "connect_timeout", "write_timeout", "api_kwargs") @@ -453,11 +453,12 @@ async def test_defaults_handling( bot_class, bot_method_name: str, bot_method, - bot: PytestExtBot, + offline_bot: PytestExtBot, raw_bot: PytestBot, ): """ - Here we check that the bot methods handle tg.ext.Defaults correctly. This has two parts: + Here we check that the offline_bot methods handle tg.ext.Defaults correctly. This has two + parts: 1. Check that ExtBot actually inserts the defaults values correctly 2. Check that tg.Bot just replaces `DefaultValue(obj)` with `obj`, i.e. that it doesn't @@ -466,8 +467,8 @@ async def test_defaults_handling( As for most defaults, we can't really check the effect, we just check if we're passing the correct kwargs to - Request.post. As bot method tests a scattered across the different test files, we do - this here in one place. + Request.post. As offline_bot method tests a scattered across the different test files, we + do this here in one place. The same test is also run for all the shortcuts (Message.reply_text) etc in the corresponding tests. @@ -477,12 +478,14 @@ async def test_defaults_handling( """ # Mocking get_me within check_defaults_handling messes with the cached values like # Bot.{bot, username, id, …}` unless we return the expected User object. - return_value = bot.bot if bot_method_name.lower().replace("_", "") == "getme" else None + return_value = ( + offline_bot.bot if bot_method_name.lower().replace("_", "") == "getme" else None + ) # Check that ExtBot does the right thing - bot_method = getattr(bot, bot_method_name) + bot_method = getattr(offline_bot, bot_method_name) raw_bot_method = getattr(raw_bot, bot_method_name) - assert await check_defaults_handling(bot_method, bot, return_value=return_value) + assert await check_defaults_handling(bot_method, offline_bot, return_value=return_value) assert await check_defaults_handling(raw_bot_method, raw_bot, return_value=return_value) @pytest.mark.parametrize( @@ -523,19 +526,19 @@ def test_ext_bot_signature(self, name, method): param.kind == ext_signature.parameters[param_name].kind ), f"Wrong parameter kind for parameter {param_name} of method {name}" - async def test_unknown_kwargs(self, bot, monkeypatch): + async def test_unknown_kwargs(self, offline_bot, monkeypatch): async def post(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters if not all([data["unknown_kwarg_1"] == "7", data["unknown_kwarg_2"] == "5"]): pytest.fail("got wrong parameters") return True - monkeypatch.setattr(bot.request, "post", post) - await bot.send_message( + monkeypatch.setattr(offline_bot.request, "post", post) + await offline_bot.send_message( 123, "text", api_kwargs={"unknown_kwarg_1": 7, "unknown_kwarg_2": 5} ) - async def test_get_updates_deserialization_error(self, bot, monkeypatch, caplog): + async def test_get_updates_deserialization_error(self, offline_bot, monkeypatch, caplog): async def faulty_do_request(*args, **kwargs): return ( HTTPStatus.OK, @@ -544,10 +547,10 @@ async def faulty_do_request(*args, **kwargs): monkeypatch.setattr(HTTPXRequest, "do_request", faulty_do_request) - bot = PytestExtBot(get_updates_request=HTTPXRequest(), token=bot.token) + offline_bot = PytestExtBot(get_updates_request=HTTPXRequest(), token=offline_bot.token) with caplog.at_level(logging.CRITICAL), pytest.raises(AttributeError): - await bot.get_updates() + await offline_bot.get_updates() assert len(caplog.records) == 1 assert caplog.records[0].name == "telegram.ext.ExtBot" @@ -558,7 +561,7 @@ async def faulty_do_request(*args, **kwargs): ) assert caplog.records[0].exc_info[0] is AttributeError - async def test_answer_web_app_query(self, bot, raw_bot, monkeypatch): + async def test_answer_web_app_query(self, offline_bot, raw_bot, monkeypatch): params = False # For now just test that our internals pass the correct data @@ -583,9 +586,9 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): result = InlineQueryResultArticle("1", "title", InputTextMessageContent("text")) copied_result = copy.copy(result) - ext_bot = bot + ext_bot = offline_bot for bot_type in (ext_bot, raw_bot): - # We need to test 1) below both the bot and raw_bot and setting this up with + # We need to test 1) below both the offline_bot and raw_bot and setting this up with # pytest.parametrize appears to be difficult ... monkeypatch.setattr(bot_type.request, "post", make_assertion) web_app_msg = await bot_type.answer_web_app_query("12345", result) @@ -679,7 +682,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def test_answer_web_app_query_defaults( self, default_bot, ilq_result, expected_params, monkeypatch ): - bot = default_bot + offline_bot = default_bot params = False # For now just test that our internals pass the correct data @@ -689,13 +692,13 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): params = request_data.parameters == expected_params return SentWebAppMessage("321").to_dict() - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) # We test different result types more thoroughly for answer_inline_query, so we just # use the one type here copied_result = copy.copy(ilq_result) - web_app_msg = await bot.answer_web_app_query("12345", ilq_result) + web_app_msg = await offline_bot.answer_web_app_query("12345", ilq_result) assert params, "something went wrong with passing arguments to the request" assert isinstance(web_app_msg, SentWebAppMessage) assert web_app_msg.inline_message_id == "321" @@ -709,7 +712,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): # TODO: Needs improvement. We need incoming inline query to test answer. @pytest.mark.parametrize("button_type", ["start", "web_app"]) - async def test_answer_inline_query(self, monkeypatch, bot, raw_bot, button_type): + async def test_answer_inline_query(self, monkeypatch, offline_bot, raw_bot, button_type): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): expected = { @@ -732,7 +735,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "id": "123", "type": "document", "document_url": ( - "https://raw.githubusercontent.com/python-telegram-bot" + "https://raw.githubusercontent.com/python-telegram-offline_bot" "/logos/master/logo/png/ptb-logo_240.png" ), "mime_type": "image/png", @@ -750,7 +753,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): else: button_dict = { "text": "button_text", - "web_app": {"url": "https://python-telegram-bot.org"}, + "web_app": {"url": "https://python-telegram-offline_bot.org"}, } expected["button"] = button_dict @@ -763,7 +766,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): InlineQueryResultDocument( id="123", document_url=( - "https://raw.githubusercontent.com/python-telegram-bot/logos/master/" + "https://raw.githubusercontent.com/python-telegram-offline_bot/logos/master/" "logo/png/ptb-logo_240.png" ), title="test_result", @@ -779,15 +782,15 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): ) elif button_type == "web_app": button = InlineQueryResultsButton( - text="button_text", web_app=WebAppInfo("https://python-telegram-bot.org") + text="button_text", web_app=WebAppInfo("https://python-telegram-offline_bot.org") ) else: button = None copied_results = copy.copy(results) - ext_bot = bot + ext_bot = offline_bot for bot_type in (ext_bot, raw_bot): - # We need to test 1) below both the bot and raw_bot and setting this up with + # We need to test 1) below both the offline_bot and raw_bot and setting this up with # pytest.parametrize appears to be difficult ... monkeypatch.setattr(bot_type.request, "post", make_assertion) assert await bot_type.answer_inline_query( @@ -817,7 +820,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): monkeypatch.delattr(bot_type.request, "post") - async def test_answer_inline_query_no_default_parse_mode(self, monkeypatch, bot): + async def test_answer_inline_query_no_default_parse_mode(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { "cache_time": 300, @@ -840,7 +843,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "type": "document", "document_url": ( "https://raw.githubusercontent.com/" - "python-telegram-bot/logos/master/logo/png/" + "python-telegram-offline_bot/logos/master/logo/png/" "ptb-logo_240.png" ), "mime_type": "image/png", @@ -853,14 +856,14 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "is_personal": True, } - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) results = [ InlineQueryResultArticle("11", "first", InputTextMessageContent("first")), InlineQueryResultArticle("12", "second", InputMessageContentLPO("second")), InlineQueryResultDocument( id="123", document_url=( - "https://raw.githubusercontent.com/python-telegram-bot/logos/master/" + "https://raw.githubusercontent.com/python-telegram-offline_bot/logos/master/" "logo/png/ptb-logo_240.png" ), title="test_result", @@ -871,7 +874,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): ] copied_results = copy.copy(results) - assert await bot.answer_inline_query( + assert await offline_bot.answer_inline_query( 1234, results=results, cache_time=300, @@ -932,7 +935,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "type": InlineQueryResultType.DOCUMENT, "document_url": ( "https://raw.githubusercontent.com/" - "python-telegram-bot/logos/master/logo/png/" + "python-telegram-offline_bot/logos/master/logo/png/" "ptb-logo_240.png" ), "mime_type": "image/png", @@ -959,7 +962,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): InlineQueryResultDocument( id="123", document_url=( - "https://raw.githubusercontent.com/python-telegram-bot/logos/master/" + "https://raw.githubusercontent.com/python-telegram-offline_bot/logos/master/" "logo/png/ptb-logo_240.png" ), title="test_result", @@ -1003,7 +1006,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): async def test_answer_inline_query_current_offset_1( self, monkeypatch, - bot, + offline_bot, inline_results, current_offset, num_results, @@ -1019,13 +1022,15 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): next_offset_matches = data["next_offset"] == str(expected_next_offset) return length_matches and ids_match and next_offset_matches - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query( + assert await offline_bot.answer_inline_query( 1234, results=inline_results, current_offset=current_offset ) - async def test_answer_inline_query_current_offset_2(self, monkeypatch, bot, inline_results): + async def test_answer_inline_query_current_offset_2( + self, monkeypatch, offline_bot, inline_results + ): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters @@ -1035,9 +1040,11 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): next_offset_matches = data["next_offset"] == "1" return length_matches and ids_match and next_offset_matches - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query(1234, results=inline_results, current_offset=0) + assert await offline_bot.answer_inline_query( + 1234, results=inline_results, current_offset=0 + ) inline_results = inline_results[:30] @@ -1049,11 +1056,13 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): next_offset_matches = not data["next_offset"] return length_matches and ids_match and next_offset_matches - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query(1234, results=inline_results, current_offset=0) + assert await offline_bot.answer_inline_query( + 1234, results=inline_results, current_offset=0 + ) - async def test_answer_inline_query_current_offset_callback(self, monkeypatch, bot): + async def test_answer_inline_query_current_offset_callback(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters @@ -1063,9 +1072,9 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): next_offset = data["next_offset"] == "2" return length and ids and next_offset - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query( + assert await offline_bot.answer_inline_query( 1234, results=inline_results_callback, current_offset=1 ) @@ -1076,61 +1085,63 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): next_offset = not data["next_offset"] return length and next_offset - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_inline_query( + assert await offline_bot.answer_inline_query( 1234, results=inline_results_callback, current_offset=6 ) - async def test_send_edit_message_mutually_exclusive_link_preview(self, bot, chat_id): + async def test_send_edit_message_mutually_exclusive_link_preview(self, offline_bot, chat_id): """Test that link_preview is mutually exclusive with disable_web_page_preview.""" with pytest.raises(ValueError, match="`link_preview_options` are mutually exclusive"): - await bot.send_message( + await offline_bot.send_message( chat_id, "text", disable_web_page_preview=True, link_preview_options="something" ) with pytest.raises(ValueError, match="`link_preview_options` are mutually exclusive"): - await bot.edit_message_text( + await offline_bot.edit_message_text( "text", chat_id, 1, disable_web_page_preview=True, link_preview_options="something" ) - async def test_rtm_aswr_mutually_exclusive_reply_parameters(self, bot, chat_id): + async def test_rtm_aswr_mutually_exclusive_reply_parameters(self, offline_bot, chat_id): """Test that reply_to_message_id and allow_sending_without_reply are mutually exclusive with reply_parameters.""" with pytest.raises(ValueError, match="`reply_to_message_id` and"): - await bot.send_message(chat_id, "text", reply_to_message_id=1, reply_parameters=True) + await offline_bot.send_message( + chat_id, "text", reply_to_message_id=1, reply_parameters=True + ) with pytest.raises(ValueError, match="`allow_sending_without_reply` and"): - await bot.send_message( + await offline_bot.send_message( chat_id, "text", allow_sending_without_reply=True, reply_parameters=True ) # Test with copy message with pytest.raises(ValueError, match="`reply_to_message_id` and"): - await bot.copy_message( + await offline_bot.copy_message( chat_id, chat_id, 1, reply_to_message_id=1, reply_parameters=True ) with pytest.raises(ValueError, match="`allow_sending_without_reply` and"): - await bot.copy_message( + await offline_bot.copy_message( chat_id, chat_id, 1, allow_sending_without_reply=True, reply_parameters=True ) # Test with send media group media = InputMediaPhoto(photo_file) with pytest.raises(ValueError, match="`reply_to_message_id` and"): - await bot.send_media_group( + await offline_bot.send_media_group( chat_id, media, reply_to_message_id=1, reply_parameters=True ) with pytest.raises(ValueError, match="`allow_sending_without_reply` and"): - await bot.send_media_group( + await offline_bot.send_media_group( chat_id, media, allow_sending_without_reply=True, reply_parameters=True ) # get_file is tested multiple times in the test_*media* modules. - # Here we only test the behaviour for bot apis in local mode - async def test_get_file_local_mode(self, bot, monkeypatch): + # Here we only test the behaviour for offline_bot apis in local mode + async def test_get_file_local_mode(self, offline_bot, monkeypatch): path = str(data_file("game.gif")) async def make_assertion(*args, **kwargs): @@ -1141,14 +1152,14 @@ async def make_assertion(*args, **kwargs): "file_path": path, } - monkeypatch.setattr(bot, "_post", make_assertion) + monkeypatch.setattr(offline_bot, "_post", make_assertion) - resulting_path = (await bot.get_file("file_id")).file_path - assert bot.token not in resulting_path + resulting_path = (await offline_bot.get_file("file_id")).file_path + assert offline_bot.token not in resulting_path assert resulting_path == path # TODO: Needs improvement. No feasible way to test until bots can add members. - async def test_ban_chat_member(self, monkeypatch, bot): + async def test_ban_chat_member(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters chat_id = data["chat_id"] == "2" @@ -1157,13 +1168,13 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): revoke_msgs = data.get("revoke_messages", "true") == "true" return chat_id and user_id and until_date and revoke_msgs - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) until = from_timestamp(1577887200) - assert await bot.ban_chat_member(2, 32) - assert await bot.ban_chat_member(2, 32, until_date=until) - assert await bot.ban_chat_member(2, 32, until_date=1577887200) - assert await bot.ban_chat_member(2, 32, revoke_messages=True) + assert await offline_bot.ban_chat_member(2, 32) + assert await offline_bot.ban_chat_member(2, 32, until_date=until) + assert await offline_bot.ban_chat_member(2, 32, until_date=1577887200) + assert await offline_bot.ban_chat_member(2, 32, revoke_messages=True) async def test_ban_chat_member_default_tz(self, monkeypatch, tz_bot): until = dtm.datetime(2020, 1, 11, 16, 13) @@ -1182,7 +1193,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): assert await tz_bot.ban_chat_member(2, 32, until_date=until) assert await tz_bot.ban_chat_member(2, 32, until_date=until_timestamp) - async def test_ban_chat_sender_chat(self, monkeypatch, bot): + async def test_ban_chat_sender_chat(self, monkeypatch, offline_bot): # For now, we just test that we pass the correct data to TG async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters @@ -1190,12 +1201,12 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): sender_chat_id = data["sender_chat_id"] == 32 return chat_id and sender_chat_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.ban_chat_sender_chat(2, 32) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.ban_chat_sender_chat(2, 32) # TODO: Needs improvement. @pytest.mark.parametrize("only_if_banned", [True, False, None]) - async def test_unban_chat_member(self, monkeypatch, bot, only_if_banned): + async def test_unban_chat_member(self, monkeypatch, offline_bot, only_if_banned): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters chat_id = data["chat_id"] == 2 @@ -1203,21 +1214,21 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): o_i_b = data.get("only_if_banned", None) == only_if_banned return chat_id and user_id and o_i_b - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.unban_chat_member(2, 32, only_if_banned=only_if_banned) + assert await offline_bot.unban_chat_member(2, 32, only_if_banned=only_if_banned) - async def test_unban_chat_sender_chat(self, monkeypatch, bot): + async def test_unban_chat_sender_chat(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters chat_id = data["chat_id"] == "2" sender_chat_id = data["sender_chat_id"] == "32" return chat_id and sender_chat_id - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.unban_chat_sender_chat(2, 32) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.unban_chat_sender_chat(2, 32) - async def test_set_chat_permissions(self, monkeypatch, bot, chat_permissions): + async def test_set_chat_permissions(self, monkeypatch, offline_bot, chat_permissions): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters chat_id = data["chat_id"] == "2" @@ -1225,11 +1236,11 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): use_independent_chat_permissions = data["use_independent_chat_permissions"] return chat_id and permissions and use_independent_chat_permissions - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.set_chat_permissions(2, chat_permissions, True) + assert await offline_bot.set_chat_permissions(2, chat_permissions, True) - async def test_set_chat_administrator_custom_title(self, monkeypatch, bot): + async def test_set_chat_administrator_custom_title(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters chat_id = data["chat_id"] == 2 @@ -1237,11 +1248,11 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): custom_title = data["custom_title"] == "custom_title" return chat_id and user_id and custom_title - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.set_chat_administrator_custom_title(2, 32, "custom_title") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.set_chat_administrator_custom_title(2, 32, "custom_title") # TODO: Needs improvement. Need an incoming callbackquery to test - async def test_answer_callback_query(self, monkeypatch, bot): + async def test_answer_callback_query(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { @@ -1252,27 +1263,27 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "text": "answer", } - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.answer_callback_query( + assert await offline_bot.answer_callback_query( 23, text="answer", show_alert=True, url="no_url", cache_time=1 ) @pytest.mark.parametrize("drop_pending_updates", [True, False]) async def test_set_webhook_delete_webhook_drop_pending_updates( - self, bot, drop_pending_updates, monkeypatch + self, offline_bot, drop_pending_updates, monkeypatch ): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.parameters return data.get("drop_pending_updates") == drop_pending_updates - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.set_webhook("", drop_pending_updates=drop_pending_updates) - assert await bot.delete_webhook(drop_pending_updates=drop_pending_updates) + assert await offline_bot.set_webhook("", drop_pending_updates=drop_pending_updates) + assert await offline_bot.delete_webhook(drop_pending_updates=drop_pending_updates) @pytest.mark.parametrize("local_file", ["str", "Path", False]) - async def test_set_webhook_params(self, bot, monkeypatch, local_file): + async def test_set_webhook_params(self, offline_bot, monkeypatch, local_file): # actually making calls to TG is done in # test_set_webhook_get_webhook_info_and_delete_webhook. Sadly secret_token can't be tested # there so we have this function \o/ @@ -1297,7 +1308,7 @@ async def make_assertion(*args, **_): and kwargs["secret_token"] == "SoSecretToken" ) - monkeypatch.setattr(bot, "_post", make_assertion) + monkeypatch.setattr(offline_bot, "_post", make_assertion) cert_path = data_file("sslcert.pem") if local_file == "str": @@ -1307,7 +1318,7 @@ async def make_assertion(*args, **_): else: certificate = cert_path.read_bytes() - assert await bot.set_webhook( + assert await offline_bot.set_webhook( "example.com", certificate, 7, @@ -1318,7 +1329,7 @@ async def make_assertion(*args, **_): ) # TODO: Needs improvement. Need incoming shipping queries to test - async def test_answer_shipping_query_ok(self, monkeypatch, bot): + async def test_answer_shipping_query_ok(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { @@ -1329,11 +1340,13 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): ], } - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) shipping_options = ShippingOption(1, "option1", [LabeledPrice("price", 100)]) - assert await bot.answer_shipping_query(1, True, shipping_options=[shipping_options]) + assert await offline_bot.answer_shipping_query( + 1, True, shipping_options=[shipping_options] + ) - async def test_answer_shipping_query_error_message(self, monkeypatch, bot): + async def test_answer_shipping_query_error_message(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { @@ -1342,19 +1355,19 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "ok": False, } - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.answer_shipping_query(1, False, error_message="Not enough fish") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.answer_shipping_query(1, False, error_message="Not enough fish") # TODO: Needs improvement. Need incoming pre checkout queries to test - async def test_answer_pre_checkout_query_ok(self, monkeypatch, bot): + async def test_answer_pre_checkout_query_ok(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == {"pre_checkout_query_id": 1, "ok": True} - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.answer_pre_checkout_query(1, True) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.answer_pre_checkout_query(1, True) - async def test_answer_pre_checkout_query_error_message(self, monkeypatch, bot): + async def test_answer_pre_checkout_query_error_message(self, monkeypatch, offline_bot): # For now just test that our internals pass the correct data async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters == { @@ -1363,10 +1376,12 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "ok": False, } - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.answer_pre_checkout_query(1, False, error_message="Not enough fish") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.answer_pre_checkout_query( + 1, False, error_message="Not enough fish" + ) - async def test_restrict_chat_member(self, bot, chat_permissions, monkeypatch): + async def test_restrict_chat_member(self, offline_bot, chat_permissions, monkeypatch): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters chat_id = data["chat_id"] == "@chat" @@ -1382,9 +1397,9 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): and use_independent_chat_permissions ) - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.restrict_chat_member("@chat", 2, chat_permissions, 200, True) + assert await offline_bot.restrict_chat_member("@chat", 2, chat_permissions, 200, True) async def test_restrict_chat_member_default_tz( self, monkeypatch, tz_bot, channel_id, chat_permissions @@ -1406,10 +1421,10 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): ) @pytest.mark.parametrize("local_mode", [True, False]) - async def test_set_chat_photo_local_files(self, monkeypatch, bot, chat_id, local_mode): + async def test_set_chat_photo_local_files(self, monkeypatch, offline_bot, chat_id, local_mode): try: - bot._local_mode = local_mode - # For just test that the correct paths are passed as we have no local bot API set up + offline_bot._local_mode = local_mode + # For just test that the correct paths are passed as we have no local Bot API set up self.test_flag = False file = data_file("telegram.jpg") expected = file.as_uri() @@ -1420,13 +1435,13 @@ async def make_assertion(_, data, *args, **kwargs): else: self.test_flag = isinstance(data.get("photo"), InputFile) - monkeypatch.setattr(bot, "_post", make_assertion) - await bot.set_chat_photo(chat_id, file) + monkeypatch.setattr(offline_bot, "_post", make_assertion) + await offline_bot.set_chat_photo(chat_id, file) assert self.test_flag finally: - bot._local_mode = False + offline_bot._local_mode = False - async def test_timeout_propagation_explicit(self, monkeypatch, bot, chat_id): + async def test_timeout_propagation_explicit(self, monkeypatch, offline_bot, chat_id): # Use BaseException that's not a subclass of Exception such that # OkException should not be caught anywhere class OkException(BaseException): @@ -1441,19 +1456,19 @@ async def do_request(*args, **kwargs): return 200, b'{"ok": true, "result": []}' - monkeypatch.setattr(bot.request, "do_request", do_request) + monkeypatch.setattr(offline_bot.request, "do_request", do_request) # Test file uploading with pytest.raises(OkException): - await bot.send_photo( + await offline_bot.send_photo( chat_id, data_file("telegram.jpg").open("rb"), read_timeout=timeout ) # Test JSON submission with pytest.raises(OkException): - await bot.get_chat_administrators(chat_id, read_timeout=timeout) + await offline_bot.get_chat_administrators(chat_id, read_timeout=timeout) - async def test_timeout_propagation_implicit(self, monkeypatch, bot, chat_id): + async def test_timeout_propagation_implicit(self, monkeypatch, offline_bot, chat_id): # Use BaseException that's not a subclass of Exception such that # OkException should not be caught anywhere class OkException(BaseException): @@ -1467,33 +1482,34 @@ async def request(*args, **kwargs): return 200, b'{"ok": true, "result": []}' monkeypatch.setattr(httpx.AsyncClient, "request", request) + monkeypatch.setattr(offline_bot, "_request", (object(), HTTPXRequest())) # Test file uploading with pytest.raises(OkException): - await bot.send_photo(chat_id, data_file("telegram.jpg").open("rb")) + await offline_bot.send_photo(chat_id, data_file("telegram.jpg").open("rb")) - async def test_log_out(self, monkeypatch, bot): + async def test_log_out(self, monkeypatch, offline_bot): # We don't actually make a request as to not break the test setup async def assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters == {} and url.split("/")[-1] == "logOut" - monkeypatch.setattr(bot.request, "post", assertion) + monkeypatch.setattr(offline_bot.request, "post", assertion) - assert await bot.log_out() + assert await offline_bot.log_out() - async def test_close(self, monkeypatch, bot): + async def test_close(self, monkeypatch, offline_bot): # We don't actually make a request as to not break the test setup async def assertion(url, request_data: RequestData, *args, **kwargs): return request_data.json_parameters == {} and url.split("/")[-1] == "close" - monkeypatch.setattr(bot.request, "post", assertion) + monkeypatch.setattr(offline_bot.request, "post", assertion) - assert await bot.close() + assert await offline_bot.close() @pytest.mark.parametrize("json_keyboard", [True, False]) @pytest.mark.parametrize("caption", ["Test", "", None]) async def test_copy_message( - self, monkeypatch, bot, chat_id, media_message, json_keyboard, caption + self, monkeypatch, offline_bot, chat_id, media_message, json_keyboard, caption ): keyboard = InlineKeyboardMarkup( [[InlineKeyboardButton(text="test", callback_data="test2")]] @@ -1525,8 +1541,8 @@ async def post(url, request_data: RequestData, *args, **kwargs): pytest.fail("I got wrong parameters in post") return data - monkeypatch.setattr(bot.request, "post", post) - await bot.copy_message( + monkeypatch.setattr(offline_bot.request, "post", post) + await offline_bot.copy_message( chat_id, from_chat_id=chat_id, message_id=media_message.message_id, @@ -1557,7 +1573,7 @@ async def test_callback_data_maxsize(self, bot_info, acd_in, maxsize): async def test_arbitrary_callback_data_no_insert(self, monkeypatch, cdc_bot): """Updates that don't need insertion shouldn't fail obviously""" - bot = cdc_bot + offline_bot = cdc_bot async def post(*args, **kwargs): update = Update( @@ -1577,14 +1593,14 @@ async def post(*args, **kwargs): try: monkeypatch.setattr(BaseRequest, "post", post) - updates = await bot.get_updates(timeout=1) + updates = await offline_bot.get_updates(timeout=1) assert len(updates) == 1 assert updates[0].update_id == 17 assert updates[0].poll.id == "42" finally: - bot.callback_data_cache.clear_callback_data() - bot.callback_data_cache.clear_callback_queries() + offline_bot.callback_data_cache.clear_callback_data() + offline_bot.callback_data_cache.clear_callback_queries() @pytest.mark.parametrize( "message_type", ["channel_post", "edited_channel_post", "message", "edited_message"] @@ -1592,7 +1608,7 @@ async def post(*args, **kwargs): async def test_arbitrary_callback_data_pinned_message_reply_to_message( self, cdc_bot, monkeypatch, message_type ): - bot = cdc_bot + offline_bot = cdc_bot reply_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text="text", callback_data="callback_data") @@ -1602,11 +1618,11 @@ async def test_arbitrary_callback_data_pinned_message_reply_to_message( 1, dtm.datetime.utcnow(), None, - reply_markup=bot.callback_data_cache.process_keyboard(reply_markup), + reply_markup=offline_bot.callback_data_cache.process_keyboard(reply_markup), ) message._unfreeze() # We do to_dict -> de_json to make sure those aren't the same objects - message.pinned_message = Message.de_json(message.to_dict(), bot) + message.pinned_message = Message.de_json(message.to_dict(), offline_bot) async def post(*args, **kwargs): update = Update( @@ -1617,7 +1633,7 @@ async def post(*args, **kwargs): dtm.datetime.utcnow(), None, pinned_message=message, - reply_to_message=Message.de_json(message.to_dict(), bot), + reply_to_message=Message.de_json(message.to_dict(), offline_bot), ) }, ) @@ -1625,7 +1641,7 @@ async def post(*args, **kwargs): try: monkeypatch.setattr(BaseRequest, "post", post) - updates = await bot.get_updates(timeout=1) + updates = await offline_bot.get_updates(timeout=1) assert isinstance(updates, tuple) assert len(updates) == 1 @@ -1646,11 +1662,11 @@ async def post(*args, **kwargs): ) finally: - bot.callback_data_cache.clear_callback_data() - bot.callback_data_cache.clear_callback_queries() + offline_bot.callback_data_cache.clear_callback_data() + offline_bot.callback_data_cache.clear_callback_queries() async def test_get_updates_invalid_callback_data(self, cdc_bot, monkeypatch): - bot = cdc_bot + offline_bot = cdc_bot async def post(*args, **kwargs): return [ @@ -1674,7 +1690,7 @@ async def post(*args, **kwargs): try: monkeypatch.setattr(BaseRequest, "post", post) - updates = await bot.get_updates(timeout=1) + updates = await offline_bot.get_updates(timeout=1) assert isinstance(updates, tuple) assert len(updates) == 1 @@ -1682,12 +1698,12 @@ async def post(*args, **kwargs): finally: # Reset b/c bots scope is session - bot.callback_data_cache.clear_callback_data() - bot.callback_data_cache.clear_callback_queries() + offline_bot.callback_data_cache.clear_callback_data() + offline_bot.callback_data_cache.clear_callback_queries() # TODO: Needs improvement. We need incoming inline query to test answer. async def test_replace_callback_data_answer_inline_query(self, monkeypatch, cdc_bot, chat_id): - bot = cdc_bot + offline_bot = cdc_bot # For now just test that our internals pass the correct data async def make_assertion( @@ -1704,7 +1720,7 @@ async def make_assertion( inline_keyboard[0][0].callback_data[32:], ) assertion_3 = ( - bot.callback_data_cache._keyboard_data[keyboard].button_data[button] + offline_bot.callback_data_cache._keyboard_data[keyboard].button_data[button] == "replace_test" ) assertion_4 = data["results"][1].reply_markup is None @@ -1713,7 +1729,7 @@ async def make_assertion( try: replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test") no_replace_button = InlineKeyboardButton( - text="no_replace", url="http://python-telegram-bot.org/" + text="no_replace", url="http://python-telegram-offline_bot.org/" ) reply_markup = InlineKeyboardMarkup.from_row( [ @@ -1722,24 +1738,25 @@ async def make_assertion( ] ) - bot.username # call this here so `bot.get_me()` won't be called after mocking - monkeypatch.setattr(bot, "_post", make_assertion) + # call this here so `offline_bot.get_me()` won't be called after mocking + offline_bot.username + monkeypatch.setattr(offline_bot, "_post", make_assertion) results = [ InlineQueryResultArticle( "11", "first", InputTextMessageContent("first"), reply_markup=reply_markup ), InlineQueryResultVoice( "22", - "https://python-telegram-bot.org/static/testfiles/telegram.ogg", + "https://python-telegram-offline_bot.org/static/testfiles/telegram.ogg", title="second", ), ] - assert await bot.answer_inline_query(chat_id, results=results) + assert await offline_bot.answer_inline_query(chat_id, results=results) finally: - bot.callback_data_cache.clear_callback_data() - bot.callback_data_cache.clear_callback_queries() + offline_bot.callback_data_cache.clear_callback_data() + offline_bot.callback_data_cache.clear_callback_queries() @pytest.mark.parametrize( "message_type", ["channel_post", "edited_channel_post", "message", "edited_message"] @@ -1813,7 +1830,7 @@ async def test_http2_runtime_error(self, recwarn, bot_class): assert warning.filename == __file__, "wrong stacklevel!" assert warning.category is PTBUserWarning - async def test_set_get_my_name(self, bot, monkeypatch): + async def test_set_get_my_name(self, offline_bot, monkeypatch): """We only test that we pass the correct values to TG since this endpoint is heavily rate limited which makes automated tests rather infeasible.""" default_name = "default_bot_name" @@ -1853,20 +1870,20 @@ async def post(url, request_data: RequestData, *args, **kwargs): get_stack.task_done() return bot_name - monkeypatch.setattr(bot.request, "post", post) + monkeypatch.setattr(offline_bot.request, "post", post) # Set the names assert all( await asyncio.gather( - bot.set_my_name(default_name), - bot.set_my_name(en_name, language_code="en"), - bot.set_my_name(de_name, language_code="de"), + offline_bot.set_my_name(default_name), + offline_bot.set_my_name(en_name, language_code="en"), + offline_bot.set_my_name(de_name, language_code="de"), ) ) # Check that they were set correctly assert await asyncio.gather( - bot.get_my_name(), bot.get_my_name("en"), bot.get_my_name("de") + offline_bot.get_my_name(), offline_bot.get_my_name("en"), offline_bot.get_my_name("de") ) == [ BotName(default_name), BotName(en_name), @@ -1876,18 +1893,18 @@ async def post(url, request_data: RequestData, *args, **kwargs): # Delete the names assert all( await asyncio.gather( - bot.set_my_name(default_name), - bot.set_my_name(None, language_code="en"), - bot.set_my_name(None, language_code="de"), + offline_bot.set_my_name(default_name), + offline_bot.set_my_name(None, language_code="en"), + offline_bot.set_my_name(None, language_code="de"), ) ) # Check that they were deleted correctly assert await asyncio.gather( - bot.get_my_name(), bot.get_my_name("en"), bot.get_my_name("de") + offline_bot.get_my_name(), offline_bot.get_my_name("en"), offline_bot.get_my_name("de") ) == 3 * [BotName(default_name)] - async def test_set_message_reaction(self, bot, monkeypatch): + async def test_set_message_reaction(self, offline_bot, monkeypatch): """This is here so we can test the convenient conversion we do in the function without having to do multiple requests to Telegram""" @@ -1918,14 +1935,22 @@ async def post(url, request_data: RequestData, *args, **kwargs): assert request_data.parameters["reaction"] == expected_param[amount] amount += 1 - monkeypatch.setattr(bot.request, "post", post) - await bot.set_message_reaction(1, 2, [ReactionTypeEmoji(ReactionEmoji.THUMBS_UP)], True) - await bot.set_message_reaction(1, 2, ReactionTypeEmoji(ReactionEmoji.RED_HEART), True) - await bot.set_message_reaction(1, 2, [ReactionTypeCustomEmoji("custom_emoji_1")], True) - await bot.set_message_reaction(1, 2, ReactionTypeCustomEmoji("custom_emoji_2"), True) - await bot.set_message_reaction(1, 2, ReactionEmoji.THUMBS_DOWN, True) - await bot.set_message_reaction(1, 2, "custom_emoji_3", True) - await bot.set_message_reaction( + monkeypatch.setattr(offline_bot.request, "post", post) + await offline_bot.set_message_reaction( + 1, 2, [ReactionTypeEmoji(ReactionEmoji.THUMBS_UP)], True + ) + await offline_bot.set_message_reaction( + 1, 2, ReactionTypeEmoji(ReactionEmoji.RED_HEART), True + ) + await offline_bot.set_message_reaction( + 1, 2, [ReactionTypeCustomEmoji("custom_emoji_1")], True + ) + await offline_bot.set_message_reaction( + 1, 2, ReactionTypeCustomEmoji("custom_emoji_2"), True + ) + await offline_bot.set_message_reaction(1, 2, ReactionEmoji.THUMBS_DOWN, True) + await offline_bot.set_message_reaction(1, 2, "custom_emoji_3", True) + await offline_bot.set_message_reaction( 1, 2, [ @@ -2047,7 +2072,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): reply_parameters=ReplyParameters(**kwargs), ) - async def test_send_poll_question_parse_mode_entities(self, bot, monkeypatch): + async def test_send_poll_question_parse_mode_entities(self, offline_bot, monkeypatch): # Currently only custom emoji are supported as entities which we can't test # We just test that the correct data is passed for now @@ -2059,8 +2084,8 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): assert request_data.parameters["question_parse_mode"] == ParseMode.MARKDOWN_V2 return make_message("dummy reply").to_dict() - monkeypatch.setattr(bot.request, "post", make_assertion) - await bot.send_poll( + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + await offline_bot.send_poll( 1, question="😀😃", options=["option1", "option2"], @@ -2123,15 +2148,15 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): monkeypatch.setattr(default_bot.request, "post", make_assertion) await default_bot.copy_message(chat_id, 1, 1, reply_parameters=ReplyParameters(**kwargs)) - async def test_do_api_request_camel_case_conversion(self, bot, monkeypatch): + async def test_do_api_request_camel_case_conversion(self, offline_bot, monkeypatch): async def make_assertion(url, request_data: RequestData, *args, **kwargs): return url.endswith("camelCase") - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.do_api_request("camel_case") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.do_api_request("camel_case") @pytest.mark.filterwarnings("ignore::telegram.warnings.PTBUserWarning") - async def test_do_api_request_media_write_timeout(self, bot, chat_id, monkeypatch): + async def test_do_api_request_media_write_timeout(self, offline_bot, chat_id, monkeypatch): test_flag = None class CustomRequest(BaseRequest): @@ -2153,8 +2178,8 @@ async def do_request(self_, *args, **kwargs) -> Tuple[int, bytes]: custom_request = CustomRequest() - bot = Bot(bot.token, request=custom_request) - await bot.do_api_request( + offline_bot = Bot(offline_bot.token, request=custom_request) + await offline_bot.do_api_request( "send_document", api_kwargs={ "chat_id": chat_id, @@ -2194,7 +2219,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): api_kwargs={"chat_id": 2, "user_id": 32, "until_date": until_timestamp}, ) - async def test_business_connection_id_argument(self, bot, monkeypatch): + async def test_business_connection_id_argument(self, offline_bot, monkeypatch): """We can't connect to a business acc, so we just test that the correct data is passed. We also can't test every single method easily, so we just test a few. Our linting will catch any unused args with the others.""" @@ -2203,24 +2228,24 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): assert request_data.parameters.get("business_connection_id") == 42 return {} - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - await bot.send_message(2, "text", business_connection_id=42) - await bot.stop_poll(chat_id=1, message_id=2, business_connection_id=42) - await bot.pin_chat_message(chat_id=1, message_id=2, business_connection_id=42) - await bot.unpin_chat_message(chat_id=1, business_connection_id=42) + await offline_bot.send_message(2, "text", business_connection_id=42) + await offline_bot.stop_poll(chat_id=1, message_id=2, business_connection_id=42) + await offline_bot.pin_chat_message(chat_id=1, message_id=2, business_connection_id=42) + await offline_bot.unpin_chat_message(chat_id=1, business_connection_id=42) - async def test_message_effect_id_argument(self, bot, monkeypatch): + async def test_message_effect_id_argument(self, offline_bot, monkeypatch): """We can't test every single method easily, so we just test one. Our linting will catch any unused args with the others.""" async def make_assertion(url, request_data: RequestData, *args, **kwargs): return request_data.parameters.get("message_effect_id") == 42 - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.send_message(2, "text", message_effect_id=42) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.send_message(2, "text", message_effect_id=42) - async def test_get_business_connection(self, bot, monkeypatch): + async def test_get_business_connection(self, offline_bot, monkeypatch): bci = "42" user = User(1, "first", False) user_chat_id = 1 @@ -2236,11 +2261,11 @@ async def do_request(*args, **kwargs): return 200, f'{{"ok": true, "result": {bc}}}'.encode() return 400, b'{"ok": false, "result": []}' - monkeypatch.setattr(bot.request, "do_request", do_request) - obj = await bot.get_business_connection(business_connection_id=bci) + monkeypatch.setattr(offline_bot.request, "do_request", do_request) + obj = await offline_bot.get_business_connection(business_connection_id=bci) assert isinstance(obj, BusinessConnection) - async def test_refund_star_payment(self, bot, monkeypatch): + async def test_refund_star_payment(self, offline_bot, monkeypatch): # can't make actual request so we just test that the correct data is passed async def make_assertion(url, request_data: RequestData, *args, **kwargs): return ( @@ -2248,10 +2273,10 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): and request_data.parameters.get("telegram_payment_charge_id") == "37" ) - monkeypatch.setattr(bot.request, "post", make_assertion) - assert await bot.refund_star_payment(42, "37") + monkeypatch.setattr(offline_bot.request, "post", make_assertion) + assert await offline_bot.refund_star_payment(42, "37") - async def test_get_star_transactions(self, bot, monkeypatch): + async def test_get_star_transactions(self, offline_bot, monkeypatch): # we just want to test the offset parameter st = StarTransactions([StarTransaction("1", 1, dtm.datetime.now())]).to_json() @@ -2261,14 +2286,14 @@ async def do_request(url, request_data: RequestData, *args, **kwargs): return 200, f'{{"ok": true, "result": {st}}}'.encode() return 400, b'{"ok": false, "result": []}' - monkeypatch.setattr(bot.request, "do_request", do_request) - obj = await bot.get_star_transactions(offset=3) + monkeypatch.setattr(offline_bot.request, "do_request", do_request) + obj = await offline_bot.get_star_transactions(offset=3) assert isinstance(obj, StarTransactions) async def test_create_chat_subscription_invite_link( self, monkeypatch, - bot, + offline_bot, ): # Since the chat invite link object does not say if the sub args are passed we can # only check here @@ -2276,9 +2301,9 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): assert request_data.parameters.get("subscription_period") == 2592000 assert request_data.parameters.get("subscription_price") == 6 - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - await bot.create_chat_subscription_invite_link(1234, 2592000, 6) + await offline_bot.create_chat_subscription_invite_link(1234, 2592000, 6) class TestBotWithRequest: diff --git a/tests/test_botcommand.py b/tests/test_botcommand.py index 1e4a360e065..f38abb320ab 100644 --- a/tests/test_botcommand.py +++ b/tests/test_botcommand.py @@ -37,15 +37,15 @@ def test_slot_behaviour(self, bot_command): assert getattr(bot_command, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(bot_command)) == len(set(mro_slots(bot_command))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = {"command": self.command, "description": self.description} - bot_command = BotCommand.de_json(json_dict, bot) + bot_command = BotCommand.de_json(json_dict, offline_bot) assert bot_command.api_kwargs == {} assert bot_command.command == self.command assert bot_command.description == self.description - assert BotCommand.de_json(None, bot) is None + assert BotCommand.de_json(None, offline_bot) is None def test_to_dict(self, bot_command): bot_command_dict = bot_command.to_dict() diff --git a/tests/test_botcommandscope.py b/tests/test_botcommandscope.py index 63766b95e17..a4bddfc8f69 100644 --- a/tests/test_botcommandscope.py +++ b/tests/test_botcommandscope.py @@ -125,14 +125,14 @@ def test_slot_behaviour(self, bot_command_scope): set(mro_slots(bot_command_scope)) ), "duplicate slot" - def test_de_json(self, bot, scope_class_and_type, chat_id): + def test_de_json(self, offline_bot, scope_class_and_type, chat_id): cls = scope_class_and_type[0] type_ = scope_class_and_type[1] - assert cls.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None json_dict = {"type": type_, "chat_id": chat_id, "user_id": 42} - bot_command_scope = BotCommandScope.de_json(json_dict, bot) + bot_command_scope = BotCommandScope.de_json(json_dict, offline_bot) assert set(bot_command_scope.api_kwargs.keys()) == {"chat_id", "user_id"} - set( cls.__slots__ ) @@ -145,18 +145,18 @@ def test_de_json(self, bot, scope_class_and_type, chat_id): if "user_id" in cls.__slots__: assert bot_command_scope.user_id == 42 - def test_de_json_invalid_type(self, bot): + def test_de_json_invalid_type(self, offline_bot): json_dict = {"type": "invalid", "chat_id": chat_id, "user_id": 42} - bot_command_scope = BotCommandScope.de_json(json_dict, bot) + bot_command_scope = BotCommandScope.de_json(json_dict, offline_bot) assert type(bot_command_scope) is BotCommandScope assert bot_command_scope.type == "invalid" - def test_de_json_subclass(self, scope_class, bot, chat_id): + def test_de_json_subclass(self, scope_class, offline_bot, chat_id): """This makes sure that e.g. BotCommandScopeDefault(data) never returns a BotCommandScopeChat instance.""" json_dict = {"type": "invalid", "chat_id": chat_id, "user_id": 42} - assert type(scope_class.de_json(json_dict, bot)) is scope_class + assert type(scope_class.de_json(json_dict, offline_bot)) is scope_class def test_to_dict(self, bot_command_scope): bot_command_scope_dict = bot_command_scope.to_dict() @@ -172,7 +172,7 @@ def test_type_enum_conversion(self): assert type(BotCommandScope("default").type) is BotCommandScopeType assert BotCommandScope("unknown").type == "unknown" - def test_equality(self, bot_command_scope, bot): + def test_equality(self, bot_command_scope, offline_bot): a = BotCommandScope("base_type") b = BotCommandScope("base_type") c = bot_command_scope @@ -200,7 +200,7 @@ def test_equality(self, bot_command_scope, bot): if hasattr(c, "chat_id"): json_dict = c.to_dict() json_dict["chat_id"] = 0 - f = c.__class__.de_json(json_dict, bot) + f = c.__class__.de_json(json_dict, offline_bot) assert c != f assert hash(c) != hash(f) @@ -208,7 +208,7 @@ def test_equality(self, bot_command_scope, bot): if hasattr(c, "user_id"): json_dict = c.to_dict() json_dict["user_id"] = 0 - g = c.__class__.de_json(json_dict, bot) + g = c.__class__.de_json(json_dict, offline_bot) assert c != g assert hash(c) != hash(g) diff --git a/tests/test_business.py b/tests/test_business.py index 735f2e7177a..e3da3694804 100644 --- a/tests/test_business.py +++ b/tests/test_business.py @@ -139,7 +139,7 @@ def test_de_json(self): assert bc.api_kwargs == {} assert isinstance(bc, BusinessConnection) - def test_de_json_localization(self, bot, raw_bot, tz_bot): + def test_de_json_localization(self, offline_bot, raw_bot, tz_bot): json_dict = { "id": self.id_, "user": self.user.to_dict(), @@ -148,7 +148,7 @@ def test_de_json_localization(self, bot, raw_bot, tz_bot): "can_reply": self.can_reply, "is_enabled": self.is_enabled, } - chat_bot = BusinessConnection.de_json(json_dict, bot) + chat_bot = BusinessConnection.de_json(json_dict, offline_bot) chat_bot_raw = BusinessConnection.de_json(json_dict, raw_bot) chat_bot_tz = BusinessConnection.de_json(json_dict, tz_bot) diff --git a/tests/test_callbackquery.py b/tests/test_callbackquery.py index 3131b34f249..7a53651a3fa 100644 --- a/tests/test_callbackquery.py +++ b/tests/test_callbackquery.py @@ -94,7 +94,7 @@ def test_slot_behaviour(self, callback_query): assert getattr(callback_query, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(callback_query)) == len(set(mro_slots(callback_query))), "same slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "from": self.from_user.to_dict(), @@ -104,7 +104,7 @@ def test_de_json(self, bot): "inline_message_id": self.inline_message_id, "game_short_name": self.game_short_name, } - callback_query = CallbackQuery.de_json(json_dict, bot) + callback_query = CallbackQuery.de_json(json_dict, offline_bot) assert callback_query.api_kwargs == {} assert callback_query.id == self.id_ diff --git a/tests/test_chat.py b/tests/test_chat.py index a3dcd6aa17f..adf2c42bc3c 100644 --- a/tests/test_chat.py +++ b/tests/test_chat.py @@ -63,7 +63,7 @@ def test_slot_behaviour(self, chat): assert getattr(chat, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(chat)) == len(set(mro_slots(chat))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "title": self.title, @@ -73,7 +73,7 @@ def test_de_json(self, bot): "first_name": self.first_name, "last_name": self.last_name, } - chat = Chat.de_json(json_dict, bot) + chat = Chat.de_json(json_dict, offline_bot) assert chat.id == self.id_ assert chat.title == self.title diff --git a/tests/test_chatadministratorrights.py b/tests/test_chatadministratorrights.py index e630693c2d7..e15de43c730 100644 --- a/tests/test_chatadministratorrights.py +++ b/tests/test_chatadministratorrights.py @@ -50,7 +50,7 @@ def test_slot_behaviour(self, chat_admin_rights): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, chat_admin_rights): + def test_de_json(self, offline_bot, chat_admin_rights): json_dict = { "can_change_info": True, "can_delete_messages": True, @@ -68,7 +68,7 @@ def test_de_json(self, bot, chat_admin_rights): "can_edit_stories": True, "can_delete_stories": True, } - chat_administrator_rights_de = ChatAdministratorRights.de_json(json_dict, bot) + chat_administrator_rights_de = ChatAdministratorRights.de_json(json_dict, offline_bot) assert chat_administrator_rights_de.api_kwargs == {} assert chat_admin_rights == chat_administrator_rights_de diff --git a/tests/test_chatbackground.py b/tests/test_chatbackground.py index 900fc58709f..ccf90d41147 100644 --- a/tests/test_chatbackground.py +++ b/tests/test_chatbackground.py @@ -168,12 +168,12 @@ def test_slot_behaviour(self, background_type): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json_required_args(self, bot, background_type): + def test_de_json_required_args(self, offline_bot, background_type): cls = background_type.__class__ - assert cls.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None json_dict = make_json_dict(background_type) - const_background_type = BackgroundType.de_json(json_dict, bot) + const_background_type = BackgroundType.de_json(json_dict, offline_bot) assert const_background_type.api_kwargs == {} assert isinstance(const_background_type, BackgroundType) @@ -181,9 +181,9 @@ def test_de_json_required_args(self, bot, background_type): for bg_type_at, const_bg_type_at in iter_args(background_type, const_background_type): assert bg_type_at == const_bg_type_at - def test_de_json_all_args(self, bot, background_type): + def test_de_json_all_args(self, offline_bot, background_type): json_dict = make_json_dict(background_type, include_optional_args=True) - const_background_type = BackgroundType.de_json(json_dict, bot) + const_background_type = BackgroundType.de_json(json_dict, offline_bot) assert const_background_type.api_kwargs == {} @@ -194,19 +194,19 @@ def test_de_json_all_args(self, bot, background_type): ): assert bg_type_at == const_bg_type_at - def test_de_json_invalid_type(self, background_type, bot): + def test_de_json_invalid_type(self, background_type, offline_bot): json_dict = {"type": "invalid", "theme_name": BTDefaults.theme_name} - background_type = BackgroundType.de_json(json_dict, bot) + background_type = BackgroundType.de_json(json_dict, offline_bot) assert type(background_type) is BackgroundType assert background_type.type == "invalid" - def test_de_json_subclass(self, background_type, bot, chat_id): - """This makes sure that e.g. BackgroundTypeFill(data, bot) never returns a + def test_de_json_subclass(self, background_type, offline_bot, chat_id): + """This makes sure that e.g. BackgroundTypeFill(data, offline_bot) never returns a BackgroundTypeWallpaper instance.""" cls = background_type.__class__ json_dict = make_json_dict(background_type, True) - assert type(cls.de_json(json_dict, bot)) is cls + assert type(cls.de_json(json_dict, offline_bot)) is cls def test_to_dict(self, background_type): bg_type_dict = background_type.to_dict() @@ -275,12 +275,12 @@ def test_slot_behaviour(self, background_fill): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json_required_args(self, bot, background_fill): + def test_de_json_required_args(self, offline_bot, background_fill): cls = background_fill.__class__ - assert cls.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None json_dict = make_json_dict(background_fill) - const_background_fill = BackgroundFill.de_json(json_dict, bot) + const_background_fill = BackgroundFill.de_json(json_dict, offline_bot) assert const_background_fill.api_kwargs == {} assert isinstance(const_background_fill, BackgroundFill) @@ -288,9 +288,9 @@ def test_de_json_required_args(self, bot, background_fill): for bg_fill_at, const_bg_fill_at in iter_args(background_fill, const_background_fill): assert bg_fill_at == const_bg_fill_at - def test_de_json_all_args(self, bot, background_fill): + def test_de_json_all_args(self, offline_bot, background_fill): json_dict = make_json_dict(background_fill, include_optional_args=True) - const_background_fill = BackgroundFill.de_json(json_dict, bot) + const_background_fill = BackgroundFill.de_json(json_dict, offline_bot) assert const_background_fill.api_kwargs == {} @@ -301,19 +301,19 @@ def test_de_json_all_args(self, bot, background_fill): ): assert bg_fill_at == const_bg_fill_at - def test_de_json_invalid_type(self, background_fill, bot): + def test_de_json_invalid_type(self, background_fill, offline_bot): json_dict = {"type": "invalid", "theme_name": BTDefaults.theme_name} - background_fill = BackgroundFill.de_json(json_dict, bot) + background_fill = BackgroundFill.de_json(json_dict, offline_bot) assert type(background_fill) is BackgroundFill assert background_fill.type == "invalid" - def test_de_json_subclass(self, background_fill, bot): - """This makes sure that e.g. BackgroundFillSolid(data, bot) never returns a + def test_de_json_subclass(self, background_fill, offline_bot): + """This makes sure that e.g. BackgroundFillSolid(data, offline_bot) never returns a BackgroundFillGradient instance.""" cls = background_fill.__class__ json_dict = make_json_dict(background_fill, True) - assert type(cls.de_json(json_dict, bot)) is cls + assert type(cls.de_json(json_dict, offline_bot)) is cls def test_to_dict(self, background_fill): bg_fill_dict = background_fill.to_dict() diff --git a/tests/test_chatboost.py b/tests/test_chatboost.py index f0ef143618a..62123df73dc 100644 --- a/tests/test_chatboost.py +++ b/tests/test_chatboost.py @@ -170,13 +170,13 @@ def test_slot_behaviour(self, chat_boost_source): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json_required_args(self, bot, chat_boost_source): + def test_de_json_required_args(self, offline_bot, chat_boost_source): cls = chat_boost_source.__class__ - assert cls.de_json({}, bot) is None - assert ChatBoost.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None + assert ChatBoost.de_json({}, offline_bot) is None json_dict = make_json_dict(chat_boost_source) - const_boost_source = ChatBoostSource.de_json(json_dict, bot) + const_boost_source = ChatBoostSource.de_json(json_dict, offline_bot) assert const_boost_source.api_kwargs == {} assert isinstance(const_boost_source, ChatBoostSource) @@ -186,9 +186,9 @@ def test_de_json_required_args(self, bot, chat_boost_source): ): assert chat_mem_type_at == const_chat_mem_at - def test_de_json_all_args(self, bot, chat_boost_source): + def test_de_json_all_args(self, offline_bot, chat_boost_source): json_dict = make_json_dict(chat_boost_source, include_optional_args=True) - const_boost_source = ChatBoostSource.de_json(json_dict, bot) + const_boost_source = ChatBoostSource.de_json(json_dict, offline_bot) assert const_boost_source.api_kwargs == {} assert isinstance(const_boost_source, ChatBoostSource) @@ -198,19 +198,19 @@ def test_de_json_all_args(self, bot, chat_boost_source): ): assert c_mem_type_at == const_c_mem_at - def test_de_json_invalid_source(self, chat_boost_source, bot): + def test_de_json_invalid_source(self, chat_boost_source, offline_bot): json_dict = {"source": "invalid"} - chat_boost_source = ChatBoostSource.de_json(json_dict, bot) + chat_boost_source = ChatBoostSource.de_json(json_dict, offline_bot) assert type(chat_boost_source) is ChatBoostSource assert chat_boost_source.source == "invalid" - def test_de_json_subclass(self, chat_boost_source, bot): - """This makes sure that e.g. ChatBoostSourcePremium(data, bot) never returns a + def test_de_json_subclass(self, chat_boost_source, offline_bot): + """This makes sure that e.g. ChatBoostSourcePremium(data, offline_bot) never returns a ChatBoostSourceGiftCode instance.""" cls = chat_boost_source.__class__ json_dict = make_json_dict(chat_boost_source, True) - assert type(cls.de_json(json_dict, bot)) is cls + assert type(cls.de_json(json_dict, offline_bot)) is cls def test_to_dict(self, chat_boost_source): chat_boost_dict = chat_boost_source.to_dict() @@ -263,14 +263,14 @@ def test_slot_behaviour(self, chat_boost): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, chat_boost): + def test_de_json(self, offline_bot, chat_boost): json_dict = { "boost_id": "2", "add_date": self.date, "expiration_date": self.date, "source": self.default_source.to_dict(), } - cb = ChatBoost.de_json(json_dict, bot) + cb = ChatBoost.de_json(json_dict, offline_bot) assert isinstance(cb, ChatBoost) assert isinstance(cb.add_date, datetime.datetime) @@ -284,7 +284,7 @@ def test_de_json(self, bot, chat_boost): for slot in cb.__slots__: assert getattr(cb, slot) == getattr(chat_boost, slot), f"attribute {slot} differs" - def test_de_json_localization(self, bot, raw_bot, tz_bot): + def test_de_json_localization(self, offline_bot, raw_bot, tz_bot): json_dict = { "boost_id": "2", "add_date": self.date, @@ -292,7 +292,7 @@ def test_de_json_localization(self, bot, raw_bot, tz_bot): "source": self.default_source.to_dict(), } - cb_bot = ChatBoost.de_json(json_dict, bot) + cb_bot = ChatBoost.de_json(json_dict, offline_bot) cb_raw = ChatBoost.de_json(json_dict, raw_bot) cb_tz = ChatBoost.de_json(json_dict, tz_bot) @@ -347,7 +347,7 @@ def test_slot_behaviour(self, chat_boost_updated): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, chat_boost): + def test_de_json(self, offline_bot, chat_boost): json_dict = { "chat": self.chat.to_dict(), "boost": { @@ -357,7 +357,7 @@ def test_de_json(self, bot, chat_boost): "source": self.default_source.to_dict(), }, } - cbu = ChatBoostUpdated.de_json(json_dict, bot) + cbu = ChatBoostUpdated.de_json(json_dict, offline_bot) assert isinstance(cbu, ChatBoostUpdated) assert cbu.chat == self.chat @@ -420,14 +420,14 @@ def test_slot_behaviour(self, chat_boost_removed): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, chat_boost_removed): + def test_de_json(self, offline_bot, chat_boost_removed): json_dict = { "chat": self.chat.to_dict(), "boost_id": "2", "remove_date": self.date, "source": self.default_source.to_dict(), } - cbr = ChatBoostRemoved.de_json(json_dict, bot) + cbr = ChatBoostRemoved.de_json(json_dict, offline_bot) assert isinstance(cbr, ChatBoostRemoved) assert cbr.chat == self.chat @@ -435,7 +435,7 @@ def test_de_json(self, bot, chat_boost_removed): assert to_timestamp(cbr.remove_date) == self.date assert cbr.source == self.default_source - def test_de_json_localization(self, bot, raw_bot, tz_bot): + def test_de_json_localization(self, offline_bot, raw_bot, tz_bot): json_dict = { "chat": self.chat.to_dict(), "boost_id": "2", @@ -443,7 +443,7 @@ def test_de_json_localization(self, bot, raw_bot, tz_bot): "source": self.default_source.to_dict(), } - cbr_bot = ChatBoostRemoved.de_json(json_dict, bot) + cbr_bot = ChatBoostRemoved.de_json(json_dict, offline_bot) cbr_raw = ChatBoostRemoved.de_json(json_dict, raw_bot) cbr_tz = ChatBoostRemoved.de_json(json_dict, tz_bot) @@ -498,7 +498,7 @@ def test_slot_behaviour(self, user_chat_boosts): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, user_chat_boosts): + def test_de_json(self, offline_bot, user_chat_boosts): json_dict = { "boosts": [ { @@ -509,7 +509,7 @@ def test_de_json(self, bot, user_chat_boosts): } ] } - ucb = UserChatBoosts.de_json(json_dict, bot) + ucb = UserChatBoosts.de_json(json_dict, offline_bot) assert isinstance(ucb, UserChatBoosts) assert isinstance(ucb.boosts[0], ChatBoost) @@ -525,7 +525,7 @@ def test_to_dict(self, user_chat_boosts): assert isinstance(user_chat_boosts_dict["boosts"], list) assert user_chat_boosts_dict["boosts"][0] == user_chat_boosts.boosts[0].to_dict() - async def test_get_user_chat_boosts(self, monkeypatch, bot): + async def test_get_user_chat_boosts(self, monkeypatch, offline_bot): async def make_assertion(url, request_data: RequestData, *args, **kwargs): data = request_data.json_parameters chat_id = data["chat_id"] == "3" @@ -534,9 +534,9 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): pytest.fail("I got wrong parameters in post") return data - monkeypatch.setattr(bot.request, "post", make_assertion) + monkeypatch.setattr(offline_bot.request, "post", make_assertion) - assert await bot.get_user_chat_boosts("3", 2) + assert await offline_bot.get_user_chat_boosts("3", 2) class TestUserChatBoostsWithRequest(ChatBoostDefaults): diff --git a/tests/test_chatfullinfo.py b/tests/test_chatfullinfo.py index 7e5bc90baae..6c105493021 100644 --- a/tests/test_chatfullinfo.py +++ b/tests/test_chatfullinfo.py @@ -150,7 +150,7 @@ def test_slot_behaviour(self, chat_full_info): assert len(mro_slots(cfi)) == len(set(mro_slots(cfi))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "title": self.title, @@ -194,7 +194,7 @@ def test_de_json(self, bot): "last_name": self.last_name, "can_send_paid_media": self.can_send_paid_media, } - cfi = ChatFullInfo.de_json(json_dict, bot) + cfi = ChatFullInfo.de_json(json_dict, offline_bot) assert cfi.id == self.id_ assert cfi.title == self.title assert cfi.type == self.type_ @@ -239,7 +239,7 @@ def test_de_json(self, bot): assert cfi.max_reaction_count == self.max_reaction_count assert cfi.can_send_paid_media == self.can_send_paid_media - def test_de_json_localization(self, bot, raw_bot, tz_bot): + def test_de_json_localization(self, offline_bot, raw_bot, tz_bot): json_dict = { "id": self.id_, "type": self.type_, @@ -247,7 +247,7 @@ def test_de_json_localization(self, bot, raw_bot, tz_bot): "max_reaction_count": self.max_reaction_count, "emoji_status_expiration_date": to_timestamp(self.emoji_status_expiration_date), } - cfi_bot = ChatFullInfo.de_json(json_dict, bot) + cfi_bot = ChatFullInfo.de_json(json_dict, offline_bot) cfi_bot_raw = ChatFullInfo.de_json(json_dict, raw_bot) cfi_bot_tz = ChatFullInfo.de_json(json_dict, tz_bot) diff --git a/tests/test_chatinvitelink.py b/tests/test_chatinvitelink.py index 9331166b466..86ca7afd3ae 100644 --- a/tests/test_chatinvitelink.py +++ b/tests/test_chatinvitelink.py @@ -66,7 +66,7 @@ def test_slot_behaviour(self, invite_link): assert getattr(invite_link, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(invite_link)) == len(set(mro_slots(invite_link))), "duplicate slot" - def test_de_json_required_args(self, bot, creator): + def test_de_json_required_args(self, offline_bot, creator): json_dict = { "invite_link": self.link, "creator": creator.to_dict(), @@ -75,7 +75,7 @@ def test_de_json_required_args(self, bot, creator): "is_revoked": self.revoked, } - invite_link = ChatInviteLink.de_json(json_dict, bot) + invite_link = ChatInviteLink.de_json(json_dict, offline_bot) assert invite_link.api_kwargs == {} assert invite_link.invite_link == self.link @@ -84,7 +84,7 @@ def test_de_json_required_args(self, bot, creator): assert invite_link.is_primary == self.primary assert invite_link.is_revoked == self.revoked - def test_de_json_all_args(self, bot, creator): + def test_de_json_all_args(self, offline_bot, creator): json_dict = { "invite_link": self.link, "creator": creator.to_dict(), @@ -99,7 +99,7 @@ def test_de_json_all_args(self, bot, creator): "subscription_price": self.subscription_price, } - invite_link = ChatInviteLink.de_json(json_dict, bot) + invite_link = ChatInviteLink.de_json(json_dict, offline_bot) assert invite_link.api_kwargs == {} assert invite_link.invite_link == self.link @@ -115,7 +115,7 @@ def test_de_json_all_args(self, bot, creator): assert invite_link.subscription_period == self.subscription_period assert invite_link.subscription_price == self.subscription_price - def test_de_json_localization(self, tz_bot, bot, raw_bot, creator): + def test_de_json_localization(self, tz_bot, offline_bot, raw_bot, creator): json_dict = { "invite_link": self.link, "creator": creator.to_dict(), @@ -129,7 +129,7 @@ def test_de_json_localization(self, tz_bot, bot, raw_bot, creator): } invite_link_raw = ChatInviteLink.de_json(json_dict, raw_bot) - invite_link_bot = ChatInviteLink.de_json(json_dict, bot) + invite_link_bot = ChatInviteLink.de_json(json_dict, offline_bot) invite_link_tz = ChatInviteLink.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable diff --git a/tests/test_chatjoinrequest.py b/tests/test_chatjoinrequest.py index cdf2787e8ea..cf0550c3006 100644 --- a/tests/test_chatjoinrequest.py +++ b/tests/test_chatjoinrequest.py @@ -70,14 +70,14 @@ def test_slot_behaviour(self, chat_join_request): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, time): + def test_de_json(self, offline_bot, time): json_dict = { "chat": self.chat.to_dict(), "from": self.from_user.to_dict(), "date": to_timestamp(time), "user_chat_id": self.from_user.id, } - chat_join_request = ChatJoinRequest.de_json(json_dict, bot) + chat_join_request = ChatJoinRequest.de_json(json_dict, offline_bot) assert chat_join_request.api_kwargs == {} assert chat_join_request.chat == self.chat @@ -87,7 +87,7 @@ def test_de_json(self, bot, time): assert chat_join_request.user_chat_id == self.from_user.id json_dict.update({"bio": self.bio, "invite_link": self.invite_link.to_dict()}) - chat_join_request = ChatJoinRequest.de_json(json_dict, bot) + chat_join_request = ChatJoinRequest.de_json(json_dict, offline_bot) assert chat_join_request.api_kwargs == {} assert chat_join_request.chat == self.chat @@ -98,7 +98,7 @@ def test_de_json(self, bot, time): assert chat_join_request.bio == self.bio assert chat_join_request.invite_link == self.invite_link - def test_de_json_localization(self, tz_bot, bot, raw_bot, time): + def test_de_json_localization(self, tz_bot, offline_bot, raw_bot, time): json_dict = { "chat": self.chat.to_dict(), "from": self.from_user.to_dict(), @@ -107,7 +107,7 @@ def test_de_json_localization(self, tz_bot, bot, raw_bot, time): } chatjoin_req_raw = ChatJoinRequest.de_json(json_dict, raw_bot) - chatjoin_req_bot = ChatJoinRequest.de_json(json_dict, bot) + chatjoin_req_bot = ChatJoinRequest.de_json(json_dict, offline_bot) chatjoin_req_tz = ChatJoinRequest.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable diff --git a/tests/test_chatlocation.py b/tests/test_chatlocation.py index 00481d644d5..b83306308be 100644 --- a/tests/test_chatlocation.py +++ b/tests/test_chatlocation.py @@ -40,12 +40,12 @@ def test_slot_behaviour(self, chat_location): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "location": self.location.to_dict(), "address": self.address, } - chat_location = ChatLocation.de_json(json_dict, bot) + chat_location = ChatLocation.de_json(json_dict, offline_bot) assert chat_location.api_kwargs == {} assert chat_location.location == self.location diff --git a/tests/test_chatmember.py b/tests/test_chatmember.py index 4296fdd2723..2058d4bdf2a 100644 --- a/tests/test_chatmember.py +++ b/tests/test_chatmember.py @@ -205,12 +205,12 @@ def test_slot_behaviour(self, chat_member_type): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json_required_args(self, bot, chat_member_type): + def test_de_json_required_args(self, offline_bot, chat_member_type): cls = chat_member_type.__class__ - assert cls.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None json_dict = make_json_dict(chat_member_type) - const_chat_member = ChatMember.de_json(json_dict, bot) + const_chat_member = ChatMember.de_json(json_dict, offline_bot) assert const_chat_member.api_kwargs == {} assert isinstance(const_chat_member, ChatMember) @@ -218,9 +218,9 @@ def test_de_json_required_args(self, bot, chat_member_type): for chat_mem_type_at, const_chat_mem_at in iter_args(chat_member_type, const_chat_member): assert chat_mem_type_at == const_chat_mem_at - def test_de_json_all_args(self, bot, chat_member_type): + def test_de_json_all_args(self, offline_bot, chat_member_type): json_dict = make_json_dict(chat_member_type, include_optional_args=True) - const_chat_member = ChatMember.de_json(json_dict, bot) + const_chat_member = ChatMember.de_json(json_dict, offline_bot) assert const_chat_member.api_kwargs == {} assert isinstance(const_chat_member, ChatMember) @@ -228,14 +228,16 @@ def test_de_json_all_args(self, bot, chat_member_type): for c_mem_type_at, const_c_mem_at in iter_args(chat_member_type, const_chat_member, True): assert c_mem_type_at == const_c_mem_at - def test_de_json_chatmemberbanned_localization(self, chat_member_type, tz_bot, bot, raw_bot): + def test_de_json_chatmemberbanned_localization( + self, chat_member_type, tz_bot, offline_bot, raw_bot + ): # We only test two classes because the other three don't have datetimes in them. if isinstance( chat_member_type, (ChatMemberBanned, ChatMemberRestricted, ChatMemberMember) ): json_dict = make_json_dict(chat_member_type, include_optional_args=True) chatmember_raw = ChatMember.de_json(json_dict, raw_bot) - chatmember_bot = ChatMember.de_json(json_dict, bot) + chatmember_bot = ChatMember.de_json(json_dict, offline_bot) chatmember_tz = ChatMember.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable @@ -248,19 +250,19 @@ def test_de_json_chatmemberbanned_localization(self, chat_member_type, tz_bot, b assert chatmember_bot.until_date.tzinfo == UTC assert chatmember_offset == tz_bot_offset - def test_de_json_invalid_status(self, chat_member_type, bot): + def test_de_json_invalid_status(self, chat_member_type, offline_bot): json_dict = {"status": "invalid", "user": CMDefaults.user.to_dict()} - chat_member_type = ChatMember.de_json(json_dict, bot) + chat_member_type = ChatMember.de_json(json_dict, offline_bot) assert type(chat_member_type) is ChatMember assert chat_member_type.status == "invalid" - def test_de_json_subclass(self, chat_member_type, bot, chat_id): - """This makes sure that e.g. ChatMemberAdministrator(data, bot) never returns a + def test_de_json_subclass(self, chat_member_type, offline_bot, chat_id): + """This makes sure that e.g. ChatMemberAdministrator(data, offline_bot) never returns a ChatMemberBanned instance.""" cls = chat_member_type.__class__ json_dict = make_json_dict(chat_member_type, True) - assert type(cls.de_json(json_dict, bot)) is cls + assert type(cls.de_json(json_dict, offline_bot)) is cls def test_to_dict(self, chat_member_type): chat_member_dict = chat_member_type.to_dict() diff --git a/tests/test_chatmemberupdated.py b/tests/test_chatmemberupdated.py index 33b07863a5a..7bdd704fbcb 100644 --- a/tests/test_chatmemberupdated.py +++ b/tests/test_chatmemberupdated.py @@ -99,7 +99,9 @@ def test_slot_behaviour(self, chat_member_updated): assert getattr(action, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(action)) == len(set(mro_slots(action))), "duplicate slot" - def test_de_json_required_args(self, bot, user, chat, old_chat_member, new_chat_member, time): + def test_de_json_required_args( + self, offline_bot, user, chat, old_chat_member, new_chat_member, time + ): json_dict = { "chat": chat.to_dict(), "from": user.to_dict(), @@ -108,7 +110,7 @@ def test_de_json_required_args(self, bot, user, chat, old_chat_member, new_chat_ "new_chat_member": new_chat_member.to_dict(), } - chat_member_updated = ChatMemberUpdated.de_json(json_dict, bot) + chat_member_updated = ChatMemberUpdated.de_json(json_dict, offline_bot) assert chat_member_updated.api_kwargs == {} assert chat_member_updated.chat == chat @@ -121,7 +123,7 @@ def test_de_json_required_args(self, bot, user, chat, old_chat_member, new_chat_ assert chat_member_updated.via_chat_folder_invite_link is None def test_de_json_all_args( - self, bot, user, time, invite_link, chat, old_chat_member, new_chat_member + self, offline_bot, user, time, invite_link, chat, old_chat_member, new_chat_member ): json_dict = { "chat": chat.to_dict(), @@ -134,7 +136,7 @@ def test_de_json_all_args( "via_join_request": True, } - chat_member_updated = ChatMemberUpdated.de_json(json_dict, bot) + chat_member_updated = ChatMemberUpdated.de_json(json_dict, offline_bot) assert chat_member_updated.api_kwargs == {} assert chat_member_updated.chat == chat @@ -148,7 +150,16 @@ def test_de_json_all_args( assert chat_member_updated.via_join_request is True def test_de_json_localization( - self, bot, raw_bot, tz_bot, user, chat, old_chat_member, new_chat_member, time, invite_link + self, + offline_bot, + raw_bot, + tz_bot, + user, + chat, + old_chat_member, + new_chat_member, + time, + invite_link, ): json_dict = { "chat": chat.to_dict(), @@ -159,7 +170,7 @@ def test_de_json_localization( "invite_link": invite_link.to_dict(), } - chat_member_updated_bot = ChatMemberUpdated.de_json(json_dict, bot) + chat_member_updated_bot = ChatMemberUpdated.de_json(json_dict, offline_bot) chat_member_updated_raw = ChatMemberUpdated.de_json(json_dict, raw_bot) chat_member_updated_tz = ChatMemberUpdated.de_json(json_dict, tz_bot) diff --git a/tests/test_chatpermissions.py b/tests/test_chatpermissions.py index 79b6bab8081..fcb93840f10 100644 --- a/tests/test_chatpermissions.py +++ b/tests/test_chatpermissions.py @@ -67,7 +67,7 @@ def test_slot_behaviour(self, chat_permissions): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "can_send_messages": self.can_send_messages, "can_send_media_messages": "can_send_media_messages", @@ -84,7 +84,7 @@ def test_de_json(self, bot): "can_send_video_notes": self.can_send_video_notes, "can_send_voice_notes": self.can_send_voice_notes, } - permissions = ChatPermissions.de_json(json_dict, bot) + permissions = ChatPermissions.de_json(json_dict, offline_bot) assert permissions.api_kwargs == {"can_send_media_messages": "can_send_media_messages"} assert permissions.can_send_messages == self.can_send_messages diff --git a/tests/test_choseninlineresult.py b/tests/test_choseninlineresult.py index 2b53b684770..8d6529c103c 100644 --- a/tests/test_choseninlineresult.py +++ b/tests/test_choseninlineresult.py @@ -49,16 +49,16 @@ def test_slot_behaviour(self, chosen_inline_result): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json_required(self, bot, user): + def test_de_json_required(self, offline_bot, user): json_dict = {"result_id": self.result_id, "from": user.to_dict(), "query": self.query} - result = ChosenInlineResult.de_json(json_dict, bot) + result = ChosenInlineResult.de_json(json_dict, offline_bot) assert result.api_kwargs == {} assert result.result_id == self.result_id assert result.from_user == user assert result.query == self.query - def test_de_json_all(self, bot, user): + def test_de_json_all(self, offline_bot, user): loc = Location(-42.003, 34.004) json_dict = { "result_id": self.result_id, @@ -67,7 +67,7 @@ def test_de_json_all(self, bot, user): "location": loc.to_dict(), "inline_message_id": "a random id", } - result = ChosenInlineResult.de_json(json_dict, bot) + result = ChosenInlineResult.de_json(json_dict, offline_bot) assert result.api_kwargs == {} assert result.result_id == self.result_id diff --git a/tests/test_dice.py b/tests/test_dice.py index df3c349d4d7..de82d29aef0 100644 --- a/tests/test_dice.py +++ b/tests/test_dice.py @@ -39,14 +39,14 @@ def test_slot_behaviour(self, dice): assert len(mro_slots(dice)) == len(set(mro_slots(dice))), "duplicate slot" @pytest.mark.parametrize("emoji", Dice.ALL_EMOJI) - def test_de_json(self, bot, emoji): + def test_de_json(self, offline_bot, emoji): json_dict = {"value": self.value, "emoji": emoji} - dice = Dice.de_json(json_dict, bot) + dice = Dice.de_json(json_dict, offline_bot) assert dice.api_kwargs == {} assert dice.value == self.value assert dice.emoji == emoji - assert Dice.de_json(None, bot) is None + assert Dice.de_json(None, offline_bot) is None def test_to_dict(self, dice): dice_dict = dice.to_dict() diff --git a/tests/test_forum.py b/tests/test_forum.py index 1f143616ee9..4fd65c5d8dd 100644 --- a/tests/test_forum.py +++ b/tests/test_forum.py @@ -86,8 +86,8 @@ async def test_expected_values(self, emoji_id, forum_group_id, forum_topic_objec assert forum_topic_object.name == TEST_TOPIC_NAME assert forum_topic_object.icon_custom_emoji_id == emoji_id - def test_de_json(self, bot, emoji_id, forum_group_id): - assert ForumTopic.de_json(None, bot=bot) is None + def test_de_json(self, offline_bot, emoji_id, forum_group_id): + assert ForumTopic.de_json(None, bot=offline_bot) is None json_dict = { "message_thread_id": forum_group_id, @@ -95,7 +95,7 @@ def test_de_json(self, bot, emoji_id, forum_group_id): "icon_color": TEST_TOPIC_ICON_COLOR, "icon_custom_emoji_id": emoji_id, } - topic = ForumTopic.de_json(json_dict, bot) + topic = ForumTopic.de_json(json_dict, offline_bot) assert topic.api_kwargs == {} assert topic.message_thread_id == forum_group_id @@ -333,11 +333,11 @@ def test_expected_values(self, topic_created): assert topic_created.icon_color == TEST_TOPIC_ICON_COLOR assert topic_created.name == TEST_TOPIC_NAME - def test_de_json(self, bot): - assert ForumTopicCreated.de_json(None, bot=bot) is None + def test_de_json(self, offline_bot): + assert ForumTopicCreated.de_json(None, bot=offline_bot) is None json_dict = {"icon_color": TEST_TOPIC_ICON_COLOR, "name": TEST_TOPIC_NAME} - action = ForumTopicCreated.de_json(json_dict, bot) + action = ForumTopicCreated.de_json(json_dict, offline_bot) assert action.api_kwargs == {} assert action.icon_color == TEST_TOPIC_ICON_COLOR diff --git a/tests/test_giveaway.py b/tests/test_giveaway.py index 35945118363..4aac4150c6a 100644 --- a/tests/test_giveaway.py +++ b/tests/test_giveaway.py @@ -66,7 +66,7 @@ def test_slot_behaviour(self, giveaway): assert getattr(giveaway, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(giveaway)) == len(set(mro_slots(giveaway))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "chats": [chat.to_dict() for chat in self.chats], "winners_selection_date": to_timestamp(self.winners_selection_date), @@ -78,7 +78,7 @@ def test_de_json(self, bot): "premium_subscription_month_count": self.premium_subscription_month_count, } - giveaway = Giveaway.de_json(json_dict, bot) + giveaway = Giveaway.de_json(json_dict, offline_bot) assert giveaway.api_kwargs == {} assert giveaway.chats == tuple(self.chats) @@ -90,9 +90,9 @@ def test_de_json(self, bot): assert giveaway.country_codes == tuple(self.country_codes) assert giveaway.premium_subscription_month_count == self.premium_subscription_month_count - assert Giveaway.de_json(None, bot) is None + assert Giveaway.de_json(None, offline_bot) is None - def test_de_json_localization(self, tz_bot, bot, raw_bot): + def test_de_json_localization(self, tz_bot, offline_bot, raw_bot): json_dict = { "chats": [chat.to_dict() for chat in self.chats], "winners_selection_date": to_timestamp(self.winners_selection_date), @@ -105,7 +105,7 @@ def test_de_json_localization(self, tz_bot, bot, raw_bot): } giveaway_raw = Giveaway.de_json(json_dict, raw_bot) - giveaway_bot = Giveaway.de_json(json_dict, bot) + giveaway_bot = Giveaway.de_json(json_dict, offline_bot) giveaway_bot_tz = Giveaway.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable @@ -213,7 +213,7 @@ def test_slot_behaviour(self, giveaway_winners): set(mro_slots(giveaway_winners)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "chat": self.chat.to_dict(), "giveaway_message_id": self.giveaway_message_id, @@ -228,7 +228,7 @@ def test_de_json(self, bot): "prize_description": self.prize_description, } - giveaway_winners = GiveawayWinners.de_json(json_dict, bot) + giveaway_winners = GiveawayWinners.de_json(json_dict, offline_bot) assert giveaway_winners.api_kwargs == {} assert giveaway_winners.chat == self.chat @@ -246,9 +246,9 @@ def test_de_json(self, bot): assert giveaway_winners.was_refunded == self.was_refunded assert giveaway_winners.prize_description == self.prize_description - assert GiveawayWinners.de_json(None, bot) is None + assert GiveawayWinners.de_json(None, offline_bot) is None - def test_de_json_localization(self, tz_bot, bot, raw_bot): + def test_de_json_localization(self, tz_bot, offline_bot, raw_bot): json_dict = { "chat": self.chat.to_dict(), "giveaway_message_id": self.giveaway_message_id, @@ -258,7 +258,7 @@ def test_de_json_localization(self, tz_bot, bot, raw_bot): } giveaway_winners_raw = GiveawayWinners.de_json(json_dict, raw_bot) - giveaway_winners_bot = GiveawayWinners.de_json(json_dict, bot) + giveaway_winners_bot = GiveawayWinners.de_json(json_dict, offline_bot) giveaway_winners_bot_tz = GiveawayWinners.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable @@ -357,21 +357,21 @@ def test_slot_behaviour(self, giveaway_completed): set(mro_slots(giveaway_completed)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "winner_count": self.winner_count, "unclaimed_prize_count": self.unclaimed_prize_count, "giveaway_message": self.giveaway_message.to_dict(), } - giveaway_completed = GiveawayCompleted.de_json(json_dict, bot) + giveaway_completed = GiveawayCompleted.de_json(json_dict, offline_bot) assert giveaway_completed.api_kwargs == {} assert giveaway_completed.winner_count == self.winner_count assert giveaway_completed.unclaimed_prize_count == self.unclaimed_prize_count assert giveaway_completed.giveaway_message == self.giveaway_message - assert GiveawayCompleted.de_json(None, bot) is None + assert GiveawayCompleted.de_json(None, offline_bot) is None def test_to_dict(self, giveaway_completed): giveaway_completed_dict = giveaway_completed.to_dict() diff --git a/tests/test_inlinequeryresultsbutton.py b/tests/test_inlinequeryresultsbutton.py index 90ce2c235ac..1ec59573a3b 100644 --- a/tests/test_inlinequeryresultsbutton.py +++ b/tests/test_inlinequeryresultsbutton.py @@ -51,16 +51,16 @@ def test_to_dict(self, inline_query_results_button): assert inline_query_results_button_dict["start_parameter"] == self.start_parameter assert inline_query_results_button_dict["web_app"] == self.web_app.to_dict() - def test_de_json(self, bot): - assert InlineQueryResultsButton.de_json(None, bot) is None - assert InlineQueryResultsButton.de_json({}, bot) is None + def test_de_json(self, offline_bot): + assert InlineQueryResultsButton.de_json(None, offline_bot) is None + assert InlineQueryResultsButton.de_json({}, offline_bot) is None json_dict = { "text": self.text, "start_parameter": self.start_parameter, "web_app": self.web_app.to_dict(), } - inline_query_results_button = InlineQueryResultsButton.de_json(json_dict, bot) + inline_query_results_button = InlineQueryResultsButton.de_json(json_dict, offline_bot) assert inline_query_results_button.text == self.text assert inline_query_results_button.start_parameter == self.start_parameter diff --git a/tests/test_keyboardbutton.py b/tests/test_keyboardbutton.py index 4493ed22320..216da894beb 100644 --- a/tests/test_keyboardbutton.py +++ b/tests/test_keyboardbutton.py @@ -81,7 +81,7 @@ def test_to_dict(self, keyboard_button): assert keyboard_button_dict["request_users"] == keyboard_button.request_users.to_dict() @pytest.mark.parametrize("request_user", [True, False]) - def test_de_json(self, bot, request_user): + def test_de_json(self, offline_bot, request_user): json_dict = { "text": self.text, "request_location": self.request_location, diff --git a/tests/test_keyboardbuttonrequest.py b/tests/test_keyboardbuttonrequest.py index 8e42b1cd374..9d9a0295206 100644 --- a/tests/test_keyboardbuttonrequest.py +++ b/tests/test_keyboardbuttonrequest.py @@ -57,14 +57,14 @@ def test_to_dict(self, request_users): assert request_users_dict["user_is_premium"] == self.user_is_premium assert request_users_dict["max_quantity"] == self.max_quantity - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "request_id": self.request_id, "user_is_bot": self.user_is_bot, "user_is_premium": self.user_is_premium, "max_quantity": self.max_quantity, } - request_users = KeyboardButtonRequestUsers.de_json(json_dict, bot) + request_users = KeyboardButtonRequestUsers.de_json(json_dict, offline_bot) assert request_users.api_kwargs == {} assert request_users.request_id == self.request_id @@ -158,7 +158,7 @@ def test_to_dict(self, request_chat): ) assert request_chat_dict["bot_is_member"] == self.bot_is_member - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "request_id": self.request_id, "chat_is_channel": self.chat_is_channel, @@ -168,7 +168,7 @@ def test_de_json(self, bot): "bot_administrator_rights": self.bot_administrator_rights.to_dict(), "bot_is_member": self.bot_is_member, } - request_chat = KeyboardButtonRequestChat.de_json(json_dict, bot) + request_chat = KeyboardButtonRequestChat.de_json(json_dict, offline_bot) assert request_chat.api_kwargs == {} assert request_chat.request_id == self.request_id @@ -179,7 +179,7 @@ def test_de_json(self, bot): assert request_chat.bot_administrator_rights == self.bot_administrator_rights assert request_chat.bot_is_member == self.bot_is_member - empty_chat = KeyboardButtonRequestChat.de_json({}, bot) + empty_chat = KeyboardButtonRequestChat.de_json({}, offline_bot) assert empty_chat is None def test_equality(self): diff --git a/tests/test_maybeinaccessiblemessage.py b/tests/test_maybeinaccessiblemessage.py index da7db43ce0e..8cad89e884c 100644 --- a/tests/test_maybeinaccessiblemessage.py +++ b/tests/test_maybeinaccessiblemessage.py @@ -59,20 +59,20 @@ def test_to_dict(self, maybe_inaccessible_message): assert maybe_inaccessible_message_dict["message_id"] == self.message_id assert maybe_inaccessible_message_dict["date"] == to_timestamp(self.date) - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "chat": self.chat.to_dict(), "message_id": self.message_id, "date": to_timestamp(self.date), } - maybe_inaccessible_message = MaybeInaccessibleMessage.de_json(json_dict, bot) + maybe_inaccessible_message = MaybeInaccessibleMessage.de_json(json_dict, offline_bot) assert maybe_inaccessible_message.api_kwargs == {} assert maybe_inaccessible_message.chat == self.chat assert maybe_inaccessible_message.message_id == self.message_id assert maybe_inaccessible_message.date == self.date - def test_de_json_localization(self, tz_bot, bot, raw_bot): + def test_de_json_localization(self, tz_bot, offline_bot, raw_bot): json_dict = { "chat": self.chat.to_dict(), "message_id": self.message_id, @@ -80,7 +80,7 @@ def test_de_json_localization(self, tz_bot, bot, raw_bot): } maybe_inaccessible_message_raw = MaybeInaccessibleMessage.de_json(json_dict, raw_bot) - maybe_inaccessible_message_bot = MaybeInaccessibleMessage.de_json(json_dict, bot) + maybe_inaccessible_message_bot = MaybeInaccessibleMessage.de_json(json_dict, offline_bot) maybe_inaccessible_message_bot_tz = MaybeInaccessibleMessage.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable @@ -95,14 +95,14 @@ def test_de_json_localization(self, tz_bot, bot, raw_bot): assert maybe_inaccessible_message_bot.date.tzinfo == UTC assert maybe_inaccessible_message_bot_tz_offset == tz_bot_offset - def test_de_json_zero_date(self, bot): + def test_de_json_zero_date(self, offline_bot): json_dict = { "chat": self.chat.to_dict(), "message_id": self.message_id, "date": 0, } - maybe_inaccessible_message = MaybeInaccessibleMessage.de_json(json_dict, bot) + maybe_inaccessible_message = MaybeInaccessibleMessage.de_json(json_dict, offline_bot) assert maybe_inaccessible_message.date == ZERO_DATE assert maybe_inaccessible_message.date is ZERO_DATE diff --git a/tests/test_menubutton.py b/tests/test_menubutton.py index d5930f805c2..d9ae7c1ef12 100644 --- a/tests/test_menubutton.py +++ b/tests/test_menubutton.py @@ -103,12 +103,12 @@ def test_slot_behaviour(self, menu_button): assert getattr(menu_button, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(menu_button)) == len(set(mro_slots(menu_button))), "duplicate slot" - def test_de_json(self, bot, scope_class_and_type): + def test_de_json(self, offline_bot, scope_class_and_type): cls = scope_class_and_type[0] type_ = scope_class_and_type[1] json_dict = {"type": type_, "text": self.text, "web_app": self.web_app.to_dict()} - menu_button = MenuButton.de_json(json_dict, bot) + menu_button = MenuButton.de_json(json_dict, offline_bot) assert set(menu_button.api_kwargs.keys()) == {"text", "web_app"} - set(cls.__slots__) assert isinstance(menu_button, MenuButton) @@ -119,22 +119,22 @@ def test_de_json(self, bot, scope_class_and_type): if "text" in cls.__slots__: assert menu_button.text == self.text - assert cls.de_json(None, bot) is None - assert MenuButton.de_json({}, bot) is None + assert cls.de_json(None, offline_bot) is None + assert MenuButton.de_json({}, offline_bot) is None - def test_de_json_invalid_type(self, bot): + def test_de_json_invalid_type(self, offline_bot): json_dict = {"type": "invalid", "text": self.text, "web_app": self.web_app.to_dict()} - menu_button = MenuButton.de_json(json_dict, bot) + menu_button = MenuButton.de_json(json_dict, offline_bot) assert menu_button.api_kwargs == {"text": self.text, "web_app": self.web_app.to_dict()} assert type(menu_button) is MenuButton assert menu_button.type == "invalid" - def test_de_json_subclass(self, scope_class, bot): + def test_de_json_subclass(self, scope_class, offline_bot): """This makes sure that e.g. MenuButtonDefault(data) never returns a MenuButtonChat instance.""" json_dict = {"type": "invalid", "text": self.text, "web_app": self.web_app.to_dict()} - assert type(scope_class.de_json(json_dict, bot)) is scope_class + assert type(scope_class.de_json(json_dict, offline_bot)) is scope_class def test_de_json_empty_data(self, scope_class): if scope_class in (MenuButtonWebApp,): @@ -157,7 +157,7 @@ def test_type_enum_conversion(self): assert type(MenuButton("commands").type) is MenuButtonType assert MenuButton("unknown").type == "unknown" - def test_equality(self, menu_button, bot): + def test_equality(self, menu_button, offline_bot): a = MenuButton("base_type") b = MenuButton("base_type") c = menu_button @@ -185,7 +185,7 @@ def test_equality(self, menu_button, bot): if hasattr(c, "web_app"): json_dict = c.to_dict() json_dict["web_app"] = WebAppInfo("https://foo.bar/web_app").to_dict() - f = c.__class__.de_json(json_dict, bot) + f = c.__class__.de_json(json_dict, offline_bot) assert c != f assert hash(c) != hash(f) @@ -193,7 +193,7 @@ def test_equality(self, menu_button, bot): if hasattr(c, "text"): json_dict = c.to_dict() json_dict["text"] = "other text" - g = c.__class__.de_json(json_dict, bot) + g = c.__class__.de_json(json_dict, offline_bot) assert c != g assert hash(c) != hash(g) diff --git a/tests/test_message.py b/tests/test_message.py index 84b2b7c3929..02d6e5b5f4a 100644 --- a/tests/test_message.py +++ b/tests/test_message.py @@ -568,8 +568,8 @@ def test_slot_behaviour(self): assert getattr(message, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(message)) == len(set(mro_slots(message))), "duplicate slot" - def test_all_possibilities_de_json_and_to_dict(self, bot, message_params): - new = Message.de_json(message_params.to_dict(), bot) + def test_all_possibilities_de_json_and_to_dict(self, offline_bot, message_params): + new = Message.de_json(message_params.to_dict(), offline_bot) assert new.api_kwargs == {} assert new.to_dict() == message_params.to_dict() @@ -579,7 +579,7 @@ def test_all_possibilities_de_json_and_to_dict(self, bot, message_params): for slot in new.__slots__: assert not isinstance(new[slot], dict) - def test_de_json_localization(self, bot, raw_bot, tz_bot): + def test_de_json_localization(self, offline_bot, raw_bot, tz_bot): json_dict = { "message_id": 12, "from_user": None, @@ -589,7 +589,7 @@ def test_de_json_localization(self, bot, raw_bot, tz_bot): } message_raw = Message.de_json(json_dict, raw_bot) - message_bot = Message.de_json(json_dict, bot) + message_bot = Message.de_json(json_dict, offline_bot) message_tz = Message.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable @@ -609,7 +609,7 @@ def test_de_json_localization(self, bot, raw_bot, tz_bot): assert message_bot.edit_date.tzinfo == UTC assert edit_date_offset == edit_date_tz_bot_offset - def test_de_json_api_kwargs_backward_compatibility(self, bot, message_params): + def test_de_json_api_kwargs_backward_compatibility(self, offline_bot, message_params): message_dict = message_params.to_dict() keys = ( "user_shared", @@ -622,7 +622,7 @@ def test_de_json_api_kwargs_backward_compatibility(self, bot, message_params): ) for key in keys: message_dict[key] = key - message = Message.de_json(message_dict, bot) + message = Message.de_json(message_dict, offline_bot) assert message.api_kwargs == {key: key for key in keys} def test_equality(self): @@ -2653,10 +2653,10 @@ async def make_assertion(*args, **kwargs): ], ) async def test_default_do_quote( - self, bot, message, default_quote, chat_type, expected, monkeypatch + self, offline_bot, message, default_quote, chat_type, expected, monkeypatch ): original_bot = message.get_bot() - temp_bot = PytestExtBot(token=bot.token, defaults=Defaults(do_quote=default_quote)) + temp_bot = PytestExtBot(token=offline_bot.token, defaults=Defaults(do_quote=default_quote)) message.set_bot(temp_bot) async def make_assertion(*_, **kwargs): diff --git a/tests/test_messageentity.py b/tests/test_messageentity.py index 3598454d8eb..4c981f45319 100644 --- a/tests/test_messageentity.py +++ b/tests/test_messageentity.py @@ -55,9 +55,9 @@ def test_slot_behaviour(self, message_entity): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = {"type": self.type_, "offset": self.offset, "length": self.length} - entity = MessageEntity.de_json(json_dict, bot) + entity = MessageEntity.de_json(json_dict, offline_bot) assert entity.api_kwargs == {} assert entity.type == self.type_ diff --git a/tests/test_messageorigin.py b/tests/test_messageorigin.py index 10d9fa77894..7b239bc3763 100644 --- a/tests/test_messageorigin.py +++ b/tests/test_messageorigin.py @@ -136,12 +136,12 @@ def test_slot_behaviour(self, message_origin_type): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json_required_args(self, bot, message_origin_type): + def test_de_json_required_args(self, offline_bot, message_origin_type): cls = message_origin_type.__class__ - assert cls.de_json({}, bot) is None + assert cls.de_json({}, offline_bot) is None json_dict = make_json_dict(message_origin_type) - const_message_origin = MessageOrigin.de_json(json_dict, bot) + const_message_origin = MessageOrigin.de_json(json_dict, offline_bot) assert const_message_origin.api_kwargs == {} assert isinstance(const_message_origin, MessageOrigin) @@ -151,9 +151,9 @@ def test_de_json_required_args(self, bot, message_origin_type): ): assert msg_origin_type_at == const_msg_origin_at - def test_de_json_all_args(self, bot, message_origin_type): + def test_de_json_all_args(self, offline_bot, message_origin_type): json_dict = make_json_dict(message_origin_type, include_optional_args=True) - const_message_origin = MessageOrigin.de_json(json_dict, bot) + const_message_origin = MessageOrigin.de_json(json_dict, offline_bot) assert const_message_origin.api_kwargs == {} @@ -164,10 +164,12 @@ def test_de_json_all_args(self, bot, message_origin_type): ): assert msg_origin_type_at == const_msg_origin_at - def test_de_json_messageorigin_localization(self, message_origin_type, tz_bot, bot, raw_bot): + def test_de_json_messageorigin_localization( + self, message_origin_type, tz_bot, offline_bot, raw_bot + ): json_dict = make_json_dict(message_origin_type, include_optional_args=True) msgorigin_raw = MessageOrigin.de_json(json_dict, raw_bot) - msgorigin_bot = MessageOrigin.de_json(json_dict, bot) + msgorigin_bot = MessageOrigin.de_json(json_dict, offline_bot) msgorigin_tz = MessageOrigin.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable @@ -178,19 +180,19 @@ def test_de_json_messageorigin_localization(self, message_origin_type, tz_bot, b assert msgorigin_bot.date.tzinfo == UTC assert msgorigin_offset == tz_bot_offset - def test_de_json_invalid_type(self, message_origin_type, bot): + def test_de_json_invalid_type(self, message_origin_type, offline_bot): json_dict = {"type": "invalid", "date": MODefaults.date} - message_origin_type = MessageOrigin.de_json(json_dict, bot) + message_origin_type = MessageOrigin.de_json(json_dict, offline_bot) assert type(message_origin_type) is MessageOrigin assert message_origin_type.type == "invalid" - def test_de_json_subclass(self, message_origin_type, bot, chat_id): - """This makes sure that e.g. MessageOriginChat(data, bot) never returns a + def test_de_json_subclass(self, message_origin_type, offline_bot, chat_id): + """This makes sure that e.g. MessageOriginChat(data, offline_bot) never returns a MessageOriginUser instance.""" cls = message_origin_type.__class__ json_dict = make_json_dict(message_origin_type, True) - assert type(cls.de_json(json_dict, bot)) is cls + assert type(cls.de_json(json_dict, offline_bot)) is cls def test_to_dict(self, message_origin_type): message_origin_dict = message_origin_type.to_dict() diff --git a/tests/test_paidmedia.py b/tests/test_paidmedia.py index be9ac14905b..6592125e789 100644 --- a/tests/test_paidmedia.py +++ b/tests/test_paidmedia.py @@ -150,7 +150,7 @@ def test_slot_behaviour(self, paid_media): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, pm_scope_class_and_type): + def test_de_json(self, offline_bot, pm_scope_class_and_type): cls = pm_scope_class_and_type[0] type_ = pm_scope_class_and_type[1] @@ -162,7 +162,7 @@ def test_de_json(self, bot, pm_scope_class_and_type): "video": self.video.to_dict(), "photo": [p.to_dict() for p in self.photo], } - pm = PaidMedia.de_json(json_dict, bot) + pm = PaidMedia.de_json(json_dict, offline_bot) assert set(pm.api_kwargs.keys()) == { "width", "height", @@ -183,10 +183,10 @@ def test_de_json(self, bot, pm_scope_class_and_type): if "photo" in cls.__slots__: assert pm.photo == self.photo - assert cls.de_json(None, bot) is None - assert PaidMedia.de_json({}, bot) is None + assert cls.de_json(None, offline_bot) is None + assert PaidMedia.de_json({}, offline_bot) is None - def test_de_json_invalid_type(self, bot): + def test_de_json_invalid_type(self, offline_bot): json_dict = { "type": "invalid", "width": self.width, @@ -195,7 +195,7 @@ def test_de_json_invalid_type(self, bot): "video": self.video.to_dict(), "photo": [p.to_dict() for p in self.photo], } - pm = PaidMedia.de_json(json_dict, bot) + pm = PaidMedia.de_json(json_dict, offline_bot) assert pm.api_kwargs == { "width": self.width, "height": self.height, @@ -207,7 +207,7 @@ def test_de_json_invalid_type(self, bot): assert type(pm) is PaidMedia assert pm.type == "invalid" - def test_de_json_subclass(self, pm_scope_class, bot): + def test_de_json_subclass(self, pm_scope_class, offline_bot): """This makes sure that e.g. PaidMediaPreivew(data) never returns a TransactionPartnerPhoto instance.""" json_dict = { @@ -218,7 +218,7 @@ def test_de_json_subclass(self, pm_scope_class, bot): "video": self.video.to_dict(), "photo": [p.to_dict() for p in self.photo], } - assert type(pm_scope_class.de_json(json_dict, bot)) is pm_scope_class + assert type(pm_scope_class.de_json(json_dict, offline_bot)) is pm_scope_class def test_to_dict(self, paid_media): pm_dict = paid_media.to_dict() @@ -238,7 +238,7 @@ def test_type_enum_conversion(self): assert type(PaidMedia("video").type) is PaidMediaType assert PaidMedia("unknown").type == "unknown" - def test_equality(self, paid_media, bot): + def test_equality(self, paid_media, offline_bot): a = PaidMedia("base_type") b = PaidMedia("base_type") c = paid_media @@ -266,7 +266,7 @@ def test_equality(self, paid_media, bot): if hasattr(c, "video"): json_dict = c.to_dict() json_dict["video"] = Video("different", "d2", 1, 1, 1).to_dict() - f = c.__class__.de_json(json_dict, bot) + f = c.__class__.de_json(json_dict, offline_bot) assert c != f assert hash(c) != hash(f) @@ -274,7 +274,7 @@ def test_equality(self, paid_media, bot): if hasattr(c, "photo"): json_dict = c.to_dict() json_dict["photo"] = [PhotoSize("different", "d2", 1, 1, 1).to_dict()] - f = c.__class__.de_json(json_dict, bot) + f = c.__class__.de_json(json_dict, offline_bot) assert c != f assert hash(c) != hash(f) @@ -292,13 +292,13 @@ def test_slot_behaviour(self, paid_media_info): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "star_count": self.star_count, "paid_media": [t.to_dict() for t in self.paid_media], } - pmi = PaidMediaInfo.de_json(json_dict, bot) - pmi_none = PaidMediaInfo.de_json(None, bot) + pmi = PaidMediaInfo.de_json(json_dict, offline_bot) + pmi_none = PaidMediaInfo.de_json(None, offline_bot) assert pmi.paid_media == tuple(self.paid_media) assert pmi.star_count == self.star_count assert pmi_none is None diff --git a/tests/test_poll.py b/tests/test_poll.py index 81619a11299..aedc5cf524b 100644 --- a/tests/test_poll.py +++ b/tests/test_poll.py @@ -305,7 +305,7 @@ class PollTestBase: class TestPollWithoutRequest(PollTestBase): - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id_, "question": self.question, @@ -321,7 +321,7 @@ def test_de_json(self, bot): "close_date": to_timestamp(self.close_date), "question_entities": [e.to_dict() for e in self.question_entities], } - poll = Poll.de_json(json_dict, bot) + poll = Poll.de_json(json_dict, offline_bot) assert poll.api_kwargs == {} assert poll.id == self.id_ @@ -343,7 +343,7 @@ def test_de_json(self, bot): assert to_timestamp(poll.close_date) == to_timestamp(self.close_date) assert poll.question_entities == tuple(self.question_entities) - def test_de_json_localization(self, tz_bot, bot, raw_bot): + def test_de_json_localization(self, tz_bot, offline_bot, raw_bot): json_dict = { "id": self.id_, "question": self.question, @@ -361,7 +361,7 @@ def test_de_json_localization(self, tz_bot, bot, raw_bot): } poll_raw = Poll.de_json(json_dict, raw_bot) - poll_bot = Poll.de_json(json_dict, bot) + poll_bot = Poll.de_json(json_dict, offline_bot) poll_bot_tz = Poll.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable diff --git a/tests/test_proximityalerttriggered.py b/tests/test_proximityalerttriggered.py index de49b699fea..6367af9d383 100644 --- a/tests/test_proximityalerttriggered.py +++ b/tests/test_proximityalerttriggered.py @@ -44,13 +44,13 @@ def test_slot_behaviour(self, proximity_alert_triggered): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "traveler": self.traveler.to_dict(), "watcher": self.watcher.to_dict(), "distance": self.distance, } - proximity_alert_triggered = ProximityAlertTriggered.de_json(json_dict, bot) + proximity_alert_triggered = ProximityAlertTriggered.de_json(json_dict, offline_bot) assert proximity_alert_triggered.api_kwargs == {} assert proximity_alert_triggered.traveler == self.traveler diff --git a/tests/test_reaction.py b/tests/test_reaction.py index 67ece80e3b0..79f3e2c40be 100644 --- a/tests/test_reaction.py +++ b/tests/test_reaction.py @@ -115,13 +115,13 @@ def test_slot_behaviour(self, reaction_type): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json_required_args(self, bot, reaction_type): + def test_de_json_required_args(self, offline_bot, reaction_type): cls = reaction_type.__class__ - assert cls.de_json(None, bot) is None - assert ReactionType.de_json({}, bot) is None + assert cls.de_json(None, offline_bot) is None + assert ReactionType.de_json({}, offline_bot) is None json_dict = make_json_dict(reaction_type) - const_reaction_type = ReactionType.de_json(json_dict, bot) + const_reaction_type = ReactionType.de_json(json_dict, offline_bot) assert const_reaction_type.api_kwargs == {} assert isinstance(const_reaction_type, ReactionType) @@ -131,9 +131,9 @@ def test_de_json_required_args(self, bot, reaction_type): ): assert reaction_type_at == const_reaction_type_at - def test_de_json_all_args(self, bot, reaction_type): + def test_de_json_all_args(self, offline_bot, reaction_type): json_dict = make_json_dict(reaction_type, include_optional_args=True) - const_reaction_type = ReactionType.de_json(json_dict, bot) + const_reaction_type = ReactionType.de_json(json_dict, offline_bot) assert const_reaction_type.api_kwargs == {} assert isinstance(const_reaction_type, ReactionType) @@ -141,19 +141,19 @@ def test_de_json_all_args(self, bot, reaction_type): for c_mem_type_at, const_c_mem_at in iter_args(reaction_type, const_reaction_type, True): assert c_mem_type_at == const_c_mem_at - def test_de_json_invalid_type(self, bot, reaction_type): + def test_de_json_invalid_type(self, offline_bot, reaction_type): json_dict = {"type": "invalid"} - reaction_type = ReactionType.de_json(json_dict, bot) + reaction_type = ReactionType.de_json(json_dict, offline_bot) assert type(reaction_type) is ReactionType assert reaction_type.type == "invalid" - def test_de_json_subclass(self, reaction_type, bot, chat_id): - """This makes sure that e.g. ReactionTypeEmoji(data, bot) never returns a + def test_de_json_subclass(self, reaction_type, offline_bot, chat_id): + """This makes sure that e.g. ReactionTypeEmoji(data, offline_bot) never returns a ReactionTypeCustomEmoji instance.""" cls = reaction_type.__class__ json_dict = make_json_dict(reaction_type, True) - assert type(cls.de_json(json_dict, bot)) is cls + assert type(cls.de_json(json_dict, offline_bot)) is cls def test_to_dict(self, reaction_type): reaction_type_dict = reaction_type.to_dict() @@ -237,13 +237,13 @@ def test_slot_behaviour(self, reaction_count): set(mro_slots(reaction_count)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "type": self.type.to_dict(), "total_count": self.total_count, } - reaction_count = ReactionCount.de_json(json_dict, bot) + reaction_count = ReactionCount.de_json(json_dict, offline_bot) assert reaction_count.api_kwargs == {} assert isinstance(reaction_count, ReactionCount) @@ -252,7 +252,7 @@ def test_de_json(self, bot): assert reaction_count.type.emoji == self.type.emoji assert reaction_count.total_count == self.total_count - assert ReactionCount.de_json(None, bot) is None + assert ReactionCount.de_json(None, offline_bot) is None def test_to_dict(self, reaction_count): reaction_count_dict = reaction_count.to_dict() diff --git a/tests/test_reply.py b/tests/test_reply.py index 5cacb7b6b5c..a450a721d7d 100644 --- a/tests/test_reply.py +++ b/tests/test_reply.py @@ -73,7 +73,7 @@ def test_slot_behaviour(self, external_reply_info): set(mro_slots(external_reply_info)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "origin": self.origin.to_dict(), "chat": self.chat.to_dict(), @@ -83,7 +83,7 @@ def test_de_json(self, bot): "paid_media": self.paid_media.to_dict(), } - external_reply_info = ExternalReplyInfo.de_json(json_dict, bot) + external_reply_info = ExternalReplyInfo.de_json(json_dict, offline_bot) assert external_reply_info.api_kwargs == {} assert external_reply_info.origin == self.origin @@ -93,7 +93,7 @@ def test_de_json(self, bot): assert external_reply_info.giveaway == self.giveaway assert external_reply_info.paid_media == self.paid_media - assert ExternalReplyInfo.de_json(None, bot) is None + assert ExternalReplyInfo.de_json(None, offline_bot) is None def test_to_dict(self, external_reply_info): ext_reply_info_dict = external_reply_info.to_dict() @@ -151,7 +151,7 @@ def test_slot_behaviour(self, text_quote): assert getattr(text_quote, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(text_quote)) == len(set(mro_slots(text_quote))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "text": self.text, "position": self.position, @@ -159,7 +159,7 @@ def test_de_json(self, bot): "is_manual": self.is_manual, } - text_quote = TextQuote.de_json(json_dict, bot) + text_quote = TextQuote.de_json(json_dict, offline_bot) assert text_quote.api_kwargs == {} assert text_quote.text == self.text @@ -167,7 +167,7 @@ def test_de_json(self, bot): assert text_quote.entities == tuple(self.entities) assert text_quote.is_manual == self.is_manual - assert TextQuote.de_json(None, bot) is None + assert TextQuote.de_json(None, offline_bot) is None def test_to_dict(self, text_quote): text_quote_dict = text_quote.to_dict() @@ -233,7 +233,7 @@ def test_slot_behaviour(self, reply_parameters): set(mro_slots(reply_parameters)) ), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "message_id": self.message_id, "chat_id": self.chat_id, @@ -244,7 +244,7 @@ def test_de_json(self, bot): "quote_position": self.quote_position, } - reply_parameters = ReplyParameters.de_json(json_dict, bot) + reply_parameters = ReplyParameters.de_json(json_dict, offline_bot) assert reply_parameters.api_kwargs == {} assert reply_parameters.message_id == self.message_id @@ -255,7 +255,7 @@ def test_de_json(self, bot): assert reply_parameters.quote_entities == tuple(self.quote_entities) assert reply_parameters.quote_position == self.quote_position - assert ReplyParameters.de_json(None, bot) is None + assert ReplyParameters.de_json(None, offline_bot) is None def test_to_dict(self, reply_parameters): reply_parameters_dict = reply_parameters.to_dict() diff --git a/tests/test_sentwebappmessage.py b/tests/test_sentwebappmessage.py index e4bc116d035..bd206eedef1 100644 --- a/tests/test_sentwebappmessage.py +++ b/tests/test_sentwebappmessage.py @@ -45,7 +45,7 @@ def test_to_dict(self, sent_web_app_message): assert isinstance(sent_web_app_message_dict, dict) assert sent_web_app_message_dict["inline_message_id"] == self.inline_message_id - def test_de_json(self, bot): + def test_de_json(self, offline_bot): data = {"inline_message_id": self.inline_message_id} m = SentWebAppMessage.de_json(data, None) assert m.api_kwargs == {} diff --git a/tests/test_shared.py b/tests/test_shared.py index c51bcf5ea91..9cc8d4bcaa8 100644 --- a/tests/test_shared.py +++ b/tests/test_shared.py @@ -47,19 +47,19 @@ def test_to_dict(self, users_shared): assert users_shared_dict["request_id"] == self.request_id assert users_shared_dict["users"] == [user.to_dict() for user in self.users] - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "request_id": self.request_id, "users": [user.to_dict() for user in self.users], "user_ids": self.user_ids, } - users_shared = UsersShared.de_json(json_dict, bot) + users_shared = UsersShared.de_json(json_dict, offline_bot) assert users_shared.api_kwargs == {"user_ids": self.user_ids} assert users_shared.request_id == self.request_id assert users_shared.users == self.users - assert UsersShared.de_json({}, bot) is None + assert UsersShared.de_json({}, offline_bot) is None def test_equality(self): a = UsersShared(self.request_id, users=self.users) @@ -108,12 +108,12 @@ def test_to_dict(self, chat_shared): assert chat_shared_dict["request_id"] == self.request_id assert chat_shared_dict["chat_id"] == self.chat_id - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "request_id": self.request_id, "chat_id": self.chat_id, } - chat_shared = ChatShared.de_json(json_dict, bot) + chat_shared = ChatShared.de_json(json_dict, offline_bot) assert chat_shared.api_kwargs == {} assert chat_shared.request_id == self.request_id @@ -178,12 +178,12 @@ def test_to_dict(self, shared_user): assert shared_user_dict["username"] == self.username assert shared_user_dict["photo"] == [photo.to_dict() for photo in self.photo] - def test_de_json_required(self, bot): + def test_de_json_required(self, offline_bot): json_dict = { "user_id": self.user_id, "first_name": self.first_name, } - shared_user = SharedUser.de_json(json_dict, bot) + shared_user = SharedUser.de_json(json_dict, offline_bot) assert shared_user.api_kwargs == {} assert shared_user.user_id == self.user_id @@ -192,7 +192,7 @@ def test_de_json_required(self, bot): assert shared_user.username is None assert shared_user.photo == () - def test_de_json_all(self, bot): + def test_de_json_all(self, offline_bot): json_dict = { "user_id": self.user_id, "first_name": self.first_name, @@ -200,7 +200,7 @@ def test_de_json_all(self, bot): "username": self.username, "photo": [photo.to_dict() for photo in self.photo], } - shared_user = SharedUser.de_json(json_dict, bot) + shared_user = SharedUser.de_json(json_dict, offline_bot) assert shared_user.api_kwargs == {} assert shared_user.user_id == self.user_id @@ -209,7 +209,7 @@ def test_de_json_all(self, bot): assert shared_user.username == self.username assert shared_user.photo == self.photo - assert SharedUser.de_json({}, bot) is None + assert SharedUser.de_json({}, offline_bot) is None def test_equality(self, chat_shared): a = SharedUser( diff --git a/tests/test_stars.py b/tests/test_stars.py index ef700ae392a..23ddb410916 100644 --- a/tests/test_stars.py +++ b/tests/test_stars.py @@ -253,7 +253,7 @@ def test_slot_behaviour(self): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "id": self.id, "amount": self.amount, @@ -261,8 +261,8 @@ def test_de_json(self, bot): "source": self.source.to_dict(), "receiver": self.receiver.to_dict(), } - st = StarTransaction.de_json(json_dict, bot) - st_none = StarTransaction.de_json(None, bot) + st = StarTransaction.de_json(json_dict, offline_bot) + st_none = StarTransaction.de_json(None, offline_bot) assert st.api_kwargs == {} assert st.id == self.id assert st.amount == self.amount @@ -271,10 +271,10 @@ def test_de_json(self, bot): assert st.receiver == self.receiver assert st_none is None - def test_de_json_star_transaction_localization(self, tz_bot, bot, raw_bot): + def test_de_json_star_transaction_localization(self, tz_bot, offline_bot, raw_bot): json_dict = star_transaction().to_dict() st_raw = StarTransaction.de_json(json_dict, raw_bot) - st_bot = StarTransaction.de_json(json_dict, bot) + st_bot = StarTransaction.de_json(json_dict, offline_bot) st_tz = StarTransaction.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable @@ -343,12 +343,12 @@ def test_slot_behaviour(self, star_transactions): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "transactions": [t.to_dict() for t in self.transactions], } - st = StarTransactions.de_json(json_dict, bot) - st_none = StarTransactions.de_json(None, bot) + st = StarTransactions.de_json(json_dict, offline_bot) + st_none = StarTransactions.de_json(None, offline_bot) assert st.api_kwargs == {} assert st.transactions == tuple(self.transactions) assert st_none is None @@ -390,7 +390,7 @@ def test_slot_behaviour(self, transaction_partner): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, tp_scope_class_and_type): + def test_de_json(self, offline_bot, tp_scope_class_and_type): cls = tp_scope_class_and_type[0] type_ = tp_scope_class_and_type[1] @@ -400,7 +400,7 @@ def test_de_json(self, bot, tp_scope_class_and_type): "withdrawal_state": self.withdrawal_state.to_dict(), "user": self.user.to_dict(), } - tp = TransactionPartner.de_json(json_dict, bot) + tp = TransactionPartner.de_json(json_dict, offline_bot) assert set(tp.api_kwargs.keys()) == {"user", "withdrawal_state", "invoice_payload"} - set( cls.__slots__ ) @@ -414,17 +414,17 @@ def test_de_json(self, bot, tp_scope_class_and_type): assert tp.user == self.user assert tp.invoice_payload == self.invoice_payload - assert cls.de_json(None, bot) is None - assert TransactionPartner.de_json({}, bot) is None + assert cls.de_json(None, offline_bot) is None + assert TransactionPartner.de_json({}, offline_bot) is None - def test_de_json_invalid_type(self, bot): + def test_de_json_invalid_type(self, offline_bot): json_dict = { "type": "invalid", "invoice_payload": self.invoice_payload, "withdrawal_state": self.withdrawal_state.to_dict(), "user": self.user.to_dict(), } - tp = TransactionPartner.de_json(json_dict, bot) + tp = TransactionPartner.de_json(json_dict, offline_bot) assert tp.api_kwargs == { "withdrawal_state": self.withdrawal_state.to_dict(), "user": self.user.to_dict(), @@ -434,7 +434,7 @@ def test_de_json_invalid_type(self, bot): assert type(tp) is TransactionPartner assert tp.type == "invalid" - def test_de_json_subclass(self, tp_scope_class, bot): + def test_de_json_subclass(self, tp_scope_class, offline_bot): """This makes sure that e.g. TransactionPartnerUser(data) never returns a TransactionPartnerFragment instance.""" json_dict = { @@ -443,7 +443,7 @@ def test_de_json_subclass(self, tp_scope_class, bot): "withdrawal_state": self.withdrawal_state.to_dict(), "user": self.user.to_dict(), } - assert type(tp_scope_class.de_json(json_dict, bot)) is tp_scope_class + assert type(tp_scope_class.de_json(json_dict, offline_bot)) is tp_scope_class def test_to_dict(self, transaction_partner): tp_dict = transaction_partner.to_dict() @@ -460,7 +460,7 @@ def test_type_enum_conversion(self): assert type(TransactionPartner("other").type) is TransactionPartnerType assert TransactionPartner("unknown").type == "unknown" - def test_equality(self, transaction_partner, bot): + def test_equality(self, transaction_partner, offline_bot): a = TransactionPartner("base_type") b = TransactionPartner("base_type") c = transaction_partner @@ -488,7 +488,7 @@ def test_equality(self, transaction_partner, bot): if hasattr(c, "user"): json_dict = c.to_dict() json_dict["user"] = User(2, "something", True).to_dict() - f = c.__class__.de_json(json_dict, bot) + f = c.__class__.de_json(json_dict, offline_bot) assert c != f assert hash(c) != hash(f) @@ -506,7 +506,7 @@ def test_slot_behaviour(self, revenue_withdrawal_state): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot, rws_scope_class_and_type): + def test_de_json(self, offline_bot, rws_scope_class_and_type): cls = rws_scope_class_and_type[0] type_ = rws_scope_class_and_type[1] @@ -515,7 +515,7 @@ def test_de_json(self, bot, rws_scope_class_and_type): "date": to_timestamp(self.date), "url": self.url, } - rws = RevenueWithdrawalState.de_json(json_dict, bot) + rws = RevenueWithdrawalState.de_json(json_dict, offline_bot) assert set(rws.api_kwargs.keys()) == {"date", "url"} - set(cls.__slots__) assert isinstance(rws, RevenueWithdrawalState) @@ -526,16 +526,16 @@ def test_de_json(self, bot, rws_scope_class_and_type): if "url" in cls.__slots__: assert rws.url == self.url - assert cls.de_json(None, bot) is None - assert RevenueWithdrawalState.de_json({}, bot) is None + assert cls.de_json(None, offline_bot) is None + assert RevenueWithdrawalState.de_json({}, offline_bot) is None - def test_de_json_invalid_type(self, bot): + def test_de_json_invalid_type(self, offline_bot): json_dict = { "type": "invalid", "date": to_timestamp(self.date), "url": self.url, } - rws = RevenueWithdrawalState.de_json(json_dict, bot) + rws = RevenueWithdrawalState.de_json(json_dict, offline_bot) assert rws.api_kwargs == { "date": to_timestamp(self.date), "url": self.url, @@ -544,7 +544,7 @@ def test_de_json_invalid_type(self, bot): assert type(rws) is RevenueWithdrawalState assert rws.type == "invalid" - def test_de_json_subclass(self, rws_scope_class, bot): + def test_de_json_subclass(self, rws_scope_class, offline_bot): """This makes sure that e.g. RevenueWithdrawalState(data) never returns a RevenueWithdrawalStateFailed instance.""" json_dict = { @@ -552,7 +552,7 @@ def test_de_json_subclass(self, rws_scope_class, bot): "date": to_timestamp(self.date), "url": self.url, } - assert type(rws_scope_class.de_json(json_dict, bot)) is rws_scope_class + assert type(rws_scope_class.de_json(json_dict, offline_bot)) is rws_scope_class def test_to_dict(self, revenue_withdrawal_state): rws_dict = revenue_withdrawal_state.to_dict() @@ -568,7 +568,7 @@ def test_type_enum_conversion(self): assert type(RevenueWithdrawalState("failed").type) is RevenueWithdrawalStateType assert RevenueWithdrawalState("unknown").type == "unknown" - def test_equality(self, revenue_withdrawal_state, bot): + def test_equality(self, revenue_withdrawal_state, offline_bot): a = RevenueWithdrawalState("base_type") b = RevenueWithdrawalState("base_type") c = revenue_withdrawal_state @@ -596,7 +596,7 @@ def test_equality(self, revenue_withdrawal_state, bot): if hasattr(c, "url"): json_dict = c.to_dict() json_dict["url"] = "something" - f = c.__class__.de_json(json_dict, bot) + f = c.__class__.de_json(json_dict, offline_bot) assert c == f assert hash(c) == hash(f) @@ -604,7 +604,7 @@ def test_equality(self, revenue_withdrawal_state, bot): if hasattr(c, "date"): json_dict = c.to_dict() json_dict["date"] = to_timestamp(datetime.datetime.utcnow()) - f = c.__class__.de_json(json_dict, bot) + f = c.__class__.de_json(json_dict, offline_bot) assert c != f assert hash(c) != hash(f) diff --git a/tests/test_story.py b/tests/test_story.py index 1aad292cb45..190c4ec133c 100644 --- a/tests/test_story.py +++ b/tests/test_story.py @@ -38,14 +38,14 @@ def test_slot_behaviour(self, story): assert getattr(story, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(story)) == len(set(mro_slots(story))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = {"chat": self.chat.to_dict(), "id": self.id} - story = Story.de_json(json_dict, bot) + story = Story.de_json(json_dict, offline_bot) assert story.api_kwargs == {} assert story.chat == self.chat assert story.id == self.id assert isinstance(story, Story) - assert Story.de_json(None, bot) is None + assert Story.de_json(None, offline_bot) is None def test_to_dict(self, story): story_dict = story.to_dict() diff --git a/tests/test_update.py b/tests/test_update.py index 46619fbfd9d..f2e9dbf610e 100644 --- a/tests/test_update.py +++ b/tests/test_update.py @@ -227,11 +227,11 @@ def test_slot_behaviour(self): assert len(mro_slots(update)) == len(set(mro_slots(update))), "duplicate slot" @pytest.mark.parametrize("paramdict", argvalues=params, ids=ids) - def test_de_json(self, bot, paramdict): + def test_de_json(self, offline_bot, paramdict): json_dict = {"update_id": self.update_id} # Convert the single update 'item' to a dict of that item and apply it to the json_dict json_dict.update({k: v.to_dict() for k, v in paramdict.items()}) - update = Update.de_json(json_dict, bot) + update = Update.de_json(json_dict, offline_bot) assert update.api_kwargs == {} assert update.update_id == self.update_id @@ -244,8 +244,8 @@ def test_de_json(self, bot, paramdict): assert getattr(update, _type) == paramdict[_type] assert i == 1 - def test_update_de_json_empty(self, bot): - update = Update.de_json(None, bot) + def test_update_de_json_empty(self, offline_bot): + update = Update.de_json(None, offline_bot) assert update is None diff --git a/tests/test_user.py b/tests/test_user.py index 073d0af58e0..d8a6265f0cf 100644 --- a/tests/test_user.py +++ b/tests/test_user.py @@ -91,8 +91,8 @@ def test_slot_behaviour(self, user): assert getattr(user, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(user)) == len(set(mro_slots(user))), "duplicate slot" - def test_de_json(self, json_dict, bot): - user = User.de_json(json_dict, bot) + def test_de_json(self, json_dict, offline_bot): + user = User.de_json(json_dict, offline_bot) assert user.api_kwargs == {} assert user.id == self.id_ diff --git a/tests/test_userprofilephotos.py b/tests/test_userprofilephotos.py index f0017ce6ca6..5ae686fad01 100644 --- a/tests/test_userprofilephotos.py +++ b/tests/test_userprofilephotos.py @@ -41,9 +41,9 @@ def test_slot_behaviour(self): assert getattr(inst, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(inst)) == len(set(mro_slots(inst))), "duplicate slot" - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = {"total_count": 2, "photos": [[y.to_dict() for y in x] for x in self.photos]} - user_profile_photos = UserProfilePhotos.de_json(json_dict, bot) + user_profile_photos = UserProfilePhotos.de_json(json_dict, offline_bot) assert user_profile_photos.api_kwargs == {} assert user_profile_photos.total_count == self.total_count assert user_profile_photos.photos == tuple(tuple(p) for p in self.photos) diff --git a/tests/test_videochat.py b/tests/test_videochat.py index 5fbdf8ba8eb..e5de669c672 100644 --- a/tests/test_videochat.py +++ b/tests/test_videochat.py @@ -105,9 +105,9 @@ def test_slot_behaviour(self, user1): assert getattr(action, attr, "err") != "err", f"got extra slot '{attr}'" assert len(mro_slots(action)) == len(set(mro_slots(action))), "duplicate slot" - def test_de_json(self, user1, user2, bot): + def test_de_json(self, user1, user2, offline_bot): json_data = {"users": [user1.to_dict(), user2.to_dict()]} - video_chat_participants = VideoChatParticipantsInvited.de_json(json_data, bot) + video_chat_participants = VideoChatParticipantsInvited.de_json(json_data, offline_bot) assert video_chat_participants.api_kwargs == {} assert isinstance(video_chat_participants.users, tuple) @@ -161,20 +161,20 @@ def test_slot_behaviour(self): def test_expected_values(self): assert VideoChatScheduled(self.start_date).start_date == self.start_date - def test_de_json(self, bot): - assert VideoChatScheduled.de_json({}, bot=bot) is None + def test_de_json(self, offline_bot): + assert VideoChatScheduled.de_json({}, bot=offline_bot) is None json_dict = {"start_date": to_timestamp(self.start_date)} - video_chat_scheduled = VideoChatScheduled.de_json(json_dict, bot) + video_chat_scheduled = VideoChatScheduled.de_json(json_dict, offline_bot) assert video_chat_scheduled.api_kwargs == {} assert abs(video_chat_scheduled.start_date - self.start_date) < dtm.timedelta(seconds=1) - def test_de_json_localization(self, tz_bot, bot, raw_bot): + def test_de_json_localization(self, tz_bot, offline_bot, raw_bot): json_dict = {"start_date": to_timestamp(self.start_date)} videochat_raw = VideoChatScheduled.de_json(json_dict, raw_bot) - videochat_bot = VideoChatScheduled.de_json(json_dict, bot) + videochat_bot = VideoChatScheduled.de_json(json_dict, offline_bot) videochat_tz = VideoChatScheduled.de_json(json_dict, tz_bot) # comparing utcoffsets because comparing timezones is unpredicatable diff --git a/tests/test_webappdata.py b/tests/test_webappdata.py index a13043042c2..ba8d4360831 100644 --- a/tests/test_webappdata.py +++ b/tests/test_webappdata.py @@ -46,9 +46,9 @@ def test_to_dict(self, web_app_data): assert web_app_data_dict["data"] == self.data assert web_app_data_dict["button_text"] == self.button_text - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = {"data": self.data, "button_text": self.button_text} - web_app_data = WebAppData.de_json(json_dict, bot) + web_app_data = WebAppData.de_json(json_dict, offline_bot) assert web_app_data.api_kwargs == {} assert web_app_data.data == self.data diff --git a/tests/test_webappinfo.py b/tests/test_webappinfo.py index 40d65873351..76dd018d59f 100644 --- a/tests/test_webappinfo.py +++ b/tests/test_webappinfo.py @@ -44,9 +44,9 @@ def test_to_dict(self, web_app_info): assert isinstance(web_app_info_dict, dict) assert web_app_info_dict["url"] == self.url - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = {"url": self.url} - web_app_info = WebAppInfo.de_json(json_dict, bot) + web_app_info = WebAppInfo.de_json(json_dict, offline_bot) assert web_app_info.api_kwargs == {} assert web_app_info.url == self.url diff --git a/tests/test_webhookinfo.py b/tests/test_webhookinfo.py index 48bb5ee38e6..cfd6810b1e2 100644 --- a/tests/test_webhookinfo.py +++ b/tests/test_webhookinfo.py @@ -72,7 +72,7 @@ def test_to_dict(self, webhook_info): == self.last_synchronization_error_date ) - def test_de_json(self, bot): + def test_de_json(self, offline_bot): json_dict = { "url": self.url, "has_custom_certificate": self.has_custom_certificate, @@ -83,7 +83,7 @@ def test_de_json(self, bot): "ip_address": self.ip_address, "last_synchronization_error_date": self.last_synchronization_error_date, } - webhook_info = WebhookInfo.de_json(json_dict, bot) + webhook_info = WebhookInfo.de_json(json_dict, offline_bot) assert webhook_info.api_kwargs == {} assert webhook_info.url == self.url @@ -99,10 +99,10 @@ def test_de_json(self, bot): self.last_synchronization_error_date ) - none = WebhookInfo.de_json(None, bot) + none = WebhookInfo.de_json(None, offline_bot) assert none is None - def test_de_json_localization(self, bot, raw_bot, tz_bot): + def test_de_json_localization(self, offline_bot, raw_bot, tz_bot): json_dict = { "url": self.url, "has_custom_certificate": self.has_custom_certificate, @@ -113,7 +113,7 @@ def test_de_json_localization(self, bot, raw_bot, tz_bot): "ip_address": self.ip_address, "last_synchronization_error_date": self.last_synchronization_error_date, } - webhook_info_bot = WebhookInfo.de_json(json_dict, bot) + webhook_info_bot = WebhookInfo.de_json(json_dict, offline_bot) webhook_info_raw = WebhookInfo.de_json(json_dict, raw_bot) webhook_info_tz = WebhookInfo.de_json(json_dict, tz_bot) From e13a30db5d20bcb2e6158a75795224e0c719dd44 Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Mon, 9 Sep 2024 22:14:20 +0200 Subject: [PATCH 8/9] Review and failing test --- tests/conftest.py | 1 - tests/request/test_request.py | 4 ++-- tests/test_bot.py | 24 ++++++++++++------------ tests/test_keyboardbutton.py | 2 +- 4 files changed, 15 insertions(+), 16 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index b677bbe5964..c2019cd6df7 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -119,7 +119,6 @@ def _disallow_requests_in_without_request_tests(request): return if "bot" in request.fixturenames: - print(request.fixturenames) pytest.fail( f"Test function {request.function} in test class {name} should not have a `bot` " f"fixture. Use `offline_bot` instead." diff --git a/tests/request/test_request.py b/tests/request/test_request.py index 34fd8d2c5d6..955a4a40fb9 100644 --- a/tests/request/test_request.py +++ b/tests/request/test_request.py @@ -85,9 +85,9 @@ async def httpx_request(): ) class TestNoSocksHTTP2WithoutRequest: async def test_init(self, offline_bot): - with pytest.raises(RuntimeError, match=r"python-telegram-offline_bot\[socks\]"): + with pytest.raises(RuntimeError, match=r"python-telegram-bot\[socks\]"): HTTPXRequest(proxy="socks5://foo") - with pytest.raises(RuntimeError, match=r"python-telegram-offline_bot\[http2\]"): + with pytest.raises(RuntimeError, match=r"python-telegram-bot\[http2\]"): HTTPXRequest(http_version="2") diff --git a/tests/test_bot.py b/tests/test_bot.py index df7cc1d9b70..fa723093f37 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -99,7 +99,7 @@ from tests.auxil.ci_bots import FALLBACKS from tests.auxil.envvars import GITHUB_ACTION, TEST_WITH_OPT_DEPS from tests.auxil.files import data_file -from tests.auxil.networking import NonchalantHttpxRequest, expect_bad_request +from tests.auxil.networking import OfflineRequest, expect_bad_request from tests.auxil.pytest_classes import PytestBot, PytestExtBot, make_bot from tests.auxil.slots import mro_slots @@ -255,7 +255,7 @@ async def initialize(*args, **kwargs): async def stop(*args, **kwargs): self.test_flag.append("stop") - temp_bot = PytestBot(token=offline_bot.token, request=NonchalantHttpxRequest()) + temp_bot = PytestBot(token=offline_bot.token, request=OfflineRequest()) orig_stop = temp_bot.request.shutdown try: @@ -735,7 +735,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "id": "123", "type": "document", "document_url": ( - "https://raw.githubusercontent.com/python-telegram-offline_bot" + "https://raw.githubusercontent.com/python-telegram-bot" "/logos/master/logo/png/ptb-logo_240.png" ), "mime_type": "image/png", @@ -753,7 +753,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): else: button_dict = { "text": "button_text", - "web_app": {"url": "https://python-telegram-offline_bot.org"}, + "web_app": {"url": "https://python-telegram-bot.org"}, } expected["button"] = button_dict @@ -766,7 +766,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): InlineQueryResultDocument( id="123", document_url=( - "https://raw.githubusercontent.com/python-telegram-offline_bot/logos/master/" + "https://raw.githubusercontent.com/python-telegram-bot/logos/master/" "logo/png/ptb-logo_240.png" ), title="test_result", @@ -782,7 +782,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): ) elif button_type == "web_app": button = InlineQueryResultsButton( - text="button_text", web_app=WebAppInfo("https://python-telegram-offline_bot.org") + text="button_text", web_app=WebAppInfo("https://python-telegram-bot.org") ) else: button = None @@ -843,7 +843,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "type": "document", "document_url": ( "https://raw.githubusercontent.com/" - "python-telegram-offline_bot/logos/master/logo/png/" + "python-telegram-bot/logos/master/logo/png/" "ptb-logo_240.png" ), "mime_type": "image/png", @@ -863,7 +863,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): InlineQueryResultDocument( id="123", document_url=( - "https://raw.githubusercontent.com/python-telegram-offline_bot/logos/master/" + "https://raw.githubusercontent.com/python-telegram-bot/logos/master/" "logo/png/ptb-logo_240.png" ), title="test_result", @@ -935,7 +935,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): "type": InlineQueryResultType.DOCUMENT, "document_url": ( "https://raw.githubusercontent.com/" - "python-telegram-offline_bot/logos/master/logo/png/" + "python-telegram-bot/logos/master/logo/png/" "ptb-logo_240.png" ), "mime_type": "image/png", @@ -962,7 +962,7 @@ async def make_assertion(url, request_data: RequestData, *args, **kwargs): InlineQueryResultDocument( id="123", document_url=( - "https://raw.githubusercontent.com/python-telegram-offline_bot/logos/master/" + "https://raw.githubusercontent.com/python-telegram-bot/logos/master/" "logo/png/ptb-logo_240.png" ), title="test_result", @@ -1729,7 +1729,7 @@ async def make_assertion( try: replace_button = InlineKeyboardButton(text="replace", callback_data="replace_test") no_replace_button = InlineKeyboardButton( - text="no_replace", url="http://python-telegram-offline_bot.org/" + text="no_replace", url="http://python-telegram-bot.org/" ) reply_markup = InlineKeyboardMarkup.from_row( [ @@ -1747,7 +1747,7 @@ async def make_assertion( ), InlineQueryResultVoice( "22", - "https://python-telegram-offline_bot.org/static/testfiles/telegram.ogg", + "https://python-telegram-bot.org/static/testfiles/telegram.ogg", title="second", ), ] diff --git a/tests/test_keyboardbutton.py b/tests/test_keyboardbutton.py index 216da894beb..91f5ccab71f 100644 --- a/tests/test_keyboardbutton.py +++ b/tests/test_keyboardbutton.py @@ -81,7 +81,7 @@ def test_to_dict(self, keyboard_button): assert keyboard_button_dict["request_users"] == keyboard_button.request_users.to_dict() @pytest.mark.parametrize("request_user", [True, False]) - def test_de_json(self, offline_bot, request_user): + def test_de_json(self, request_user): json_dict = { "text": self.text, "request_location": self.request_location, From 948e4c9484b8e0241738c8a8acd11cbeaac56723 Mon Sep 17 00:00:00 2001 From: Hinrich Mahler <22366557+Bibo-Joshi@users.noreply.github.com> Date: Wed, 11 Sep 2024 22:05:34 +0200 Subject: [PATCH 9/9] Better documentation/commentary for _disallow_requests_in_without_request_tests --- tests/conftest.py | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/tests/conftest.py b/tests/conftest.py index c2019cd6df7..b637f89573c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -104,12 +104,18 @@ def pytest_collection_modifyitems(items: List[pytest.Item]): # matrix entries @pytest.fixture(autouse=True) def _disallow_requests_in_without_request_tests(request): - """This fixture prevents tests that don't require requests from using the online-bot.""" + """This fixture prevents tests that don't require requests from using the online-bot. + This is a sane-effort approach on trying to prevent requests from being made in the + *WithoutRequest classes. Note that we can not prevent all requests, as one can still + manually build a `Bot` object or use `httpx` directly. See #4317 and #4465 for some + discussion. + """ if type(request).__name__ == "SubRequest": - # We want to allow *WithoutRequest test classes to use fixtures that do use requests, - # e.g. `animation` and so on. Unfortunately the `SubRequest` class is not public, so - # we check only the name for less dependency on pytests internal structure. + # Some fixtures used in the *WithoutRequests test classes do use requests, e.g. + # `animation`. Separating that would be too much effort, hence we allow that. + # Unfortunately the `SubRequest` class is not public, so we check only the name for + # less dependency on pytest's internal structure. return if not request.cls: pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy