Testing the telegram bot

I am developing a telegram bot using the aiogram library and I need to test the functions of my bot. But unfortunately, I do not have access to the device on which telegram is installed and there is no way to install it, and I also do not have access to the phone to which the telegram account is linked.

Question:
I need to somehow simulate requests to the bot to test it. I tried using the Telegram Bot API, but there are no necessary functions there. I need to send a request to the bot and get a response from the bot. Or try to simulate a chat with a telegram bot in the console (asynchronous functions should be used to process messages in the console).

Code:

from aiogram import Bot, Dispatcher, executor, types


#aiogram import --> pip install --force-reinstall -v "aiogram==2.23.1"

TOKEN = 'token'
bot = Bot(token=TOKEN)
dp = Dispatcher(bot)



@dp.message_handler(commands=['start'])
async def cmd_start(message: types.Message):
    print("/start")
    await message.reply("/start")

@dp.message_handler(commands=['help'])
async def cmd_help(message: types.Message):
    print("/help")
    await message.reply('/help')


if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)

Use the pytest/pytest-asyncio library and create mock objects to simulate the types.Message

For example:

import pytest
from aiogram import types, Bot, Dispatcher
from yourscript import dp  # This is to import your Dispatcher

# And then you create the mock messages like
class MockMessage:
    def __init__(self, text, chat_id):
        self.text = text
        self.chat = types.Chat(id=chat_id, type='private')

    async def reply(self, text):
        print(f"Mock Reply: {text}")

@pytest.mark.asyncio
async def test_start_command():
    mock_message = MockMessage("/start", chat_id=12345)
    await dp.message_handlers.notify(mock_message)

@pytest.mark.asyncio
async def test_help_command():
    mock_message = MockMessage("/help", chat_id=12345)
    await dp.message_handlers.notify(mock_message)

After that you can run the test using the pytest

pytest yourscript.py

Ps.: Remember to install both libraries
pip install pytest pytest-asyncio

You can read the documentation here.

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.