Unit-tests for python-telegram-bot.
This is a first version of library
Only long polling mode supported!
Library starts your python-telegram-bot object with custom url (our unit-test server on Flask running under waitress). Now you can communicate in unit-tests with your bot as you do in Telegram.
- send text message
- send command
- send file
- receive file
User object to send messages and check incoming messages from your bot
Your bot object. See 'Using'
Check echo of Echo Bot from python-telegram-bot example.
def test_echobot_message(bot, user): user.send_message('testing message') message = user.get_message() assert message['text'] == 'testing message'
Check /start command of Echo Bot
def test_echobot_start(bot, user): user.send_command('/start') message = user.get_message() assert message['text'] == 'Hi [FN LN](tg://user?id=1)\!'
Bot renames file you send to him.
def test_echobot_file(bot, user): current_dir = os.path.dirname(os.path.abspath(__file__)) user.send_document(current_dir, 'test.txt') document = user.get_document() file_io = document.path_or_bytes assert file_io.name == 'echo_test.txt' content = io.TextIOWrapper(file_io, encoding='utf-8').read() assert content == 'Hello world!\nHello world!'
You can install or upgrade telegram-bot-unittest with:
$ pip install telegram-bot-unittest --upgrade
Or you can install from source with:
$ git clone https://github.com/dontsovcmc/telegram-bot-unittest --recursive $ cd telegram-bot-unittest $ python setup.py install
1. Create non-bloking function 'setup_bot' that runs your bot. We need to separate updater.idle() and creating Updater().
def setup_bot(bot_token: str, base_url: str = None) -> Updater: updater = Updater(bot_token, base_url=base_url) dispatcher = updater.dispatcher dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("help", help_command)) dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo)) updater.start_polling() return updater def main(base_url: str = None) -> None: updater = setup_bot(BOT_TOKEN, base_url) updater.idle()
- Add fixture 'bot' to you fixture.py file. Example:
import pytest from <your module> import <start_bot_function> from telegram_bot_unittest.routes import TELEGRAM_URL from telegram_bot_unittest.user import BOT_TOKEN @pytest.fixture(scope='session') def bot(telegram_server): updater = start_bot_function(BOT_TOKEN, TELEGRAM_URL) yield updater.bot updater.stop()
- add 'telegram_bot_unittest.fixtures' to 'pytest_plugins' list in conftest.py
- Add fixture 'bot' to you test functions.
- Enjoy!
Contributions of all sizes are welcome.
You may copy, distribute and modify the software provided that modifications are described and licensed for free under LGPL-3. Derivatives works (including modifications or anything statically linked to the library) can only be redistributed under LGPL-3, but applications that use the library don't have to be.