mirror of
https://github.com/python-telegram-bot/python-telegram-bot.git
synced 2024-10-23 17:36:26 +02:00
Bump ruff
and Add New Rules (#4416)
Co-authored-by: Bibo-Joshi <22366557+Bibo-Joshi@users.noreply.github.com>
This commit is contained in:
parent
1787586902
commit
8f9db63f4f
61 changed files with 161 additions and 151 deletions
|
@ -7,7 +7,7 @@ ci:
|
||||||
|
|
||||||
repos:
|
repos:
|
||||||
- repo: https://github.com/astral-sh/ruff-pre-commit
|
- repo: https://github.com/astral-sh/ruff-pre-commit
|
||||||
rev: 'v0.5.0'
|
rev: 'v0.5.6'
|
||||||
hooks:
|
hooks:
|
||||||
- id: ruff
|
- id: ruff
|
||||||
name: ruff
|
name: ruff
|
||||||
|
|
|
@ -16,6 +16,7 @@
|
||||||
# You should have received a copy of the GNU Lesser Public License
|
# You should have received a copy of the GNU Lesser Public License
|
||||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||||
import collections.abc
|
import collections.abc
|
||||||
|
import contextlib
|
||||||
import inspect
|
import inspect
|
||||||
import re
|
import re
|
||||||
import typing
|
import typing
|
||||||
|
@ -153,13 +154,11 @@ def autodoc_process_docstring(
|
||||||
if isinstance(obj, telegram.ext.filters.BaseFilter):
|
if isinstance(obj, telegram.ext.filters.BaseFilter):
|
||||||
obj = obj.__class__
|
obj = obj.__class__
|
||||||
|
|
||||||
try:
|
with contextlib.suppress(Exception):
|
||||||
source_lines, start_line = inspect.getsourcelines(obj)
|
source_lines, start_line = inspect.getsourcelines(obj)
|
||||||
end_line = start_line + len(source_lines)
|
end_line = start_line + len(source_lines)
|
||||||
file = Path(inspect.getsourcefile(obj)).relative_to(FILE_ROOT)
|
file = Path(inspect.getsourcefile(obj)).relative_to(FILE_ROOT)
|
||||||
LINE_NUMBERS[name] = (file, start_line, end_line)
|
LINE_NUMBERS[name] = (file, start_line, end_line)
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
# Since we don't document the `__init__`, we call this manually to have it available for
|
# Since we don't document the `__init__`, we call this manually to have it available for
|
||||||
# attributes -- see the note above
|
# attributes -- see the note above
|
||||||
|
|
|
@ -88,7 +88,6 @@ class TGConstXRefRole(PyXRefRole):
|
||||||
refnode.rawsource,
|
refnode.rawsource,
|
||||||
CONSTANTS_ROLE,
|
CONSTANTS_ROLE,
|
||||||
)
|
)
|
||||||
return title, target
|
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
sphinx_logger.exception(
|
sphinx_logger.exception(
|
||||||
"%s:%d: WARNING: Did not convert reference %s due to an exception.",
|
"%s:%d: WARNING: Did not convert reference %s due to an exception.",
|
||||||
|
@ -98,3 +97,5 @@ class TGConstXRefRole(PyXRefRole):
|
||||||
exc_info=exc,
|
exc_info=exc,
|
||||||
)
|
)
|
||||||
return title, target
|
return title, target
|
||||||
|
else:
|
||||||
|
return title, target
|
||||||
|
|
|
@ -128,14 +128,21 @@ explicit-preview-rules = true # TODO: Drop this when RUF022 and RUF023 are out
|
||||||
ignore = ["PLR2004", "PLR0911", "PLR0912", "PLR0913", "PLR0915", "PERF203"]
|
ignore = ["PLR2004", "PLR0911", "PLR0912", "PLR0913", "PLR0915", "PERF203"]
|
||||||
select = ["E", "F", "I", "PL", "UP", "RUF", "PTH", "C4", "B", "PIE", "SIM", "RET", "RSE",
|
select = ["E", "F", "I", "PL", "UP", "RUF", "PTH", "C4", "B", "PIE", "SIM", "RET", "RSE",
|
||||||
"G", "ISC", "PT", "ASYNC", "TCH", "SLOT", "PERF", "PYI", "FLY", "AIR", "RUF022",
|
"G", "ISC", "PT", "ASYNC", "TCH", "SLOT", "PERF", "PYI", "FLY", "AIR", "RUF022",
|
||||||
"RUF023", "Q", "INP", "W", "YTT", "DTZ", "ARG", "T20", "FURB"]
|
"RUF023", "Q", "INP", "W", "YTT", "DTZ", "ARG", "T20", "FURB", "DOC", "TRY",
|
||||||
|
"D100", "D101", "D102", "D103", "D300", "D418", "D419", "S"]
|
||||||
# Add "A (flake8-builtins)" after we drop pylint
|
# Add "A (flake8-builtins)" after we drop pylint
|
||||||
|
|
||||||
[tool.ruff.lint.per-file-ignores]
|
[tool.ruff.lint.per-file-ignores]
|
||||||
"tests/*.py" = ["B018"]
|
"tests/*.py" = ["B018"]
|
||||||
"tests/**.py" = ["RUF012", "ASYNC230", "DTZ", "ARG", "T201"]
|
"tests/**.py" = ["RUF012", "ASYNC230", "DTZ", "ARG", "T201", "ASYNC109", "D", "S", "TRY"]
|
||||||
"docs/**.py" = ["INP001", "ARG"]
|
"telegram/**.py" = ["TRY003"]
|
||||||
"examples/**.py" = ["ARG"]
|
"telegram/ext/_applicationbuilder.py" = ["TRY004"]
|
||||||
|
"telegram/ext/filters.py" = ["D102"]
|
||||||
|
"docs/**.py" = ["INP001", "ARG", "D", "TRY003", "S"]
|
||||||
|
"examples/**.py" = ["ARG", "D", "S105", "TRY003"]
|
||||||
|
|
||||||
|
[tool.ruff.lint.pydocstyle]
|
||||||
|
convention = "google"
|
||||||
|
|
||||||
# PYLINT:
|
# PYLINT:
|
||||||
[tool.pylint."messages control"]
|
[tool.pylint."messages control"]
|
||||||
|
|
|
@ -17,7 +17,7 @@
|
||||||
# You should have received a copy of the GNU Lesser Public License
|
# You should have received a copy of the GNU Lesser Public License
|
||||||
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
# along with this program. If not, see [http://www.gnu.org/licenses/].
|
||||||
# pylint: disable=missing-module-docstring
|
# pylint: disable=missing-module-docstring
|
||||||
# ruff: noqa: T201
|
# ruff: noqa: T201, D100, S603, S607
|
||||||
import subprocess
|
import subprocess
|
||||||
import sys
|
import sys
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
|
|
|
@ -324,10 +324,10 @@ class Bot(TelegramObject, AsyncContextManager["Bot"]):
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
await self.initialize()
|
await self.initialize()
|
||||||
return self
|
except Exception:
|
||||||
except Exception as exc:
|
|
||||||
await self.shutdown()
|
await self.shutdown()
|
||||||
raise exc
|
raise
|
||||||
|
return self
|
||||||
|
|
||||||
async def __aexit__(
|
async def __aexit__(
|
||||||
self,
|
self,
|
||||||
|
@ -4271,7 +4271,7 @@ class Bot(TelegramObject, AsyncContextManager["Bot"]):
|
||||||
self,
|
self,
|
||||||
offset: Optional[int] = None,
|
offset: Optional[int] = None,
|
||||||
limit: Optional[int] = None,
|
limit: Optional[int] = None,
|
||||||
timeout: Optional[int] = None,
|
timeout: Optional[int] = None, # noqa: ASYNC109
|
||||||
allowed_updates: Optional[Sequence[str]] = None,
|
allowed_updates: Optional[Sequence[str]] = None,
|
||||||
*,
|
*,
|
||||||
read_timeout: ODVInput[float] = DEFAULT_NONE,
|
read_timeout: ODVInput[float] = DEFAULT_NONE,
|
||||||
|
@ -4387,7 +4387,7 @@ class Bot(TelegramObject, AsyncContextManager["Bot"]):
|
||||||
self._LOGGER.critical(
|
self._LOGGER.critical(
|
||||||
"Error while parsing updates! Received data was %r", result, exc_info=exc
|
"Error while parsing updates! Received data was %r", result, exc_info=exc
|
||||||
)
|
)
|
||||||
raise exc
|
raise
|
||||||
|
|
||||||
async def set_webhook(
|
async def set_webhook(
|
||||||
self,
|
self,
|
||||||
|
|
|
@ -414,7 +414,7 @@ class TelegramObject:
|
||||||
obj = cls(**data, api_kwargs=api_kwargs)
|
obj = cls(**data, api_kwargs=api_kwargs)
|
||||||
except TypeError as exc:
|
except TypeError as exc:
|
||||||
if "__init__() got an unexpected keyword argument" not in str(exc):
|
if "__init__() got an unexpected keyword argument" not in str(exc):
|
||||||
raise exc
|
raise
|
||||||
|
|
||||||
if cls.__INIT_PARAMS_CHECK is not cls:
|
if cls.__INIT_PARAMS_CHECK is not cls:
|
||||||
signature = inspect.signature(cls)
|
signature = inspect.signature(cls)
|
||||||
|
|
|
@ -250,7 +250,7 @@ class AIORateLimiter(BaseRateLimiter[int]):
|
||||||
_LOGGER.exception(
|
_LOGGER.exception(
|
||||||
"Rate limit hit after maximum of %d retries", max_retries, exc_info=exc
|
"Rate limit hit after maximum of %d retries", max_retries, exc_info=exc
|
||||||
)
|
)
|
||||||
raise exc
|
raise
|
||||||
|
|
||||||
sleep = exc.retry_after + 0.1
|
sleep = exc.retry_after + 0.1
|
||||||
_LOGGER.info("Rate limit hit. Retrying after %f seconds", sleep)
|
_LOGGER.info("Rate limit hit. Retrying after %f seconds", sleep)
|
||||||
|
|
|
@ -384,10 +384,10 @@ class Application(Generic[BT, CCT, UD, CD, BD, JQ], AsyncContextManager["Applica
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
await self.initialize()
|
await self.initialize()
|
||||||
return self
|
except Exception:
|
||||||
except Exception as exc:
|
|
||||||
await self.shutdown()
|
await self.shutdown()
|
||||||
raise exc
|
raise
|
||||||
|
return self
|
||||||
|
|
||||||
async def __aexit__(
|
async def __aexit__(
|
||||||
self,
|
self,
|
||||||
|
@ -646,9 +646,9 @@ class Application(Generic[BT, CCT, UD, CD, BD, JQ], AsyncContextManager["Applica
|
||||||
)
|
)
|
||||||
_LOGGER.info("Application started")
|
_LOGGER.info("Application started")
|
||||||
|
|
||||||
except Exception as exc:
|
except Exception:
|
||||||
self._running = False
|
self._running = False
|
||||||
raise exc
|
raise
|
||||||
|
|
||||||
async def stop(self) -> None:
|
async def stop(self) -> None:
|
||||||
"""Stops the process after processing any pending updates or tasks created by
|
"""Stops the process after processing any pending updates or tasks created by
|
||||||
|
@ -1227,7 +1227,7 @@ class Application(Generic[BT, CCT, UD, CD, BD, JQ], AsyncContextManager["Applica
|
||||||
await self.process_error(update=update, error=exception, coroutine=coroutine)
|
await self.process_error(update=update, error=exception, coroutine=coroutine)
|
||||||
|
|
||||||
# Raise exception so that it can be set on the task and retrieved by task.exception()
|
# Raise exception so that it can be set on the task and retrieved by task.exception()
|
||||||
raise exception
|
raise
|
||||||
finally:
|
finally:
|
||||||
self._mark_for_persistence_update(update=update)
|
self._mark_for_persistence_update(update=update)
|
||||||
|
|
||||||
|
@ -1445,14 +1445,16 @@ class Application(Generic[BT, CCT, UD, CD, BD, JQ], AsyncContextManager["Applica
|
||||||
1: [CallbackQueryHandler(...), CommandHandler(...)]
|
1: [CallbackQueryHandler(...), CommandHandler(...)]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
:exc:`TypeError`: If the combination of arguments is invalid.
|
||||||
"""
|
"""
|
||||||
if isinstance(handlers, dict) and not isinstance(group, DefaultValue):
|
if isinstance(handlers, dict) and not isinstance(group, DefaultValue):
|
||||||
raise ValueError("The `group` argument can only be used with a sequence of handlers.")
|
raise TypeError("The `group` argument can only be used with a sequence of handlers.")
|
||||||
|
|
||||||
if isinstance(handlers, dict):
|
if isinstance(handlers, dict):
|
||||||
for handler_group, grp_handlers in handlers.items():
|
for handler_group, grp_handlers in handlers.items():
|
||||||
if not isinstance(grp_handlers, (list, tuple)):
|
if not isinstance(grp_handlers, (list, tuple)):
|
||||||
raise ValueError(f"Handlers for group {handler_group} must be a list or tuple")
|
raise TypeError(f"Handlers for group {handler_group} must be a list or tuple")
|
||||||
|
|
||||||
for handler in grp_handlers:
|
for handler in grp_handlers:
|
||||||
self.add_handler(handler, handler_group)
|
self.add_handler(handler, handler_group)
|
||||||
|
@ -1462,7 +1464,7 @@ class Application(Generic[BT, CCT, UD, CD, BD, JQ], AsyncContextManager["Applica
|
||||||
self.add_handler(handler, DefaultValue.get_value(group))
|
self.add_handler(handler, DefaultValue.get_value(group))
|
||||||
|
|
||||||
else:
|
else:
|
||||||
raise ValueError(
|
raise TypeError(
|
||||||
"The `handlers` argument must be a sequence of handlers or a "
|
"The `handlers` argument must be a sequence of handlers or a "
|
||||||
"dictionary where the keys are groups and values are sequences of handlers."
|
"dictionary where the keys are groups and values are sequences of handlers."
|
||||||
)
|
)
|
||||||
|
@ -1644,9 +1646,10 @@ class Application(Generic[BT, CCT, UD, CD, BD, JQ], AsyncContextManager["Applica
|
||||||
self.__update_persistence_event.wait(),
|
self.__update_persistence_event.wait(),
|
||||||
timeout=self.persistence.update_interval,
|
timeout=self.persistence.update_interval,
|
||||||
)
|
)
|
||||||
return
|
|
||||||
except asyncio.TimeoutError:
|
except asyncio.TimeoutError:
|
||||||
pass
|
pass
|
||||||
|
else:
|
||||||
|
return
|
||||||
|
|
||||||
# putting this *after* the wait_for so we don't immediately update on startup as
|
# putting this *after* the wait_for so we don't immediately update on startup as
|
||||||
# that would make little sense
|
# that would make little sense
|
||||||
|
|
|
@ -207,7 +207,7 @@ class ApplicationBuilder(Generic[BT, CCT, UD, CD, BD, JQ]):
|
||||||
self._job_queue: ODVInput[JobQueue] = DefaultValue(JobQueue())
|
self._job_queue: ODVInput[JobQueue] = DefaultValue(JobQueue())
|
||||||
except RuntimeError as exc:
|
except RuntimeError as exc:
|
||||||
if "PTB must be installed via" not in str(exc):
|
if "PTB must be installed via" not in str(exc):
|
||||||
raise exc
|
raise
|
||||||
self._job_queue = DEFAULT_NONE
|
self._job_queue = DEFAULT_NONE
|
||||||
|
|
||||||
self._persistence: ODVInput[BasePersistence] = DEFAULT_NONE
|
self._persistence: ODVInput[BasePersistence] = DEFAULT_NONE
|
||||||
|
|
|
@ -81,10 +81,10 @@ class BaseUpdateProcessor(AsyncContextManager["BaseUpdateProcessor"], ABC):
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
await self.initialize()
|
await self.initialize()
|
||||||
return self
|
except Exception:
|
||||||
except Exception as exc:
|
|
||||||
await self.shutdown()
|
await self.shutdown()
|
||||||
raise exc
|
raise
|
||||||
|
return self
|
||||||
|
|
||||||
async def __aexit__(
|
async def __aexit__(
|
||||||
self,
|
self,
|
||||||
|
|
|
@ -272,7 +272,9 @@ class CallbackContext(Generic[BT, UD, CD, BD]):
|
||||||
)
|
)
|
||||||
self.bot.callback_data_cache.drop_data(callback_query)
|
self.bot.callback_data_cache.drop_data(callback_query)
|
||||||
else:
|
else:
|
||||||
raise RuntimeError("telegram.Bot does not allow for arbitrary callback data.")
|
raise RuntimeError( # noqa: TRY004
|
||||||
|
"telegram.Bot does not allow for arbitrary callback data."
|
||||||
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_error(
|
def from_error(
|
||||||
|
|
|
@ -278,9 +278,9 @@ class CallbackDataCache:
|
||||||
button_data = keyboard_data.button_data[button]
|
button_data = keyboard_data.button_data[button]
|
||||||
# Update the timestamp for the LRU
|
# Update the timestamp for the LRU
|
||||||
keyboard_data.update_access_time()
|
keyboard_data.update_access_time()
|
||||||
return keyboard, button_data
|
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return None, InvalidCallbackData(callback_data)
|
return None, InvalidCallbackData(callback_data)
|
||||||
|
return keyboard, button_data
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def extract_uuids(callback_data: str) -> Tuple[str, str]:
|
def extract_uuids(callback_data: str) -> Tuple[str, str]:
|
||||||
|
|
|
@ -188,7 +188,7 @@ class ContextTypes(Generic[CCT, UD, CD, BD]):
|
||||||
user_data: Type[ADict] = dict,
|
user_data: Type[ADict] = dict,
|
||||||
):
|
):
|
||||||
if not issubclass(context, CallbackContext):
|
if not issubclass(context, CallbackContext):
|
||||||
raise ValueError("context must be a subclass of CallbackContext.")
|
raise TypeError("context must be a subclass of CallbackContext.")
|
||||||
|
|
||||||
# We make all those only accessible via properties because we don't currently support
|
# We make all those only accessible via properties because we don't currently support
|
||||||
# changing this at runtime, so overriding the attributes doesn't make sense
|
# changing this at runtime, so overriding the attributes doesn't make sense
|
||||||
|
|
|
@ -637,7 +637,7 @@ class ExtBot(Bot, Generic[RLARGS]):
|
||||||
self,
|
self,
|
||||||
offset: Optional[int] = None,
|
offset: Optional[int] = None,
|
||||||
limit: Optional[int] = None,
|
limit: Optional[int] = None,
|
||||||
timeout: Optional[int] = None,
|
timeout: Optional[int] = None, # noqa: ASYNC109
|
||||||
allowed_updates: Optional[Sequence[str]] = None,
|
allowed_updates: Optional[Sequence[str]] = None,
|
||||||
*,
|
*,
|
||||||
read_timeout: ODVInput[float] = DEFAULT_NONE,
|
read_timeout: ODVInput[float] = DEFAULT_NONE,
|
||||||
|
|
|
@ -145,10 +145,10 @@ class Updater(AsyncContextManager["Updater"]):
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
await self.initialize()
|
await self.initialize()
|
||||||
return self
|
except Exception:
|
||||||
except Exception as exc:
|
|
||||||
await self.shutdown()
|
await self.shutdown()
|
||||||
raise exc
|
raise
|
||||||
|
return self
|
||||||
|
|
||||||
async def __aexit__(
|
async def __aexit__(
|
||||||
self,
|
self,
|
||||||
|
@ -214,7 +214,7 @@ class Updater(AsyncContextManager["Updater"]):
|
||||||
async def start_polling(
|
async def start_polling(
|
||||||
self,
|
self,
|
||||||
poll_interval: float = 0.0,
|
poll_interval: float = 0.0,
|
||||||
timeout: int = 10,
|
timeout: int = 10, # noqa: ASYNC109
|
||||||
bootstrap_retries: int = -1,
|
bootstrap_retries: int = -1,
|
||||||
read_timeout: ODVInput[float] = DEFAULT_NONE,
|
read_timeout: ODVInput[float] = DEFAULT_NONE,
|
||||||
write_timeout: ODVInput[float] = DEFAULT_NONE,
|
write_timeout: ODVInput[float] = DEFAULT_NONE,
|
||||||
|
@ -339,16 +339,15 @@ class Updater(AsyncContextManager["Updater"]):
|
||||||
_LOGGER.debug("Waiting for polling to start")
|
_LOGGER.debug("Waiting for polling to start")
|
||||||
await polling_ready.wait()
|
await polling_ready.wait()
|
||||||
_LOGGER.debug("Polling updates from Telegram started")
|
_LOGGER.debug("Polling updates from Telegram started")
|
||||||
|
except Exception:
|
||||||
return self.update_queue
|
|
||||||
except Exception as exc:
|
|
||||||
self._running = False
|
self._running = False
|
||||||
raise exc
|
raise
|
||||||
|
return self.update_queue
|
||||||
|
|
||||||
async def _start_polling(
|
async def _start_polling(
|
||||||
self,
|
self,
|
||||||
poll_interval: float,
|
poll_interval: float,
|
||||||
timeout: int,
|
timeout: int, # noqa: ASYNC109
|
||||||
read_timeout: ODVInput[float],
|
read_timeout: ODVInput[float],
|
||||||
write_timeout: ODVInput[float],
|
write_timeout: ODVInput[float],
|
||||||
connect_timeout: ODVInput[float],
|
connect_timeout: ODVInput[float],
|
||||||
|
@ -384,9 +383,9 @@ class Updater(AsyncContextManager["Updater"]):
|
||||||
pool_timeout=pool_timeout,
|
pool_timeout=pool_timeout,
|
||||||
allowed_updates=allowed_updates,
|
allowed_updates=allowed_updates,
|
||||||
)
|
)
|
||||||
except TelegramError as exc:
|
except TelegramError:
|
||||||
# TelegramErrors should be processed by the network retry loop
|
# TelegramErrors should be processed by the network retry loop
|
||||||
raise exc
|
raise
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
# Other exceptions should not. Let's log them for now.
|
# Other exceptions should not. Let's log them for now.
|
||||||
_LOGGER.critical(
|
_LOGGER.critical(
|
||||||
|
@ -446,13 +445,12 @@ class Updater(AsyncContextManager["Updater"]):
|
||||||
pool_timeout=pool_timeout,
|
pool_timeout=pool_timeout,
|
||||||
allowed_updates=allowed_updates,
|
allowed_updates=allowed_updates,
|
||||||
)
|
)
|
||||||
except TelegramError as exc:
|
except TelegramError:
|
||||||
_LOGGER.error(
|
_LOGGER.exception(
|
||||||
"Error while calling `get_updates` one more time to mark all fetched updates "
|
"Error while calling `get_updates` one more time to mark all fetched updates "
|
||||||
"as read: %s. Suppressing error to ensure graceful shutdown. When polling for "
|
"as read: %s. Suppressing error to ensure graceful shutdown. When polling for "
|
||||||
"updates is restarted, updates may be fetched again. Please adjust timeouts "
|
"updates is restarted, updates may be fetched again. Please adjust timeouts "
|
||||||
"via `ApplicationBuilder` or the parameter `get_updates_request` of `Bot`.",
|
"via `ApplicationBuilder` or the parameter `get_updates_request` of `Bot`.",
|
||||||
exc_info=exc,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
self.__polling_cleanup_cb = _get_updates_cleanup
|
self.__polling_cleanup_cb = _get_updates_cleanup
|
||||||
|
@ -623,9 +621,9 @@ class Updater(AsyncContextManager["Updater"]):
|
||||||
_LOGGER.debug("Waiting for webhook server to start")
|
_LOGGER.debug("Waiting for webhook server to start")
|
||||||
await webhook_ready.wait()
|
await webhook_ready.wait()
|
||||||
_LOGGER.debug("Webhook server started")
|
_LOGGER.debug("Webhook server started")
|
||||||
except Exception as exc:
|
except Exception:
|
||||||
self._running = False
|
self._running = False
|
||||||
raise exc
|
raise
|
||||||
|
|
||||||
# Return the update queue so the main thread can insert updates
|
# Return the update queue so the main thread can insert updates
|
||||||
return self.update_queue
|
return self.update_queue
|
||||||
|
@ -761,11 +759,11 @@ class Updater(AsyncContextManager["Updater"]):
|
||||||
_LOGGER.debug("Timed out %s: %s", description, toe)
|
_LOGGER.debug("Timed out %s: %s", description, toe)
|
||||||
# If failure is due to timeout, we should retry asap.
|
# If failure is due to timeout, we should retry asap.
|
||||||
cur_interval = 0
|
cur_interval = 0
|
||||||
except InvalidToken as pex:
|
except InvalidToken:
|
||||||
_LOGGER.error("Invalid token; aborting")
|
_LOGGER.exception("Invalid token; aborting")
|
||||||
raise pex
|
raise
|
||||||
except TelegramError as telegram_exc:
|
except TelegramError as telegram_exc:
|
||||||
_LOGGER.error("Error while %s: %s", description, telegram_exc)
|
_LOGGER.exception("Error while %s:", description)
|
||||||
on_err_cb(telegram_exc)
|
on_err_cb(telegram_exc)
|
||||||
|
|
||||||
# increase waiting times on subsequent errors up to 30secs
|
# increase waiting times on subsequent errors up to 30secs
|
||||||
|
|
|
@ -115,10 +115,10 @@ class BaseRequest(
|
||||||
"""
|
"""
|
||||||
try:
|
try:
|
||||||
await self.initialize()
|
await self.initialize()
|
||||||
return self
|
except Exception:
|
||||||
except Exception as exc:
|
|
||||||
await self.shutdown()
|
await self.shutdown()
|
||||||
raise exc
|
raise
|
||||||
|
return self
|
||||||
|
|
||||||
async def __aexit__(
|
async def __aexit__(
|
||||||
self,
|
self,
|
||||||
|
@ -339,8 +339,8 @@ class BaseRequest(
|
||||||
connect_timeout=connect_timeout,
|
connect_timeout=connect_timeout,
|
||||||
pool_timeout=pool_timeout,
|
pool_timeout=pool_timeout,
|
||||||
)
|
)
|
||||||
except TelegramError as exc:
|
except TelegramError:
|
||||||
raise exc
|
raise
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
raise NetworkError(f"Unknown error in HTTP implementation: {exc!r}") from exc
|
raise NetworkError(f"Unknown error in HTTP implementation: {exc!r}") from exc
|
||||||
|
|
||||||
|
@ -408,7 +408,7 @@ class BaseRequest(
|
||||||
try:
|
try:
|
||||||
return json.loads(decoded_s)
|
return json.loads(decoded_s)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
_LOGGER.error('Can not load invalid JSON data: "%s"', decoded_s)
|
_LOGGER.exception('Can not load invalid JSON data: "%s"', decoded_s)
|
||||||
raise TelegramError("Invalid server response") from exc
|
raise TelegramError("Invalid server response") from exc
|
||||||
|
|
||||||
@abc.abstractmethod
|
@abc.abstractmethod
|
||||||
|
|
|
@ -189,7 +189,7 @@ class HTTPXRequest(BaseRequest):
|
||||||
self._client = self._build_client()
|
self._client = self._build_client()
|
||||||
except ImportError as exc:
|
except ImportError as exc:
|
||||||
if "httpx[http2]" not in str(exc) and "httpx[socks]" not in str(exc):
|
if "httpx[http2]" not in str(exc) and "httpx[socks]" not in str(exc):
|
||||||
raise exc
|
raise
|
||||||
|
|
||||||
if "httpx[socks]" in str(exc):
|
if "httpx[socks]" in str(exc):
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
|
|
|
@ -37,7 +37,7 @@ from tests.auxil.files import data_file
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def animation_file():
|
def animation_file():
|
||||||
with data_file("game.gif").open("rb") as f:
|
with data_file("game.gif").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
|
|
@ -37,7 +37,7 @@ from tests.auxil.files import data_file
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def audio_file():
|
def audio_file():
|
||||||
with data_file("telegram.mp3").open("rb") as f:
|
with data_file("telegram.mp3").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
|
|
@ -36,7 +36,7 @@ from tests.auxil.networking import expect_bad_request
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def chatphoto_file():
|
def chatphoto_file():
|
||||||
with data_file("telegram.jpg").open("rb") as f:
|
with data_file("telegram.jpg").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
|
|
@ -37,7 +37,7 @@ from tests.auxil.files import data_file
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def document_file():
|
def document_file():
|
||||||
with data_file("telegram.png").open("rb") as f:
|
with data_file("telegram.png").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
|
|
@ -235,7 +235,7 @@ class TestLocationWithRequest:
|
||||||
assert protected.has_protected_content
|
assert protected.has_protected_content
|
||||||
assert not unprotected.has_protected_content
|
assert not unprotected.has_protected_content
|
||||||
|
|
||||||
@pytest.mark.xfail()
|
@pytest.mark.xfail
|
||||||
async def test_send_live_location(self, bot, chat_id):
|
async def test_send_live_location(self, bot, chat_id):
|
||||||
message = await bot.send_location(
|
message = await bot.send_location(
|
||||||
chat_id=chat_id,
|
chat_id=chat_id,
|
||||||
|
|
|
@ -38,7 +38,7 @@ from tests.auxil.networking import expect_bad_request
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def photo_file():
|
def photo_file():
|
||||||
with data_file("telegram.jpg").open("rb") as f:
|
with data_file("telegram.jpg").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
|
|
@ -49,7 +49,7 @@ from tests.auxil.files import data_file
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def sticker_file():
|
def sticker_file():
|
||||||
with data_file("telegram.webp").open("rb") as file:
|
with data_file("telegram.webp").open("rb") as file:
|
||||||
yield file
|
yield file
|
||||||
|
@ -65,7 +65,7 @@ async def sticker(bot, chat_id):
|
||||||
return sticker
|
return sticker
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def animated_sticker_file():
|
def animated_sticker_file():
|
||||||
with data_file("telegram_animated_sticker.tgs").open("rb") as f:
|
with data_file("telegram_animated_sticker.tgs").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
@ -77,7 +77,7 @@ async def animated_sticker(bot, chat_id):
|
||||||
return (await bot.send_sticker(chat_id, sticker=f, read_timeout=50)).sticker
|
return (await bot.send_sticker(chat_id, sticker=f, read_timeout=50)).sticker
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def video_sticker_file():
|
def video_sticker_file():
|
||||||
with data_file("telegram_video_sticker.webm").open("rb") as f:
|
with data_file("telegram_video_sticker.webm").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
@ -524,7 +524,7 @@ class TestStickerWithRequest(TestStickerBase):
|
||||||
await bot.send_sticker(chat_id, "")
|
await bot.send_sticker(chat_id, "")
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
async def sticker_set(bot):
|
async def sticker_set(bot):
|
||||||
ss = await bot.get_sticker_set(f"test_by_{bot.username}")
|
ss = await bot.get_sticker_set(f"test_by_{bot.username}")
|
||||||
if len(ss.stickers) > 100:
|
if len(ss.stickers) > 100:
|
||||||
|
@ -538,7 +538,7 @@ async def sticker_set(bot):
|
||||||
return ss
|
return ss
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
async def animated_sticker_set(bot):
|
async def animated_sticker_set(bot):
|
||||||
ss = await bot.get_sticker_set(f"animated_test_by_{bot.username}")
|
ss = await bot.get_sticker_set(f"animated_test_by_{bot.username}")
|
||||||
if len(ss.stickers) > 100:
|
if len(ss.stickers) > 100:
|
||||||
|
@ -552,7 +552,7 @@ async def animated_sticker_set(bot):
|
||||||
return ss
|
return ss
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
async def video_sticker_set(bot):
|
async def video_sticker_set(bot):
|
||||||
ss = await bot.get_sticker_set(f"video_test_by_{bot.username}")
|
ss = await bot.get_sticker_set(f"video_test_by_{bot.username}")
|
||||||
if len(ss.stickers) > 100:
|
if len(ss.stickers) > 100:
|
||||||
|
@ -566,7 +566,7 @@ async def video_sticker_set(bot):
|
||||||
return ss
|
return ss
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def sticker_set_thumb_file():
|
def sticker_set_thumb_file():
|
||||||
with data_file("sticker_set_thumb.png").open("rb") as file:
|
with data_file("sticker_set_thumb.png").open("rb") as file:
|
||||||
yield file
|
yield file
|
||||||
|
|
|
@ -37,7 +37,7 @@ from tests.auxil.files import data_file
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def video_file():
|
def video_file():
|
||||||
with data_file("telegram.mp4").open("rb") as f:
|
with data_file("telegram.mp4").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
|
|
@ -36,7 +36,7 @@ from tests.auxil.files import data_file
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def video_note_file():
|
def video_note_file():
|
||||||
with data_file("telegram2.mp4").open("rb") as f:
|
with data_file("telegram2.mp4").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
|
|
@ -37,7 +37,7 @@ from tests.auxil.files import data_file
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def voice_file():
|
def voice_file():
|
||||||
with data_file("telegram.ogg").open("rb") as f:
|
with data_file("telegram.ogg").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
|
|
@ -68,7 +68,7 @@ def false_update(request):
|
||||||
return Update(update_id=2, **request.param)
|
return Update(update_id=2, **request.param)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def inline_query(bot):
|
def inline_query(bot):
|
||||||
update = Update(
|
update = Update(
|
||||||
0,
|
0,
|
||||||
|
|
|
@ -124,7 +124,7 @@ async def bot(bot_info):
|
||||||
yield _bot
|
yield _bot
|
||||||
|
|
||||||
|
|
||||||
@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)
|
||||||
|
@ -206,7 +206,7 @@ def provider_token(bot_info):
|
||||||
return bot_info["payment_provider_token"]
|
return bot_info["payment_provider_token"]
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
async def app(bot_info):
|
async def app(bot_info):
|
||||||
# We build a new bot each time so that we use `app` in a context manager without problems
|
# We build a new bot each time so that we use `app` in a context manager without problems
|
||||||
application = (
|
application = (
|
||||||
|
@ -218,7 +218,7 @@ async def app(bot_info):
|
||||||
await application.shutdown()
|
await application.shutdown()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
async def updater(bot_info):
|
async def updater(bot_info):
|
||||||
# We build a new bot each time so that we use `updater` in a context manager without problems
|
# 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())
|
up = Updater(bot=make_bot(bot_info), update_queue=asyncio.Queue())
|
||||||
|
@ -228,7 +228,7 @@ async def updater(bot_info):
|
||||||
await up.shutdown()
|
await up.shutdown()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def thumb_file():
|
def thumb_file():
|
||||||
with data_file("thumb.jpg").open("rb") as f:
|
with data_file("thumb.jpg").open("rb") as f:
|
||||||
yield f
|
yield f
|
||||||
|
@ -291,6 +291,6 @@ def timezone(tzinfo):
|
||||||
return tzinfo
|
return tzinfo
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def tmp_file(tmp_path) -> Path:
|
def tmp_file(tmp_path) -> Path:
|
||||||
return tmp_path / uuid4().hex
|
return tmp_path / uuid4().hex
|
||||||
|
|
|
@ -23,14 +23,14 @@ from telegram.ext._utils.trackingdict import TrackingDict
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def td() -> TrackingDict:
|
def td() -> TrackingDict:
|
||||||
td = TrackingDict()
|
td = TrackingDict()
|
||||||
td.update_no_track({1: 1})
|
td.update_no_track({1: 1})
|
||||||
return td
|
return td
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def data() -> dict:
|
def data() -> dict:
|
||||||
return {1: 1}
|
return {1: 1}
|
||||||
|
|
||||||
|
|
|
@ -639,11 +639,11 @@ class TestApplication:
|
||||||
assert len(app.handlers[-1]) == 1
|
assert len(app.handlers[-1]) == 1
|
||||||
|
|
||||||
# Now lets test the errors which can be produced-
|
# Now lets test the errors which can be produced-
|
||||||
with pytest.raises(ValueError, match="The `group` argument"):
|
with pytest.raises(TypeError, match="The `group` argument"):
|
||||||
app.add_handlers({2: [msg_handler_set_count]}, group=0)
|
app.add_handlers({2: [msg_handler_set_count]}, group=0)
|
||||||
with pytest.raises(ValueError, match="Handlers for group 3"):
|
with pytest.raises(TypeError, match="Handlers for group 3"):
|
||||||
app.add_handlers({3: msg_handler_set_count})
|
app.add_handlers({3: msg_handler_set_count})
|
||||||
with pytest.raises(ValueError, match="The `handlers` argument must be a sequence"):
|
with pytest.raises(TypeError, match="The `handlers` argument must be a sequence"):
|
||||||
app.add_handlers({msg_handler_set_count})
|
app.add_handlers({msg_handler_set_count})
|
||||||
|
|
||||||
await app.stop()
|
await app.stop()
|
||||||
|
|
|
@ -48,7 +48,7 @@ from tests.auxil.files import data_file
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def builder():
|
def builder():
|
||||||
return ApplicationBuilder()
|
return ApplicationBuilder()
|
||||||
|
|
||||||
|
|
|
@ -261,7 +261,7 @@ def build_conversation_handler(name: str, persistent: bool = True) -> BaseHandle
|
||||||
return TrackingConversationHandler(name=name, persistent=persistent)
|
return TrackingConversationHandler(name=name, persistent=persistent)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def papp(request, bot_info) -> Application:
|
def papp(request, bot_info) -> Application:
|
||||||
papp_input = request.param
|
papp_input = request.param
|
||||||
store_data = {}
|
store_data = {}
|
||||||
|
|
|
@ -28,7 +28,7 @@ from tests.auxil.asyncio_helpers import call_after
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def mock_processor():
|
def mock_processor():
|
||||||
class MockProcessor(SimpleUpdateProcessor):
|
class MockProcessor(SimpleUpdateProcessor):
|
||||||
test_flag = False
|
test_flag = False
|
||||||
|
|
|
@ -88,7 +88,7 @@ def business_connection(bot):
|
||||||
return bc
|
return bc
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def business_connection_update(bot, business_connection):
|
def business_connection_update(bot, business_connection):
|
||||||
return Update(0, business_connection=business_connection)
|
return Update(0, business_connection=business_connection)
|
||||||
|
|
||||||
|
|
|
@ -85,7 +85,7 @@ def business_messages_deleted(bot):
|
||||||
return bmd
|
return bmd
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def business_messages_deleted_update(bot, business_messages_deleted):
|
def business_messages_deleted_update(bot, business_messages_deleted):
|
||||||
return Update(0, deleted_business_messages=business_messages_deleted)
|
return Update(0, deleted_business_messages=business_messages_deleted)
|
||||||
|
|
||||||
|
|
|
@ -31,7 +31,7 @@ from tests.auxil.envvars import TEST_WITH_OPT_DEPS
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def callback_data_cache(bot):
|
def callback_data_cache(bot):
|
||||||
return CallbackDataCache(bot)
|
return CallbackDataCache(bot)
|
||||||
|
|
||||||
|
|
|
@ -65,7 +65,7 @@ def false_update(request):
|
||||||
return Update(update_id=2, **request.param)
|
return Update(update_id=2, **request.param)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def callback_query(bot):
|
def callback_query(bot):
|
||||||
update = Update(0, callback_query=CallbackQuery(2, User(1, "", False), None, data="test data"))
|
update = Update(0, callback_query=CallbackQuery(2, User(1, "", False), None, data="test data"))
|
||||||
update._unfreeze()
|
update._unfreeze()
|
||||||
|
|
|
@ -96,7 +96,7 @@ def chat_join_request(time, bot):
|
||||||
return cjr
|
return cjr
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def chat_join_request_update(bot, chat_join_request):
|
def chat_join_request_update(bot, chat_join_request):
|
||||||
return Update(0, chat_join_request=chat_join_request)
|
return Update(0, chat_join_request=chat_join_request)
|
||||||
|
|
||||||
|
|
|
@ -81,7 +81,7 @@ def chat_member_updated():
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def chat_member(bot, chat_member_updated):
|
def chat_member(bot, chat_member_updated):
|
||||||
update = Update(0, my_chat_member=chat_member_updated)
|
update = Update(0, my_chat_member=chat_member_updated)
|
||||||
update._unfreeze()
|
update._unfreeze()
|
||||||
|
|
|
@ -40,7 +40,7 @@ class TestContextTypes:
|
||||||
assert ct.chat_data is float
|
assert ct.chat_data is float
|
||||||
assert ct.user_data is bool
|
assert ct.user_data is bool
|
||||||
|
|
||||||
with pytest.raises(ValueError, match="subclass of CallbackContext"):
|
with pytest.raises(TypeError, match="subclass of CallbackContext"):
|
||||||
ContextTypes(context=bool)
|
ContextTypes(context=bool)
|
||||||
|
|
||||||
def test_data_assignment(self):
|
def test_data_assignment(self):
|
||||||
|
|
|
@ -31,27 +31,27 @@ def _reset_callback_data_cache(cdc_bot):
|
||||||
cdc_bot.callback_data_cache.clear_callback_queries()
|
cdc_bot.callback_data_cache.clear_callback_queries()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def bot_data():
|
def bot_data():
|
||||||
return {"test1": "test2", "test3": {"test4": "test5"}}
|
return {"test1": "test2", "test3": {"test4": "test5"}}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def chat_data():
|
def chat_data():
|
||||||
return {-12345: {"test1": "test2", "test3": {"test4": "test5"}}, -67890: {3: "test4"}}
|
return {-12345: {"test1": "test2", "test3": {"test4": "test5"}}, -67890: {3: "test4"}}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def user_data():
|
def user_data():
|
||||||
return {12345: {"test1": "test2", "test3": {"test4": "test5"}}, 67890: {3: "test4"}}
|
return {12345: {"test1": "test2", "test3": {"test4": "test5"}}, 67890: {3: "test4"}}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def callback_data():
|
def callback_data():
|
||||||
return [("test1", 1000, {"button1": "test0", "button2": "test1"})], {"test1": "test2"}
|
return [("test1", 1000, {"button1": "test0", "button2": "test1"})], {"test1": "test2"}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def conversations():
|
def conversations():
|
||||||
return {
|
return {
|
||||||
"name1": {(123, 123): 3, (456, 654): 4},
|
"name1": {(123, 123): 3, (456, 654): 4},
|
||||||
|
@ -60,27 +60,27 @@ def conversations():
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def user_data_json(user_data):
|
def user_data_json(user_data):
|
||||||
return json.dumps(user_data)
|
return json.dumps(user_data)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def chat_data_json(chat_data):
|
def chat_data_json(chat_data):
|
||||||
return json.dumps(chat_data)
|
return json.dumps(chat_data)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def bot_data_json(bot_data):
|
def bot_data_json(bot_data):
|
||||||
return json.dumps(bot_data)
|
return json.dumps(bot_data)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def callback_data_json(callback_data):
|
def callback_data_json(callback_data):
|
||||||
return json.dumps(callback_data)
|
return json.dumps(callback_data)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def conversations_json(conversations):
|
def conversations_json(conversations):
|
||||||
return """{"name1": {"[123, 123]": 3, "[456, 654]": 4}, "name2":
|
return """{"name1": {"[123, 123]": 3, "[456, 654]": 4}, "name2":
|
||||||
{"[123, 321]": 1, "[890, 890]": 2}, "name3":
|
{"[123, 321]": 1, "[890, 890]": 2}, "name3":
|
||||||
|
|
|
@ -43,7 +43,7 @@ from telegram.ext import filters
|
||||||
from tests.auxil.slots import mro_slots
|
from tests.auxil.slots import mro_slots
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def update():
|
def update():
|
||||||
update = Update(
|
update = Update(
|
||||||
0,
|
0,
|
||||||
|
|
|
@ -44,7 +44,7 @@ class CustomContext(CallbackContext):
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
async def job_queue(app):
|
async def job_queue(app):
|
||||||
jq = JobQueue()
|
jq = JobQueue()
|
||||||
jq.set_application(app)
|
jq.set_application(app)
|
||||||
|
|
|
@ -112,12 +112,12 @@ def message_reaction_count_updated(time, bot):
|
||||||
return mr
|
return mr
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def message_reaction_update(bot, message_reaction_updated):
|
def message_reaction_update(bot, message_reaction_updated):
|
||||||
return Update(0, message_reaction=message_reaction_updated)
|
return Update(0, message_reaction=message_reaction_updated)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def message_reaction_count_update(bot, message_reaction_count_updated):
|
def message_reaction_count_update(bot, message_reaction_count_updated):
|
||||||
return Update(0, message_reaction_count=message_reaction_count_updated)
|
return Update(0, message_reaction_count=message_reaction_count_updated)
|
||||||
|
|
||||||
|
|
|
@ -50,27 +50,27 @@ def _reset_callback_data_cache(cdc_bot):
|
||||||
cdc_bot.callback_data_cache.clear_callback_queries()
|
cdc_bot.callback_data_cache.clear_callback_queries()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def bot_data():
|
def bot_data():
|
||||||
return {"test1": "test2", "test3": {"test4": "test5"}}
|
return {"test1": "test2", "test3": {"test4": "test5"}}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def chat_data():
|
def chat_data():
|
||||||
return {-12345: {"test1": "test2", "test3": {"test4": "test5"}}, -67890: {3: "test4"}}
|
return {-12345: {"test1": "test2", "test3": {"test4": "test5"}}, -67890: {3: "test4"}}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def user_data():
|
def user_data():
|
||||||
return {12345: {"test1": "test2", "test3": {"test4": "test5"}}, 67890: {3: "test4"}}
|
return {12345: {"test1": "test2", "test3": {"test4": "test5"}}, 67890: {3: "test4"}}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def callback_data():
|
def callback_data():
|
||||||
return [("test1", 1000, {"button1": "test0", "button2": "test1"})], {"test1": "test2"}
|
return [("test1", 1000, {"button1": "test0", "button2": "test1"})], {"test1": "test2"}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def conversations():
|
def conversations():
|
||||||
return {
|
return {
|
||||||
"name1": {(123, 123): 3, (456, 654): 4},
|
"name1": {(123, 123): 3, (456, 654): 4},
|
||||||
|
@ -79,7 +79,7 @@ def conversations():
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def pickle_persistence():
|
def pickle_persistence():
|
||||||
return PicklePersistence(
|
return PicklePersistence(
|
||||||
filepath="pickletest",
|
filepath="pickletest",
|
||||||
|
@ -88,7 +88,7 @@ def pickle_persistence():
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def pickle_persistence_only_bot():
|
def pickle_persistence_only_bot():
|
||||||
return PicklePersistence(
|
return PicklePersistence(
|
||||||
filepath="pickletest",
|
filepath="pickletest",
|
||||||
|
@ -98,7 +98,7 @@ def pickle_persistence_only_bot():
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def pickle_persistence_only_chat():
|
def pickle_persistence_only_chat():
|
||||||
return PicklePersistence(
|
return PicklePersistence(
|
||||||
filepath="pickletest",
|
filepath="pickletest",
|
||||||
|
@ -108,7 +108,7 @@ def pickle_persistence_only_chat():
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def pickle_persistence_only_user():
|
def pickle_persistence_only_user():
|
||||||
return PicklePersistence(
|
return PicklePersistence(
|
||||||
filepath="pickletest",
|
filepath="pickletest",
|
||||||
|
@ -118,7 +118,7 @@ def pickle_persistence_only_user():
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def pickle_persistence_only_callback():
|
def pickle_persistence_only_callback():
|
||||||
return PicklePersistence(
|
return PicklePersistence(
|
||||||
filepath="pickletest",
|
filepath="pickletest",
|
||||||
|
@ -128,7 +128,7 @@ def pickle_persistence_only_callback():
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def bad_pickle_files():
|
def bad_pickle_files():
|
||||||
for name in [
|
for name in [
|
||||||
"pickletest_user_data",
|
"pickletest_user_data",
|
||||||
|
@ -142,7 +142,7 @@ def bad_pickle_files():
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def invalid_pickle_files():
|
def invalid_pickle_files():
|
||||||
for name in [
|
for name in [
|
||||||
"pickletest_user_data",
|
"pickletest_user_data",
|
||||||
|
@ -159,7 +159,7 @@ def invalid_pickle_files():
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def good_pickle_files(user_data, chat_data, bot_data, callback_data, conversations):
|
def good_pickle_files(user_data, chat_data, bot_data, callback_data, conversations):
|
||||||
data = {
|
data = {
|
||||||
"user_data": user_data,
|
"user_data": user_data,
|
||||||
|
@ -183,7 +183,7 @@ def good_pickle_files(user_data, chat_data, bot_data, callback_data, conversatio
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def pickle_files_wo_bot_data(user_data, chat_data, callback_data, conversations):
|
def pickle_files_wo_bot_data(user_data, chat_data, callback_data, conversations):
|
||||||
data = {
|
data = {
|
||||||
"user_data": user_data,
|
"user_data": user_data,
|
||||||
|
@ -204,7 +204,7 @@ def pickle_files_wo_bot_data(user_data, chat_data, callback_data, conversations)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def pickle_files_wo_callback_data(user_data, chat_data, bot_data, conversations):
|
def pickle_files_wo_callback_data(user_data, chat_data, bot_data, conversations):
|
||||||
data = {
|
data = {
|
||||||
"user_data": user_data,
|
"user_data": user_data,
|
||||||
|
@ -225,7 +225,7 @@ def pickle_files_wo_callback_data(user_data, chat_data, bot_data, conversations)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def update(bot):
|
def update(bot):
|
||||||
user = User(id=321, first_name="test_user", is_bot=False)
|
user = User(id=321, first_name="test_user", is_bot=False)
|
||||||
chat = Chat(id=123, type="group")
|
chat = Chat(id=123, type="group")
|
||||||
|
|
|
@ -67,7 +67,7 @@ def false_update(request):
|
||||||
return Update(update_id=2, **request.param)
|
return Update(update_id=2, **request.param)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def poll_answer(bot):
|
def poll_answer(bot):
|
||||||
return Update(0, poll_answer=PollAnswer(1, [0, 1], User(2, "test user", False), Chat(1, "")))
|
return Update(0, poll_answer=PollAnswer(1, [0, 1], User(2, "test user", False), Chat(1, "")))
|
||||||
|
|
||||||
|
|
|
@ -56,15 +56,15 @@ class TestPrefixHandler(BaseTest):
|
||||||
def commands(self, request):
|
def commands(self, request):
|
||||||
return TestPrefixHandler.COMMANDS[: request.param]
|
return TestPrefixHandler.COMMANDS[: request.param]
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def prefix_message_text(self, prefix, command):
|
def prefix_message_text(self, prefix, command):
|
||||||
return prefix + command
|
return prefix + command
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def prefix_message(self, prefix_message_text):
|
def prefix_message(self, prefix_message_text):
|
||||||
return make_message(prefix_message_text)
|
return make_message(prefix_message_text)
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def prefix_message_update(self, prefix_message):
|
def prefix_message_update(self, prefix_message):
|
||||||
return make_message_update(prefix_message)
|
return make_message_update(prefix_message)
|
||||||
|
|
||||||
|
|
|
@ -86,7 +86,7 @@ class TestUpdater:
|
||||||
|
|
||||||
# This is needed instead of pytest's temp_path because the file path gets too long on macOS
|
# This is needed instead of pytest's temp_path because the file path gets too long on macOS
|
||||||
# otherwise
|
# otherwise
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def file_path(self) -> str:
|
def file_path(self) -> str:
|
||||||
path = TEST_DATA_PATH / "test.sock"
|
path = TEST_DATA_PATH / "test.sock"
|
||||||
yield str(path)
|
yield str(path)
|
||||||
|
@ -571,7 +571,7 @@ class TestUpdater:
|
||||||
else:
|
else:
|
||||||
assert len(caplog.records) > 0
|
assert len(caplog.records) > 0
|
||||||
assert any(
|
assert any(
|
||||||
"Error while getting Updates: TestMessage" in record.getMessage()
|
"Error while getting Updates:" in record.getMessage()
|
||||||
and record.name == "telegram.ext.Updater"
|
and record.name == "telegram.ext.Updater"
|
||||||
for record in caplog.records
|
for record in caplog.records
|
||||||
)
|
)
|
||||||
|
@ -593,7 +593,7 @@ class TestUpdater:
|
||||||
else:
|
else:
|
||||||
assert len(caplog.records) > 0
|
assert len(caplog.records) > 0
|
||||||
assert any(
|
assert any(
|
||||||
"Error while getting Updates: TestMessage" in record.getMessage()
|
"Error while getting Updates:" in record.getMessage()
|
||||||
and record.name == "telegram.ext.Updater"
|
and record.name == "telegram.ext.Updater"
|
||||||
for record in caplog.records
|
for record in caplog.records
|
||||||
)
|
)
|
||||||
|
|
|
@ -74,7 +74,7 @@ def mocker_factory(
|
||||||
return make_assertion
|
return make_assertion
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
async def httpx_request():
|
async def httpx_request():
|
||||||
async with NonchalantHttpxRequest() as rq:
|
async with NonchalantHttpxRequest() as rq:
|
||||||
yield rq
|
yield rq
|
||||||
|
|
|
@ -107,7 +107,7 @@ from ._files.test_photo import photo_file
|
||||||
from .auxil.build_messages import make_message
|
from .auxil.build_messages import make_message
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
async def message(bot, chat_id): # mostly used in tests for edit_message
|
async def message(bot, chat_id): # mostly used in tests for edit_message
|
||||||
out = await bot.send_message(
|
out = await bot.send_message(
|
||||||
chat_id, "Text", disable_web_page_preview=True, disable_notification=True
|
chat_id, "Text", disable_web_page_preview=True, disable_notification=True
|
||||||
|
|
|
@ -146,7 +146,7 @@ def iter_args(
|
||||||
yield inst_at, json_at
|
yield inst_at, json_at
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def background_type(request):
|
def background_type(request):
|
||||||
return request.param()
|
return request.param()
|
||||||
|
|
||||||
|
@ -254,7 +254,7 @@ class TestBackgroundTypeWithoutRequest:
|
||||||
assert hash(f) != hash(c)
|
assert hash(f) != hash(c)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def background_fill(request):
|
def background_fill(request):
|
||||||
return request.param()
|
return request.param()
|
||||||
|
|
||||||
|
|
|
@ -107,7 +107,7 @@ def user_chat_boosts(chat_boost):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def chat_boost_source(request):
|
def chat_boost_source(request):
|
||||||
return request.param()
|
return request.param()
|
||||||
|
|
||||||
|
|
|
@ -181,7 +181,7 @@ def iter_args(instance: ChatMember, de_json_inst: ChatMember, include_optional:
|
||||||
yield inst_at, json_at
|
yield inst_at, json_at
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def chat_member_type(request):
|
def chat_member_type(request):
|
||||||
return request.param()
|
return request.param()
|
||||||
|
|
||||||
|
|
|
@ -56,7 +56,7 @@ async def forum_topic_object(forum_group_id, emoji_id):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
async def real_topic(bot, emoji_id, forum_group_id):
|
async def real_topic(bot, emoji_id, forum_group_id):
|
||||||
result = await bot.create_forum_topic(
|
result = await bot.create_forum_topic(
|
||||||
chat_id=forum_group_id,
|
chat_id=forum_group_id,
|
||||||
|
|
|
@ -114,7 +114,7 @@ def iter_args(
|
||||||
yield inst_at, json_at
|
yield inst_at, json_at
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def message_origin_type(request):
|
def message_origin_type(request):
|
||||||
return request.param()
|
return request.param()
|
||||||
|
|
||||||
|
|
|
@ -68,7 +68,7 @@ def false_update(request):
|
||||||
return Update(update_id=2, **request.param)
|
return Update(update_id=2, **request.param)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def poll(bot):
|
def poll(bot):
|
||||||
return Update(
|
return Update(
|
||||||
0,
|
0,
|
||||||
|
|
|
@ -89,7 +89,7 @@ def iter_args(instance: ReactionType, de_json_inst: ReactionType, include_option
|
||||||
yield inst_at, json_at
|
yield inst_at, json_at
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def reaction_type(request):
|
def reaction_type(request):
|
||||||
return request.param()
|
return request.param()
|
||||||
|
|
||||||
|
|
|
@ -49,12 +49,12 @@ def withdrawal_state_succeeded():
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def withdrawal_state_failed():
|
def withdrawal_state_failed():
|
||||||
return RevenueWithdrawalStateFailed()
|
return RevenueWithdrawalStateFailed()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def withdrawal_state_pending():
|
def withdrawal_state_pending():
|
||||||
return RevenueWithdrawalStatePending()
|
return RevenueWithdrawalStatePending()
|
||||||
|
|
||||||
|
@ -65,7 +65,7 @@ def transaction_partner_user():
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def transaction_partner_other():
|
def transaction_partner_other():
|
||||||
return TransactionPartnerOther()
|
return TransactionPartnerOther()
|
||||||
|
|
||||||
|
@ -86,7 +86,7 @@ def star_transaction():
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def star_transactions():
|
def star_transactions():
|
||||||
return StarTransactions(
|
return StarTransactions(
|
||||||
transactions=[
|
transactions=[
|
||||||
|
|
|
@ -47,7 +47,7 @@ def json_dict():
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture()
|
@pytest.fixture
|
||||||
def user(bot):
|
def user(bot):
|
||||||
user = User(
|
user = User(
|
||||||
id=TestUserBase.id_,
|
id=TestUserBase.id_,
|
||||||
|
|
Loading…
Reference in a new issue