Skip to content

Reduce Creation of HTTP Clients in Tests #4493

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions tests/auxil/build_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,17 @@
DATE = datetime.datetime.now()


def make_message(text, **kwargs):
def make_message(text: str, offline: bool = True, **kwargs):
"""
Testing utility factory to create a fake ``telegram.Message`` with
reasonable defaults for mimicking a real message.
:param text: (str) message text
:param offline: (bool) whether the bot should be offline
:return: a (fake) ``telegram.Message``
"""
bot = kwargs.pop("bot", None)
if bot is None:
bot = make_bot(BOT_INFO_PROVIDER.get_info())
bot = make_bot(BOT_INFO_PROVIDER.get_info(), offline=offline)
message = Message(
message_id=1,
from_user=kwargs.pop("user", User(id=1, first_name="", is_bot=False)),
Expand Down
2 changes: 1 addition & 1 deletion tests/auxil/pytest_classes.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class PytestUpdater(Updater):
pass


def make_bot(bot_info=None, offline: bool = False, **kwargs):
def make_bot(bot_info=None, offline: bool = True, **kwargs):
"""
Tests are executed on tg.ext.ExtBot, as that class only extends the functionality of tg.bot
"""
Expand Down
10 changes: 5 additions & 5 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ def bot_info() -> Dict[str, str]:
@pytest.fixture(scope="session")
async def bot(bot_info):
"""Makes an ExtBot instance with the given bot_info"""
async with make_bot(bot_info) as _bot:
async with make_bot(bot_info, offline=False) as _bot:
yield _bot


Expand All @@ -168,13 +168,13 @@ async def offline_bot(bot_info):
@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)
return make_bot(bot_info, offline=False)


@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) as _bot:
async with make_bot(bot_info, arbitrary_callback_data=True, offline=False) as _bot:
yield _bot


Expand Down Expand Up @@ -204,7 +204,7 @@ async def default_bot(request, bot_info):
# If the bot is already created, return it. Else make a new one.
default_bot = _default_bots.get(defaults)
if default_bot is None:
default_bot = make_bot(bot_info, defaults=defaults)
default_bot = make_bot(bot_info, defaults=defaults, offline=False)
await default_bot.initialize()
_default_bots[defaults] = default_bot # Defaults object is hashable
return default_bot
Expand All @@ -216,7 +216,7 @@ async def tz_bot(timezone, bot_info):
try: # If the bot is already created, return it. Saves time since get_me is not called again.
return _default_bots[defaults]
except KeyError:
default_bot = make_bot(bot_info, defaults=defaults)
default_bot = make_bot(bot_info, defaults=defaults, offline=False)
await default_bot.initialize()
_default_bots[defaults] = default_bot
return default_bot
Expand Down
15 changes: 11 additions & 4 deletions tests/ext/test_basepersistence.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import logging
import sys
import time
from http import HTTPStatus
from pathlib import Path
from typing import NamedTuple, Optional

Expand All @@ -43,8 +44,9 @@
PersistenceInput,
filters,
)
from telegram.request import HTTPXRequest
from telegram.warnings import PTBUserWarning
from tests.auxil.build_messages import make_message_update
from tests.auxil.build_messages import make_message, make_message_update
from tests.auxil.pytest_classes import PytestApplication, make_bot
from tests.auxil.slots import mro_slots

Expand Down Expand Up @@ -245,9 +247,9 @@ def build_papp(
persistence = TrackingPersistence(store_data=store_data, fill_data=fill_data)

if bot_info is not None:
bot = make_bot(bot_info, arbitrary_callback_data=True)
bot = make_bot(bot_info, arbitrary_callback_data=True, offline=False)
else:
bot = make_bot(token=token, arbitrary_callback_data=True)
bot = make_bot(token=token, arbitrary_callback_data=True, offline=False)
return (
ApplicationBuilder()
.bot(bot)
Expand All @@ -262,7 +264,7 @@ def build_conversation_handler(name: str, persistent: bool = True) -> BaseHandle


@pytest.fixture
def papp(request, bot_info) -> Application:
def papp(request, bot_info, monkeypatch) -> Application:
papp_input = request.param
store_data = {}
if papp_input.bot_data is not None:
Expand All @@ -274,6 +276,11 @@ def papp(request, bot_info) -> Application:
if papp_input.callback_data is not None:
store_data["callback_data"] = papp_input.callback_data

async def do_request(*args, **kwargs):
return HTTPStatus.OK, make_message(text="text")

monkeypatch.setattr(HTTPXRequest, "do_request", do_request)

app = build_papp(
bot_info=bot_info,
store_data=store_data,
Expand Down
2 changes: 1 addition & 1 deletion tests/ext/test_callbackcontext.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ def test_drop_callback_data_exception(self, bot, app, raw_bot):
app.bot = bot

async def test_drop_callback_data(self, bot, chat_id):
new_bot = make_bot(token=bot.token, arbitrary_callback_data=True)
new_bot = make_bot(token=bot.token, arbitrary_callback_data=True, offline=False)
app = ApplicationBuilder().bot(new_bot).build()

update = Update(
Expand Down
10 changes: 5 additions & 5 deletions tests/test_bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,13 +361,13 @@ async def test_equality(self):
"link",
],
)
async def test_get_me_and_properties_not_initialized(self, offline_bot: Bot, attribute):
offline_bot = Bot(token=offline_bot.token)
async def test_get_me_and_properties_not_initialized(self, attribute):
bot = make_bot(offline=True, token="randomtoken")
try:
with pytest.raises(RuntimeError, match="not properly initialized"):
offline_bot[attribute]
bot[attribute]
finally:
await offline_bot.shutdown()
await bot.shutdown()

async def test_get_me_and_properties(self, offline_bot):
get_me_bot = await ExtBot(offline_bot.token).get_me()
Expand Down Expand Up @@ -1564,7 +1564,7 @@ async def post(url, request_data: RequestData, *args, **kwargs):
[(True, 1024), (False, 1024), (0, 0), (None, None)],
)
async def test_callback_data_maxsize(self, bot_info, acd_in, maxsize):
async with make_bot(bot_info, arbitrary_callback_data=acd_in) as acd_bot:
async with make_bot(bot_info, arbitrary_callback_data=acd_in, offline=True) as acd_bot:
if acd_in is not False:
assert acd_bot.callback_data_cache.maxsize == maxsize
else:
Expand Down
Loading