コード例 #1
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.Message:
        """
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'))
        data['entities'] = MessageEntity.de_list(data.get('entities'))
        data['forward_from'] = User.de_json(data.get('forward_from'))
        data['forward_date'] = Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = \
            Message.de_json(data.get('reply_to_message'))
        data['audio'] = Audio.de_json(data.get('audio'))
        data['document'] = Document.de_json(data.get('document'))
        data['photo'] = PhotoSize.de_list(data.get('photo'))
        data['sticker'] = Sticker.de_json(data.get('sticker'))
        data['video'] = Video.de_json(data.get('video'))
        data['voice'] = Voice.de_json(data.get('voice'))
        data['contact'] = Contact.de_json(data.get('contact'))
        data['location'] = Location.de_json(data.get('location'))
        data['venue'] = Venue.de_json(data.get('venue'))
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'))
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'))
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'))
        data['pinned_message'] = Message.de_json(data.get('pinned_message'))

        return Message(**data)
コード例 #2
0
ファイル: message.py プロジェクト: noam09/deluge-telegramer
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(Message, cls).de_json(data, bot)

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['date'] = from_timestamp(data['date'])
        data['chat'] = Chat.de_json(data.get('chat'), bot)
        data['entities'] = MessageEntity.de_list(data.get('entities'), bot)
        data['forward_from'] = User.de_json(data.get('forward_from'), bot)
        data['forward_from_chat'] = Chat.de_json(data.get('forward_from_chat'), bot)
        data['forward_date'] = from_timestamp(data.get('forward_date'))
        data['reply_to_message'] = Message.de_json(data.get('reply_to_message'), bot)
        data['edit_date'] = from_timestamp(data.get('edit_date'))
        data['audio'] = Audio.de_json(data.get('audio'), bot)
        data['document'] = Document.de_json(data.get('document'), bot)
        data['game'] = Game.de_json(data.get('game'), bot)
        data['photo'] = PhotoSize.de_list(data.get('photo'), bot)
        data['sticker'] = Sticker.de_json(data.get('sticker'), bot)
        data['video'] = Video.de_json(data.get('video'), bot)
        data['voice'] = Voice.de_json(data.get('voice'), bot)
        data['video_note'] = VideoNote.de_json(data.get('video_note'), bot)
        data['contact'] = Contact.de_json(data.get('contact'), bot)
        data['location'] = Location.de_json(data.get('location'), bot)
        data['venue'] = Venue.de_json(data.get('venue'), bot)
        data['new_chat_member'] = User.de_json(data.get('new_chat_member'), bot)
        data['new_chat_members'] = User.de_list(data.get('new_chat_members'), bot)
        data['left_chat_member'] = User.de_json(data.get('left_chat_member'), bot)
        data['new_chat_photo'] = PhotoSize.de_list(data.get('new_chat_photo'), bot)
        data['pinned_message'] = Message.de_json(data.get('pinned_message'), bot)
        data['invoice'] = Invoice.de_json(data.get('invoice'), bot)
        data['successful_payment'] = SuccessfulPayment.de_json(data.get('successful_payment'), bot)

        return cls(bot=bot, **data)
コード例 #3
0
ファイル: message.py プロジェクト: SalamiArmy/hitagibot
    def de_json(data):
        """
        Args:
            data (str):

        Returns:
            telegram.Message:
        """
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['date'] = datetime.fromtimestamp(data['date'])
        if 'first_name' in data.get('chat', ''):
            data['chat'] = User.de_json(data.get('chat'))
        elif 'title' in data.get('chat', ''):
            data['chat'] = GroupChat.de_json(data.get('chat'))
        data['forward_from'] = \
            User.de_json(data.get('forward_from'))
        data['forward_date'] = \
            Message._fromtimestamp(data.get('forward_date'))
        data['reply_to_message'] = \
            Message.de_json(data.get('reply_to_message'))
        data['audio'] = \
            Audio.de_json(data.get('audio'))
        data['document'] = \
            Document.de_json(data.get('document'))
        data['photo'] = \
            PhotoSize.de_list(data.get('photo'))
        data['sticker'] = \
            Sticker.de_json(data.get('sticker'))
        data['video'] = \
            Video.de_json(data.get('video'))
        data['voice'] = \
            Voice.de_json(data.get('voice'))
        data['contact'] = \
            Contact.de_json(data.get('contact'))
        data['location'] = \
            Location.de_json(data.get('location'))
        data['new_chat_participant'] = \
            User.de_json(data.get('new_chat_participant'))
        data['left_chat_participant'] = \
            User.de_json(data.get('left_chat_participant'))
        data['new_chat_photo'] = \
            PhotoSize.de_list(data.get('new_chat_photo'))

        return Message(**data)
コード例 #4
0
    def de_json(data):
        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['message'] = Message.de_json(data.get('message'))

        return CallbackQuery(**data)
コード例 #5
0
    def test_de_json(self, json_dict, bot):
        user = User.de_json(json_dict, bot)

        assert user.id == self.id
        assert user.is_bot == self.is_bot
        assert user.first_name == self.first_name
        assert user.last_name == self.last_name
        assert user.username == self.username
        assert user.language_code == self.language_code
コード例 #6
0
    def de_json(cls, data, bot):
        data = super(MessageEntity, cls).de_json(data, bot)

        if not data:
            return None

        data['user'] = User.de_json(data.get('user'), bot)

        return cls(**data)
コード例 #7
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(GameHighScore, cls).de_json(data, bot)

        data['user'] = User.de_json(data.get('user'), bot)

        return cls(**data)
コード例 #8
0
ファイル: inlinequery.py プロジェクト: technoekat/prodeda1
    def de_json(cls, data, bot):
        data = super(InlineQuery, cls).de_json(data, bot)

        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['location'] = Location.de_json(data.get('location'), bot)

        return cls(bot=bot, **data)
コード例 #9
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(PreCheckoutQuery, cls).de_json(data, bot)

        data['from_user'] = User.de_json(data.pop('from'), bot)
        data['order_info'] = OrderInfo.de_json(data.get('order_info'), bot)

        return cls(**data)
コード例 #10
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(ChatMember, cls).de_json(data, bot)

        data['user'] = User.de_json(data.get('user'), bot)
        data['until_date'] = from_timestamp(data.get('until_date', None))

        return cls(**data)
コード例 #11
0
ファイル: shippingquery.py プロジェクト: technoekat/prodeda1
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(ShippingQuery, cls).de_json(data, bot)

        data['from_user'] = User.de_json(data.pop('from'), bot)
        data['shipping_address'] = ShippingAddress.de_json(data.get('shipping_address'), bot)

        return cls(**data)
コード例 #12
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(CallbackQuery, cls).de_json(data, bot)

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['message'] = Message.de_json(data.get('message'), bot)

        return cls(bot=bot, **data)
コード例 #13
0
    def de_json(cls, data, bot):
        if not data:
            return None

        data = super(ChosenInlineResult, cls).de_json(data, bot)
        # Required
        data['from_user'] = User.de_json(data.pop('from'), bot)
        # Optionals
        data['location'] = Location.de_json(data.get('location'), bot)

        return cls(**data)
コード例 #14
0
    def test_de_json_without_username(self, json_dict, bot):
        del json_dict['username']

        user = User.de_json(json_dict, bot)

        assert user.id == self.id
        assert user.is_bot == self.is_bot
        assert user.first_name == self.first_name
        assert user.last_name == self.last_name
        assert user.username is None
        assert user.language_code == self.language_code
コード例 #15
0
ファイル: bot.py プロジェクト: kalloc/python-telegram-bot
    def getMe(self):
        """A simple method for testing your bot's auth token.

        Returns:
          A telegram.User instance representing that bot if the
          credentials are valid, None otherwise.
        """
        url = "%s/getMe" % (self.base_url)

        json_data = self._requestUrl(url, "GET")
        data = self._parseAndCheckTelegram(json_data.decode())

        return User.de_json(data)
コード例 #16
0
ファイル: bot.py プロジェクト: peczony/python-telegram-bot
    def getMe(self):
        """A simple method for testing your bot's auth token.

        Returns:
          A telegram.User instance representing that bot if the
          credentials are valid, None otherwise.
        """
        url = '%s/getMe' % self.base_url

        result = request.get(url)

        self.bot = User.de_json(result)

        return self.bot
コード例 #17
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.InlineQuery:
        """
        if not data:
            return None
        data = data.copy()
        data['from_user'] = User.de_json(data.pop('from'))

        return InlineQuery(**data)
コード例 #18
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.ChatMember:
        """
        if not data:
            return None

        data['user'] = User.de_json(data.get('user'))

        return ChatMember(**data)
コード例 #19
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.ChosenInlineResult:
        """
        if not data:
            return None
        data = data.copy()
        data['from_user'] = User.de_json(data.pop('from'))

        return ChosenInlineResult(**data)
コード例 #20
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.Game:
        """
        if not data:
            return None

        data['user'] = User.de_json(data.get('user'), bot)

        return GameHighScore(**data)
コード例 #21
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.ChatMember:
        """
        if not data:
            return None

        data["user"] = User.de_json(data.get("user"), bot)

        return ChatMember(**data)
コード例 #22
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.InlineQuery:
        """
        data = super(InlineQuery, InlineQuery).de_json(data)

        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'))
        data['location'] = Location.de_json(data.get('location'))

        return InlineQuery(**data)
コード例 #23
0
    def de_json(data):
        """
        Args:
            data (dict):

        Returns:
            telegram.ChosenInlineResult:
        """
        if not data:
            return None

        # Required
        data['from_user'] = User.de_json(data.pop('from'))
        # Optionals
        data['location'] = Location.de_json(data.get('location'))

        return ChosenInlineResult(**data)
コード例 #24
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.CallbackQuery:
        """

        if not data:
            return None

        data['from_user'] = User.de_json(data.get('from'), bot)
        data['message'] = Message.de_json(data.get('message'), bot)

        return CallbackQuery(bot=bot, **data)
コード例 #25
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.PreCheckoutQuery:
        """
        if not data:
            return None

        data = super(PreCheckoutQuery, PreCheckoutQuery).de_json(data, bot)

        data['from_user'] = User.de_json(data.pop('from'), bot)
        data['order_info'] = OrderInfo.de_json(data.get('order_info'), bot)

        return PreCheckoutQuery(**data)
コード例 #26
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.ShippingQuery:
        """
        if not data:
            return None

        data = super(ShippingQuery, ShippingQuery).de_json(data, bot)

        data['from_user'] = User.de_json(data.pop('from'), bot)
        data['shipping_address'] = ShippingAddress.de_json(data.get('shipping_address'), bot)

        return ShippingQuery(**data)
コード例 #27
0
    def de_json(data, bot):
        """
        Args:
            data (dict):
            bot (telegram.Bot):

        Returns:
            telegram.ChosenInlineResult:
        """
        if not data:
            return None

        data = super(ChosenInlineResult, ChosenInlineResult).de_json(data, bot)
        # Required
        data['from_user'] = User.de_json(data.pop('from'), bot)
        # Optionals
        data['location'] = Location.de_json(data.get('location'), bot)

        return ChosenInlineResult(**data)
コード例 #28
0
ファイル: bot.py プロジェクト: Gurzo/python-telegram-bot
    def getMe(self):
        """A simple method for testing your bot's auth token.

        Returns:
            :class:`telegram.User`: A :class:`telegram.User` instance
            representing that bot if the credentials are valid, `None`
            otherwise.

        Raises:
            :class:`telegram.TelegramError`

        """

        url = '{0}/getMe'.format(self.base_url)

        result = request.get(url)

        self.bot = User.de_json(result)

        return self.bot
コード例 #29
0
    def test_persisting_no_user_no_chat(self, cdp):
        class OwnPersistence(BasePersistence):
            def __init__(self):
                super().__init__()
                self.store_user_data = True
                self.store_chat_data = True
                self.store_bot_data = True
                self.test_flag_bot_data = False
                self.test_flag_chat_data = False
                self.test_flag_user_data = False

            def update_bot_data(self, data):
                self.test_flag_bot_data = True

            def update_chat_data(self, chat_id, data):
                self.test_flag_chat_data = True

            def update_user_data(self, user_id, data):
                self.test_flag_user_data = True

            def update_conversation(self, name, key, new_state):
                pass

            def get_conversations(self, name):
                pass

            def get_user_data(self):
                pass

            def get_bot_data(self):
                pass

            def get_chat_data(self):
                pass

        def callback(update, context):
            pass

        handler = MessageHandler(Filters.all, callback)
        cdp.add_handler(handler)
        cdp.persistence = OwnPersistence()

        update = Update(1,
                        message=Message(1,
                                        None,
                                        None,
                                        from_user=User(1, '', False),
                                        text='Text'))
        cdp.process_update(update)
        assert cdp.persistence.test_flag_bot_data
        assert cdp.persistence.test_flag_user_data
        assert not cdp.persistence.test_flag_chat_data

        cdp.persistence.test_flag_bot_data = False
        cdp.persistence.test_flag_user_data = False
        cdp.persistence.test_flag_chat_data = False
        update = Update(1,
                        message=Message(1,
                                        None,
                                        Chat(1, ''),
                                        from_user=None,
                                        text='Text'))
        cdp.process_update(update)
        assert cdp.persistence.test_flag_bot_data
        assert not cdp.persistence.test_flag_user_data
        assert cdp.persistence.test_flag_chat_data
コード例 #30
0
    def test_webhook(self):
        print('Testing Webhook')
        bot = MockBot('', messages=0)
        self.updater.bot = bot
        d = self.updater.dispatcher
        d.addTelegramMessageHandler(self.telegramHandlerTest)

        # Select random port for travis
        port = randrange(1024, 49152)
        self.updater.start_webhook('127.0.0.1',
                                   port,
                                   './tests/test_updater.py',
                                   './tests/test_updater.py',
                                   listen='127.0.0.1')
        sleep(0.5)
        # SSL-Wrapping will fail, so we start the server without SSL
        Thread(target=self.updater.httpd.serve_forever).start()

        # Now, we send an update to the server via urlopen
        message = Message(1, User(1, "Tester"), datetime.now(),
                          GroupChat(1, "Test Group"))

        message.text = "Webhook Test"
        update = Update(1)
        update.message = message

        try:
            payload = bytes(update.to_json(), encoding='utf-8')
        except TypeError:
            payload = bytes(update.to_json())

        header = {
            'content-type': 'application/json',
            'content-length': str(len(payload))
        }

        r = Request('http://127.0.0.1:%d/TOKEN' % port,
                    data=payload,
                    headers=header)

        urlopen(r)

        sleep(1)
        self.assertEqual(self.received_message, 'Webhook Test')

        print("Test other webhook server functionalites...")
        request = Request('http://localhost:%d/webookhandler.py' % port)
        response = urlopen(request)
        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        request.get_method = lambda: 'HEAD'

        response = urlopen(request)
        self.assertEqual(b'', response.read())
        self.assertEqual(200, response.code)

        # Test multiple shutdown() calls
        self.updater.httpd.shutdown()
        self.updater.httpd.shutdown()
        self.assertTrue(True)
コード例 #31
0
    def de_json(data, bot):
        data = super(MessageEntity, MessageEntity).de_json(data, bot)

        data['user'] = User.de_json(data.get('user'), bot)

        return MessageEntity(**data)
コード例 #32
0
class TestDispatcher:
    message_update = Update(1,
                            message=Message(1,
                                            None,
                                            Chat(1, ''),
                                            from_user=User(1, '', False),
                                            text='Text'))
    received = None
    count = 0

    @pytest.fixture(autouse=True, name='reset')
    def reset_fixture(self):
        self.reset()

    def reset(self):
        self.received = None
        self.count = 0

    def error_handler(self, bot, update, error):
        self.received = error.message

    def error_handler_context(self, update, context):
        self.received = context.error.message

    def error_handler_raise_error(self, bot, update, error):
        raise Exception('Failing bigly')

    def callback_increase_count(self, bot, update):
        self.count += 1

    def callback_set_count(self, count):
        def callback(bot, update):
            self.count = count

        return callback

    def callback_raise_error(self, bot, update):
        if isinstance(bot, Bot):
            raise TelegramError(update.message.text)
        raise TelegramError(bot.message.text)

    def callback_if_not_update_queue(self, bot, update, update_queue=None):
        if update_queue is not None:
            self.received = update.message

    def callback_context(self, update, context):
        if (isinstance(context, CallbackContext)
                and isinstance(context.bot, Bot)
                and isinstance(context.update_queue, Queue)
                and isinstance(context.job_queue, JobQueue)
                and isinstance(context.error, TelegramError)):
            self.received = context.error.message

    def test_one_context_per_update(self, cdp):
        def one(update, context):
            if update.message.text == 'test':
                context.my_flag = True

        def two(update, context):
            if update.message.text == 'test':
                if not hasattr(context, 'my_flag'):
                    pytest.fail()
            else:
                if hasattr(context, 'my_flag'):
                    pytest.fail()

        cdp.add_handler(MessageHandler(Filters.regex('test'), one), group=1)
        cdp.add_handler(MessageHandler(None, two), group=2)
        u = Update(1, Message(1, None, None, None, text='test'))
        cdp.process_update(u)
        u.message.text = 'something'
        cdp.process_update(u)

    def test_error_handler(self, dp):
        dp.add_error_handler(self.error_handler)
        error = TelegramError('Unauthorized.')
        dp.update_queue.put(error)
        sleep(0.1)
        assert self.received == 'Unauthorized.'

        # Remove handler
        dp.remove_error_handler(self.error_handler)
        self.reset()

        dp.update_queue.put(error)
        sleep(0.1)
        assert self.received is None

    def test_double_add_error_handler(self, dp, caplog):
        dp.add_error_handler(self.error_handler)
        with caplog.at_level(logging.DEBUG):
            dp.add_error_handler(self.error_handler)
            assert len(caplog.records) == 1
            assert caplog.records[-1].getMessage().startswith(
                'The callback is already registered')

    def test_construction_with_bad_persistence(self, caplog, bot):
        class my_per:
            def __init__(self):
                self.store_user_data = False
                self.store_chat_data = False
                self.store_bot_data = False

        with pytest.raises(
                TypeError,
                match=
                'persistence must be based on telegram.ext.BasePersistence'):
            Dispatcher(bot, None, persistence=my_per())

    def test_error_handler_that_raises_errors(self, dp):
        """
        Make sure that errors raised in error handlers don't break the main loop of the dispatcher
        """
        handler_raise_error = MessageHandler(Filters.all,
                                             self.callback_raise_error)
        handler_increase_count = MessageHandler(Filters.all,
                                                self.callback_increase_count)
        error = TelegramError('Unauthorized.')

        dp.add_error_handler(self.error_handler_raise_error)

        # From errors caused by handlers
        dp.add_handler(handler_raise_error)
        dp.update_queue.put(self.message_update)
        sleep(0.1)

        # From errors in the update_queue
        dp.remove_handler(handler_raise_error)
        dp.add_handler(handler_increase_count)
        dp.update_queue.put(error)
        dp.update_queue.put(self.message_update)
        sleep(0.1)

        assert self.count == 1

    @pytest.mark.parametrize(['run_async', 'expected_output'], [(True, 5),
                                                                (False, 0)])
    def test_default_run_async_error_handler(self, dp, monkeypatch, run_async,
                                             expected_output):
        def mock_async_err_handler(*args, **kwargs):
            self.count = 5

        # set defaults value to dp.bot
        dp.bot.defaults = Defaults(run_async=run_async)
        try:
            dp.add_handler(
                MessageHandler(Filters.all, self.callback_raise_error))
            dp.add_error_handler(self.error_handler)

            monkeypatch.setattr(dp, 'run_async', mock_async_err_handler)
            dp.process_update(self.message_update)

            assert self.count == expected_output

        finally:
            # reset dp.bot.defaults values
            dp.bot.defaults = None

    @pytest.mark.parametrize(['run_async', 'expected_output'],
                             [(True, 'running async'), (False, None)])
    def test_default_run_async(self, monkeypatch, dp, run_async,
                               expected_output):
        def mock_run_async(*args, **kwargs):
            self.received = 'running async'

        # set defaults value to dp.bot
        dp.bot.defaults = Defaults(run_async=run_async)
        try:
            dp.add_handler(MessageHandler(Filters.all, lambda u, c: None))
            monkeypatch.setattr(dp, 'run_async', mock_run_async)
            dp.process_update(self.message_update)
            assert self.received == expected_output

        finally:
            # reset defaults value
            dp.bot.defaults = None

    def test_run_async_multiple(self, bot, dp, dp2):
        def get_dispatcher_name(q):
            q.put(current_thread().name)

        q1 = Queue()
        q2 = Queue()

        dp.run_async(get_dispatcher_name, q1)
        dp2.run_async(get_dispatcher_name, q2)

        sleep(0.1)

        name1 = q1.get()
        name2 = q2.get()

        assert name1 != name2

    def test_multiple_run_async_decorator(self, dp, dp2):
        # Make sure we got two dispatchers and that they are not the same
        assert isinstance(dp, Dispatcher)
        assert isinstance(dp2, Dispatcher)
        assert dp is not dp2

        @run_async
        def must_raise_runtime_error():
            pass

        with pytest.raises(RuntimeError):
            must_raise_runtime_error()

    def test_run_async_with_args(self, dp):
        dp.add_handler(
            MessageHandler(Filters.all,
                           run_async(self.callback_if_not_update_queue),
                           pass_update_queue=True))

        dp.update_queue.put(self.message_update)
        sleep(0.1)
        assert self.received == self.message_update.message

    def test_multiple_run_async_deprecation(self, dp):
        assert isinstance(dp, Dispatcher)

        @run_async
        def callback(update, context):
            pass

        dp.add_handler(MessageHandler(Filters.all, callback))

        with pytest.warns(TelegramDeprecationWarning,
                          match='@run_async decorator'):
            dp.process_update(self.message_update)

    def test_async_raises_dispatcher_handler_stop(self, dp, caplog):
        @run_async
        def callback(update, context):
            raise DispatcherHandlerStop()

        dp.add_handler(MessageHandler(Filters.all, callback))

        with caplog.at_level(logging.WARNING):
            dp.update_queue.put(self.message_update)
            sleep(0.1)
            assert len(caplog.records) == 1
            assert (caplog.records[-1].getMessage().startswith(
                'DispatcherHandlerStop is not supported '
                'with async functions'))

    def test_async_raises_exception(self, dp, caplog):
        @run_async
        def callback(update, context):
            raise RuntimeError('async raising exception')

        dp.add_handler(MessageHandler(Filters.all, callback))

        with caplog.at_level(logging.WARNING):
            dp.update_queue.put(self.message_update)
            sleep(0.1)
            assert len(caplog.records) == 1
            assert (caplog.records[-1].getMessage().startswith(
                'A promise with deactivated error handling'))

    def test_add_async_handler(self, dp):
        dp.add_handler(
            MessageHandler(
                Filters.all,
                self.callback_if_not_update_queue,
                pass_update_queue=True,
                run_async=True,
            ))

        dp.update_queue.put(self.message_update)
        sleep(0.1)
        assert self.received == self.message_update.message

    def test_run_async_no_error_handler(self, dp, caplog):
        def func():
            raise RuntimeError('Async Error')

        with caplog.at_level(logging.ERROR):
            dp.run_async(func)
            sleep(0.1)
            assert len(caplog.records) == 1
            assert caplog.records[-1].getMessage().startswith(
                'No error handlers are registered')

    def test_async_handler_error_handler(self, dp):
        dp.add_handler(
            MessageHandler(Filters.all,
                           self.callback_raise_error,
                           run_async=True))
        dp.add_error_handler(self.error_handler)

        dp.update_queue.put(self.message_update)
        sleep(0.1)
        assert self.received == self.message_update.message.text

    def test_async_handler_async_error_handler_context(self, cdp):
        cdp.add_handler(
            MessageHandler(Filters.all,
                           self.callback_raise_error,
                           run_async=True))
        cdp.add_error_handler(self.error_handler_context, run_async=True)

        cdp.update_queue.put(self.message_update)
        sleep(2)
        assert self.received == self.message_update.message.text

    def test_async_handler_error_handler_that_raises_error(self, dp, caplog):
        handler = MessageHandler(Filters.all,
                                 self.callback_raise_error,
                                 run_async=True)
        dp.add_handler(handler)
        dp.add_error_handler(self.error_handler_raise_error, run_async=False)

        with caplog.at_level(logging.ERROR):
            dp.update_queue.put(self.message_update)
            sleep(0.1)
            assert len(caplog.records) == 1
            assert caplog.records[-1].getMessage().startswith(
                'An uncaught error was raised')

        # Make sure that the main loop still runs
        dp.remove_handler(handler)
        dp.add_handler(
            MessageHandler(Filters.all,
                           self.callback_increase_count,
                           run_async=True))
        dp.update_queue.put(self.message_update)
        sleep(0.1)
        assert self.count == 1

    def test_async_handler_async_error_handler_that_raises_error(
            self, dp, caplog):
        handler = MessageHandler(Filters.all,
                                 self.callback_raise_error,
                                 run_async=True)
        dp.add_handler(handler)
        dp.add_error_handler(self.error_handler_raise_error, run_async=True)

        with caplog.at_level(logging.ERROR):
            dp.update_queue.put(self.message_update)
            sleep(0.1)
            assert len(caplog.records) == 1
            assert caplog.records[-1].getMessage().startswith(
                'An uncaught error was raised')

        # Make sure that the main loop still runs
        dp.remove_handler(handler)
        dp.add_handler(
            MessageHandler(Filters.all,
                           self.callback_increase_count,
                           run_async=True))
        dp.update_queue.put(self.message_update)
        sleep(0.1)
        assert self.count == 1

    def test_error_in_handler(self, dp):
        dp.add_handler(MessageHandler(Filters.all, self.callback_raise_error))
        dp.add_error_handler(self.error_handler)

        dp.update_queue.put(self.message_update)
        sleep(0.1)
        assert self.received == self.message_update.message.text

    def test_add_remove_handler(self, dp):
        handler = MessageHandler(Filters.all, self.callback_increase_count)
        dp.add_handler(handler)
        dp.update_queue.put(self.message_update)
        sleep(0.1)
        assert self.count == 1
        dp.remove_handler(handler)
        dp.update_queue.put(self.message_update)
        assert self.count == 1

    def test_add_remove_handler_non_default_group(self, dp):
        handler = MessageHandler(Filters.all, self.callback_increase_count)
        dp.add_handler(handler, group=2)
        with pytest.raises(KeyError):
            dp.remove_handler(handler)
        dp.remove_handler(handler, group=2)

    def test_error_start_twice(self, dp):
        assert dp.running
        dp.start()

    def test_handler_order_in_group(self, dp):
        dp.add_handler(
            MessageHandler(Filters.photo, self.callback_set_count(1)))
        dp.add_handler(MessageHandler(Filters.all, self.callback_set_count(2)))
        dp.add_handler(MessageHandler(Filters.text,
                                      self.callback_set_count(3)))
        dp.update_queue.put(self.message_update)
        sleep(0.1)
        assert self.count == 2

    def test_groups(self, dp):
        dp.add_handler(
            MessageHandler(Filters.all, self.callback_increase_count))
        dp.add_handler(MessageHandler(Filters.all,
                                      self.callback_increase_count),
                       group=2)
        dp.add_handler(MessageHandler(Filters.all,
                                      self.callback_increase_count),
                       group=-1)

        dp.update_queue.put(self.message_update)
        sleep(0.1)
        assert self.count == 3

    def test_add_handler_errors(self, dp):
        handler = 'not a handler'
        with pytest.raises(TypeError, match='handler is not an instance of'):
            dp.add_handler(handler)

        handler = MessageHandler(Filters.photo, self.callback_set_count(1))
        with pytest.raises(TypeError, match='group is not int'):
            dp.add_handler(handler, 'one')

    def test_flow_stop(self, dp, bot):
        passed = []

        def start1(b, u):
            passed.append('start1')
            raise DispatcherHandlerStop

        def start2(b, u):
            passed.append('start2')

        def start3(b, u):
            passed.append('start3')

        def error(b, u, e):
            passed.append('error')
            passed.append(e)

        update = Update(
            1,
            message=Message(
                1,
                None,
                None,
                None,
                text='/start',
                entities=[
                    MessageEntity(type=MessageEntity.BOT_COMMAND,
                                  offset=0,
                                  length=len('/start'))
                ],
                bot=bot,
            ),
        )

        # If Stop raised handlers in other groups should not be called.
        passed = []
        dp.add_handler(CommandHandler('start', start1), 1)
        dp.add_handler(CommandHandler('start', start3), 1)
        dp.add_handler(CommandHandler('start', start2), 2)
        dp.process_update(update)
        assert passed == ['start1']

    def test_exception_in_handler(self, dp, bot):
        passed = []
        err = Exception('General exception')

        def start1(b, u):
            passed.append('start1')
            raise err

        def start2(b, u):
            passed.append('start2')

        def start3(b, u):
            passed.append('start3')

        def error(b, u, e):
            passed.append('error')
            passed.append(e)

        update = Update(
            1,
            message=Message(
                1,
                None,
                None,
                None,
                text='/start',
                entities=[
                    MessageEntity(type=MessageEntity.BOT_COMMAND,
                                  offset=0,
                                  length=len('/start'))
                ],
                bot=bot,
            ),
        )

        # If an unhandled exception was caught, no further handlers from the same group should be
        # called. Also, the error handler should be called and receive the exception
        passed = []
        dp.add_handler(CommandHandler('start', start1), 1)
        dp.add_handler(CommandHandler('start', start2), 1)
        dp.add_handler(CommandHandler('start', start3), 2)
        dp.add_error_handler(error)
        dp.process_update(update)
        assert passed == ['start1', 'error', err, 'start3']

    def test_telegram_error_in_handler(self, dp, bot):
        passed = []
        err = TelegramError('Telegram error')

        def start1(b, u):
            passed.append('start1')
            raise err

        def start2(b, u):
            passed.append('start2')

        def start3(b, u):
            passed.append('start3')

        def error(b, u, e):
            passed.append('error')
            passed.append(e)

        update = Update(
            1,
            message=Message(
                1,
                None,
                None,
                None,
                text='/start',
                entities=[
                    MessageEntity(type=MessageEntity.BOT_COMMAND,
                                  offset=0,
                                  length=len('/start'))
                ],
                bot=bot,
            ),
        )

        # If a TelegramException was caught, an error handler should be called and no further
        # handlers from the same group should be called.
        dp.add_handler(CommandHandler('start', start1), 1)
        dp.add_handler(CommandHandler('start', start2), 1)
        dp.add_handler(CommandHandler('start', start3), 2)
        dp.add_error_handler(error)
        dp.process_update(update)
        assert passed == ['start1', 'error', err, 'start3']
        assert passed[2] is err

    def test_error_while_saving_chat_data(self, bot):
        increment = []

        class OwnPersistence(BasePersistence):
            def __init__(self):
                super().__init__()
                self.store_user_data = True
                self.store_chat_data = True
                self.store_bot_data = True

            def get_bot_data(self):
                return dict()

            def update_bot_data(self, data):
                raise Exception

            def get_chat_data(self):
                return defaultdict(dict)

            def update_chat_data(self, chat_id, data):
                raise Exception

            def get_user_data(self):
                return defaultdict(dict)

            def update_user_data(self, user_id, data):
                raise Exception

            def get_conversations(self, name):
                pass

            def update_conversation(self, name, key, new_state):
                pass

        def start1(b, u):
            pass

        def error(b, u, e):
            increment.append("error")

        # If updating a user_data or chat_data from a persistence object throws an error,
        # the error handler should catch it

        update = Update(
            1,
            message=Message(
                1,
                None,
                Chat(1, "lala"),
                from_user=User(1, "Test", False),
                text='/start',
                entities=[
                    MessageEntity(type=MessageEntity.BOT_COMMAND,
                                  offset=0,
                                  length=len('/start'))
                ],
                bot=bot,
            ),
        )
        my_persistence = OwnPersistence()
        dp = Dispatcher(bot,
                        None,
                        persistence=my_persistence,
                        use_context=False)
        dp.add_handler(CommandHandler('start', start1))
        dp.add_error_handler(error)
        dp.process_update(update)
        assert increment == ["error", "error", "error"]

    def test_flow_stop_in_error_handler(self, dp, bot):
        passed = []
        err = TelegramError('Telegram error')

        def start1(b, u):
            passed.append('start1')
            raise err

        def start2(b, u):
            passed.append('start2')

        def start3(b, u):
            passed.append('start3')

        def error(b, u, e):
            passed.append('error')
            passed.append(e)
            raise DispatcherHandlerStop

        update = Update(
            1,
            message=Message(
                1,
                None,
                None,
                None,
                text='/start',
                entities=[
                    MessageEntity(type=MessageEntity.BOT_COMMAND,
                                  offset=0,
                                  length=len('/start'))
                ],
                bot=bot,
            ),
        )

        # If a TelegramException was caught, an error handler should be called and no further
        # handlers from the same group should be called.
        dp.add_handler(CommandHandler('start', start1), 1)
        dp.add_handler(CommandHandler('start', start2), 1)
        dp.add_handler(CommandHandler('start', start3), 2)
        dp.add_error_handler(error)
        dp.process_update(update)
        assert passed == ['start1', 'error', err]
        assert passed[2] is err

    def test_error_handler_context(self, cdp):
        cdp.add_error_handler(self.callback_context)

        error = TelegramError('Unauthorized.')
        cdp.update_queue.put(error)
        sleep(0.1)
        assert self.received == 'Unauthorized.'

    def test_sensible_worker_thread_names(self, dp2):
        thread_names = [
            thread.name
            for thread in getattr(dp2, '_Dispatcher__async_threads')
        ]
        print(thread_names)
        for thread_name in thread_names:
            assert thread_name.startswith(f"Bot:{dp2.bot.id}:worker:")

    def test_non_context_deprecation(self, dp):
        with pytest.warns(TelegramDeprecationWarning):
            Dispatcher(dp.bot,
                       dp.update_queue,
                       job_queue=dp.job_queue,
                       workers=0,
                       use_context=False)

    def test_error_while_persisting(self, cdp, monkeypatch):
        class OwnPersistence(BasePersistence):
            def __init__(self):
                super().__init__()
                self.store_user_data = True
                self.store_chat_data = True
                self.store_bot_data = True

            def update(self, data):
                raise Exception('PersistenceError')

            def update_bot_data(self, data):
                self.update(data)

            def update_chat_data(self, chat_id, data):
                self.update(data)

            def update_user_data(self, user_id, data):
                self.update(data)

            def get_chat_data(self):
                pass

            def get_bot_data(self):
                pass

            def get_user_data(self):
                pass

            def get_conversations(self, name):
                pass

            def update_conversation(self, name, key, new_state):
                pass

        def callback(update, context):
            pass

        test_flag = False

        def error(update, context):
            nonlocal test_flag
            test_flag = str(context.error) == 'PersistenceError'
            raise Exception('ErrorHandlingError')

        def logger(message):
            assert 'uncaught error was raised while handling' in message

        update = Update(1,
                        message=Message(1,
                                        None,
                                        Chat(1, ''),
                                        from_user=User(1, '', False),
                                        text='Text'))
        handler = MessageHandler(Filters.all, callback)
        cdp.add_handler(handler)
        cdp.add_error_handler(error)
        monkeypatch.setattr(cdp.logger, 'exception', logger)

        cdp.persistence = OwnPersistence()
        cdp.process_update(update)
        assert test_flag

    def test_persisting_no_user_no_chat(self, cdp):
        class OwnPersistence(BasePersistence):
            def __init__(self):
                super().__init__()
                self.store_user_data = True
                self.store_chat_data = True
                self.store_bot_data = True
                self.test_flag_bot_data = False
                self.test_flag_chat_data = False
                self.test_flag_user_data = False

            def update_bot_data(self, data):
                self.test_flag_bot_data = True

            def update_chat_data(self, chat_id, data):
                self.test_flag_chat_data = True

            def update_user_data(self, user_id, data):
                self.test_flag_user_data = True

            def update_conversation(self, name, key, new_state):
                pass

            def get_conversations(self, name):
                pass

            def get_user_data(self):
                pass

            def get_bot_data(self):
                pass

            def get_chat_data(self):
                pass

        def callback(update, context):
            pass

        handler = MessageHandler(Filters.all, callback)
        cdp.add_handler(handler)
        cdp.persistence = OwnPersistence()

        update = Update(1,
                        message=Message(1,
                                        None,
                                        None,
                                        from_user=User(1, '', False),
                                        text='Text'))
        cdp.process_update(update)
        assert cdp.persistence.test_flag_bot_data
        assert cdp.persistence.test_flag_user_data
        assert not cdp.persistence.test_flag_chat_data

        cdp.persistence.test_flag_bot_data = False
        cdp.persistence.test_flag_user_data = False
        cdp.persistence.test_flag_chat_data = False
        update = Update(1,
                        message=Message(1,
                                        None,
                                        Chat(1, ''),
                                        from_user=None,
                                        text='Text'))
        cdp.process_update(update)
        assert cdp.persistence.test_flag_bot_data
        assert not cdp.persistence.test_flag_user_data
        assert cdp.persistence.test_flag_chat_data

    def test_update_persistence_once_per_update(self, monkeypatch, dp):
        def update_persistence(*args, **kwargs):
            self.count += 1

        def dummy_callback(*args):
            pass

        monkeypatch.setattr(dp, 'update_persistence', update_persistence)

        for group in range(5):
            dp.add_handler(MessageHandler(Filters.text, dummy_callback),
                           group=group)

        update = Update(1,
                        message=Message(1,
                                        None,
                                        Chat(1, ''),
                                        from_user=None,
                                        text=None))
        dp.process_update(update)
        assert self.count == 0

        update = Update(1,
                        message=Message(1,
                                        None,
                                        Chat(1, ''),
                                        from_user=None,
                                        text='text'))
        dp.process_update(update)
        assert self.count == 1

    def test_update_persistence_all_async(self, monkeypatch, dp):
        def update_persistence(*args, **kwargs):
            self.count += 1

        def dummy_callback(*args, **kwargs):
            pass

        monkeypatch.setattr(dp, 'update_persistence', update_persistence)
        monkeypatch.setattr(dp, 'run_async', dummy_callback)

        for group in range(5):
            dp.add_handler(MessageHandler(Filters.text,
                                          dummy_callback,
                                          run_async=True),
                           group=group)

        update = Update(1,
                        message=Message(1,
                                        None,
                                        Chat(1, ''),
                                        from_user=None,
                                        text='Text'))
        dp.process_update(update)
        assert self.count == 0

        dp.bot.defaults = Defaults(run_async=True)
        try:
            for group in range(5):
                dp.add_handler(MessageHandler(Filters.text, dummy_callback),
                               group=group)

            update = Update(1,
                            message=Message(1,
                                            None,
                                            Chat(1, ''),
                                            from_user=None,
                                            text='Text'))
            dp.process_update(update)
            assert self.count == 0
        finally:
            dp.bot.defaults = None

    @pytest.mark.parametrize('run_async', [DEFAULT_FALSE, False])
    def test_update_persistence_one_sync(self, monkeypatch, dp, run_async):
        def update_persistence(*args, **kwargs):
            self.count += 1

        def dummy_callback(*args, **kwargs):
            pass

        monkeypatch.setattr(dp, 'update_persistence', update_persistence)
        monkeypatch.setattr(dp, 'run_async', dummy_callback)

        for group in range(5):
            dp.add_handler(MessageHandler(Filters.text,
                                          dummy_callback,
                                          run_async=True),
                           group=group)
        dp.add_handler(MessageHandler(Filters.text,
                                      dummy_callback,
                                      run_async=run_async),
                       group=5)

        update = Update(1,
                        message=Message(1,
                                        None,
                                        Chat(1, ''),
                                        from_user=None,
                                        text='Text'))
        dp.process_update(update)
        assert self.count == 1

    @pytest.mark.parametrize('run_async,expected', [(DEFAULT_FALSE, 1),
                                                    (False, 1), (True, 0)])
    def test_update_persistence_defaults_async(self, monkeypatch, dp,
                                               run_async, expected):
        def update_persistence(*args, **kwargs):
            self.count += 1

        def dummy_callback(*args, **kwargs):
            pass

        monkeypatch.setattr(dp, 'update_persistence', update_persistence)
        monkeypatch.setattr(dp, 'run_async', dummy_callback)
        dp.bot.defaults = Defaults(run_async=run_async)

        try:
            for group in range(5):
                dp.add_handler(MessageHandler(Filters.text, dummy_callback),
                               group=group)

            update = Update(1,
                            message=Message(1,
                                            None,
                                            Chat(1, ''),
                                            from_user=None,
                                            text='Text'))
            dp.process_update(update)
            assert self.count == expected
        finally:
            dp.bot.defaults = None
コード例 #33
0
class TestMessage(object):
    id_ = 1
    from_user = User(2, 'testuser', False)
    date = datetime.utcnow()
    chat = Chat(3, 'private')
    test_entities = [{'length': 4, 'offset': 10, 'type': 'bold'},
                     {'length': 3, 'offset': 16, 'type': 'italic'},
                     {'length': 3, 'offset': 20, 'type': 'italic'},
                     {'length': 4, 'offset': 25, 'type': 'code'},
                     {'length': 5, 'offset': 31, 'type': 'text_link',
                      'url': 'http://github.com/ab_'},
                     {'length': 12, 'offset': 38, 'type': 'text_mention',
                      'user': User(123456789, 'mentioned user', False)},
                     {'length': 3, 'offset': 55, 'type': 'pre', 'language': 'python'},
                     {'length': 21, 'offset': 60, 'type': 'url'}]
    test_text = 'Test for <bold, ita_lic, code, links, text-mention and pre. http://google.com/ab_'
    test_entities_v2 = [{'length': 4, 'offset': 0, 'type': 'underline'},
                        {'length': 4, 'offset': 10, 'type': 'bold'},
                        {'length': 7, 'offset': 16, 'type': 'italic'},
                        {'length': 6, 'offset': 25, 'type': 'code'},
                        {'length': 5, 'offset': 33, 'type': 'text_link',
                            'url': 'http://github.com/abc\)def'},
                        {'length': 12, 'offset': 40, 'type': 'text_mention',
                            'user': User(123456789, 'mentioned user', False)},
                        {'length': 5, 'offset': 57, 'type': 'pre'},
                        {'length': 17, 'offset': 64, 'type': 'url'},
                        {'length': 36, 'offset': 86, 'type': 'italic'},
                        {'length': 24, 'offset': 91, 'type': 'bold'},
                        {'length': 4, 'offset': 101, 'type': 'strikethrough'},
                        {'length': 10, 'offset': 124, 'type': 'pre', 'language': 'python'}]
    test_text_v2 = ('Test for <bold, ita_lic, \`code, links, text-mention and `\pre. '
                    'http://google.com and bold nested in strk nested in italic. Python pre.')
    test_message = Message(message_id=1,
                           from_user=None,
                           date=None,
                           chat=None,
                           text=test_text,
                           entities=[MessageEntity(**e) for e in test_entities],
                           caption=test_text,
                           caption_entities=[MessageEntity(**e) for e in test_entities])
    test_message_v2 = Message(message_id=1,
                              from_user=None,
                              date=None,
                              chat=None,
                              text=test_text_v2,
                              entities=[MessageEntity(**e) for e in test_entities_v2],
                              caption=test_text_v2,
                              caption_entities=[
                                  MessageEntity(**e) for e in test_entities_v2
                              ])

    def test_all_posibilities_de_json_and_to_dict(self, bot, message_params):
        new = Message.de_json(message_params.to_dict(), bot)

        assert new.to_dict() == message_params.to_dict()

    def test_dict_approach(self, message):
        assert message['date'] == message.date
        assert message['chat_id'] == message.chat_id
        assert message['no_key'] is None

    def test_parse_entity(self):
        text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
                b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape')
        entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
        message = Message(1, self.from_user, self.date, self.chat, text=text, entities=[entity])
        assert message.parse_entity(entity) == 'http://google.com'

    def test_parse_caption_entity(self):
        caption = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
                   b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape')
        entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
        message = Message(1, self.from_user, self.date, self.chat, caption=caption,
                          caption_entities=[entity])
        assert message.parse_caption_entity(entity) == 'http://google.com'

    def test_parse_entities(self):
        text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
                b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape')
        entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
        entity_2 = MessageEntity(type=MessageEntity.BOLD, offset=13, length=1)
        message = Message(1, self.from_user, self.date, self.chat,
                          text=text, entities=[entity_2, entity])
        assert message.parse_entities(MessageEntity.URL) == {entity: 'http://google.com'}
        assert message.parse_entities() == {entity: 'http://google.com', entity_2: 'h'}

    def test_parse_caption_entities(self):
        text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
                b'\\u200d\\U0001f467\\U0001f431http://google.com').decode('unicode-escape')
        entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
        entity_2 = MessageEntity(type=MessageEntity.BOLD, offset=13, length=1)
        message = Message(1, self.from_user, self.date, self.chat,
                          caption=text, caption_entities=[entity_2, entity])
        assert message.parse_caption_entities(MessageEntity.URL) == {entity: 'http://google.com'}
        assert message.parse_caption_entities() == {entity: 'http://google.com', entity_2: 'h'}

    def test_text_html_simple(self):
        test_html_string = ('<u>Test</u> for &lt;<b>bold</b>, <i>ita_lic</i>, <code>\`code</code>,'
                            ' <a href="http://github.com/abc\)def">links</a>, '
                            '<a href="tg://user?id=123456789">text-mention</a> and '
                            '<pre>`\pre</pre>. http://google.com '
                            'and <i>bold <b>nested in <s>strk</s> nested in</b> italic</i>. '
                            '<pre><code class="python">Python pre</code></pre>.')
        text_html = self.test_message_v2.text_html
        assert text_html == test_html_string

    def test_text_html_empty(self, message):
        message.text = None
        message.caption = "test"
        assert message.text_html is None

    def test_text_html_urled(self):
        test_html_string = ('<u>Test</u> for &lt;<b>bold</b>, <i>ita_lic</i>, <code>\`code</code>,'
                            ' <a href="http://github.com/abc\)def">links</a>, '
                            '<a href="tg://user?id=123456789">text-mention</a> and '
                            '<pre>`\pre</pre>. <a href="http://google.com">http://google.com</a> '
                            'and <i>bold <b>nested in <s>strk</s> nested in</b> italic</i>. '
                            '<pre><code class="python">Python pre</code></pre>.')
        text_html = self.test_message_v2.text_html_urled
        assert text_html == test_html_string

    def test_text_markdown_simple(self):
        test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),'
                          ' [text-mention](tg://user?id=123456789) and ```python\npre```. '
                          'http://google.com/ab\_')
        text_markdown = self.test_message.text_markdown
        assert text_markdown == test_md_string

    def test_text_markdown_v2_simple(self):
        test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, '
                          '[links](http://github.com/abc\\\\\)def), '
                          '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. '
                          'http://google\.com and _bold *nested in ~strk~ nested in* italic_\. '
                          '```python\nPython pre```\.')
        text_markdown = self.test_message_v2.text_markdown_v2
        assert text_markdown == test_md_string

    def test_text_markdown_new_in_v2(self, message):
        message.text = 'test'
        message.entities = [MessageEntity(MessageEntity.BOLD, offset=0, length=4),
                            MessageEntity(MessageEntity.ITALIC, offset=0, length=4)]
        with pytest.raises(ValueError):
            assert message.text_markdown

        message.entities = [MessageEntity(MessageEntity.UNDERLINE, offset=0, length=4)]
        with pytest.raises(ValueError):
            message.text_markdown

        message.entities = [MessageEntity(MessageEntity.STRIKETHROUGH, offset=0, length=4)]
        with pytest.raises(ValueError):
            message.text_markdown

        message.entities = []

    def test_text_markdown_empty(self, message):
        message.text = None
        message.caption = "test"
        assert message.text_markdown is None
        assert message.text_markdown_v2 is None

    def test_text_markdown_urled(self):
        test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),'
                          ' [text-mention](tg://user?id=123456789) and ```python\npre```. '
                          '[http://google.com/ab_](http://google.com/ab_)')
        text_markdown = self.test_message.text_markdown_urled
        assert text_markdown == test_md_string

    def test_text_markdown_v2_urled(self):
        test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, '
                          '[links](http://github.com/abc\\\\\)def), '
                          '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. '
                          '[http://google\.com](http://google.com) and _bold *nested in ~strk~ '
                          'nested in* italic_\. ```python\nPython pre```\.')
        text_markdown = self.test_message_v2.text_markdown_v2_urled
        assert text_markdown == test_md_string

    def test_text_html_emoji(self):
        text = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode('unicode-escape')
        expected = b'\\U0001f469\\u200d\\U0001f469\\u200d <b>ABC</b>'.decode('unicode-escape')
        bold_entity = MessageEntity(type=MessageEntity.BOLD, offset=7, length=3)
        message = Message(1, self.from_user, self.date, self.chat,
                          text=text, entities=[bold_entity])
        assert expected == message.text_html

    def test_text_markdown_emoji(self):
        text = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode('unicode-escape')
        expected = b'\\U0001f469\\u200d\\U0001f469\\u200d *ABC*'.decode('unicode-escape')
        bold_entity = MessageEntity(type=MessageEntity.BOLD, offset=7, length=3)
        message = Message(1, self.from_user, self.date, self.chat,
                          text=text, entities=[bold_entity])
        assert expected == message.text_markdown

    def test_caption_html_simple(self):
        test_html_string = ('<u>Test</u> for &lt;<b>bold</b>, <i>ita_lic</i>, <code>\`code</code>,'
                            ' <a href="http://github.com/abc\)def">links</a>, '
                            '<a href="tg://user?id=123456789">text-mention</a> and '
                            '<pre>`\pre</pre>. http://google.com '
                            'and <i>bold <b>nested in <s>strk</s> nested in</b> italic</i>. '
                            '<pre><code class="python">Python pre</code></pre>.')
        caption_html = self.test_message_v2.caption_html
        assert caption_html == test_html_string

    def test_caption_html_empty(self, message):
        message.text = "test"
        message.caption = None
        assert message.caption_html is None

    def test_caption_html_urled(self):
        test_html_string = ('<u>Test</u> for &lt;<b>bold</b>, <i>ita_lic</i>, <code>\`code</code>,'
                            ' <a href="http://github.com/abc\)def">links</a>, '
                            '<a href="tg://user?id=123456789">text-mention</a> and '
                            '<pre>`\pre</pre>. <a href="http://google.com">http://google.com</a> '
                            'and <i>bold <b>nested in <s>strk</s> nested in</b> italic</i>. '
                            '<pre><code class="python">Python pre</code></pre>.')
        caption_html = self.test_message_v2.caption_html_urled
        assert caption_html == test_html_string

    def test_caption_markdown_simple(self):
        test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),'
                          ' [text-mention](tg://user?id=123456789) and ```python\npre```. '
                          'http://google.com/ab\_')
        caption_markdown = self.test_message.caption_markdown
        assert caption_markdown == test_md_string

    def test_caption_markdown_v2_simple(self):
        test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, '
                          '[links](http://github.com/abc\\\\\\)def), '
                          '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. '
                          'http://google\.com and _bold *nested in ~strk~ nested in* italic_\. '
                          '```python\nPython pre```\.')
        caption_markdown = self.test_message_v2.caption_markdown_v2
        assert caption_markdown == test_md_string

    def test_caption_markdown_empty(self, message):
        message.text = "test"
        message.caption = None
        assert message.caption_markdown is None
        assert message.caption_markdown_v2 is None

    def test_caption_markdown_urled(self):
        test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),'
                          ' [text-mention](tg://user?id=123456789) and ```python\npre```. '
                          '[http://google.com/ab_](http://google.com/ab_)')
        caption_markdown = self.test_message.caption_markdown_urled
        assert caption_markdown == test_md_string

    def test_caption_markdown_v2_urled(self):
        test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, '
                          '[links](http://github.com/abc\\\\\\)def), '
                          '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. '
                          '[http://google\.com](http://google.com) and _bold *nested in ~strk~ '
                          'nested in* italic_\. ```python\nPython pre```\.')
        caption_markdown = self.test_message_v2.caption_markdown_v2_urled
        assert caption_markdown == test_md_string

    def test_caption_html_emoji(self):
        caption = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode('unicode-escape')
        expected = b'\\U0001f469\\u200d\\U0001f469\\u200d <b>ABC</b>'.decode('unicode-escape')
        bold_entity = MessageEntity(type=MessageEntity.BOLD, offset=7, length=3)
        message = Message(1, self.from_user, self.date, self.chat,
                          caption=caption, caption_entities=[bold_entity])
        assert expected == message.caption_html

    def test_caption_markdown_emoji(self):
        caption = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode('unicode-escape')
        expected = b'\\U0001f469\\u200d\\U0001f469\\u200d *ABC*'.decode('unicode-escape')
        bold_entity = MessageEntity(type=MessageEntity.BOLD, offset=7, length=3)
        message = Message(1, self.from_user, self.date, self.chat,
                          caption=caption, caption_entities=[bold_entity])
        assert expected == message.caption_markdown

    def test_parse_entities_url_emoji(self):
        url = b'http://github.com/?unicode=\\u2713\\U0001f469'.decode('unicode-escape')
        text = 'some url'
        link_entity = MessageEntity(type=MessageEntity.URL, offset=0, length=8, url=url)
        message = Message(1, self.from_user, self.date, self.chat,
                          text=text, entities=[link_entity])
        assert message.parse_entities() == {link_entity: text}
        assert next(iter(message.parse_entities())).url == url

    def test_chat_id(self, message):
        assert message.chat_id == message.chat.id

    @pytest.mark.parametrize('type', argvalues=[Chat.SUPERGROUP, Chat.CHANNEL])
    def test_link_with_username(self, message, type):
        message.chat.username = '******'
        message.chat.type = type
        assert message.link == 'https://t.me/{}/{}'.format(message.chat.username,
                                                           message.message_id)

    @pytest.mark.parametrize('type, id', argvalues=[
        (Chat.CHANNEL, -1003), (Chat.SUPERGROUP, -1003)])
    def test_link_with_id(self, message, type, id):
        message.chat.username = None
        message.chat.id = id
        message.chat.type = type
        # The leading - for group ids/ -100 for supergroup ids isn't supposed to be in the link
        assert message.link == 'https://t.me/c/{}/{}'.format(3, message.message_id)

    @pytest.mark.parametrize('id, username', argvalues=[
        (None, 'username'), (-3, None)
    ])
    def test_link_private_chats(self, message, id, username):
        message.chat.type = Chat.PRIVATE
        message.chat.id = id
        message.chat.username = username
        assert message.link is None
        message.chat.type = Chat.GROUP
        assert message.link is None

    def test_effective_attachment(self, message_params):
        for i in ('audio', 'game', 'document', 'animation', 'photo', 'sticker', 'video', 'voice',
                  'video_note', 'contact', 'location', 'venue', 'invoice', 'invoice',
                  'successful_payment'):
            item = getattr(message_params, i, None)
            if item:
                break
        else:
            item = None
        assert message_params.effective_attachment == item

    def test_reply_text(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            text = args[1] == 'test'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and text and reply

        monkeypatch.setattr(message.bot, 'send_message', test)
        assert message.reply_text('test')
        assert message.reply_text('test', quote=True)
        assert message.reply_text('test', reply_to_message_id=message.message_id, quote=True)

    def test_reply_markdown(self, monkeypatch, message):
        test_md_string = ('Test for <*bold*, _ita_\__lic_, `code`, [links](http://github.com/ab_),'
                          ' [text-mention](tg://user?id=123456789) and ```python\npre```. '
                          'http://google.com/ab\_')

        def test(*args, **kwargs):
            cid = args[0] == message.chat_id
            markdown_text = args[1] == test_md_string
            markdown_enabled = kwargs['parse_mode'] == ParseMode.MARKDOWN
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return all([cid, markdown_text, reply, markdown_enabled])

        text_markdown = self.test_message.text_markdown
        assert text_markdown == test_md_string

        monkeypatch.setattr(message.bot, 'send_message', test)
        assert message.reply_markdown(self.test_message.text_markdown)
        assert message.reply_markdown(self.test_message.text_markdown, quote=True)
        assert message.reply_markdown(self.test_message.text_markdown,
                                      reply_to_message_id=message.message_id,
                                      quote=True)

    def test_reply_markdown_v2(self, monkeypatch, message):
        test_md_string = (r'__Test__ for <*bold*, _ita\_lic_, `\\\`code`, '
                          '[links](http://github.com/abc\\\\\)def), '
                          '[text\-mention](tg://user?id=123456789) and ```\`\\\\pre```\. '
                          'http://google\.com and _bold *nested in ~strk~ nested in* italic_\. '
                          '```python\nPython pre```\.')

        def test(*args, **kwargs):
            cid = args[0] == message.chat_id
            markdown_text = args[1] == test_md_string
            markdown_enabled = kwargs['parse_mode'] == ParseMode.MARKDOWN_V2
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return all([cid, markdown_text, reply, markdown_enabled])

        text_markdown = self.test_message_v2.text_markdown_v2
        assert text_markdown == test_md_string

        monkeypatch.setattr(message.bot, 'send_message', test)
        assert message.reply_markdown_v2(self.test_message_v2.text_markdown_v2)
        assert message.reply_markdown_v2(self.test_message_v2.text_markdown_v2, quote=True)
        assert message.reply_markdown_v2(self.test_message_v2.text_markdown_v2,
                                         reply_to_message_id=message.message_id,
                                         quote=True)

    def test_reply_html(self, monkeypatch, message):
        test_html_string = ('<u>Test</u> for &lt;<b>bold</b>, <i>ita_lic</i>, <code>\`code</code>,'
                            ' <a href="http://github.com/abc\)def">links</a>, '
                            '<a href="tg://user?id=123456789">text-mention</a> and '
                            '<pre>`\pre</pre>. http://google.com '
                            'and <i>bold <b>nested in <s>strk</s> nested in</b> italic</i>. '
                            '<pre><code class="python">Python pre</code></pre>.')

        def test(*args, **kwargs):
            cid = args[0] == message.chat_id
            html_text = args[1] == test_html_string
            html_enabled = kwargs['parse_mode'] == ParseMode.HTML
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return all([cid, html_text, reply, html_enabled])

        text_html = self.test_message_v2.text_html
        assert text_html == test_html_string

        monkeypatch.setattr(message.bot, 'send_message', test)
        assert message.reply_html(self.test_message_v2.text_html)
        assert message.reply_html(self.test_message_v2.text_html, quote=True)
        assert message.reply_html(self.test_message_v2.text_html,
                                  reply_to_message_id=message.message_id,
                                  quote=True)

    def test_reply_media_group(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            media = kwargs['media'] == 'reply_media_group'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and media and reply

        monkeypatch.setattr(message.bot, 'send_media_group', test)
        assert message.reply_media_group(media='reply_media_group')
        assert message.reply_media_group(media='reply_media_group', quote=True)

    def test_reply_photo(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            photo = kwargs['photo'] == 'test_photo'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and photo and reply

        monkeypatch.setattr(message.bot, 'send_photo', test)
        assert message.reply_photo(photo='test_photo')
        assert message.reply_photo(photo='test_photo', quote=True)

    def test_reply_audio(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            audio = kwargs['audio'] == 'test_audio'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and audio and reply

        monkeypatch.setattr(message.bot, 'send_audio', test)
        assert message.reply_audio(audio='test_audio')
        assert message.reply_audio(audio='test_audio', quote=True)

    def test_reply_document(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            document = kwargs['document'] == 'test_document'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and document and reply

        monkeypatch.setattr(message.bot, 'send_document', test)
        assert message.reply_document(document='test_document')
        assert message.reply_document(document='test_document', quote=True)

    def test_reply_animation(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            animation = kwargs['animation'] == 'test_animation'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and animation and reply

        monkeypatch.setattr(message.bot, 'send_animation', test)
        assert message.reply_animation(animation='test_animation')
        assert message.reply_animation(animation='test_animation', quote=True)

    def test_reply_sticker(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            sticker = kwargs['sticker'] == 'test_sticker'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and sticker and reply

        monkeypatch.setattr(message.bot, 'send_sticker', test)
        assert message.reply_sticker(sticker='test_sticker')
        assert message.reply_sticker(sticker='test_sticker', quote=True)

    def test_reply_video(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            video = kwargs['video'] == 'test_video'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and video and reply

        monkeypatch.setattr(message.bot, 'send_video', test)
        assert message.reply_video(video='test_video')
        assert message.reply_video(video='test_video', quote=True)

    def test_reply_video_note(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            video_note = kwargs['video_note'] == 'test_video_note'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and video_note and reply

        monkeypatch.setattr(message.bot, 'send_video_note', test)
        assert message.reply_video_note(video_note='test_video_note')
        assert message.reply_video_note(video_note='test_video_note', quote=True)

    def test_reply_voice(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            voice = kwargs['voice'] == 'test_voice'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and voice and reply

        monkeypatch.setattr(message.bot, 'send_voice', test)
        assert message.reply_voice(voice='test_voice')
        assert message.reply_voice(voice='test_voice', quote=True)

    def test_reply_location(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            location = kwargs['location'] == 'test_location'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and location and reply

        monkeypatch.setattr(message.bot, 'send_location', test)
        assert message.reply_location(location='test_location')
        assert message.reply_location(location='test_location', quote=True)

    def test_reply_venue(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            venue = kwargs['venue'] == 'test_venue'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and venue and reply

        monkeypatch.setattr(message.bot, 'send_venue', test)
        assert message.reply_venue(venue='test_venue')
        assert message.reply_venue(venue='test_venue', quote=True)

    def test_reply_contact(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            contact = kwargs['contact'] == 'test_contact'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and contact and reply

        monkeypatch.setattr(message.bot, 'send_contact', test)
        assert message.reply_contact(contact='test_contact')
        assert message.reply_contact(contact='test_contact', quote=True)

    def test_reply_poll(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            contact = kwargs['question'] == 'test_poll'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and contact and reply

        monkeypatch.setattr(message.bot, 'send_poll', test)
        assert message.reply_poll(question='test_poll')
        assert message.reply_poll(question='test_poll', quote=True)

    def test_reply_dice(self, monkeypatch, message):
        def test(*args, **kwargs):
            id_ = args[0] == message.chat_id
            contact = kwargs['disable_notification'] is True
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id_ and contact and reply

        monkeypatch.setattr(message.bot, 'send_dice', test)
        assert message.reply_dice(disable_notification=True)
        assert message.reply_dice(disable_notification=True, quote=True)

    def test_forward(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == 123456
            from_chat = kwargs['from_chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            if kwargs.get('disable_notification'):
                notification = kwargs['disable_notification'] is True
            else:
                notification = True
            return chat_id and from_chat and message_id and notification

        monkeypatch.setattr(message.bot, 'forward_message', test)
        assert message.forward(123456)
        assert message.forward(123456, disable_notification=True)
        assert not message.forward(635241)

    def test_edit_text(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            text = kwargs['text'] == 'test'
            return chat_id and message_id and text

        monkeypatch.setattr(message.bot, 'edit_message_text', test)
        assert message.edit_text(text='test')

    def test_edit_caption(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            caption = kwargs['caption'] == 'new caption'
            return chat_id and message_id and caption

        monkeypatch.setattr(message.bot, 'edit_message_caption', test)
        assert message.edit_caption(caption='new caption')

    def test_edit_media(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            media = kwargs['media'] == 'my_media'
            return chat_id and message_id and media

        monkeypatch.setattr(message.bot, 'edit_message_media', test)
        assert message.edit_media('my_media')

    def test_edit_reply_markup(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            reply_markup = kwargs['reply_markup'] == [['1', '2']]
            return chat_id and message_id and reply_markup

        monkeypatch.setattr(message.bot, 'edit_message_reply_markup', test)
        assert message.edit_reply_markup(reply_markup=[['1', '2']])

    def test_delete(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            return chat_id and message_id

        monkeypatch.setattr(message.bot, 'delete_message', test)
        assert message.delete()

    def test_default_quote(self, message):
        kwargs = {}

        message.default_quote = False
        message._quote(kwargs)
        assert 'reply_to_message_id' not in kwargs

        message.default_quote = True
        message._quote(kwargs)
        assert 'reply_to_message_id' in kwargs

        kwargs = {}
        message.default_quote = None
        message.chat.type = Chat.PRIVATE
        message._quote(kwargs)
        assert 'reply_to_message_id' not in kwargs

        message.chat.type = Chat.GROUP
        message._quote(kwargs)
        assert 'reply_to_message_id' in kwargs

    def test_equality(self):
        id_ = 1
        a = Message(id_, self.from_user, self.date, self.chat)
        b = Message(id_, self.from_user, self.date, self.chat)
        c = Message(id_, User(0, '', False), self.date, self.chat)
        d = Message(0, self.from_user, self.date, self.chat)
        e = Update(id_)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
コード例 #34
0
def update():
    return Update(
        0,
        Message(0, User(0, 'Testuser', False), datetime.datetime.utcnow(),
                Chat(0, 'private')))
コード例 #35
0
ファイル: test_filters.py プロジェクト: mandarin41/keks
def message():
    return Message(0, User(0, 'Testuser', False), datetime.datetime.now(),
                   Chat(0, 'private'))
コード例 #36
0
def callback_query(bot):
    return Update(0,
                  callback_query=CallbackQuery(2,
                                               User(1, '', False),
                                               None,
                                               data='test data'))
コード例 #37
0
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program.  If not, see [http://www.gnu.org/licenses/].

import pytest

from telegram import (Message, Update, Chat, Bot, User, CallbackQuery,
                      InlineQuery, ChosenInlineResult, ShippingQuery,
                      PreCheckoutQuery)
from telegram.ext import CommandHandler, Filters, BaseFilter

message = Message(1, User(1, '', False), None, Chat(1, ''), text='test')

params = [{
    'callback_query':
    CallbackQuery(1, User(1, '', False), 'chat', message=message)
}, {
    'channel_post': message
}, {
    'edited_channel_post': message
}, {
    'inline_query': InlineQuery(1, User(1, '', False), '', '')
}, {
    'chosen_inline_result':
    ChosenInlineResult('id', User(1, '', False), '')
}, {
    'shipping_query': ShippingQuery('id', User(1, '', False), '', None)
コード例 #38
0
class TestDispatcher(object):
    message_update = Update(1,
                            message=Message(1,
                                            User(1, '', False),
                                            None,
                                            Chat(1, ''),
                                            text='Text'))
    received = None
    count = 0

    @pytest.fixture(autouse=True)
    def reset(self):
        self.received = None
        self.count = 0

    def error_handler(self, bot, update, error):
        self.received = error.message

    def error_handler_raise_error(self, bot, update, error):
        raise Exception('Failing bigly')

    def callback_increase_count(self, bot, update):
        self.count += 1

    def callback_set_count(self, count):
        def callback(bot, update):
            self.count = count

        return callback

    def callback_raise_error(self, bot, update):
        raise TelegramError(update.message.text)

    def callback_if_not_update_queue(self, bot, update, update_queue=None):
        if update_queue is not None:
            self.received = update.message

    def test_error_handler(self, dp):
        dp.add_error_handler(self.error_handler)
        error = TelegramError('Unauthorized.')
        dp.update_queue.put(error)
        sleep(.1)
        assert self.received == 'Unauthorized.'

        # Remove handler
        dp.remove_error_handler(self.error_handler)
        self.reset()

        dp.update_queue.put(error)
        sleep(.1)
        assert self.received is None

    def test_error_handler_that_raises_errors(self, dp):
        """
        Make sure that errors raised in error handlers don't break the main loop of the dispatcher
        """
        handler_raise_error = MessageHandler(Filters.all,
                                             self.callback_raise_error)
        handler_increase_count = MessageHandler(Filters.all,
                                                self.callback_increase_count)
        error = TelegramError('Unauthorized.')

        dp.add_error_handler(self.error_handler_raise_error)

        # From errors caused by handlers
        dp.add_handler(handler_raise_error)
        dp.update_queue.put(self.message_update)
        sleep(.1)

        # From errors in the update_queue
        dp.remove_handler(handler_raise_error)
        dp.add_handler(handler_increase_count)
        dp.update_queue.put(error)
        dp.update_queue.put(self.message_update)
        sleep(.1)

        assert self.count == 1

    def test_run_async_multiple(self, bot, dp, dp2):
        def get_dispatcher_name(q):
            q.put(current_thread().name)

        q1 = Queue()
        q2 = Queue()

        dp.run_async(get_dispatcher_name, q1)
        dp2.run_async(get_dispatcher_name, q2)

        sleep(.1)

        name1 = q1.get()
        name2 = q2.get()

        assert name1 != name2

    def test_multiple_run_async_decorator(self, dp, dp2):
        # Make sure we got two dispatchers and that they are not the same
        assert isinstance(dp, Dispatcher)
        assert isinstance(dp2, Dispatcher)
        assert dp is not dp2

        @run_async
        def must_raise_runtime_error():
            pass

        with pytest.raises(RuntimeError):
            must_raise_runtime_error()

    def test_run_async_with_args(self, dp):
        dp.add_handler(
            MessageHandler(Filters.all,
                           run_async(self.callback_if_not_update_queue),
                           pass_update_queue=True))

        dp.update_queue.put(self.message_update)
        sleep(.1)
        assert self.received == self.message_update.message

    def test_error_in_handler(self, dp):
        dp.add_handler(MessageHandler(Filters.all, self.callback_raise_error))
        dp.add_error_handler(self.error_handler)

        dp.update_queue.put(self.message_update)
        sleep(.1)
        assert self.received == self.message_update.message.text

    def test_add_remove_handler(self, dp):
        handler = MessageHandler(Filters.all, self.callback_increase_count)
        dp.add_handler(handler)
        dp.update_queue.put(self.message_update)
        sleep(.1)
        assert self.count == 1
        dp.remove_handler(handler)
        dp.update_queue.put(self.message_update)
        assert self.count == 1

    def test_add_remove_handler_non_default_group(self, dp):
        handler = MessageHandler(Filters.all, self.callback_increase_count)
        dp.add_handler(handler, group=2)
        with pytest.raises(KeyError):
            dp.remove_handler(handler)
        dp.remove_handler(handler, group=2)

    def test_error_start_twice(self, dp):
        assert dp.running
        dp.start()

    def test_handler_order_in_group(self, dp):
        dp.add_handler(
            MessageHandler(Filters.photo, self.callback_set_count(1)))
        dp.add_handler(MessageHandler(Filters.all, self.callback_set_count(2)))
        dp.add_handler(MessageHandler(Filters.text,
                                      self.callback_set_count(3)))
        dp.update_queue.put(self.message_update)
        sleep(.1)
        assert self.count == 2

    def test_groups(self, dp):
        dp.add_handler(
            MessageHandler(Filters.all, self.callback_increase_count))
        dp.add_handler(MessageHandler(Filters.all,
                                      self.callback_increase_count),
                       group=2)
        dp.add_handler(MessageHandler(Filters.all,
                                      self.callback_increase_count),
                       group=-1)

        dp.update_queue.put(self.message_update)
        sleep(.1)
        assert self.count == 3

    def test_add_handler_errors(self, dp):
        handler = 'not a handler'
        with pytest.raises(TypeError, match='handler is not an instance of'):
            dp.add_handler(handler)

        handler = MessageHandler(Filters.photo, self.callback_set_count(1))
        with pytest.raises(TypeError, match='group is not int'):
            dp.add_handler(handler, 'one')

    def test_flow_stop(self, dp, bot):
        passed = []

        def start1(b, u):
            passed.append('start1')
            raise DispatcherHandlerStop

        def start2(b, u):
            passed.append('start2')

        def start3(b, u):
            passed.append('start3')

        def error(b, u, e):
            passed.append('error')
            passed.append(e)

        update = Update(1,
                        message=Message(1,
                                        None,
                                        None,
                                        None,
                                        text='/start',
                                        bot=bot))

        # If Stop raised handlers in other groups should not be called.
        passed = []
        dp.add_handler(CommandHandler('start', start1), 1)
        dp.add_handler(CommandHandler('start', start3), 1)
        dp.add_handler(CommandHandler('start', start2), 2)
        dp.process_update(update)
        assert passed == ['start1']

    def test_exception_in_handler(self, dp, bot):
        passed = []

        def start1(b, u):
            passed.append('start1')
            raise Exception('General exception')

        def start2(b, u):
            passed.append('start2')

        def start3(b, u):
            passed.append('start3')

        def error(b, u, e):
            passed.append('error')
            passed.append(e)

        update = Update(1,
                        message=Message(1,
                                        None,
                                        None,
                                        None,
                                        text='/start',
                                        bot=bot))

        # If an unhandled exception was caught, no further handlers from the same group should be
        # called.
        passed = []
        dp.add_handler(CommandHandler('start', start1), 1)
        dp.add_handler(CommandHandler('start', start2), 1)
        dp.add_handler(CommandHandler('start', start3), 2)
        dp.add_error_handler(error)
        dp.process_update(update)
        assert passed == ['start1', 'start3']

    def test_telegram_error_in_handler(self, dp, bot):
        passed = []
        err = TelegramError('Telegram error')

        def start1(b, u):
            passed.append('start1')
            raise err

        def start2(b, u):
            passed.append('start2')

        def start3(b, u):
            passed.append('start3')

        def error(b, u, e):
            passed.append('error')
            passed.append(e)

        update = Update(1,
                        message=Message(1,
                                        None,
                                        None,
                                        None,
                                        text='/start',
                                        bot=bot))

        # If a TelegramException was caught, an error handler should be called and no further
        # handlers from the same group should be called.
        dp.add_handler(CommandHandler('start', start1), 1)
        dp.add_handler(CommandHandler('start', start2), 1)
        dp.add_handler(CommandHandler('start', start3), 2)
        dp.add_error_handler(error)
        dp.process_update(update)
        assert passed == ['start1', 'error', err, 'start3']
        assert passed[2] is err

    def test_flow_stop_in_error_handler(self, dp, bot):
        passed = []
        err = TelegramError('Telegram error')

        def start1(b, u):
            passed.append('start1')
            raise err

        def start2(b, u):
            passed.append('start2')

        def start3(b, u):
            passed.append('start3')

        def error(b, u, e):
            passed.append('error')
            passed.append(e)
            raise DispatcherHandlerStop

        update = Update(1,
                        message=Message(1,
                                        None,
                                        None,
                                        None,
                                        text='/start',
                                        bot=bot))

        # If a TelegramException was caught, an error handler should be called and no further
        # handlers from the same group should be called.
        dp.add_handler(CommandHandler('start', start1), 1)
        dp.add_handler(CommandHandler('start', start2), 1)
        dp.add_handler(CommandHandler('start', start3), 2)
        dp.add_error_handler(error)
        dp.process_update(update)
        assert passed == ['start1', 'error', err]
        assert passed[2] is err
コード例 #39
0
#
# You should have received a copy of the GNU Lesser Public License
# along with this program.  If not, see [http://www.gnu.org/licenses/].
from queue import Queue

import pytest

from telegram import (Update, CallbackQuery, Bot, Message, User, Chat,
                      InlineQuery, ChosenInlineResult, ShippingQuery,
                      PreCheckoutQuery)
from telegram.ext import CallbackQueryHandler, CallbackContext, JobQueue

message = Message(1,
                  None,
                  Chat(1, ''),
                  from_user=User(1, '', False),
                  text='Text')

params = [{
    'message': message
}, {
    'edited_message': message
}, {
    'channel_post': message
}, {
    'edited_channel_post': message
}, {
    'inline_query': InlineQuery(1, User(1, '', False), '', '')
}, {
    'chosen_inline_result':
    ChosenInlineResult('id', User(1, '', False), '')
コード例 #40
0
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser Public License for more details.
#
# You should have received a copy of the GNU Lesser Public License
# along with this program.  If not, see [http://www.gnu.org/licenses/].

import pytest

from telegram import (Message, Update, Chat, Bot, User, CallbackQuery, InlineQuery,
                      ChosenInlineResult, ShippingQuery, PreCheckoutQuery)
from telegram.ext import CommandHandler, Filters

message = Message(1, User(1, '', False), None, Chat(1, ''), text='test')

params = [
    {'callback_query': CallbackQuery(1, User(1, '', False), 'chat', message=message)},
    {'channel_post': message},
    {'edited_channel_post': message},
    {'inline_query': InlineQuery(1, User(1, '', False), '', '')},
    {'chosen_inline_result': ChosenInlineResult('id', User(1, '', False), '')},
    {'shipping_query': ShippingQuery('id', User(1, '', False), '', None)},
    {'pre_checkout_query': PreCheckoutQuery('id', User(1, '', False), '', 0, '')},
    {'callback_query': CallbackQuery(1, User(1, '', False), 'chat')}
]

ids = ('callback_query', 'channel_post', 'edited_channel_post', 'inline_query',
       'chosen_inline_result', 'shipping_query', 'pre_checkout_query',
       'callback_query_without_message',)
コード例 #41
0
class TestCallbackQuery(object):
    id = 'id'
    from_user = User(1, 'test_user', False)
    chat_instance = 'chat_instance'
    message = Message(3, User(5, 'bot', False), None, Chat(4, 'private'))
    data = 'data'
    inline_message_id = 'inline_message_id'
    game_short_name = 'the_game'

    def test_de_json(self, bot):
        json_dict = {
            'id': self.id,
            'from': self.from_user.to_dict(),
            'chat_instance': self.chat_instance,
            'message': self.message.to_dict(),
            'data': self.data,
            'inline_message_id': self.inline_message_id,
            'game_short_name': self.game_short_name
        }
        callback_query = CallbackQuery.de_json(json_dict, bot)

        assert callback_query.id == self.id
        assert callback_query.from_user == self.from_user
        assert callback_query.chat_instance == self.chat_instance
        assert callback_query.message == self.message
        assert callback_query.data == self.data
        assert callback_query.inline_message_id == self.inline_message_id
        assert callback_query.game_short_name == self.game_short_name

    def test_to_dict(self, callback_query):
        callback_query_dict = callback_query.to_dict()

        assert isinstance(callback_query_dict, dict)
        assert callback_query_dict['id'] == callback_query.id
        assert callback_query_dict['from'] == callback_query.from_user.to_dict(
        )
        assert callback_query_dict[
            'chat_instance'] == callback_query.chat_instance
        if callback_query.message:
            assert callback_query_dict[
                'message'] == callback_query.message.to_dict()
        else:
            assert callback_query_dict[
                'inline_message_id'] == callback_query.inline_message_id
        assert callback_query_dict['data'] == callback_query.data
        assert callback_query_dict[
            'game_short_name'] == callback_query.game_short_name

    def test_answer(self, monkeypatch, callback_query):
        def test(*args, **kwargs):
            return args[1] == callback_query.id

        monkeypatch.setattr('telegram.Bot.answerCallbackQuery', test)
        # TODO: PEP8
        assert callback_query.answer()

    def test_edit_message_text(self, monkeypatch, callback_query):
        def test(*args, **kwargs):
            try:
                id = kwargs[
                    'inline_message_id'] == callback_query.inline_message_id
                text = kwargs['text'] == 'test'
                return id and text
            except KeyError:
                chat_id = kwargs['chat_id'] == callback_query.message.chat_id
                message_id = kwargs[
                    'message_id'] == callback_query.message.message_id
                text = kwargs['text'] == 'test'
                return chat_id and message_id and text

        monkeypatch.setattr('telegram.Bot.edit_message_text', test)
        assert callback_query.edit_message_text(text='test')

    def test_edit_message_caption(self, monkeypatch, callback_query):
        def test(*args, **kwargs):
            try:
                id = kwargs[
                    'inline_message_id'] == callback_query.inline_message_id
                caption = kwargs['caption'] == 'new caption'
                return id and caption
            except KeyError:
                id = kwargs['chat_id'] == callback_query.message.chat_id
                message = kwargs[
                    'message_id'] == callback_query.message.message_id
                caption = kwargs['caption'] == 'new caption'
                return id and message and caption

        monkeypatch.setattr('telegram.Bot.edit_message_caption', test)
        assert callback_query.edit_message_caption(caption='new caption')

    def test_edit_message_reply_markup(self, monkeypatch, callback_query):
        def test(*args, **kwargs):
            try:
                id = kwargs[
                    'inline_message_id'] == callback_query.inline_message_id
                reply_markup = kwargs['reply_markup'] == [['1', '2']]
                return id and reply_markup
            except KeyError:
                id = kwargs['chat_id'] == callback_query.message.chat_id
                message = kwargs[
                    'message_id'] == callback_query.message.message_id
                reply_markup = kwargs['reply_markup'] == [['1', '2']]
                return id and message and reply_markup

        monkeypatch.setattr('telegram.Bot.edit_message_reply_markup', test)
        assert callback_query.edit_message_reply_markup(
            reply_markup=[['1', '2']])

    def test_equality(self):
        a = CallbackQuery(self.id, self.from_user, 'chat')
        b = CallbackQuery(self.id, self.from_user, 'chat')
        c = CallbackQuery(self.id, None, '')
        d = CallbackQuery('', None, 'chat')
        e = Audio(self.id, 1)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
コード例 #42
0
    def test_guess_member(self, monkeypatch):
        monkeypatch.setattr(Photon, 'geocode', get_address_from_cache)

        Member.set_akadressen_credentials('http://all', 'http://active', '',
                                          '')

        with open(check_file_path('tests/data/akadressen.pdf'),
                  'rb') as akadressen:
            responses.add(
                responses.GET,
                'http://all',
                body=akadressen.read(),
                stream=True,
                status=200,
                adding_headers={'Transfer-Encoding': 'chunked'},
            )

        with open(check_file_path('tests/data/akadressen-active.pdf'),
                  'rb') as akadressen_active:
            responses.add(
                responses.GET,
                'http://active',
                body=akadressen_active.read(),
                stream=True,
                status=200,
                adding_headers={'Transfer-Encoding': 'chunked'},
            )

        assert Member._AKADRESSEN_CACHE_TIME is None
        assert Member._AKADRESSEN is None
        user_1 = User(1, is_bot=False, first_name='John', last_name='Doe')
        members = Member.guess_member(user_1)
        assert Member._AKADRESSEN_CACHE_TIME == dt.date.today()
        assert isinstance(Member._AKADRESSEN, pd.DataFrame)
        assert len(members) == 1
        member = members[0]
        assert member.user_id == 1
        assert member.last_name == 'Doe'
        assert member.first_name == 'John'
        assert member.nickname == 'Jonny'
        assert member.date_of_birth == dt.date(2000, 1, 1)
        assert member.instruments == [instruments.Trumpet()]
        assert member.address == 'Münzstraße 5, 38100 Braunschweig'
        assert member.joined == 2004

        Member._AKADRESSEN = None
        user_2 = User(2, is_bot=False, first_name='Marcel', last_name='Marcel')
        members = Member.guess_member(user_2)
        assert Member._AKADRESSEN_CACHE_TIME == dt.date.today()
        assert isinstance(Member._AKADRESSEN, pd.DataFrame)
        assert len(members) == 1
        member = members[0]
        assert member.user_id == 2
        assert member.last_name == 'Marcel'
        assert member.first_name == 'Marcel'
        assert member.nickname is None
        assert member.date_of_birth == dt.date(2000, 5, 1)
        assert member.instruments == []
        assert member.address == 'Universitätsplatz 2, 38106 Braunschweig'
        assert member.joined == 2005

        test_flag = False

        def _get_akadressen(*args, **kwargs):
            nonlocal test_flag
            test_flag = True

        monkeypatch.setattr(Member, '_get_akadressen', _get_akadressen)

        user_3 = User(3, is_bot=False, first_name='Test', username='******')
        members = Member.guess_member(user_3)
        assert Member._AKADRESSEN_CACHE_TIME == dt.date.today()
        assert isinstance(Member._AKADRESSEN, pd.DataFrame)
        assert not test_flag
        assert len(members) == 1
        member = members[0]
        assert member.user_id == 3
        assert member.last_name == 'Zufall'
        assert member.first_name == 'Rainer'
        assert member.nickname == 'Das Brot'
        assert member.date_of_birth == dt.date(2007, 7, 5)
        assert member.instruments == [instruments.Flute()]
        assert member.address == 'Bültenweg 74-75, 38106 Braunschweig'
        assert member.joined is None

        user_4 = User(1, is_bot=False, first_name=None)
        assert Member.guess_member(user_4) is None
コード例 #43
0
    def test_dispatcher_integration_handlers(self, caplog, bot,
                                             base_persistence, chat_data,
                                             user_data):
        def get_user_data():
            return user_data

        def get_chat_data():
            return chat_data

        base_persistence.get_user_data = get_user_data
        base_persistence.get_chat_data = get_chat_data
        # base_persistence.update_chat_data = lambda x: x
        # base_persistence.update_user_data = lambda x: x
        updater = Updater(bot=bot,
                          persistence=base_persistence,
                          use_context=True)
        dp = updater.dispatcher

        def callback_known_user(update, context):
            if not context.user_data['test1'] == 'test2':
                pytest.fail('user_data corrupt')

        def callback_known_chat(update, context):
            if not context.chat_data['test3'] == 'test4':
                pytest.fail('chat_data corrupt')

        def callback_unknown_user_or_chat(update, context):
            if not context.user_data == {}:
                pytest.fail('user_data corrupt')
            if not context.chat_data == {}:
                pytest.fail('chat_data corrupt')
            context.user_data[1] = 'test7'
            context.chat_data[2] = 'test8'

        known_user = MessageHandler(Filters.user(user_id=12345),
                                    callback_known_user,
                                    pass_chat_data=True,
                                    pass_user_data=True)
        known_chat = MessageHandler(Filters.chat(chat_id=-67890),
                                    callback_known_chat,
                                    pass_chat_data=True,
                                    pass_user_data=True)
        unknown = MessageHandler(Filters.all,
                                 callback_unknown_user_or_chat,
                                 pass_chat_data=True,
                                 pass_user_data=True)
        dp.add_handler(known_user)
        dp.add_handler(known_chat)
        dp.add_handler(unknown)
        user1 = User(id=12345, first_name='test user', is_bot=False)
        user2 = User(id=54321, first_name='test user', is_bot=False)
        chat1 = Chat(id=-67890, type='group')
        chat2 = Chat(id=-987654, type='group')
        m = Message(1, user1, None, chat2)
        u = Update(0, m)
        with caplog.at_level(logging.ERROR):
            dp.process_update(u)
        rec = caplog.records[-1]
        assert rec.msg == 'Saving user data raised an error'
        assert rec.levelname == 'ERROR'
        rec = caplog.records[-2]
        assert rec.msg == 'Saving chat data raised an error'
        assert rec.levelname == 'ERROR'
        m.from_user = user2
        m.chat = chat1
        u = Update(1, m)
        dp.process_update(u)
        m.chat = chat2
        u = Update(2, m)

        def save_chat_data(data):
            if -987654 not in data:
                pytest.fail()

        def save_user_data(data):
            if 54321 not in data:
                pytest.fail()

        base_persistence.update_chat_data = save_chat_data
        base_persistence.update_user_data = save_user_data
        dp.process_update(u)

        assert dp.user_data[54321][1] == 'test7'
        assert dp.chat_data[-987654][2] == 'test8'
コード例 #44
0
    def de_json(data, bot):
        data = super(MessageEntity, MessageEntity).de_json(data, bot)

        data['user'] = User.de_json(data.get('user'), bot)

        return MessageEntity(**data)
コード例 #45
0
    def test_error_while_persisting(self, cdp, monkeypatch):
        class OwnPersistence(BasePersistence):
            def __init__(self):
                super().__init__()
                self.store_user_data = True
                self.store_chat_data = True
                self.store_bot_data = True

            def update(self, data):
                raise Exception('PersistenceError')

            def update_bot_data(self, data):
                self.update(data)

            def update_chat_data(self, chat_id, data):
                self.update(data)

            def update_user_data(self, user_id, data):
                self.update(data)

            def get_chat_data(self):
                pass

            def get_bot_data(self):
                pass

            def get_user_data(self):
                pass

            def get_conversations(self, name):
                pass

            def update_conversation(self, name, key, new_state):
                pass

        def callback(update, context):
            pass

        test_flag = False

        def error(update, context):
            nonlocal test_flag
            test_flag = str(context.error) == 'PersistenceError'
            raise Exception('ErrorHandlingError')

        def logger(message):
            assert 'uncaught error was raised while handling' in message

        update = Update(1,
                        message=Message(1,
                                        None,
                                        Chat(1, ''),
                                        from_user=User(1, '', False),
                                        text='Text'))
        handler = MessageHandler(Filters.all, callback)
        cdp.add_handler(handler)
        cdp.add_error_handler(error)
        monkeypatch.setattr(cdp.logger, 'exception', logger)

        cdp.persistence = OwnPersistence()
        cdp.process_update(update)
        assert test_flag
コード例 #46
0
 def setUp(self):
     self.message = Message(0, User(0, "Testuser"), datetime.now(),
                            Chat(0, 'private'))
     self.e = functools.partial(MessageEntity, offset=0, length=0)
コード例 #47
0
    def test_error_while_saving_chat_data(self, bot):
        increment = []

        class OwnPersistence(BasePersistence):
            def __init__(self):
                super().__init__()
                self.store_user_data = True
                self.store_chat_data = True
                self.store_bot_data = True

            def get_bot_data(self):
                return dict()

            def update_bot_data(self, data):
                raise Exception

            def get_chat_data(self):
                return defaultdict(dict)

            def update_chat_data(self, chat_id, data):
                raise Exception

            def get_user_data(self):
                return defaultdict(dict)

            def update_user_data(self, user_id, data):
                raise Exception

            def get_conversations(self, name):
                pass

            def update_conversation(self, name, key, new_state):
                pass

        def start1(b, u):
            pass

        def error(b, u, e):
            increment.append("error")

        # If updating a user_data or chat_data from a persistence object throws an error,
        # the error handler should catch it

        update = Update(
            1,
            message=Message(
                1,
                None,
                Chat(1, "lala"),
                from_user=User(1, "Test", False),
                text='/start',
                entities=[
                    MessageEntity(type=MessageEntity.BOT_COMMAND,
                                  offset=0,
                                  length=len('/start'))
                ],
                bot=bot,
            ),
        )
        my_persistence = OwnPersistence()
        dp = Dispatcher(bot,
                        None,
                        persistence=my_persistence,
                        use_context=False)
        dp.add_handler(CommandHandler('start', start1))
        dp.add_error_handler(error)
        dp.process_update(update)
        assert increment == ["error", "error", "error"]
コード例 #48
0
                      SuccessfulPayment)


@pytest.fixture(scope='class')
def message(bot):
    return Message(TestMessage.id,
                   TestMessage.from_user,
                   TestMessage.date,
                   TestMessage.chat,
                   bot=bot)


@pytest.fixture(
    scope='function',
    params=[{
        'forward_from': User(99, 'forward_user', False),
        'forward_date': datetime.now()
    }, {
        'forward_from_chat': Chat(-23, 'channel'),
        'forward_from_message_id': 101,
        'forward_date': datetime.now()
    }, {
        'reply_to_message': Message(50, None, None, None)
    }, {
        'edit_date': datetime.now()
    }, {
        'text':
        'a text message',
        'enitites':
        [MessageEntity('bold', 10, 4),
         MessageEntity('italic', 16, 7)]
コード例 #49
0
class TestMessage(object):
    id = 1
    from_user = User(2, 'testuser', False)
    date = datetime.now()
    chat = Chat(3, 'private')
    test_entities = [{
        'length': 4,
        'offset': 10,
        'type': 'bold'
    }, {
        'length': 7,
        'offset': 16,
        'type': 'italic'
    }, {
        'length': 4,
        'offset': 25,
        'type': 'code'
    }, {
        'length': 5,
        'offset': 31,
        'type': 'text_link',
        'url': 'http://github.com/'
    }, {
        'length': 3,
        'offset': 41,
        'type': 'pre'
    }, {
        'length': 17,
        'offset': 46,
        'type': 'url'
    }]
    test_text = 'Test for <bold, ita_lic, code, links and pre. http://google.com'
    test_message = Message(
        message_id=1,
        from_user=None,
        date=None,
        chat=None,
        text=test_text,
        entities=[MessageEntity(**e) for e in test_entities],
        caption=test_text,
        caption_entities=[MessageEntity(**e) for e in test_entities])

    def test_all_posibilities_de_json_and_to_dict(self, bot, message_params):
        new = Message.de_json(message_params.to_dict(), bot)

        assert new.to_dict() == message_params.to_dict()

    def test_dict_approach(self, message):
        assert message['date'] == message.date
        assert message['chat_id'] == message.chat_id
        assert message['no_key'] is None

    def test_parse_entity(self):
        text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
                b'\\u200d\\U0001f467\\U0001f431http://google.com'
                ).decode('unicode-escape')
        entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
        message = Message(1,
                          self.from_user,
                          self.date,
                          self.chat,
                          text=text,
                          entities=[entity])
        assert message.parse_entity(entity) == 'http://google.com'

    def test_parse_caption_entity(self):
        caption = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
                   b'\\u200d\\U0001f467\\U0001f431http://google.com'
                   ).decode('unicode-escape')
        entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
        message = Message(1,
                          self.from_user,
                          self.date,
                          self.chat,
                          caption=caption,
                          caption_entities=[entity])
        assert message.parse_caption_entity(entity) == 'http://google.com'

    def test_parse_entities(self):
        text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
                b'\\u200d\\U0001f467\\U0001f431http://google.com'
                ).decode('unicode-escape')
        entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
        entity_2 = MessageEntity(type=MessageEntity.BOLD, offset=13, length=1)
        message = Message(1,
                          self.from_user,
                          self.date,
                          self.chat,
                          text=text,
                          entities=[entity_2, entity])
        assert message.parse_entities(MessageEntity.URL) == {
            entity: 'http://google.com'
        }
        assert message.parse_entities() == {
            entity: 'http://google.com',
            entity_2: 'h'
        }

    def test_parse_caption_entities(self):
        text = (b'\\U0001f469\\u200d\\U0001f469\\u200d\\U0001f467'
                b'\\u200d\\U0001f467\\U0001f431http://google.com'
                ).decode('unicode-escape')
        entity = MessageEntity(type=MessageEntity.URL, offset=13, length=17)
        entity_2 = MessageEntity(type=MessageEntity.BOLD, offset=13, length=1)
        message = Message(1,
                          self.from_user,
                          self.date,
                          self.chat,
                          caption=text,
                          caption_entities=[entity_2, entity])
        assert message.parse_caption_entities(MessageEntity.URL) == {
            entity: 'http://google.com'
        }
        assert message.parse_caption_entities() == {
            entity: 'http://google.com',
            entity_2: 'h'
        }

    def test_text_html_simple(self):
        test_html_string = (
            'Test for &lt;<b>bold</b>, <i>ita_lic</i>, <code>code</code>, '
            '<a href="http://github.com/">links</a> and <pre>pre</pre>. '
            'http://google.com')
        text_html = self.test_message.text_html
        assert text_html == test_html_string

    def test_text_html_urled(self):
        test_html_string = (
            'Test for &lt;<b>bold</b>, <i>ita_lic</i>, <code>code</code>, '
            '<a href="http://github.com/">links</a> and <pre>pre</pre>. '
            '<a href="http://google.com">http://google.com</a>')
        text_html = self.test_message.text_html_urled
        assert text_html == test_html_string

    def test_text_markdown_simple(self):
        test_md_string = (
            'Test for <*bold*, _ita\_lic_, `code`, [links](http://github.com/) and '
            '```pre```. http://google.com')
        text_markdown = self.test_message.text_markdown
        assert text_markdown == test_md_string

    def test_text_markdown_urled(self):
        test_md_string = (
            'Test for <*bold*, _ita\_lic_, `code`, [links](http://github.com/) and '
            '```pre```. [http://google.com](http://google.com)')
        text_markdown = self.test_message.text_markdown_urled
        assert text_markdown == test_md_string

    def test_text_html_emoji(self):
        text = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode(
            'unicode-escape')
        expected = b'\\U0001f469\\u200d\\U0001f469\\u200d <b>ABC</b>'.decode(
            'unicode-escape')
        bold_entity = MessageEntity(type=MessageEntity.BOLD,
                                    offset=7,
                                    length=3)
        message = Message(1,
                          self.from_user,
                          self.date,
                          self.chat,
                          text=text,
                          entities=[bold_entity])
        assert expected == message.text_html

    def test_text_markdown_emoji(self):
        text = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode(
            'unicode-escape')
        expected = b'\\U0001f469\\u200d\\U0001f469\\u200d *ABC*'.decode(
            'unicode-escape')
        bold_entity = MessageEntity(type=MessageEntity.BOLD,
                                    offset=7,
                                    length=3)
        message = Message(1,
                          self.from_user,
                          self.date,
                          self.chat,
                          text=text,
                          entities=[bold_entity])
        assert expected == message.text_markdown

    def test_caption_html_simple(self):
        test_html_string = (
            'Test for &lt;<b>bold</b>, <i>ita_lic</i>, <code>code</code>, '
            '<a href="http://github.com/">links</a> and <pre>pre</pre>. '
            'http://google.com')
        caption_html = self.test_message.caption_html
        assert caption_html == test_html_string

    def test_caption_html_urled(self):
        test_html_string = (
            'Test for &lt;<b>bold</b>, <i>ita_lic</i>, <code>code</code>, '
            '<a href="http://github.com/">links</a> and <pre>pre</pre>. '
            '<a href="http://google.com">http://google.com</a>')
        caption_html = self.test_message.caption_html_urled
        assert caption_html == test_html_string

    def test_caption_markdown_simple(self):
        test_md_string = (
            'Test for <*bold*, _ita\_lic_, `code`, [links](http://github.com/) and '
            '```pre```. http://google.com')
        caption_markdown = self.test_message.caption_markdown
        assert caption_markdown == test_md_string

    def test_caption_markdown_urled(self):
        test_md_string = (
            'Test for <*bold*, _ita\_lic_, `code`, [links](http://github.com/) and '
            '```pre```. [http://google.com](http://google.com)')
        caption_markdown = self.test_message.caption_markdown_urled
        assert caption_markdown == test_md_string

    def test_caption_html_emoji(self):
        caption = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode(
            'unicode-escape')
        expected = b'\\U0001f469\\u200d\\U0001f469\\u200d <b>ABC</b>'.decode(
            'unicode-escape')
        bold_entity = MessageEntity(type=MessageEntity.BOLD,
                                    offset=7,
                                    length=3)
        message = Message(1,
                          self.from_user,
                          self.date,
                          self.chat,
                          caption=caption,
                          caption_entities=[bold_entity])
        assert expected == message.caption_html

    def test_caption_markdown_emoji(self):
        caption = b'\\U0001f469\\u200d\\U0001f469\\u200d ABC'.decode(
            'unicode-escape')
        expected = b'\\U0001f469\\u200d\\U0001f469\\u200d *ABC*'.decode(
            'unicode-escape')
        bold_entity = MessageEntity(type=MessageEntity.BOLD,
                                    offset=7,
                                    length=3)
        message = Message(1,
                          self.from_user,
                          self.date,
                          self.chat,
                          caption=caption,
                          caption_entities=[bold_entity])
        assert expected == message.caption_markdown

    def test_parse_entities_url_emoji(self):
        url = b'http://github.com/?unicode=\\u2713\\U0001f469'.decode(
            'unicode-escape')
        text = 'some url'
        link_entity = MessageEntity(type=MessageEntity.URL,
                                    offset=0,
                                    length=8,
                                    url=url)
        message = Message(1,
                          self.from_user,
                          self.date,
                          self.chat,
                          text=text,
                          entities=[link_entity])
        assert message.parse_entities() == {link_entity: text}
        assert next(iter(message.parse_entities())).url == url

    def test_chat_id(self, message):
        assert message.chat_id == message.chat.id

    def test_effective_attachment(self, message_params):
        for i in ('audio', 'game', 'document', 'photo', 'sticker', 'video',
                  'voice', 'video_note', 'contact', 'location', 'venue',
                  'invoice', 'invoice', 'successful_payment'):
            item = getattr(message_params, i, None)
            if item:
                break
        else:
            item = None
        assert message_params.effective_attachment == item

    def test_reply_text(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            text = args[2] == 'test'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and text and reply

        monkeypatch.setattr('telegram.Bot.send_message', test)
        assert message.reply_text('test')
        assert message.reply_text('test', quote=True)
        assert message.reply_text('test',
                                  reply_to_message_id=message.message_id,
                                  quote=True)

    def test_reply_markdown(self, monkeypatch, message):
        test_md_string = (
            'Test for <*bold*, _ita\_lic_, `code`, [links](http://github.com/) and '
            '```pre```. http://google.com')

        def test(*args, **kwargs):
            cid = args[1] == message.chat_id
            markdown_text = args[2] == test_md_string
            markdown_enabled = kwargs['parse_mode'] == ParseMode.MARKDOWN
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return all([cid, markdown_text, reply, markdown_enabled])

        text_markdown = self.test_message.text_markdown
        assert text_markdown == test_md_string

        monkeypatch.setattr('telegram.Bot.send_message', test)
        assert message.reply_markdown(self.test_message.text_markdown)
        assert message.reply_markdown(self.test_message.text_markdown,
                                      quote=True)
        assert message.reply_markdown(self.test_message.text_markdown,
                                      reply_to_message_id=message.message_id,
                                      quote=True)

    def test_reply_html(self, monkeypatch, message):
        test_html_string = (
            'Test for &lt;<b>bold</b>, <i>ita_lic</i>, <code>code</code>, '
            '<a href="http://github.com/">links</a> and <pre>pre</pre>. '
            'http://google.com')

        def test(*args, **kwargs):
            cid = args[1] == message.chat_id
            html_text = args[2] == test_html_string
            html_enabled = kwargs['parse_mode'] == ParseMode.HTML
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return all([cid, html_text, reply, html_enabled])

        text_html = self.test_message.text_html
        assert text_html == test_html_string

        monkeypatch.setattr('telegram.Bot.send_message', test)
        assert message.reply_html(self.test_message.text_html)
        assert message.reply_html(self.test_message.text_html, quote=True)
        assert message.reply_html(self.test_message.text_html,
                                  reply_to_message_id=message.message_id,
                                  quote=True)

    def test_reply_media_group(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            media = kwargs['media'] == 'reply_media_group'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and media and reply

        monkeypatch.setattr('telegram.Bot.send_media_group', test)
        assert message.reply_media_group(media='reply_media_group')
        assert message.reply_media_group(media='reply_media_group', quote=True)

    def test_reply_photo(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            photo = kwargs['photo'] == 'test_photo'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and photo and reply

        monkeypatch.setattr('telegram.Bot.send_photo', test)
        assert message.reply_photo(photo='test_photo')
        assert message.reply_photo(photo='test_photo', quote=True)

    def test_reply_audio(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            audio = kwargs['audio'] == 'test_audio'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and audio and reply

        monkeypatch.setattr('telegram.Bot.send_audio', test)
        assert message.reply_audio(audio='test_audio')
        assert message.reply_audio(audio='test_audio', quote=True)

    def test_reply_document(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            document = kwargs['document'] == 'test_document'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and document and reply

        monkeypatch.setattr('telegram.Bot.send_document', test)
        assert message.reply_document(document='test_document')
        assert message.reply_document(document='test_document', quote=True)

    def test_reply_sticker(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            sticker = kwargs['sticker'] == 'test_sticker'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and sticker and reply

        monkeypatch.setattr('telegram.Bot.send_sticker', test)
        assert message.reply_sticker(sticker='test_sticker')
        assert message.reply_sticker(sticker='test_sticker', quote=True)

    def test_reply_video(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            video = kwargs['video'] == 'test_video'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and video and reply

        monkeypatch.setattr('telegram.Bot.send_video', test)
        assert message.reply_video(video='test_video')
        assert message.reply_video(video='test_video', quote=True)

    def test_reply_video_note(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            video_note = kwargs['video_note'] == 'test_video_note'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and video_note and reply

        monkeypatch.setattr('telegram.Bot.send_video_note', test)
        assert message.reply_video_note(video_note='test_video_note')
        assert message.reply_video_note(video_note='test_video_note',
                                        quote=True)

    def test_reply_voice(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            voice = kwargs['voice'] == 'test_voice'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and voice and reply

        monkeypatch.setattr('telegram.Bot.send_voice', test)
        assert message.reply_voice(voice='test_voice')
        assert message.reply_voice(voice='test_voice', quote=True)

    def test_reply_location(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            location = kwargs['location'] == 'test_location'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and location and reply

        monkeypatch.setattr('telegram.Bot.send_location', test)
        assert message.reply_location(location='test_location')
        assert message.reply_location(location='test_location', quote=True)

    def test_reply_venue(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            venue = kwargs['venue'] == 'test_venue'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and venue and reply

        monkeypatch.setattr('telegram.Bot.send_venue', test)
        assert message.reply_venue(venue='test_venue')
        assert message.reply_venue(venue='test_venue', quote=True)

    def test_reply_contact(self, monkeypatch, message):
        def test(*args, **kwargs):
            id = args[1] == message.chat_id
            contact = kwargs['contact'] == 'test_contact'
            if kwargs.get('reply_to_message_id'):
                reply = kwargs['reply_to_message_id'] == message.message_id
            else:
                reply = True
            return id and contact and reply

        monkeypatch.setattr('telegram.Bot.send_contact', test)
        assert message.reply_contact(contact='test_contact')
        assert message.reply_contact(contact='test_contact', quote=True)

    def test_forward(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == 123456
            from_chat = kwargs['from_chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            if kwargs.get('disable_notification'):
                notification = kwargs['disable_notification'] is True
            else:
                notification = True
            return chat_id and from_chat and message_id and notification

        monkeypatch.setattr('telegram.Bot.forward_message', test)
        assert message.forward(123456)
        assert message.forward(123456, disable_notification=True)
        assert not message.forward(635241)

    def test_edit_text(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            text = kwargs['text'] == 'test'
            return chat_id and message_id and text

        monkeypatch.setattr('telegram.Bot.edit_message_text', test)
        assert message.edit_text(text='test')

    def test_edit_caption(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            caption = kwargs['caption'] == 'new caption'
            return chat_id and message_id and caption

        monkeypatch.setattr('telegram.Bot.edit_message_caption', test)
        assert message.edit_caption(caption='new caption')

    def test_edit_reply_markup(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            reply_markup = kwargs['reply_markup'] == [['1', '2']]
            return chat_id and message_id and reply_markup

        monkeypatch.setattr('telegram.Bot.edit_message_reply_markup', test)
        assert message.edit_reply_markup(reply_markup=[['1', '2']])

    def test_delete(self, monkeypatch, message):
        def test(*args, **kwargs):
            chat_id = kwargs['chat_id'] == message.chat_id
            message_id = kwargs['message_id'] == message.message_id
            return chat_id and message_id

        monkeypatch.setattr('telegram.Bot.delete_message', test)
        assert message.delete()

    def test_equality(self):
        id = 1
        a = Message(id, self.from_user, self.date, self.chat)
        b = Message(id, self.from_user, self.date, self.chat)
        c = Message(id, User(0, '', False), self.date, self.chat)
        d = Message(0, self.from_user, self.date, self.chat)
        e = Update(id)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
コード例 #50
0
def update(bot):
    user = User(id=321, first_name='test_user', is_bot=False)
    chat = Chat(id=123, type='group')
    message = Message(1, user, None, chat, text="Hi there", bot=bot)
    return Update(0, message=message)
コード例 #51
0
def user(bot):
    return User(id=TestUser.id, first_name=TestUser.first_name, is_bot=TestUser.is_bot,
                last_name=TestUser.last_name, username=TestUser.username,
                language_code=TestUser.language_code, bot=bot)
コード例 #52
0
class TestShippingQuery:
    id_ = 5
    invoice_payload = 'invoice_payload'
    from_user = User(0, '', False)
    shipping_address = ShippingAddress('GB', '', 'London',
                                       '12 Grimmauld Place', '', 'WC1')

    def test_de_json(self, bot):
        json_dict = {
            'id': TestShippingQuery.id_,
            'invoice_payload': TestShippingQuery.invoice_payload,
            'from': TestShippingQuery.from_user.to_dict(),
            'shipping_address': TestShippingQuery.shipping_address.to_dict(),
        }
        shipping_query = ShippingQuery.de_json(json_dict, bot)

        assert shipping_query.id == self.id_
        assert shipping_query.invoice_payload == self.invoice_payload
        assert shipping_query.from_user == self.from_user
        assert shipping_query.shipping_address == self.shipping_address
        assert shipping_query.bot is bot

    def test_to_dict(self, shipping_query):
        shipping_query_dict = shipping_query.to_dict()

        assert isinstance(shipping_query_dict, dict)
        assert shipping_query_dict['id'] == shipping_query.id
        assert shipping_query_dict[
            'invoice_payload'] == shipping_query.invoice_payload
        assert shipping_query_dict['from'] == shipping_query.from_user.to_dict(
        )
        assert shipping_query_dict[
            'shipping_address'] == shipping_query.shipping_address.to_dict()

    def test_answer(self, monkeypatch, shipping_query):
        answer_shipping_query = shipping_query.bot.answer_shipping_query

        def make_assertion(*_, **kwargs):
            return kwargs[
                'shipping_query_id'] == shipping_query.id and check_shortcut_call(
                    kwargs, answer_shipping_query)

        assert check_shortcut_signature(ShippingQuery.answer,
                                        Bot.answer_shipping_query,
                                        ['shipping_query_id'], [])

        monkeypatch.setattr(shipping_query.bot, 'answer_shipping_query',
                            make_assertion)
        assert shipping_query.answer(ok=True)

    def test_equality(self):
        a = ShippingQuery(self.id_, self.from_user, self.invoice_payload,
                          self.shipping_address)
        b = ShippingQuery(self.id_, self.from_user, self.invoice_payload,
                          self.shipping_address)
        c = ShippingQuery(self.id_, None, '', None)
        d = ShippingQuery(0, self.from_user, self.invoice_payload,
                          self.shipping_address)
        e = Update(self.id_)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
コード例 #53
0
def user2():
    return User(first_name='Mister Test', id=124, is_bot=False)
コード例 #54
0
def user():
    return User(1, 'First name', False)
コード例 #55
0
def user1():
    return User(first_name='Misses Test', id=123, is_bot=False)
コード例 #56
0
def message(bot):
    return Message(1, User(1, '', False), None, Chat(1, ''), bot=bot)
コード例 #57
0
class TestShippingQuery(object):
    id = 5
    invoice_payload = 'invoice_payload'
    from_user = User(0, '', False)
    shipping_address = ShippingAddress('GB', '', 'London',
                                       '12 Grimmauld Place', '', 'WC1')

    def test_de_json(self, bot):
        json_dict = {
            'id': TestShippingQuery.id,
            'invoice_payload': TestShippingQuery.invoice_payload,
            'from': TestShippingQuery.from_user.to_dict(),
            'shipping_address': TestShippingQuery.shipping_address.to_dict()
        }
        shipping_query = ShippingQuery.de_json(json_dict, bot)

        assert shipping_query.id == self.id
        assert shipping_query.invoice_payload == self.invoice_payload
        assert shipping_query.from_user == self.from_user
        assert shipping_query.shipping_address == self.shipping_address

    @staticmethod
    def test_to_dict(shipping_query):
        shipping_query_dict = shipping_query.to_dict()

        assert isinstance(shipping_query_dict, dict)
        assert shipping_query_dict['id'] == shipping_query.id
        assert shipping_query_dict[
            'invoice_payload'] == shipping_query.invoice_payload
        assert shipping_query_dict['from'] == shipping_query.from_user.to_dict(
        )
        assert shipping_query_dict[
            'shipping_address'] == shipping_query.shipping_address.to_dict()

    @staticmethod
    def test_answer(monkeypatch, shipping_query):
        def test(*args, **kwargs):
            return args[1] == shipping_query.id

        monkeypatch.setattr('telegram.Bot.answer_shipping_query', test)
        assert shipping_query.answer()

    def test_equality(self):
        a = ShippingQuery(self.id, self.from_user, self.invoice_payload,
                          self.shipping_address)
        b = ShippingQuery(self.id, self.from_user, self.invoice_payload,
                          self.shipping_address)
        c = ShippingQuery(self.id, None, '', None)
        d = ShippingQuery(0, self.from_user, self.invoice_payload,
                          self.shipping_address)
        e = Update(self.id)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
コード例 #58
0
 def setUp(self):
     self.message = Message(0, User(0, "Testuser"), datetime.now(),
                            Chat(0, 'private'))
     self.update = Update(0, message=self.message)
コード例 #59
0
ファイル: message.py プロジェクト: o0khoiclub0o/thimbot
    def de_json(data):
        if 'from' in data:  # from is a reserved word, use from_user instead.
            from telegram import User
            from_user = User.de_json(data['from'])
        else:
            from_user = None

        if 'date' in data:
            date = datetime.fromtimestamp(data['date'])
        else:
            date = None

        if 'chat' in data:
            if 'first_name' in data['chat']:
                from telegram import User
                chat = User.de_json(data['chat'])
            if 'title' in data['chat']:
                from telegram import GroupChat
                chat = GroupChat.de_json(data['chat'])
        else:
            chat = None

        if 'forward_from' in data:
            from telegram import User
            forward_from = User.de_json(data['forward_from'])
        else:
            forward_from = None

        if 'forward_date' in data:
            forward_date = datetime.fromtimestamp(data['forward_date'])
        else:
            forward_date = None

        if 'reply_to_message' in data:
            reply_to_message = Message.de_json(data['reply_to_message'])
        else:
            reply_to_message = None

        if 'audio' in data:
            from telegram import Audio
            audio = Audio.de_json(data['audio'])
        else:
            audio = None

        if 'document' in data:
            from telegram import Document
            document = Document.de_json(data['document'])
        else:
            document = None

        if 'photo' in data:
            from telegram import PhotoSize
            photo = [PhotoSize.de_json(x) for x in data['photo']]
        else:
            photo = None

        if 'sticker' in data:
            from telegram import Sticker
            sticker = Sticker.de_json(data['sticker'])
        else:
            sticker = None

        if 'video' in data:
            from telegram import Video
            video = Video.de_json(data['video'])
        else:
            video = None

        if 'voice' in data:
            from telegram import Voice
            voice = Voice.de_json(data['voice'])
        else:
            voice = None

        if 'contact' in data:
            from telegram import Contact
            contact = Contact.de_json(data['contact'])
        else:
            contact = None

        if 'location' in data:
            from telegram import Location
            location = Location.de_json(data['location'])
        else:
            location = None

        if 'new_chat_participant' in data:
            from telegram import User
            new_chat_participant = User.de_json(data['new_chat_participant'])
        else:
            new_chat_participant = None

        if 'left_chat_participant' in data:
            from telegram import User
            left_chat_participant = User.de_json(data['left_chat_participant'])
        else:
            left_chat_participant = None

        if 'new_chat_photo' in data:
            from telegram import PhotoSize
            new_chat_photo = \
                [PhotoSize.de_json(x) for x in data['new_chat_photo']]
        else:
            new_chat_photo = None

        return Message(message_id=data.get('message_id', None),
                       from_user=from_user,
                       date=date,
                       chat=chat,
                       forward_from=forward_from,
                       forward_date=forward_date,
                       reply_to_message=reply_to_message,
                       text=data.get('text', ''),
                       audio=audio,
                       document=document,
                       photo=photo,
                       sticker=sticker,
                       video=video,
                       voice=voice,
                       caption=data.get('caption', ''),
                       contact=contact,
                       location=location,
                       new_chat_participant=new_chat_participant,
                       left_chat_participant=left_chat_participant,
                       new_chat_title=data.get('new_chat_title', None),
                       new_chat_photo=new_chat_photo,
                       delete_chat_photo=data.get('delete_chat_photo', None),
                       group_chat_created=data.get('group_chat_created', None))
コード例 #60
0
class TestPreCheckoutQuery(object):
    id = 5
    invoice_payload = 'invoice_payload'
    shipping_option_id = 'shipping_option_id'
    currency = 'EUR'
    total_amount = 100
    from_user = User(0, '')
    order_info = OrderInfo()

    def test_de_json(self, bot):
        json_dict = {
            'id': self.id,
            'invoice_payload': self.invoice_payload,
            'shipping_option_id': self.shipping_option_id,
            'currency': self.currency,
            'total_amount': self.total_amount,
            'from': self.from_user.to_dict(),
            'order_info': self.order_info.to_dict()
        }
        pre_checkout_query = PreCheckoutQuery.de_json(json_dict, bot)

        assert pre_checkout_query.id == self.id
        assert pre_checkout_query.invoice_payload == self.invoice_payload
        assert pre_checkout_query.shipping_option_id == self.shipping_option_id
        assert pre_checkout_query.currency == self.currency
        assert pre_checkout_query.from_user == self.from_user
        assert pre_checkout_query.order_info == self.order_info

    def test_to_dict(self, pre_checkout_query):
        pre_checkout_query_dict = pre_checkout_query.to_dict()

        assert isinstance(pre_checkout_query_dict, dict)
        assert pre_checkout_query_dict['id'] == pre_checkout_query.id
        assert pre_checkout_query_dict['invoice_payload'] == pre_checkout_query.invoice_payload
        assert pre_checkout_query_dict['shipping_option_id'] == \
               pre_checkout_query.shipping_option_id
        assert pre_checkout_query_dict['currency'] == pre_checkout_query.currency
        assert pre_checkout_query_dict['from'] == pre_checkout_query.from_user.to_dict()
        assert pre_checkout_query_dict['order_info'] == pre_checkout_query.order_info.to_dict()

    def test_answer(self, monkeypatch, pre_checkout_query):
        def test(*args, **kwargs):
            return args[1] == pre_checkout_query.id

        monkeypatch.setattr('telegram.Bot.answer_pre_checkout_query', test)
        assert pre_checkout_query.answer()

    def test_equality(self):
        a = PreCheckoutQuery(self.id, self.from_user, self.currency, self.total_amount,
                             self.invoice_payload)
        b = PreCheckoutQuery(self.id, self.from_user, self.currency, self.total_amount,
                             self.invoice_payload)
        c = PreCheckoutQuery(self.id, None, '', 0, '')
        d = PreCheckoutQuery(0, self.from_user, self.currency, self.total_amount,
                             self.invoice_payload)
        e = Update(self.id)

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)