mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2024-11-21 14:46:29 +01:00
Reduce Creation of HTTP Clients in Tests (#4493)
This commit is contained in:
parent
bd3cdbcdbd
commit
79e589b39e
6 changed files with 26 additions and 18 deletions
|
@ -27,16 +27,17 @@ CMD_PATTERN = re.compile(r"/[\da-z_]{1,32}(?:@\w{1,32})?")
|
||||||
DATE = datetime.datetime.now()
|
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
|
Testing utility factory to create a fake ``telegram.Message`` with
|
||||||
reasonable defaults for mimicking a real message.
|
reasonable defaults for mimicking a real message.
|
||||||
:param text: (str) message text
|
:param text: (str) message text
|
||||||
|
:param offline: (bool) whether the bot should be offline
|
||||||
:return: a (fake) ``telegram.Message``
|
:return: a (fake) ``telegram.Message``
|
||||||
"""
|
"""
|
||||||
bot = kwargs.pop("bot", None)
|
bot = kwargs.pop("bot", None)
|
||||||
if bot is 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 = Message(
|
||||||
message_id=1,
|
message_id=1,
|
||||||
from_user=kwargs.pop("user", User(id=1, first_name="", is_bot=False)),
|
from_user=kwargs.pop("user", User(id=1, first_name="", is_bot=False)),
|
||||||
|
|
|
@ -93,7 +93,7 @@ class PytestUpdater(Updater):
|
||||||
pass
|
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
|
Tests are executed on tg.ext.ExtBot, as that class only extends the functionality of tg.bot
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -152,7 +152,7 @@ def bot_info() -> Dict[str, str]:
|
||||||
@pytest.fixture(scope="session")
|
@pytest.fixture(scope="session")
|
||||||
async def bot(bot_info):
|
async def bot(bot_info):
|
||||||
"""Makes an ExtBot instance with the given 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
|
yield _bot
|
||||||
|
|
||||||
|
|
||||||
|
@ -168,13 +168,13 @@ async def offline_bot(bot_info):
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def one_time_bot(bot_info):
|
def one_time_bot(bot_info):
|
||||||
"""A function scoped bot since the session bot would shutdown when `async with app` finishes"""
|
"""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")
|
@pytest.fixture(scope="session")
|
||||||
async def cdc_bot(bot_info):
|
async def cdc_bot(bot_info):
|
||||||
"""Makes an ExtBot instance with the given bot_info that uses arbitrary callback_data"""
|
"""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
|
yield _bot
|
||||||
|
|
||||||
|
|
||||||
|
@ -204,7 +204,7 @@ async def default_bot(request, bot_info):
|
||||||
# If the bot is already created, return it. Else make a new one.
|
# If the bot is already created, return it. Else make a new one.
|
||||||
default_bot = _default_bots.get(defaults)
|
default_bot = _default_bots.get(defaults)
|
||||||
if default_bot is None:
|
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()
|
await default_bot.initialize()
|
||||||
_default_bots[defaults] = default_bot # Defaults object is hashable
|
_default_bots[defaults] = default_bot # Defaults object is hashable
|
||||||
return default_bot
|
return default_bot
|
||||||
|
@ -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.
|
try: # If the bot is already created, return it. Saves time since get_me is not called again.
|
||||||
return _default_bots[defaults]
|
return _default_bots[defaults]
|
||||||
except KeyError:
|
except KeyError:
|
||||||
default_bot = make_bot(bot_info, defaults=defaults)
|
default_bot = make_bot(bot_info, defaults=defaults, offline=False)
|
||||||
await default_bot.initialize()
|
await default_bot.initialize()
|
||||||
_default_bots[defaults] = default_bot
|
_default_bots[defaults] = default_bot
|
||||||
return default_bot
|
return default_bot
|
||||||
|
|
|
@ -24,6 +24,7 @@ import functools
|
||||||
import logging
|
import logging
|
||||||
import sys
|
import sys
|
||||||
import time
|
import time
|
||||||
|
from http import HTTPStatus
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import NamedTuple, Optional
|
from typing import NamedTuple, Optional
|
||||||
|
|
||||||
|
@ -43,8 +44,9 @@ from telegram.ext import (
|
||||||
PersistenceInput,
|
PersistenceInput,
|
||||||
filters,
|
filters,
|
||||||
)
|
)
|
||||||
|
from telegram.request import HTTPXRequest
|
||||||
from telegram.warnings import PTBUserWarning
|
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.pytest_classes import PytestApplication, make_bot
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
@ -245,9 +247,9 @@ def build_papp(
|
||||||
persistence = TrackingPersistence(store_data=store_data, fill_data=fill_data)
|
persistence = TrackingPersistence(store_data=store_data, fill_data=fill_data)
|
||||||
|
|
||||||
if bot_info is not None:
|
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:
|
else:
|
||||||
bot = make_bot(token=token, arbitrary_callback_data=True)
|
bot = make_bot(token=token, arbitrary_callback_data=True, offline=False)
|
||||||
return (
|
return (
|
||||||
ApplicationBuilder()
|
ApplicationBuilder()
|
||||||
.bot(bot)
|
.bot(bot)
|
||||||
|
@ -262,7 +264,7 @@ def build_conversation_handler(name: str, persistent: bool = True) -> BaseHandle
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
def papp(request, bot_info) -> Application:
|
def papp(request, bot_info, monkeypatch) -> Application:
|
||||||
papp_input = request.param
|
papp_input = request.param
|
||||||
store_data = {}
|
store_data = {}
|
||||||
if papp_input.bot_data is not None:
|
if papp_input.bot_data is not None:
|
||||||
|
@ -274,6 +276,11 @@ def papp(request, bot_info) -> Application:
|
||||||
if papp_input.callback_data is not None:
|
if papp_input.callback_data is not None:
|
||||||
store_data["callback_data"] = papp_input.callback_data
|
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(
|
app = build_papp(
|
||||||
bot_info=bot_info,
|
bot_info=bot_info,
|
||||||
store_data=store_data,
|
store_data=store_data,
|
||||||
|
|
|
@ -211,7 +211,7 @@ class TestCallbackContext:
|
||||||
app.bot = bot
|
app.bot = bot
|
||||||
|
|
||||||
async def test_drop_callback_data(self, bot, chat_id):
|
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()
|
app = ApplicationBuilder().bot(new_bot).build()
|
||||||
|
|
||||||
update = Update(
|
update = Update(
|
||||||
|
|
|
@ -361,13 +361,13 @@ class TestBotWithoutRequest:
|
||||||
"link",
|
"link",
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
async def test_get_me_and_properties_not_initialized(self, offline_bot: Bot, attribute):
|
async def test_get_me_and_properties_not_initialized(self, attribute):
|
||||||
offline_bot = Bot(token=offline_bot.token)
|
bot = make_bot(offline=True, token="randomtoken")
|
||||||
try:
|
try:
|
||||||
with pytest.raises(RuntimeError, match="not properly initialized"):
|
with pytest.raises(RuntimeError, match="not properly initialized"):
|
||||||
offline_bot[attribute]
|
bot[attribute]
|
||||||
finally:
|
finally:
|
||||||
await offline_bot.shutdown()
|
await bot.shutdown()
|
||||||
|
|
||||||
async def test_get_me_and_properties(self, offline_bot):
|
async def test_get_me_and_properties(self, offline_bot):
|
||||||
get_me_bot = await ExtBot(offline_bot.token).get_me()
|
get_me_bot = await ExtBot(offline_bot.token).get_me()
|
||||||
|
@ -1564,7 +1564,7 @@ class TestBotWithoutRequest:
|
||||||
[(True, 1024), (False, 1024), (0, 0), (None, None)],
|
[(True, 1024), (False, 1024), (0, 0), (None, None)],
|
||||||
)
|
)
|
||||||
async def test_callback_data_maxsize(self, bot_info, acd_in, maxsize):
|
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:
|
if acd_in is not False:
|
||||||
assert acd_bot.callback_data_cache.maxsize == maxsize
|
assert acd_bot.callback_data_cache.maxsize == maxsize
|
||||||
else:
|
else:
|
||||||
|
|
Loading…
Reference in a new issue