From 58e04b0b0887dba71b6a4f2b3ce47aff88c158e6 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 4 Oct 2025 10:33:20 +0500 Subject: [PATCH] Docs: add guide 'Testing your bot' (pytest examples) --- docs/guide/testing.rst | 88 ++++++++++++++++++++++++++++++++++++++++++ docs/index.rst | 1 + 2 files changed, 89 insertions(+) create mode 100644 docs/guide/testing.rst diff --git a/docs/guide/testing.rst b/docs/guide/testing.rst new file mode 100644 index 00000000..2f33f341 --- /dev/null +++ b/docs/guide/testing.rst @@ -0,0 +1,88 @@ +Testing your bot (pytest) +========================= + +This guide shows how to test your handlers **without using the real Telegram API**. +We will use `pytest` and `pytest-asyncio`. + +Installation:: + + pip install -U pytest pytest-asyncio + +Simple echo handler +------------------- + +**Handler:** + +.. code-block:: python + + # app/bot.py + from aiogram.types import Message + + async def echo_handler(message: Message): + await message.answer(message.text) + +**Test:** + +.. code-block:: python + + # tests/test_echo.py + import pytest + from app.bot import echo_handler + + @pytest.mark.asyncio + async def test_echo_handler(): + sent = [] + + class DummyMessage: + def __init__(self, text): + self.text = text + async def answer(self, text): + sent.append(text) + + msg = DummyMessage("hello") + await echo_handler(msg) + + assert sent == ["hello"] + +Callback query example +---------------------- + +**Handler:** + +.. code-block:: python + + # app/callbacks.py + from aiogram.types import CallbackQuery + + async def ping_pong(cb: CallbackQuery): + if cb.data == "ping": + await cb.message.edit_text("pong") + await cb.answer() + +**Test:** + +.. code-block:: python + + # tests/test_callbacks.py + import pytest + from app.callbacks import ping_pong + + @pytest.mark.asyncio + async def test_ping_pong(): + calls = {"edited": None, "answered": False} + + class DummyMsg: + async def edit_text(self, text): + calls["edited"] = text + + class DummyCb: + data = "ping" + message = DummyMsg() + async def answer(self): + calls["answered"] = True + + cb = DummyCb() + await ping_pong(cb) + + assert calls["edited"] == "pong" + assert calls["answered"] is True diff --git a/docs/index.rst b/docs/index.rst index a923cab1..e60361c1 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -27,3 +27,4 @@ Contents utils/index changelog contributing + guide/testing