def setUp(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() # Some generators for users and chats self.cg = ChatGenerator() # And a Messagegenerator and updater (for use with the bot.) self.mg = MessageGenerator(self.bot) self.updater = Updater(bot=self.bot) # type: ignore
def setUp(self): # For use within the tests we need some stuff. Starting with a Mockbot self.bot = Mockbot() # Some generators for users self.ug = UserGenerator() # And a Messagegenerator, CallbackQueryGenerator and updater (for use with the bot.) self.mg = MessageGenerator(self.bot) self.cqg = CallbackQueryGenerator(self.bot) self.updater = Updater(bot=self.bot)
def __init__(self, bot=None): PtbGenerator.__init__(self) self.ug = UserGenerator() if not bot: self.bot = Mockbot() elif isinstance(bot, Mockbot): self.bot = bot else: raise BadBotException
def setUp(self): # For use within the tests we need some stuff. Starting with a Mockbot self.bot = Mockbot() # Some generators for users and chats self.ug = UserGenerator() self.cg = ChatGenerator() # And a Messagegenerator and updater (for use with the bot.) self.mg = MessageGenerator(self.bot) self.updater = Updater(bot=self.bot) GamesController.init()
class TestClass: bot = Mockbot() ug = UserGenerator() cg = ChatGenerator() mg = MessageGenerator(bot) pp = PicklePersistence(filename='bbqreserve_test') updater = Updater(bot=bot, persistence=pp, use_context=True) @pytest.mark.parametrize("test_input, expected, userdata, delme", create_reserve_parameters) def test_create_reservation(self, test_input, expected, userdata, delme): user = self.ug.get_user(id=userdata['id'], first_name=userdata['first_name'], last_name=userdata['last_name']) chat = self.cg.get_chat(user=user) self.updater.dispatcher.add_handler(reserve.reserve_conv_handler) self.updater.start_polling() update = self.mg.get_message(user=user, chat=chat, text=test_input) self.bot.insertUpdate(update) sent = self.bot.sent_messages self.updater.stop() if delme: import os os.remove("bbqreserve_test") # check expected result with actual result assert sent[-1]['text'] == expected
def test_dejson_and_to_dict(self): import json d = self.mockbot.to_dict() self.assertIsInstance(d, dict) js = json.loads(json.dumps(d)) b = Mockbot.de_json(js, None) self.assertIsInstance(b, Mockbot)
def create_bot(mock=False): global telegram_bot if mock: telegram_bot = Mockbot() else: telegram_bot = telegram.Bot(token) return telegram_bot
def test_required_auto_set(self): u = self.cqg.get_callback_query(inline_message_id=True, data="test-data") self.assertIsInstance(u.callback_query.from_user, User) self.assertIsInstance(u.callback_query.chat_instance, str) bot = Mockbot(username="******") cqg2 = CallbackQueryGenerator(bot=bot) self.assertEqual(bot.username, cqg2.bot.username) with self.assertRaises(BadBotException): cqg3 = CallbackQueryGenerator(bot="bot")
def test_bot(self): u = self.mg.get_message() self.assertIsInstance(u.message.bot, Mockbot) self.assertEqual(u.message.bot.username, "MockBot") b = Mockbot(username="******") mg2 = MessageGenerator(bot=b) u = mg2.get_message() self.assertEqual(u.message.bot.username, "AnotherBot") with self.assertRaises(BadBotException): mg3 = MessageGenerator(bot="Yeah!")
def test_properties(self): self.assertEqual(self.mockbot.id, 0) self.assertEqual(self.mockbot.first_name, "Mockbot") self.assertEqual(self.mockbot.last_name, "Bot") self.assertEqual(self.mockbot.name, "@MockBot") mb2 = Mockbot("OtherUsername") self.assertEqual(mb2.name, "@OtherUsername") self.mockbot.sendMessage(1, "test 1") self.mockbot.sendMessage(2, "test 2") self.assertEqual(len(self.mockbot.sent_messages), 2) self.mockbot.reset() self.assertEqual(len(self.mockbot.sent_messages), 0)
def test_standard(self): u = self.iqg.get_inline_query() self.assertIsInstance(u, Update) self.assertIsInstance(u.inline_query, InlineQuery) self.assertIsInstance(u.inline_query.from_user, User) bot = Mockbot(username="******") iqg2 = InlineQueryGenerator(bot=bot) self.assertEqual(bot.username, iqg2.bot.username) with self.assertRaises(BadBotException): iqg3 = InlineQueryGenerator(bot="bot")
def setUpClass(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() self.bot.request = telegram.utils.request.Request() # Some generators for users and chats self.ug = UserGenerator() self.cg = ChatGenerator() # And a Messagegenerator,CallbackQueryGenerator and updater (for use with the bot.) self.mg = MessageGenerator(self.bot) self.cqg = CallbackQueryGenerator(self.bot) self.updater = Updater(bot=self.bot) init_db("test.sqlite3") install_commands() add_all_handlers(self.updater.dispatcher) with db_session: for listable_type in Listable.__subclasses__(): for i in range(6): listable_type(name=listable_type._discriminator_ + " " + str(i), url="https://url" + str(i) + ".com", validated=True) self.updater.start_polling()
class TestClass: bot = Mockbot() ug = UserGenerator() cg = ChatGenerator() mg = MessageGenerator(bot) pp = PicklePersistence(filename='bbqreserve_test') updater = Updater(bot=bot, persistence=pp, use_context=True) @pytest.mark.parametrize("test_input, expected, userdata", cancel_reserve_parameters) def test_cancel_reservation(self, test_input, expected, userdata): user = self.ug.get_user(id=userdata['id'], first_name=userdata['first_name'], last_name=userdata['last_name']) chat = self.cg.get_chat(user=user) self.updater.dispatcher.add_handler(cancel.cancel_reserve_conv_handler) self.updater.start_polling() update = self.mg.get_message(user=user, chat=chat, text=test_input) self.bot.insertUpdate(update) sent = self.bot.sent_messages self.updater.stop() print(sent)
class TestDCUBABot(unittest.TestCase): @classmethod def setUpClass(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() self.bot.request = telegram.utils.request.Request() # Some generators for users and chats self.ug = UserGenerator() self.cg = ChatGenerator() # And a Messagegenerator,CallbackQueryGenerator and updater (for use with the bot.) self.mg = MessageGenerator(self.bot) self.cqg = CallbackQueryGenerator(self.bot) self.updater = Updater(bot=self.bot) init_db("test.sqlite3") install_commands() add_all_handlers(self.updater.dispatcher) with db_session: for listable_type in Listable.__subclasses__(): for i in range(6): listable_type(name=listable_type._discriminator_ + " " + str(i), url="https://url" + str(i) + ".com", validated=True) self.updater.start_polling() @classmethod def tearDownClass(self): self.updater.stop() os.remove("test.sqlite3") @classmethod def sendCommand(self, command, chat_id=None): user = self.ug.get_user(first_name="Test", last_name="The Bot") if chat_id: chat = self.cg.get_chat(chat_id) else: chat = self.cg.get_chat(user=user) update = self.mg.get_message(user=user, chat=chat, text=command) self.bot.insertUpdate(update) return user, chat # TODO: Cleanup this def assert_bot_response(self, message_text, response_text, chat_id=None, random=False): if isinstance(response_text, str): response_text = [response_text] sent_messages = self.bot.sent_messages sent_messages_before = len(sent_messages) self.sendCommand(message_text, chat_id=chat_id) response_sent_messages = len(sent_messages) - sent_messages_before expected_sent_messages = 0 if not response_text else\ (1 if random else len(response_text)) self.assertEqual(response_sent_messages, expected_sent_messages) for i in range(response_sent_messages): sent = sent_messages[sent_messages_before + i] self.assertEqual(sent['method'], "sendMessage") if not random: self.assertEqual(sent['text'], response_text[i]) else: self.assertIn(sent['text'], response_text) def get_keyboard(self, message): return json.loads(message['reply_markup'])['inline_keyboard'] def button_in_list(self, name, url, list_command): self.sendCommand("/" + list_command) inline_keyboard = self.get_keyboard(self.bot.sent_messages[-1]) for row in inline_keyboard: for button in row: if button["text"] == name and button["url"] == url: return True return False def test_help(self): with db_session: for c in Command.select(): c.description = "" Command(name="comandoSinDescripcion1") Command(name="comandoConDescripcion1", description="Descripción 1") Command(name="comandoSinDescripcion2") Command(name="comandoConDescripcion2", description="Descripción 2") Command(name="comandoSinDescripcion3") Command(name="comandoConDescripcion3", description="Descripción 3") self.assert_bot_response("/help", ("/comandoConDescripcion1 - Descripción 1\n" "/comandoConDescripcion2 - Descripción 2\n" "/comandoConDescripcion3 - Descripción 3\n")) def test_start(self): self.assert_bot_response( "/start", "Hola, ¿qué tal? ¡Mandame /help si no sabés qué puedo hacer!") def test_estasvivo(self): self.assert_bot_response("/estasvivo", "Sí, estoy vivo.") def test_rozendioanalisis(self): self.assert_bot_response("/rozendioanalisis", "¡Sí, Rozen ya dio el final de análisis!") # TODO: Rename def list_test(self, command, listable_type): self.assert_bot_response(command, "Grupos: ") # Assertions on keyboard inline_keyboard = self.get_keyboard(self.bot.sent_messages[-1]) self.assertEqual(len(inline_keyboard), 2) # Number of rows for i in range(2): row = inline_keyboard[i] self.assertEqual((len(row)), 3) # Number of columns for j in range(3): button = row[j] button_number = i * 3 + j self.assertEqual( button['text'], listable_type._discriminator_ + " " + str(button_number)) self.assertEqual(button['url'], "https://url" + str(button_number) + ".com") self.assertEqual(button['callback_data'], button['url']) def test_listar(self): self.list_test("/listar", Obligatoria) def test_listaroptativa(self): self.list_test("/listaroptativa", Optativa) def test_listarotro(self): self.list_test("/listarotro", Otro) def suggestion_test(self, command, list_command, listable_type): name = "Sugerido" url = "sugerido.com" error_message = "Hiciste algo mal, la idea es que pongas:\n" +\ command + " <nombre>|<link>" # Invalid command usages self.assert_bot_response(command, error_message) self.assert_bot_response(command + " " + name, error_message) self.assert_bot_response(command + " " + name + "|", error_message) self.assert_bot_response(command + " |" + url, error_message) self.assert_bot_response(command + " |", error_message) self.assert_bot_response(command + " " + name + "|" + url + "|sobra", error_message) # Make a group suggestion to accept self.assert_bot_response(command + " " + name + "|" + url, [ listable_type.__name__ + ": " + name + "\n" + url, "OK, se lo mando a Rozen." ]) # Assertions on keyboard inline_keyboard = self.get_keyboard(self.bot.sent_messages[-2]) self.assertEqual(len(inline_keyboard), 1) # Number of rows row = inline_keyboard[0] self.assertEqual(len(row), 2) # Number of columns self.assertEqual(row[0]["text"], "Aceptar") self.assertEqual(row[1]["text"], "Rechazar") # The suggested group shouldn't be listed self.assertFalse(self.button_in_list(name, url, list_command)) # Pressing the "Aceptar" button makes the group listable u = self.cqg.get_callback_query(message=self.mg.get_message().message, data=row[0]["callback_data"]) self.bot.insertUpdate(u) self.assertTrue(self.button_in_list(name, url, list_command)) with db_session: delete(l for l in Listable if l.name == name) # Make a group suggestion to reject self.sendCommand(command + " " + name + "|" + url) inline_keyboard = self.get_keyboard(self.bot.sent_messages[-2]) row = inline_keyboard[0] # Pressing the "Rechazar" button doesn't make the group listable u = self.cqg.get_callback_query(message=self.mg.get_message().message, data=row[1]["callback_data"]) self.bot.insertUpdate(u) self.assertFalse(self.button_in_list(name, url, list_command)) # The database is clean of rejected suggestions with db_session: self.assertEqual(count(l for l in Listable if l.name == name), 0) def test_sugerirgrupo(self): self.suggestion_test("/sugerirgrupo", "listar", Obligatoria) def test_sugeriroptativa(self): self.suggestion_test("/sugeriroptativa", "listaroptativa", Optativa) def test_sugerirotro(self): self.suggestion_test("/sugerirotro", "listarotro", Otro) def test_logger(self): with self.assertLogs("DCUBABOT", level='INFO') as cm: user, _ = self.sendCommand("/listar") first_message = 'INFO:DCUBABOT:' + str(user.id) + ': /listar' user, _ = self.sendCommand("/estasvivo") second_message = 'INFO:DCUBABOT:' + str(user.id) + ': /estasvivo' self.assertEqual(cm.output, [first_message, second_message]) def test_cubawiki(self): cubawiki_url = "https://www.cubawiki.com.ar/index.php/Segundo_Parcial_del_10/12/18" positive_chat_id = -123456 negative_chat_id_no_cubawiki = -654321 negative_chat_id_no_entry = -123321 with db_session: Obligatoria(name="Cubawiki", url="test.com", chat_id=positive_chat_id, cubawiki_url=cubawiki_url) Obligatoria(name="Cubawiki", url="test.com", chat_id=negative_chat_id_no_cubawiki) # Positive test case self.assert_bot_response("/cubawiki", cubawiki_url, chat_id=positive_chat_id) # Negative test cases self.assert_bot_response("/cubawiki", None, chat_id=negative_chat_id_no_cubawiki) self.assert_bot_response("/cubawiki", None, chat_id=negative_chat_id_no_entry) with db_session: delete(o for o in Obligatoria if o.name == "Cubawiki") def test_felizdia(self): today = datetime.datetime(2019, 1, 1) self.assertEqual(felizdia_text(today), "Feliz 1 de Enero") today = datetime.datetime(2019, 2, 1) self.assertEqual(felizdia_text(today), "Feliz 1 de Febrero") today = datetime.datetime(2019, 3, 1) self.assertEqual(felizdia_text(today), "Feliz 1 de Marzo") today = datetime.datetime(2019, 4, 4) self.assertEqual(felizdia_text(today), "Feliz 4 de Abril") today = datetime.datetime(2019, 5, 21) self.assertEqual(felizdia_text(today), "Feliz 21 de Mayo") # TODO: Test randomness? def test_noitip(self): noitips = ["me siento boludeadisimo", "Not this shit again", "noitip"] with db_session: for phrase in noitips: Noitip(text=phrase) self.assert_bot_response("/noitip", noitips, random=True) def test_asm(self): with db_session: AsmInstruction(mnemonic="AAD", summary="ASCII Adjust AX Before Division", url="https://www.felixcloutier.com/x86/aad") AsmInstruction(mnemonic="ADD", summary="Add", url="https://www.felixcloutier.com/x86/add") AsmInstruction( mnemonic="ADDPD", summary="Add Packed Double-Precision Floating-Point Values", url="https://www.felixcloutier.com/x86/addpd") AsmInstruction(mnemonic="MOV", summary="Move to/from Control Registers", url="http://www.felixcloutier.com/x86/MOV-1.html") AsmInstruction(mnemonic="MOV", summary="Move to/from Debug Registers", url="http://www.felixcloutier.com/x86/MOV-2.html") AsmInstruction( mnemonic="INT n", summary="Call to Interrupt Procedure", url="http://www.felixcloutier.com/x86/INT%20n:INTO:INT%203.html" ) not_found = "No pude encontrar esa instrucción." possibles = not_found + "\nQuizás quisiste decir:" add_info = ("[ADD] Descripción: Add.\n" "Más info: https://www.felixcloutier.com/x86/add") addpd_info = ( "[ADDPD] Descripción: Add Packed Double-Precision Floating-Point Values.\n" "Más info: https://www.felixcloutier.com/x86/addpd") mov1_info = ("[MOV] Descripción: Move to/from Control Registers.\n" "Más info: http://www.felixcloutier.com/x86/MOV-1.html") mov2_info = ("[MOV] Descripción: Move to/from Debug Registers.\n" "Más info: http://www.felixcloutier.com/x86/MOV-2.html") intn_info = ( "[INT n] Descripción: Call to Interrupt Procedure.\n" "Más info: http://www.felixcloutier.com/x86/INT%20n:INTO:INT%203.html" ) self.assert_bot_response("/asm", "No me pasaste ninguna instrucción.") self.assert_bot_response("/asm add", add_info) self.assert_bot_response("/asm ADDPD", addpd_info) self.assert_bot_response("/asm a", not_found) self.assert_bot_response("/asm Adp", possibles + "\n" + add_info) self.assert_bot_response("/asm ADDPS", possibles + "\n" + addpd_info) self.assert_bot_response( "/asm addP", possibles + "\n" + add_info + "\n" + addpd_info) self.assert_bot_response("/asm MOV", mov1_info + "\n" + mov2_info) self.assert_bot_response("/asm INT n", intn_info)
class TestExplore(unittest.TestCase): def setUp(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() # Some generators for users and chats self.ug = UserGenerator() self.cg = ChatGenerator() # And a Messagegenerator and updater (for use with the bot.) self.mg = MessageGenerator(self.bot) self.updater = Updater(bot=self.bot) def test_help(self): # Then register the handler with he updater's dispatcher and start polling self.updater.dispatcher.add_handler( CommandHandler("explore", explore.explore, pass_chat_data=True)) self.updater.start_polling() # We want to simulate a message. Since we don't care wich user sends it we let the MessageGenerator # create random ones update = self.mg.get_message(text="/explore") # We insert the update with the bot so the updater can retrieve it. self.bot.insertUpdate(update) # sent_messages is the list with calls to the bot's outbound actions. Since we hope the message we inserted # only triggered one sendMessage action it's length should be 1. self.assertEqual(len(self.bot.sent_messages), 1) sent = self.bot.sent_messages[0] self.assertEqual(sent['method'], "sendMessage") self.updater.stop() def test_start(self): def start(bot, update): update.message.reply_text('Hi!') self.updater.dispatcher.add_handler(CommandHandler("start", start)) self.updater.start_polling() # Here you can see how we would handle having our own user and chat user = self.ug.get_user(first_name="Test", last_name="The Bot") chat = self.cg.get_chat(user=user) update = self.mg.get_message(user=user, chat=chat, text="/start") self.bot.insertUpdate(update) self.assertEqual(len(self.bot.sent_messages), 1) sent = self.bot.sent_messages[0] self.assertEqual(sent['method'], "sendMessage") self.assertEqual(sent['text'], "Hi!") self.updater.stop() def test_echo(self): def echo(bot, update): update.message.reply_text(update.message.text) self.updater.dispatcher.add_handler(MessageHandler(Filters.text, echo)) self.updater.start_polling() update = self.mg.get_message(text="first message") update2 = self.mg.get_message(text="second message") self.bot.insertUpdate(update) self.bot.insertUpdate(update2) self.assertEqual(len(self.bot.sent_messages), 2) sent = self.bot.sent_messages self.assertEqual(sent[0]['method'], "sendMessage") self.assertEqual(sent[0]['text'], "first message") self.assertEqual(sent[1]['text'], "second message") self.updater.stop()
def setUp(self): self.mockbot = Mockbot()
class TestMockbot(unittest.TestCase): def setUp(self): self.mockbot = Mockbot() def test_updater_works_with_mockbot(self): # handler method def start(bot, update): message = bot.sendMessage(update.message.chat_id, "this works") self.assertIsInstance(message, Message) updater = Updater(workers=2, bot=self.mockbot) dp = updater.dispatcher dp.add_handler(CommandHandler("start", start)) updater.start_polling() user = User(id=1, first_name="test") chat = Chat(45, "group") message = Message( 404, user, None, chat, text="/start", bot=self.mockbot) message2 = Message( 404, user, None, chat, text="start", bot=self.mockbot) message3 = Message( 404, user, None, chat, text="/start@MockBot", bot=self.mockbot) message4 = Message( 404, user, None, chat, text="/start@OtherBot", bot=self.mockbot) self.mockbot.insertUpdate(Update(0, message=message)) self.mockbot.insertUpdate(Update(1, message=message2)) self.mockbot.insertUpdate(Update(1, message=message3)) self.mockbot.insertUpdate(Update(1, message=message4)) data = self.mockbot.sent_messages self.assertEqual(len(data), 2) data = data[0] self.assertEqual(data['method'], 'sendMessage') self.assertEqual(data['chat_id'], chat.id) updater.stop() def test_properties(self): self.assertEqual(self.mockbot.id, 0) self.assertEqual(self.mockbot.first_name, "Mockbot") self.assertEqual(self.mockbot.last_name, "Bot") self.assertEqual(self.mockbot.name, "@MockBot") mb2 = Mockbot("OtherUsername") self.assertEqual(mb2.name, "@OtherUsername") self.mockbot.sendMessage(1, "test 1") self.mockbot.sendMessage(2, "test 2") self.assertEqual(len(self.mockbot.sent_messages), 2) self.mockbot.reset() self.assertEqual(len(self.mockbot.sent_messages), 0) def test_dejson_and_to_dict(self): import json d = self.mockbot.to_dict() self.assertIsInstance(d, dict) js = json.loads(json.dumps(d)) b = Mockbot.de_json(js, None) self.assertIsInstance(b, Mockbot) def test_answerCallbackQuery(self): self.mockbot.answerCallbackQuery( 1, "done", show_alert=True, url="google.com", cache_time=2) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "answerCallbackQuery") self.assertEqual(data['text'], "done") def test_answerInlineQuery(self): r = [ InlineQueryResult("string", "1"), InlineQueryResult("string", "2") ] self.mockbot.answerInlineQuery( 1, r, is_personal=True, next_offset=3, switch_pm_parameter="asd", switch_pm_text="pm") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "answerInlineQuery") self.assertEqual(data['results'][0]['id'], "1") def test_editMessageCaption(self): self.mockbot.editMessageCaption(chat_id=12, message_id=23) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "editMessageCaption") self.assertEqual(data['chat_id'], 12) self.mockbot.editMessageCaption( inline_message_id=23, caption="new cap", photo=True) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "editMessageCaption") with self.assertRaises(TelegramError): self.mockbot.editMessageCaption() with self.assertRaises(TelegramError): self.mockbot.editMessageCaption(chat_id=12) with self.assertRaises(TelegramError): self.mockbot.editMessageCaption(message_id=12) def test_editMessageReplyMarkup(self): self.mockbot.editMessageReplyMarkup(chat_id=1, message_id=1) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "editMessageReplyMarkup") self.assertEqual(data['chat_id'], 1) self.mockbot.editMessageReplyMarkup(inline_message_id=1) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "editMessageReplyMarkup") self.assertEqual(data['inline_message_id'], 1) with self.assertRaises(TelegramError): self.mockbot.editMessageReplyMarkup() with self.assertRaises(TelegramError): self.mockbot.editMessageReplyMarkup(chat_id=12) with self.assertRaises(TelegramError): self.mockbot.editMessageReplyMarkup(message_id=12) def test_editMessageText(self): self.mockbot.editMessageText("test", chat_id=1, message_id=1) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "editMessageText") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['text'], "test") self.mockbot.editMessageText( "test", inline_message_id=1, parse_mode="Markdown", disable_web_page_preview=True) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "editMessageText") self.assertEqual(data['inline_message_id'], 1) def test_forwardMessage(self): self.mockbot.forwardMessage(1, 2, 3) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "forwardMessage") self.assertEqual(data['chat_id'], 1) def test_getChat(self): self.mockbot.getChat(1) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "getChat") self.assertEqual(data['chat_id'], 1) def test_getChatAdministrators(self): self.mockbot.getChatAdministrators(chat_id=2) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "getChatAdministrators") self.assertEqual(data['chat_id'], 2) def test_getChatMember(self): self.mockbot.getChatMember(1, 3) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "getChatMember") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['user_id'], 3) def test_getChatMembersCount(self): self.mockbot.getChatMembersCount(1) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "getChatMembersCount") self.assertEqual(data['chat_id'], 1) def test_getFile(self): self.mockbot.getFile("12345") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "getFile") self.assertEqual(data['file_id'], "12345") def test_getGameHighScores(self): self.mockbot.getGameHighScores( 1, chat_id=2, message_id=3, inline_message_id=4) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "getGameHighScores") self.assertEqual(data['user_id'], 1) def test_getMe(self): data = self.mockbot.getMe() self.assertIsInstance(data, User) self.assertEqual(data.name, "@MockBot") def test_getUpdates(self): data = self.mockbot.getUpdates() self.assertEqual(data, []) def test_getUserProfilePhotos(self): self.mockbot.getUserProfilePhotos(1, offset=2) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "getUserProfilePhotos") self.assertEqual(data['user_id'], 1) def test_kickChatMember(self): self.mockbot.kickChatMember(chat_id=1, user_id=2) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "kickChatMember") self.assertEqual(data['user_id'], 2) def test_leaveChat(self): self.mockbot.leaveChat(1) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "leaveChat") def test_sendAudio(self): self.mockbot.sendAudio( 1, "123", duration=2, performer="singer", title="song", caption="this song") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendAudio") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['duration'], 2) self.assertEqual(data['performer'], "singer") self.assertEqual(data['title'], "song") self.assertEqual(data['caption'], "this song") def test_sendChatAction(self): self.mockbot.sendChatAction(1, ChatAction.TYPING) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendChatAction") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['action'], "typing") def test_sendContact(self): self.mockbot.sendContact(1, "123456", "test", last_name="me") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendContact") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['phone_number'], "123456") self.assertEqual(data['last_name'], "me") def test_sendDocument(self): self.mockbot.sendDocument( 1, "45", filename="jaja.docx", caption="good doc") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendDocument") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['filename'], "jaja.docx") self.assertEqual(data['caption'], "good doc") def test_sendGame(self): self.mockbot.sendGame(1, "testgame") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendGame") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['game_short_name'], "testgame") def test_sendLocation(self): self.mockbot.sendLocation(1, 52.123, 4.23) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendLocation") self.assertEqual(data['chat_id'], 1) def test_sendMessage(self): keyb = InlineKeyboardMarkup( [[InlineKeyboardButton( "test 1", callback_data="test1")], [InlineKeyboardButton( "test 2", callback_data="test2")]]) self.mockbot.sendMessage( 1, "test", parse_mode=telegram.ParseMode.MARKDOWN, reply_markup=keyb, disable_notification=True, reply_to_message_id=334, disable_web_page_preview=True) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendMessage") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['text'], "test") self.assertEqual( eval(data['reply_markup'])['inline_keyboard'][1][0][ 'callback_data'], "test2") def test_sendPhoto(self): self.mockbot.sendPhoto(1, "test.png", caption="photo") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendPhoto") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['caption'], "photo") def test_sendSticker(self): self.mockbot.sendSticker(-4231, "test") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendSticker") self.assertEqual(data['chat_id'], -4231) def test_sendVenue(self): self.mockbot.sendVenue( 1, 4.2, 5.1, "nice place", "somewherestreet 2", foursquare_id=2) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendVenue") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['foursquare_id'], 2) def test_sendVideo(self): self.mockbot.sendVideo(1, "some file", duration=3, caption="video") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendVideo") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['duration'], 3) self.assertEqual(data['caption'], "video") def test_sendVoice(self): self.mockbot.sendVoice(1, "some file", duration=3, caption="voice") data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "sendVoice") self.assertEqual(data['chat_id'], 1) self.assertEqual(data['duration'], 3) self.assertEqual(data['caption'], "voice") def test_setGameScore(self): self.mockbot.setGameScore( 1, 200, chat_id=2, message_id=3, inline_message_id=4, force=True, disable_edit_message=True) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "setGameScore") self.assertEqual(data['user_id'], 1) self.mockbot.setGameScore(1, 200, edit_message=True) def test_unbanChatMember(self): self.mockbot.unbanChatMember(1, 2) data = self.mockbot.sent_messages[-1] self.assertEqual(data['method'], "unbanChatMember") self.assertEqual(data['chat_id'], 1)
class TestInlineKeyboard(unittest.TestCase): def setUp(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() # Some generators for users and chats self.cg = ChatGenerator() # And a Messagegenerator, CallbackQueryGenerator and updater (for use with the bot.) self.mg = MessageGenerator(self.bot) self.cqg = CallbackQueryGenerator(self.bot) self.updater = Updater(bot=self.bot) def test_callback(self): # first insert the callbackhandler, register it and start polling def button(bot, update): query = update.callback_query bot.editMessageText(text="Selected option: %s" % query.data, chat_id=query.message.chat_id, message_id=query.message.message_id) dp = self.updater.dispatcher dp.add_handler(CallbackQueryHandler(button)) self.updater.start_polling() # the start callback in this example generates a message that will be edited, so let's mimick that message # for future reference keyboard = [[ InlineKeyboardButton("Option 1", callback_data='1'), InlineKeyboardButton("Option 2", callback_data='2') ], [InlineKeyboardButton("Option 3", callback_data='3')]] reply_markup = InlineKeyboardMarkup(keyboard) chat = self.cg.get_chat() start_message = self.bot.sendMessage(chat_id=chat.id, text='Please choose:', reply_markup=reply_markup) # now let's create some callback query's to send u1 = self.cqg.get_callback_query(message=start_message, data="1") u2 = self.cqg.get_callback_query(message=start_message, data="2") u3 = self.cqg.get_callback_query(message=start_message, data="3") # And test them one by one self.bot.insertUpdate(u1) data = self.bot.sent_messages[-1] self.assertEqual(data['text'], "Selected option: 1") self.assertEqual(data['chat_id'], start_message.chat.id) self.assertEqual(data['message_id'], start_message.message_id) self.bot.insertUpdate(u2) data = self.bot.sent_messages[-1] self.assertEqual(data['text'], "Selected option: 2") self.assertEqual(data['chat_id'], start_message.chat.id) self.assertEqual(data['message_id'], start_message.message_id) self.bot.insertUpdate(u3) data = self.bot.sent_messages[-1] self.assertEqual(data['text'], "Selected option: 3") self.assertEqual(data['chat_id'], start_message.chat.id) self.assertEqual(data['message_id'], start_message.message_id) # stop polling self.updater.stop()
class Testtimerbot(unittest.TestCase): def setUp(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() # Some generators for users and chats self.cg = ChatGenerator() # And a Messagegenerator and updater (for use with the bot.) self.mg = MessageGenerator(self.bot) self.updater = Updater(bot=self.bot) # type: ignore def test_timer(self): # first declare the callback methods def alarm(context): """Function to send the alarm message""" context.bot.sendMessage(context.job.context["chat_id"], text='Beep!') def set(update, context): """Adds a job to the queue""" chat_id = update.message.chat_id try: args = context.args # args[0] should contain the time for the timer in seconds due = int(args[0]) if due < 0: update.message.reply_text( 'Sorry we can not go back to the past!') return # Add job to queue context.user_data["job"] = context.job_queue.run_once( callback=alarm, when=due, context={"chat_id": chat_id}) update.message.reply_text('Timer successfully set!') except (IndexError, ValueError): update.message.reply_text('Usage: /set <seconds>') def unset(update, context): """Removes the job if the user changed their mind""" if 'job' not in context.user_data: update.message.reply_text('You have no active timer') return job = context.user_data['job'] job.schedule_removal() del context.user_data['job'] update.message.reply_text('Timer successfully unset!') # Now add those handlers to the updater and start polling dp = self.updater.dispatcher dp.add_handler(CommandHandler("set", set)) dp.add_handler(CommandHandler("unset", unset)) self.updater.start_polling() # we want to check if the bot returns a message to the same chat after a period of time # so let's create a chat to use chat = self.cg.get_chat() # let's generate some updates we can use u1 = self.mg.get_message(chat=chat, text="/set", parse_mode="HTML") u2 = self.mg.get_message(chat=chat, text="/set -20", parse_mode="HTML") u3 = self.mg.get_message(chat=chat, text="/set 6", parse_mode="HTML") u4 = self.mg.get_message(chat=chat, text="/unset", parse_mode="HTML") # first check some errors self.bot.insertUpdate(u1) self.bot.insertUpdate(u2) self.bot.insertUpdate(u4) data = self.bot.sent_messages self.assertEqual(len(data), 3) self.assertEqual(data[0]['text'], "Usage: /set <seconds>") self.assertEqual(data[1]['text'], 'Sorry we can not go back to the past!') self.assertEqual(data[2]['text'], 'You have no active timer') # now check if setting and unsetting works (within timer limit) self.bot.insertUpdate(u3) data = self.bot.sent_messages[-1] self.assertEqual(data['text'], 'Timer successfully set!') time.sleep(2) self.bot.insertUpdate(u4) data = self.bot.sent_messages[-1] self.assertEqual(data['text'], 'Timer successfully unset!') # and to be certain we have to wait some more to see if it stops sending the message # we reset the bot so we can be sure nothing more has been sent self.bot.reset() time.sleep(5) data = self.bot.sent_messages self.assertEqual(len(data), 0) # lastly we will make sure an alarm message is sent after the timelimit has passed self.bot.insertUpdate(u3) time.sleep(6) data = self.bot.sent_messages[-1] self.assertEqual(data['text'], 'Beep!') self.assertEqual(data['chat_id'], chat.id) # and stop the updater. self.updater.stop()
class TestCommands(unittest.TestCase): def setUp(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() # Some generators for users and chats self.ug = UserGenerator() self.cg = ChatGenerator() # And a Messagegenerator and updater (for use with the bot.) self.mg = MessageGenerator(self.bot) self.updater = Updater(bot=self.bot) GamesController.init() def test_ping(self): # Then register the handler with he updater's dispatcher and start polling self.updater.dispatcher.add_handler( CommandHandler("ping", command_ping)) self.updater.start_polling() # create with random user update = self.mg.get_message(text="/ping") # We insert the update with the bot so the updater can retrieve it. self.bot.insertUpdate(update) # sent_messages is the list with calls to the bot's outbound actions. Since we hope the message we inserted # only triggered one sendMessage action it's length should be 1. self.assertEqual(len(self.bot.sent_messages), 1) sent = self.bot.sent_messages[0] self.assertEqual(sent['method'], "sendMessage") self.assertEqual(sent['text'], "pong - v0.4") # Always stop the updater at the end of a testcase so it won't hang. self.updater.stop() def test_start(self): self.updater.dispatcher.add_handler( CommandHandler("start", command_start)) self.updater.start_polling() update = self.mg.get_message(text="/start") self.bot.insertUpdate(update) self.assertEqual(len(self.bot.sent_messages), 2) start = self.bot.sent_messages[0] self.assertEqual(start['method'], "sendMessage") self.assertIn("Secret Blue is a social deduction game", start['text']) help = self.bot.sent_messages[1] self.assertEqual(help['method'], "sendMessage") self.assertIn("The following commands are available", help['text']) self.updater.stop() def test_symbols(self): self.updater.dispatcher.add_handler( CommandHandler("symbols", command_symbols)) self.updater.start_polling() update = self.mg.get_message(text="/symbols") self.bot.insertUpdate(update) self.assertEqual(len(self.bot.sent_messages), 1) sent = self.bot.sent_messages[0] self.assertEqual(sent['method'], "sendMessage") self.assertIn("The following symbols can appear on the board:", sent['text']) self.updater.stop() def test_board_when_there_is_no_game(self): self.updater.dispatcher.add_handler( CommandHandler("board", command_board)) self.updater.start_polling() update = self.mg.get_message(text="/board") self.bot.insertUpdate(update) self.assertEqual(len(self.bot.sent_messages), 1) sent = self.bot.sent_messages[0] self.assertEqual(sent['method'], "sendMessage") self.assertIn( "There is no game in this chat. Create a new game with /newgame", sent['text']) self.updater.stop() def test_board_when_game_is_not_running(self): game = Game(-999, 12345) GamesController.games[-999] = game self.updater.dispatcher.add_handler( CommandHandler("board", command_board)) self.updater.start_polling() chat = self.cg.get_chat(cid=-999) update = self.mg.get_message(chat=chat, text="/board") self.bot.insertUpdate(update) self.assertEqual(len(self.bot.sent_messages), 1) sent = self.bot.sent_messages[0] self.assertEqual(sent['method'], "sendMessage") self.assertIn( "There is no running game in this chat. Please start the game with /startgame", sent['text']) self.updater.stop() def test_board_when_game_is_running(self): game = Game(-999, 12345) game.board = Board(5, game) GamesController.games[-999] = game self.updater.dispatcher.add_handler( CommandHandler("board", command_board)) self.updater.start_polling() chat = self.cg.get_chat(cid=-999) update = self.mg.get_message(chat=chat, text="/board") self.bot.insertUpdate(update) self.assertEqual(len(self.bot.sent_messages), 1) sent = self.bot.sent_messages[0] self.assertEqual(sent['method'], "sendMessage") self.assertIn("--- Liberal acts ---", sent['text']) self.updater.stop()
def setUp(self): self.bot = Mockbot() self.ug = UserGenerator() self.cg = ChatGenerator() self.mg = MessageGenerator(self.bot) self.updater = Updater(bot=self.bot)
class TestInlineBot(unittest.TestCase): def setUp(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() # And an InlineQueryGenerator and updater (for use with the bot.) self.iqg = InlineQueryGenerator(self.bot) self.updater = Updater(bot=self.bot) def test_inline_bot(self): # create some handlers and add them def escape_markdown(text): """Helper function to escape telegram markup symbols""" escape_chars = '\*_`\[' return re.sub(r'([%s])' % escape_chars, r'\\\1', text) def inlinequery(bot, update): query = update.inline_query.query results = list() results.append( InlineQueryResultArticle( id=uuid4(), title="Caps", input_message_content=InputTextMessageContent( query.upper()))) results.append( InlineQueryResultArticle( id=uuid4(), title="Bold", input_message_content=InputTextMessageContent( "*%s*" % escape_markdown(query), parse_mode=ParseMode.MARKDOWN))) results.append( InlineQueryResultArticle( id=uuid4(), title="Italic", input_message_content=InputTextMessageContent( "_%s_" % escape_markdown(query), parse_mode=ParseMode.MARKDOWN))) update.inline_query.answer(results) dp = self.updater.dispatcher dp.add_handler(InlineQueryHandler(inlinequery)) self.updater.start_polling() # Now test the handler u1 = self.iqg.get_inline_query(query="test data") self.bot.insertUpdate(u1) data = self.bot.sent_messages[-1] self.assertEqual(len(data['results']), 3) results = data['results'] self.assertEqual(results[0]['title'], "Caps") self.assertEqual(results[0]['input_message_content']['message_text'], "TEST DATA") self.assertEqual(results[1]['title'], "Bold") self.assertEqual(results[1]['input_message_content']['message_text'], "*test data*") self.assertEqual(results[2]['title'], "Italic") self.assertEqual(results[2]['input_message_content']['message_text'], "_test data_") self.updater.stop()
class TestConversationbot2(unittest.TestCase): def setUp(self): self.bot = Mockbot() self.cg = ChatGenerator() self.ug = UserGenerator() self.mg = MessageGenerator(self.bot) self.updater = Updater(bot=self.bot) def test_conversation(self): CHOOSING, TYPING_REPLY, TYPING_CHOICE = range(3) reply_keyboard = [['Age', 'Favourite colour'], ['Number of siblings', 'Something else...'], ['Done']] markup = ReplyKeyboardMarkup(reply_keyboard, one_time_keyboard=True) def facts_to_str(user_data): facts = list() for key, value in user_data.items(): facts.append('%s - %s' % (key, value)) return "\n".join(facts).join(['\n', '\n']) def start(bot, update): update.message.reply_text( "Hi! My name is Doctor Botter. I will hold a more complex conversation with you. " "Why don't you tell me something about yourself?", reply_markup=markup) return CHOOSING def regular_choice(bot, update, user_data): text = update.message.text user_data['choice'] = text update.message.reply_text('Your %s? Yes, I would love to hear about that!' % text.lower()) return TYPING_REPLY def custom_choice(bot, update): update.message.reply_text('Alright, please send me the category first, ' 'for example "Most impressive skill"') return TYPING_CHOICE def received_information(bot, update, user_data): text = update.message.text category = user_data['choice'] user_data[category] = text del user_data['choice'] update.message.reply_text("Neat! Just so you know, this is what you already told me:" "%s" "You can tell me more, or change your opinion on something." % facts_to_str(user_data), reply_markup=markup) return CHOOSING def done(bot, update, user_data): if 'choice' in user_data: del user_data['choice'] update.message.reply_text("I learned these facts about you:" "%s" "Until next time!" % facts_to_str(user_data)) user_data.clear() return ConversationHandler.END conv_handler = ConversationHandler( entry_points=[CommandHandler('start', start)], states={ CHOOSING: [RegexHandler('^(Age|Favourite colour|Number of siblings)$', regular_choice, pass_user_data=True), RegexHandler('^Something else...$', custom_choice), ], TYPING_CHOICE: [MessageHandler(Filters.text, regular_choice, pass_user_data=True), ], TYPING_REPLY: [MessageHandler(Filters.text, received_information, pass_user_data=True), ], }, fallbacks=[RegexHandler('^Done$', done, pass_user_data=True)] ) dp = self.updater.dispatcher dp.add_handler(conv_handler) self.updater.start_polling() # We are going to test a conversationhandler. Since this is tied in with user and chat we need to # create both for consistancy user = self.ug.get_user() chat = self.cg.get_chat(type="group") user2 = self.ug.get_user() chat2 = self.cg.get_chat(user=user) # let's start the conversation u = self.mg.get_message(user=user, chat=chat, text="/start") self.bot.insertUpdate(u) data = self.bot.sent_messages[-1] self.assertRegexpMatches(data['text'], r"Doctor Botter\. I will") u = self.mg.get_message(user=user, chat=chat, text="Age") self.bot.insertUpdate(u) data = self.bot.sent_messages[-1] self.assertRegexpMatches(data['text'], r"Your age\? Yes") # now let's see what happens when another user in another chat starts conversating with the bot u = self.mg.get_message(user=user2, chat=chat2, text="/start") self.bot.insertUpdate(u) data = self.bot.sent_messages[-1] self.assertRegexpMatches(data['text'], r"Doctor Botter\. I will") self.assertEqual(data['chat_id'], chat2.id) self.assertNotEqual(data['chat_id'], chat.id) # and cancels his conv. u = self.mg.get_message(user=user2, chat=chat2, text="Done") self.bot.insertUpdate(u) data = self.bot.sent_messages[-1] self.assertRegexpMatches(data['text'], r"Until next time!") # cary on with first user u = self.mg.get_message(user=user, chat=chat, text="23") self.bot.insertUpdate(u) data = self.bot.sent_messages[-1] self.assertRegexpMatches(data['text'], r"Age - 23") u = self.mg.get_message(user=user, chat=chat, text="Something else...") self.bot.insertUpdate(u) data = self.bot.sent_messages[-1] self.assertRegexpMatches(data['text'], r"Most impressive skill") u = self.mg.get_message(user=user, chat=chat, text="programming skill") self.bot.insertUpdate(u) data = self.bot.sent_messages[-1] self.assertRegexpMatches(data['text'], r"Your programming skill\? Yes") u = self.mg.get_message(user=user, chat=chat, text="High") self.bot.insertUpdate(u) data = self.bot.sent_messages[-1] self.assertRegexpMatches(data['text'], r"programming skill - High") u = self.mg.get_message(user=user, chat=chat, text="Done") self.bot.insertUpdate(u) data = self.bot.sent_messages[-1] self.assertRegexpMatches(data['text'], r"programming skill - High") self.assertRegexpMatches(data['text'], r"Age - 23") self.updater.stop()
class CallbackQueryGenerator(PtbGenerator): """ Callback query generator class. Attributes: bot (ptbtest.Mockbot): Bot to encode with the messages Args: bot (Optional[ptbtest.Mockbot]): supply your own for a custom botname """ def __init__(self, bot=None): PtbGenerator.__init__(self) self.ug = UserGenerator() if not bot: self.bot = Mockbot() elif isinstance(bot, Mockbot): self.bot = bot else: raise BadBotException @update("callback_query") def get_callback_query(self, user=None, chat_instance=None, message=None, data=None, inline_message_id=None, game_short_name=None): """ Returns a telegram.Update object containing a callback_query. Notes: One of message and inline_message_id must be present One of data and game_short_name must be present Parameters: user (Optional[telegram.User]): User that initiated the callback_query chat_instance (Optional[str]): unique identifier, not used message (Optional[telegram.Message]): Message the callback_query button belongs to inline_message_id (Optional[str]): Message the callback_query button belongs to data (Optional[string]): Data attached to the button game_short_name (Optional[str]): game identifier with this button Returns: telegram.Update: containing a :py:class:`telegram.CallbackQuery` """ # Required if user: if not isinstance(user, User): raise BadUserException else: user = self.ug.get_user() if not chat_instance: chat_instance = self._gen_id() if message: if isinstance(message, Message): pass elif isinstance(message, bool): chat = ChatGenerator().get_chat(user=user) message = MessageGenerator().get_message( user=self.bot.getMe(), chat=chat, bot=self.bot.getMe()).message else: raise BadMessageException if inline_message_id: if isinstance(inline_message_id, str): pass elif isinstance(inline_message_id, bool): inline_message_id = self._gen_id() else: raise BadCallbackQueryException( "inline_message_id should be string or True") if not len([x for x in [message, inline_message_id] if x]) == 1: raise BadCallbackQueryException( "exactly 1 of message and inline_message_id is needed") if not len([x for x in [data, game_short_name] if x]) == 1: raise BadCallbackQueryException( "exactly 1 of data and game_short_name is needed") return CallbackQuery(self._gen_id(), user, chat_instance, message, data, inline_message_id, game_short_name, self.bot) def _gen_id(self): return str(uuid.uuid4())
class TestBot2(unittest.TestCase): def setUp(self): self.bot = Mockbot() self.ug = UserGenerator() self.cg = ChatGenerator() self.mg = MessageGenerator(self.bot) self.updater = Updater(bot=self.bot) def test_start(self): def start(bot, update): text = 'Привет! Введи номер теста который хочешь пройти:\n' update.message.reply_text(text) self.updater.dispatcher.add_handler(CommandHandler("start", start)) self.updater.start_polling() update = self.mg.get_message(text="/start") self.bot.insertUpdate(update) self.assertEqual(len(self.bot.sent_messages), 1) sent = self.bot.sent_messages[0] self.assertEqual(sent['method'], "sendMessage") self.assertEqual(sent['text'], "Привет! Введи номер теста который хочешь пройти:\n") self.updater.stop() def test_create(self): def create(bot, update): text = 'Чтобы добавить свой текст введите его в соответствуюшем формате:\n' \ 'Тест про кошек\n' \ '1)Какая ты кошка?;глотка шорсный,пушистый,лысый;3,2,1\n' \ '2)Где ты живешь?;спб,мск;1,0\n' \ '3)Любишь бегать?;да,нет;1,0\n' \ '4)Что любишь Кушать?;сосиски,молоко;2,1\n' \ 'Хороший кот;5;7\n' \ 'Нормальный кот;2;4\n' \ 'Не кот;0;1' update.message.reply_text(text) self.updater.dispatcher.add_handler(CommandHandler("create", create)) self.updater.start_polling() update = self.mg.get_message(text="/create") self.bot.insertUpdate(update) self.assertEqual(len(self.bot.sent_messages), 1) sent = self.bot.sent_messages[0] self.assertEqual(sent['method'], "sendMessage") text = 'Чтобы добавить свой текст введите его в соответствуюшем формате:\n' \ 'Тест про кошек\n' \ '1)Какая ты кошка?;глотка шорсный,пушистый,лысый;3,2,1\n' \ '2)Где ты живешь?;спб,мск;1,0\n' \ '3)Любишь бегать?;да,нет;1,0\n' \ '4)Что любишь Кушать?;сосиски,молоко;2,1\n' \ 'Хороший кот;5;7\n' \ 'Нормальный кот;2;4\n' \ 'Не кот;0;1' self.assertEqual(sent['text'], text) self.updater.stop() def test_parser(self): @mock.patch('test_bot.parse_text', return_value="Вы что то не так ввели") def parser(bot, update, mock_parse_text): if update.message.text == '/reset' or update.message.text == '/start': return update.message.reply_text(parse_text(update.message.text)) self.updater.dispatcher.add_handler( MessageHandler(Filters.text, parser)) self.updater.start_polling() update = self.mg.get_message(text="/reset") self.bot.insertUpdate(update) sent = self.bot.sent_messages self.assertEqual(sent.__len__(), 0) self.updater.stop() self.updater.start_polling() update = self.mg.get_message(text="NAME\n1)Question1;a,b;1,2") self.bot.insertUpdate(update) sent = self.bot.sent_messages self.assertEqual(sent[0]['method'], "sendMessage") self.assertEqual(sent[0]['text'], "Вы что то не так ввели") self.updater.stop()
def setUp(self): # For use within the tests we nee some stuff. Starting with a Mockbot self.bot = Mockbot() # And an InlineQueryGenerator and updater (for use with the bot.) self.iqg = InlineQueryGenerator(self.bot) self.updater = Updater(bot=self.bot)