Ejemplo n.º 1
0
 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 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()
Ejemplo n.º 3
0
    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!")
Ejemplo n.º 4
0
class TestMessageGeneratorReplies(unittest.TestCase):
    def setUp(self):
        self.mg = MessageGenerator()

    def test_reply(self):
        u1 = self.mg.get_message(text="this is the first")
        u2 = self.mg.get_message(
            text="This is the second", reply_to_message=u1.message)
        self.assertEqual(u1.message.text, u2.message.reply_to_message.text)

        with self.assertRaises(BadMessageException):
            u = "This is not a Messages"
            self.mg.get_message(reply_to_message=u)
Ejemplo n.º 5
0
class TestMessageGeneratorChannelPost(unittest.TestCase):
    def setUp(self):
        self.mg = MessageGenerator()

    def test_channel_post(self):
        u = self.mg.get_channel_post()
        self.assertIsInstance(u, Update)
        self.assertIsInstance(u.channel_post, Message)
        self.assertEqual(u.channel_post.chat.type, "channel")
        self.assertEqual(u.channel_post.from_user, None)

    def test_with_chat(self):
        cg = ChatGenerator()
        group = cg.get_chat(type="group")
        channel = cg.get_chat(type="channel")
        u = self.mg.get_channel_post(chat=channel)
        self.assertEqual(channel.title, u.channel_post.chat.title)

        with self.assertRaisesRegexp(BadChatException, "telegram\.Chat"):
            self.mg.get_channel_post(chat="chat")
        with self.assertRaisesRegexp(BadChatException, "chat\.type"):
            self.mg.get_channel_post(chat=group)

    def test_with_user(self):
        ug = UserGenerator()
        user = ug.get_user()
        u = self.mg.get_channel_post(user=user)
        self.assertEqual(u.channel_post.from_user.id, user.id)

    def test_with_content(self):
        u = self.mg.get_channel_post(
            text="this is *bold* _italic_", parse_mode="Markdown")
        self.assertEqual(u.channel_post.text, "this is bold italic")
        self.assertEqual(len(u.channel_post.entities), 2)
Ejemplo n.º 6
0
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
Ejemplo n.º 7
0
    def test_message(self):
        mg = MessageGenerator()
        message = mg.get_message().message
        u = self.cqg.get_callback_query(message=message, data="test-data")
        self.assertIsInstance(u, Update)
        self.assertIsInstance(u.callback_query, CallbackQuery)
        self.assertEqual(u.callback_query.message.message_id,
                         message.message_id)

        u = self.cqg.get_callback_query(message=True, data="test-data")
        self.assertIsInstance(u.callback_query.message, Message)
        self.assertEqual(u.callback_query.message.from_user.username,
                         self.cqg.bot.username)

        with self.assertRaises(BadMessageException):
            self.cqg.get_callback_query(message="message", data="test-data")
Ejemplo n.º 8
0
class TestMessageGeneratorForwards(unittest.TestCase):
    def setUp(self):
        self.mg = MessageGenerator()
        self.ug = UserGenerator()
        self.cg = ChatGenerator()

    def test_forwarded_message(self):
        u1 = self.ug.get_user()
        u2 = self.ug.get_user()
        c = self.cg.get_chat(type="group")
        u = self.mg.get_message(user=u1,
                                chat=c,
                                forward_from=u2,
                                text="This is a test")
        self.assertEqual(u.message.from_user.id, u1.id)
        self.assertEqual(u.message.forward_from.id, u2.id)
        self.assertNotEqual(u.message.from_user.id, u.message.forward_from.id)
        self.assertEqual(u.message.text, "This is a test")
        self.assertIsInstance(u.message.forward_date, int)
        import datetime
        self.mg.get_message(forward_from=u2,
                            forward_date=datetime.datetime.now())

        with self.assertRaises(BadUserException):
            u3 = "This is not a User"
            u = self.mg.get_message(user=u1,
                                    chat=c,
                                    forward_from=u3,
                                    text="This is a test")

    def test_forwarded_channel_message(self):
        c = self.cg.get_chat(type="channel")
        us = self.ug.get_user()
        u = self.mg.get_message(text="This is a test",
                                forward_from=us,
                                forward_from_chat=c)
        self.assertNotEqual(u.message.chat.id, c.id)
        self.assertNotEqual(u.message.from_user.id, us.id)
        self.assertEqual(u.message.forward_from.id, us.id)
        self.assertEqual(u.message.text, "This is a test")
        self.assertIsInstance(u.message.forward_from_message_id, int)
        self.assertIsInstance(u.message.forward_date, int)

        u = self.mg.get_message(text="This is a test", forward_from_chat=c)
        self.assertNotEqual(u.message.from_user.id, u.message.forward_from.id)
        self.assertIsInstance(u.message.forward_from, User)
        self.assertIsInstance(u.message.forward_from_message_id, int)
        self.assertIsInstance(u.message.forward_date, int)

        with self.assertRaises(BadChatException):
            c = "Not a Chat"
            u = self.mg.get_message(text="This is a test", forward_from_chat=c)

        with self.assertRaises(BadChatException):
            c = self.cg.get_chat(type="group")
            u = self.mg.get_message(text="This is a test", forward_from_chat=c)
Ejemplo n.º 9
0
 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)
Ejemplo n.º 10
0
class TestMessageGeneratorEditedMessage(unittest.TestCase):
    def setUp(self):
        self.mg = MessageGenerator()

    def test_edited_message(self):
        u = self.mg.get_edited_message()
        self.assertIsInstance(u.edited_message, Message)
        self.assertIsInstance(u, Update)

    def test_with_parameters(self):
        u = self.mg.get_edited_message(
            text="New *text*", parse_mode="Markdown")
        self.assertEqual(u.edited_message.text, "New text")
        self.assertEqual(len(u.edited_message.entities), 1)

    def test_with_message(self):
        m = self.mg.get_message(text="first").message
        u = self.mg.get_edited_message(message=m, text="second")
        self.assertEqual(m.message_id, u.edited_message.message_id)
        self.assertEqual(m.chat.id, u.edited_message.chat.id)
        self.assertEqual(m.from_user.id, u.edited_message.from_user.id)
        self.assertEqual(u.edited_message.text, "second")

        with self.assertRaises(BadMessageException):
            self.mg.get_edited_message(message="Message")
Ejemplo n.º 11
0
 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()
Ejemplo n.º 12
0
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)
Ejemplo n.º 13
0
class TestMessageGeneratorEditedChannelPost(unittest.TestCase):
    def setUp(self):
        self.mg = MessageGenerator()

    def test_edited_channel_post(self):
        u = self.mg.get_edited_channel_post()
        self.assertIsInstance(u.edited_channel_post, Message)
        self.assertIsInstance(u, Update)

    def test_with_parameters(self):
        u = self.mg.get_edited_channel_post(
            text="New *text*", parse_mode="Markdown")
        self.assertEqual(u.edited_channel_post.text, "New text")
        self.assertEqual(len(u.edited_channel_post.entities), 1)

    def test_with_channel_post(self):
        m = self.mg.get_channel_post(text="first").channel_post
        u = self.mg.get_edited_channel_post(channel_post=m, text="second")
        self.assertEqual(m.message_id, u.edited_channel_post.message_id)
        self.assertEqual(m.chat.id, u.edited_channel_post.chat.id)
        self.assertEqual(u.edited_channel_post.text, "second")

        with self.assertRaises(BadMessageException):
            self.mg.get_edited_channel_post(channel_post="Message")
Ejemplo n.º 14
0
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()
Ejemplo n.º 15
0
class TestMessageGeneratorStatusMessages(unittest.TestCase):
    def setUp(self):
        self.mg = MessageGenerator()
        self.ug = UserGenerator()
        self.cg = ChatGenerator()

    def test_new_chat_member(self):
        user = self.ug.get_user()
        chat = self.cg.get_chat(type="group")
        u = self.mg.get_message(chat=chat, new_chat_member=user)
        self.assertEqual(u.message.new_chat_member.id, user.id)

        with self.assertRaises(BadChatException):
            self.mg.get_message(new_chat_member=user)
        with self.assertRaises(BadUserException):
            self.mg.get_message(chat=chat, new_chat_member="user")

    def test_left_chat_member(self):
        user = self.ug.get_user()
        chat = self.cg.get_chat(type='group')
        u = self.mg.get_message(chat=chat, left_chat_member=user)
        self.assertEqual(u.message.left_chat_member.id, user.id)

        with self.assertRaises(BadChatException):
            self.mg.get_message(left_chat_member=user)
        with self.assertRaises(BadUserException):
            self.mg.get_message(chat=chat, left_chat_member="user")

    def test_new_chat_title(self):
        chat = self.cg.get_chat(type="group")
        u = self.mg.get_message(chat=chat, new_chat_title="New title")
        self.assertEqual(u.message.chat.title, "New title")
        self.assertEqual(u.message.chat.title, chat.title)

        with self.assertRaises(BadChatException):
            self.mg.get_message(new_chat_title="New title")

    def test_new_chat_photo(self):
        chat = self.cg.get_chat(type="group")
        u = self.mg.get_message(chat=chat, new_chat_photo=True)
        self.assertIsInstance(u.message.new_chat_photo, list)
        self.assertIsInstance(u.message.new_chat_photo[0], PhotoSize)
        photo = [PhotoSize("2", 1, 1, file_size=3)]
        u = self.mg.get_message(chat=chat, new_chat_photo=photo)
        self.assertEqual(len(u.message.new_chat_photo), 1)

        with self.assertRaises(BadChatException):
            self.mg.get_message(new_chat_photo=True)

        photo = "foto's!"
        with self.assertRaises(BadMessageException):
            self.mg.get_message(chat=chat, new_chat_photo=photo)
        with self.assertRaises(BadMessageException):
            self.mg.get_message(chat=chat, new_chat_photo=[1, 2, 3])

    def test_pinned_message(self):
        chat = self.cg.get_chat(type="supergroup")
        message = self.mg.get_message(
            chat=chat, text="this will be pinned").message
        u = self.mg.get_message(chat=chat, pinned_message=message)
        self.assertEqual(u.message.pinned_message.text, "this will be pinned")

        with self.assertRaises(BadChatException):
            self.mg.get_message(pinned_message=message)
        with self.assertRaises(BadMessageException):
            self.mg.get_message(chat=chat, pinned_message="message")

    def test_multiple_statusmessages(self):
        with self.assertRaises(BadMessageException):
            self.mg.get_message(
                private=False,
                new_chat_member=self.ug.get_user(),
                new_chat_title="New title")
Ejemplo n.º 16
0
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()
Ejemplo n.º 17
0
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()
Ejemplo n.º 18
0
 def setUp(self):
     self.bot = Mockbot()
     self.ug = UserGenerator()
     self.cg = ChatGenerator()
     self.mg = MessageGenerator(self.bot)
     self.updater = Updater(bot=self.bot)
Ejemplo n.º 19
0
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()
Ejemplo n.º 20
0
 def setUp(self):
     self.mg = MessageGenerator()
     self.ug = UserGenerator()
     self.cg = ChatGenerator()
Ejemplo n.º 21
0
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)
Ejemplo n.º 22
0
class TestMessageGeneratorText(unittest.TestCase):
    def setUp(self):
        self.mg = MessageGenerator()

    def test_simple_text(self):
        u = self.mg.get_message(text="This is a test")
        self.assertEqual(u.message.text, "This is a test")

    def test_text_with_markdown(self):
        teststr = "we have *bold* `code` [google](www.google.com) @username #hashtag _italics_ ```pre block``` " \
                  "ftp://snt.utwente.nl /start"
        u = self.mg.get_message(text=teststr)
        self.assertEqual(u.message.text, teststr)

        u = self.mg.get_message(text=teststr, parse_mode="Markdown")
        self.assertEqual(len(u.message.entities), 9)
        for ent in u.message.entities:
            if ent.type == "bold":
                self.assertEqual(ent.offset, 8)
                self.assertEqual(ent.length, 4)
            elif ent.type == "code":
                self.assertEqual(ent.offset, 13)
                self.assertEqual(ent.length, 4)
            elif ent.type == "italic":
                self.assertEqual(ent.offset, 44)
                self.assertEqual(ent.length, 7)
            elif ent.type == "pre":
                self.assertEqual(ent.offset, 52)
                self.assertEqual(ent.length, 9)
            elif ent.type == "text_link":
                self.assertEqual(ent.offset, 18)
                self.assertEqual(ent.length, 6)
                self.assertEqual(ent.url, "www.google.com")
            elif ent.type == "mention":
                self.assertEqual(ent.offset, 25)
                self.assertEqual(ent.length, 9)
            elif ent.type == "hashtag":
                self.assertEqual(ent.offset, 35)
                self.assertEqual(ent.length, 8)
            elif ent.type == "url":
                self.assertEqual(ent.offset, 62)
                self.assertEqual(ent.length, 20)
            elif ent.type == "bot_command":
                self.assertEqual(ent.offset, 83)
                self.assertEqual(ent.length, 6)

        with self.assertRaises(BadMarkupException):
            self.mg.get_message(
                text="bad *_double_* markdown", parse_mode="Markdown")

    def test_with_html(self):
        teststr = "we have <b>bold</b> <code>code</code> <a href='www.google.com'>google</a> @username #hashtag " \
                  "<i>italics</i> <pre>pre block</pre> ftp://snt.utwente.nl /start"
        u = self.mg.get_message(text=teststr)
        self.assertEqual(u.message.text, teststr)

        u = self.mg.get_message(text=teststr, parse_mode="HTML")
        self.assertEqual(len(u.message.entities), 9)
        for ent in u.message.entities:
            if ent.type == "bold":
                self.assertEqual(ent.offset, 8)
                self.assertEqual(ent.length, 4)
            elif ent.type == "code":
                self.assertEqual(ent.offset, 13)
                self.assertEqual(ent.length, 4)
            elif ent.type == "italic":
                self.assertEqual(ent.offset, 44)
                self.assertEqual(ent.length, 7)
            elif ent.type == "pre":
                self.assertEqual(ent.offset, 52)
                self.assertEqual(ent.length, 9)
            elif ent.type == "text_link":
                self.assertEqual(ent.offset, 18)
                self.assertEqual(ent.length, 6)
                self.assertEqual(ent.url, "www.google.com")
            elif ent.type == "mention":
                self.assertEqual(ent.offset, 25)
                self.assertEqual(ent.length, 9)
            elif ent.type == "hashtag":
                self.assertEqual(ent.offset, 35)
                self.assertEqual(ent.length, 8)
            elif ent.type == "url":
                self.assertEqual(ent.offset, 62)
                self.assertEqual(ent.length, 20)
            elif ent.type == "bot_command":
                self.assertEqual(ent.offset, 83)
                self.assertEqual(ent.length, 6)

        with self.assertRaises(BadMarkupException):
            self.mg.get_message(
                text="bad <b><i>double</i></b> markup", parse_mode="HTML")

    def test_wrong_markup(self):
        with self.assertRaises(BadMarkupException):
            self.mg.get_message(text="text", parse_mode="htmarkdownl")
Ejemplo n.º 23
0
class TestMessageGeneratorAttachments(unittest.TestCase):
    def setUp(self):
        self.mg = MessageGenerator()

    def test_caption_solo(self):
        with self.assertRaisesRegexp(BadMessageException, r"caption without"):
            self.mg.get_message(caption="my cap")

    def test_more_than_one(self):
        with self.assertRaisesRegexp(BadMessageException, "more than one"):
            self.mg.get_message(photo=True, video=True)

    def test_location(self):
        loc = Location(50.012, -32.11)
        u = self.mg.get_message(location=loc)
        self.assertEqual(loc.longitude, u.message.location.longitude)

        u = self.mg.get_message(location=True)
        self.assertIsInstance(u.message.location, Location)

        with self.assertRaisesRegexp(BadMessageException,
                                     r"telegram\.Location"):
            self.mg.get_message(location="location")

    def test_venue(self):
        ven = Venue(Location(1.0, 1.0), "some place", "somewhere")
        u = self.mg.get_message(venue=ven)
        self.assertEqual(u.message.venue.title, ven.title)

        u = self.mg.get_message(venue=True)
        self.assertIsInstance(u.message.venue, Venue)

        with self.assertRaisesRegexp(BadMessageException, r"telegram\.Venue"):
            self.mg.get_message(venue="Venue")

    def test_contact(self):
        con = Contact("0612345", "testman")
        u = self.mg.get_message(contact=con)
        self.assertEqual(con.phone_number, u.message.contact.phone_number)

        u = self.mg.get_message(contact=True)
        self.assertIsInstance(u.message.contact, Contact)

        with self.assertRaisesRegexp(BadMessageException,
                                     r"telegram\.Contact"):
            self.mg.get_message(contact="contact")

    def test_voice(self):
        voice = Voice("idyouknow", 12)
        u = self.mg.get_message(voice=voice)
        self.assertEqual(voice.file_id, u.message.voice.file_id)

        cap = "voice file"
        u = self.mg.get_message(voice=voice, caption=cap)
        self.assertEqual(u.message.caption, cap)

        u = self.mg.get_message(voice=True)
        self.assertIsInstance(u.message.voice, Voice)

        with self.assertRaisesRegexp(BadMessageException, r"telegram\.Voice"):
            self.mg.get_message(voice="voice")

    def test_video(self):
        video = Video("idyouknow", 200, 200, 10)
        u = self.mg.get_message(video=video)
        self.assertEqual(video.file_id, u.message.video.file_id)

        cap = "video file"
        u = self.mg.get_message(video=video, caption=cap)
        self.assertEqual(u.message.caption, cap)

        u = self.mg.get_message(video=True)
        self.assertIsInstance(u.message.video, Video)

        with self.assertRaisesRegexp(BadMessageException, r"telegram\.Video"):
            self.mg.get_message(video="video")

    def test_sticker(self):
        sticker = Sticker("idyouknow", 30, 30)
        u = self.mg.get_message(sticker=sticker)
        self.assertEqual(sticker.file_id, u.message.sticker.file_id)

        cap = "sticker file"
        u = self.mg.get_message(sticker=sticker, caption=cap)
        self.assertEqual(u.message.caption, cap)

        u = self.mg.get_message(sticker=True)
        self.assertIsInstance(u.message.sticker, Sticker)

        with self.assertRaisesRegexp(BadMessageException,
                                     r"telegram\.Sticker"):
            self.mg.get_message(sticker="sticker")

    def test_document(self):
        document = Document("idyouknow", file_name="test.pdf")
        u = self.mg.get_message(document=document)
        self.assertEqual(document.file_id, u.message.document.file_id)

        cap = "document file"
        u = self.mg.get_message(document=document, caption=cap)
        self.assertEqual(u.message.caption, cap)

        u = self.mg.get_message(document=True)
        self.assertIsInstance(u.message.document, Document)

        with self.assertRaisesRegexp(BadMessageException,
                                     r"telegram\.Document"):
            self.mg.get_message(document="document")

    def test_audio(self):
        audio = Audio("idyouknow", 23)
        u = self.mg.get_message(audio=audio)
        self.assertEqual(audio.file_id, u.message.audio.file_id)

        cap = "audio file"
        u = self.mg.get_message(audio=audio, caption=cap)
        self.assertEqual(u.message.caption, cap)

        u = self.mg.get_message(audio=True)
        self.assertIsInstance(u.message.audio, Audio)

        with self.assertRaisesRegexp(BadMessageException, r"telegram\.Audio"):
            self.mg.get_message(audio="audio")

    def test_photo(self):
        photo = [PhotoSize("2", 1, 1, file_size=3)]
        u = self.mg.get_message(photo=photo)
        self.assertEqual(photo[0].file_size, u.message.photo[0].file_size)

        cap = "photo file"
        u = self.mg.get_message(photo=photo, caption=cap)
        self.assertEqual(u.message.caption, cap)

        u = self.mg.get_message(photo=True)
        self.assertIsInstance(u.message.photo, list)
        self.assertIsInstance(u.message.photo[0], PhotoSize)

        with self.assertRaisesRegexp(BadMessageException, r"telegram\.Photo"):
            self.mg.get_message(photo="photo")
        with self.assertRaisesRegexp(BadMessageException, r"telegram\.Photo"):
            self.mg.get_message(photo=[1, 2, 3])
Ejemplo n.º 24
0
 def setUp(self):
     self.mg = MessageGenerator()
Ejemplo n.º 25
0
class TestMessageGeneratorCore(unittest.TestCase):
    def setUp(self):
        self.mg = MessageGenerator()

    def test_is_update(self):
        u = self.mg.get_message()
        self.assertIsInstance(u, Update)
        self.assertIsInstance(u.message, Message)

    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_private_message(self):
        u = self.mg.get_message(private=True)
        self.assertEqual(u.message.from_user.id, u.message.chat.id)

    def test_not_private(self):
        u = self.mg.get_message(private=False)
        self.assertEqual(u.message.chat.type, "group")
        self.assertNotEqual(u.message.from_user.id, u.message.chat.id)

    def test_with_user(self):
        ug = UserGenerator()
        us = ug.get_user()
        u = self.mg.get_message(user=us, private=False)
        self.assertEqual(u.message.from_user.id, us.id)
        self.assertNotEqual(u.message.from_user.id, u.message.chat.id)

        u = self.mg.get_message(user=us)
        self.assertEqual(u.message.from_user, us)
        self.assertEqual(u.message.from_user.id, u.message.chat.id)

        with self.assertRaises(BadUserException):
            us = "not a telegram.User"
            u = self.mg.get_message(user=us)

    def test_with_chat(self):
        cg = ChatGenerator()
        c = cg.get_chat()
        u = self.mg.get_message(chat=c)
        self.assertEqual(u.message.chat.id, u.message.from_user.id)
        self.assertEqual(u.message.chat.id, c.id)

        c = cg.get_chat(type="group")
        u = self.mg.get_message(chat=c)
        self.assertNotEqual(u.message.from_user.id, u.message.chat.id)
        self.assertEqual(u.message.chat.id, c.id)

        with self.assertRaisesRegexp(BadChatException, "get_channel_post"):
            c = cg.get_chat(type="channel")
            self.mg.get_message(chat=c)

        with self.assertRaises(BadChatException):
            c = "Not a telegram.Chat"
            self.mg.get_message(chat=c)

    def test_with_chat_and_user(self):
        cg = ChatGenerator()
        ug = UserGenerator()
        us = ug.get_user()
        c = cg.get_chat()
        u = self.mg.get_message(user=us, chat=c)
        self.assertNotEqual(u.message.from_user.id, u.message.chat.id)
        self.assertEqual(u.message.from_user.id, us.id)
        self.assertEqual(u.message.chat.id, c.id)

        us = "not a telegram.User"
        with self.assertRaises(BadUserException):
            u = self.mg.get_message(user=us)
        with self.assertRaises(BadUserException):
            u = self.mg.get_message(chat=c, user="******")

        c = "Not a telegram.Chat"
        with self.assertRaises(BadChatException):
            self.mg.get_message(chat=c)
        with self.assertRaises(BadChatException):
            self.mg.get_message(user=u, chat="chat")
Ejemplo n.º 26
0
    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)
Ejemplo n.º 27
0
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()