From 03454eb1baf866116853d900413f23e4cb9261a0 Mon Sep 17 00:00:00 2001 From: Vlad Date: Sat, 4 Oct 2025 18:20:53 +0500 Subject: [PATCH] Docs: add testing guide + newsfragment 1727.docs.rst --- docs/guide/testing.rst | 88 +++++++++++++++++++++++++++++++++++++++++ docs/index.rst | 1 + newsfragments/.docs.rst | 8 ++++ 3 files changed, 97 insertions(+) create mode 100644 docs/guide/testing.rst create mode 100644 newsfragments/.docs.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 diff --git a/newsfragments/.docs.rst b/newsfragments/.docs.rst new file mode 100644 index 00000000..7e81977c --- /dev/null +++ b/newsfragments/.docs.rst @@ -0,0 +1,8 @@ +Docs: add guide "Testing your bot" (pytest examples) + +Add a new documentation page that shows how to test bot handlers with pytest +without sending real requests to the Telegram API. The guide includes: +- an echo handler example +- a callback query example + +Both examples use dummy objects so developers can test logic in isolation.