def test_get_yes_no_filters_and_proceed(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.set_chat_id(1) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text=YES) message.chat = chat update.message = message data = c.get_yes_no_filters_and_proceed(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == TelegramConversation.STATUS.BUILD_FILTERS message = Message(1, timezone.now(), chat=chat, text=NO) message.chat = chat update.message = message data = c.get_yes_no_filters_and_proceed(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == TelegramConversation.STATUS.BUILD_AGGREGATE_YES_NO
def adapt_channel_post(self, update: Update, context: CallbackContext) -> None: """ Method to modify :py:class:telegram.Update containing channel message, so that it can be handled a a normal received message. Dispatches modified update again. Args: update: context: Returns: """ if update.channel_post: update.message = update.channel_post update.channel_post = None elif update.edited_channel_post: update.message = update.edited_channel_post update.edited_channel_post = None entities = update.message.parse_entities() for entity in entities: if entity.type == entity.MENTION and context.bot.username == entities[ entity][1:]: # Strip mention from message update.message.text = ( update.message.text[0:entity.offset] + update.message.text[entity.offset + entity.length:]).strip() self.updater.dispatcher.process_update(update) return
def test_get_mode_show_mode_options_w_f_and_c(mocker): log = logging.getLogger() c = ConvTestFiltersCommands(log, 'created_at', suffix='dev') c.set_chat_id(1) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) mocker.patch('os.listdir', return_value=["x.py"]) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text=BTN_CAPTION_BUILD_QUERY) message.chat = chat update.message = message data = c.get_mode_show_mode_options(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == TelegramConversation.STATUS.BUILD_PERIOD message = Message(1, timezone.now(), chat=chat, text=BTN_CAPTION_USE_SAVED_FILTER) message.chat = chat update.message = message data = c.get_mode_show_mode_options(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == TelegramConversation.STATUS.SAVED_FILTER_SELECT message = Message(1, timezone.now(), chat=chat, text=BTN_CAPTION_CUSTOM_MGMT) message.chat = chat update.message = message data = c.get_mode_show_mode_options(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == TelegramConversation.STATUS.CUSTOM_MGMT_COMMAND_SELECT
def test_webhook(self): print('Testing Webhook') self._setup_updater('', messages=0) 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, url_path='TOKEN', cert='./tests/test_updater.py', key='./tests/test_updater.py') 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(), Chat(1, "group", title="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 functionalities...") 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)
def test_effective_message_type(self): test_message = Message(message_id=1, from_user=None, date=None, chat=None) test_message.text = 'Test' assert helpers.effective_message_type(test_message) == 'text' test_message.text = None test_message.sticker = Sticker('sticker_id', 50, 50) assert helpers.effective_message_type(test_message) == 'sticker' test_message.sticker = None test_message.new_chat_members = [User(55, 'new_user', False)] assert helpers.effective_message_type( test_message) == 'new_chat_members' test_update = Update(1) test_message.text = 'Test' test_update.message = test_message assert helpers.effective_message_type(test_update) == 'text' empty_update = Update(2) assert helpers.effective_message_type(empty_update) is None
def test_authorized_only(default_conf, mocker, caplog) -> None: patch_coinmarketcap(mocker) patch_exchange(mocker, None) chat = Chat(0, 0) update = Update(randint(1, 100)) update.message = Message(randint(1, 100), 0, datetime.utcnow(), chat) default_conf['telegram']['enabled'] = False bot = FreqtradeBot(default_conf) patch_get_signal(bot, (True, False)) dummy = DummyCls(bot) dummy.dummy_handler(bot=MagicMock(), update=update) assert dummy.state['called'] is True assert log_has( 'Executing handler: dummy_handler for chat_id: 0', caplog.record_tuples ) assert not log_has( 'Rejected unauthorized message from: 0', caplog.record_tuples ) assert not log_has( 'Exception occurred within Telegram module', caplog.record_tuples )
def test_webhook(self): print('Testing Webhook') self._setup_updater('', messages=0) 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, url_path='TOKEN', cert='./tests/test_updater.py', key='./tests/test_updater.py') 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(), Chat(1, "group", title="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 functionalities...") 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)
def typing_dates_error(update: Update, context, message=s.typing_dates_error): context.bot.send_message(chat_id=update.effective_chat.id, text=message, parse_mode=ParseMode.HTML) update.message = None select_start_date(update, context) return TYPING_DATES
def test_webhook_no_ssl(self): print("Testing Webhook without SSL") 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) sleep(0.5) # Now, we send an update to the server via urlopen message = Message(1, User(1, "Tester 2"), datetime.now(), GroupChat(1, "Test Group 2")) message.text = "Webhook Test 2" 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/" % port, data=payload, headers=header) urlopen(r) sleep(1) self.assertEqual(self.received_message, "Webhook Test 2")
def test_effective_message_type(self): def build_test_message(**kwargs): config = dict( message_id=1, from_user=None, date=None, chat=None, ) config.update(**kwargs) return Message(**config) test_message = build_test_message(text='Test') assert helpers.effective_message_type(test_message) == 'text' test_message.text = None test_message = build_test_message(sticker=Sticker('sticker_id', 'unique_id', 50, 50, False)) assert helpers.effective_message_type(test_message) == 'sticker' test_message.sticker = None test_message = build_test_message(new_chat_members=[User(55, 'new_user', False)]) assert helpers.effective_message_type(test_message) == 'new_chat_members' test_message = build_test_message(left_chat_member=[User(55, 'new_user', False)]) assert helpers.effective_message_type(test_message) == 'left_chat_member' test_update = Update(1) test_message = build_test_message(text='Test') test_update.message = test_message assert helpers.effective_message_type(test_update) == 'text' empty_update = Update(2) assert helpers.effective_message_type(empty_update) is None
def test_execute_command_exception(mocker): log = logging.getLogger() c = ConvTestFiltersCommands(log, 'created_at', suffix='dev') c.set_chat_id(1) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) mocker.patch( DJANGO_CALL_COMMAND, side_effect=Exception('ERROR'), ) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text='10') message.chat = chat update.message = message data = c.execute_custom_command(update, 'xx') assert mock.called assert mock.call_args[0] == ("``` Error xx:\nERROR ```", ) assert data is False assert c.query_context == { 'mode': '', 'period': { 'uom': '', 'quantity': 0, 'timedelta': None, }, 'filters': [], 'aggregate': { 'type': '', 'property': '', }, 'saved': '', 'custom_command': '', }
def test_authorized_only_exception(default_conf, mocker, caplog) -> None: """ Test authorized_only() method when an exception is thrown """ patch_get_signal(mocker, (True, False)) patch_coinmarketcap(mocker) mocker.patch('freqtrade.freqtradebot.exchange.init', MagicMock()) update = Update(randint(1, 100)) update.message = Message(randint(1, 100), 0, datetime.utcnow(), Chat(0, 0)) conf = deepcopy(default_conf) conf['telegram']['enabled'] = False dummy = DummyCls(FreqtradeBot(conf, create_engine('sqlite://'))) dummy.dummy_exception(bot=MagicMock(), update=update) assert dummy.state['called'] is False assert not log_has( 'Executing handler: dummy_handler for chat_id: 0', caplog.record_tuples ) assert not log_has( 'Rejected unauthorized message from: 0', caplog.record_tuples ) assert log_has( 'Exception occurred within Telegram module', caplog.record_tuples )
def test_get_mode_show_mode_options(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.set_chat_id(1) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text=BTN_CAPTION_BUILD_QUERY) message.chat = chat update.message = message data = c.get_mode_show_mode_options(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == TelegramConversation.STATUS.BUILD_PERIOD message = Message(1, timezone.now(), chat=chat, text=BTN_CAPTION_USE_SAVED_FILTER) message.chat = chat update.message = message data = c.get_mode_show_mode_options(update, None) assert mock.called assert mock.call_args[0] == ( '``` No saved filters found for this command ```', ) assert data == ConversationHandler.END message = Message(1, timezone.now(), chat=chat, text=BTN_CAPTION_CUSTOM_MGMT) message.chat = chat update.message = message data = c.get_mode_show_mode_options(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == ConversationHandler.END
def test_get_yes_no_aggregate_and_proceed(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.set_chat_id(1) c.set_query_period_uom(WEEKS) c.set_query_period_quantity(10) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text=YES) message.chat = chat update.message = message data = c.get_yes_no_aggregate_and_proceed(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == TelegramConversation.STATUS.BUILD_AGGREGATE fake_data = MockSet() for _i in range(1, 15): fake_data.add( MockModel( mock_name=f'name{_i}', id=f'id{_i}', name=f'name{_i}', status='pending', created_at=timezone.now(), )) mocker.patch( INITIAL_QUERY_SET_METHOD, return_value=fake_data, ) message = Message(1, timezone.now(), chat=chat, text=NO) message.chat = chat update.message = message data = c.get_yes_no_aggregate_and_proceed(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == ConversationHandler.END
def save_task(update: Update, context: CallbackContext, task_number: int, done: bool): current_list = context.user_data["current_list"] tasks = db.get_tasks(current_list["id"]) try: task = tasks[task_number - 1] except IndexError: update.message(f"Your task number is invalid - \"{task_number}\".") return ConversationHandler.END db.edit_task(id=task["id"], title=task["title"], done=done) user = update.message.from_user value = "done" if done else "undone" logger.info("User %s marked task \"%s\" as \"%s\".", user.first_name, task["title"], value) update.message.reply_text(f"Task \"{task_number}\" marked as {value}.") return ConversationHandler.END
def mockUpdate(self, text): message = Message(0, User(0, 'Testuser'), None, Chat(0, Chat.GROUP)) message.text = text update = Update(0) if self.edited: update.edited_message = message else: update.message = message return update
def mockUpdate(self, text): message = Message(0, None, None, None) message.text = text update = Update(0) if self.edited: update.edited_message = message else: update.message = message return update
def mockUpdate(self, text): message = Message(0, None, None, None) message.text = text update = Update(0) if self.edited: update.edited_message = message else: update.message = message return update
def test_authorized_only_exception(default_conf, mocker): mocker.patch.dict('freqtrade.rpc.telegram._CONF', default_conf) update = Update(randint(1, 100)) update.message = Message(randint(1, 100), 0, datetime.utcnow(), Chat(0, 0)) @authorized_only def dummy_handler(*args, **kwargs) -> None: raise Exception('test') dummy_handler(MagicMock(), update)
def mock_update(self, text): message = Message(0, User(0, 'Testuser'), None, Chat(0, Chat.GROUP), bot=self) message.text = text update = Update(0) if self.edited: update.edited_message = message else: update.message = message return update
def test_authorized_only_exception(default_conf, mocker): mocker.patch.dict('freqtrade.rpc.telegram._CONF', default_conf) update = Update(randint(1, 100)) update.message = Message(randint(1, 100), 0, datetime.utcnow(), Chat(0, 0)) @authorized_only def dummy_handler(*args, **kwargs) -> None: raise Exception('test') dummy_handler(MagicMock(), update)
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, url_path="TOKEN", cert="./tests/test_updater.py", key="./tests/test_updater.py" ) 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 functionalities...") 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)
def adapt_edited_message(self, update: Update, context: CallbackContext) -> None: """ Method to modify :py:class:telegram.Update containing edited message, so that it can be handled a a normal received message. Dispatches modified update again. Args: update: context: """ update.message = update.edited_message update.edited_message = None self.updater.dispatcher.process_update(update)
def test_authorized_only_unauthorized(default_conf, mocker): mocker.patch.dict('freqtrade.rpc.telegram._CONF', default_conf) chat = Chat(0xdeadbeef, 0) update = Update(randint(1, 100)) update.message = Message(randint(1, 100), 0, datetime.utcnow(), chat) state = {'called': False} @authorized_only def dummy_handler(*args, **kwargs) -> None: state['called'] = True dummy_handler(MagicMock(), update) assert state['called'] is False
def test_webhook(self): self._setup_updater('', messages=0) d = self.updater.dispatcher handler = MessageHandler([], self.telegramHandlerTest) d.addHandler(handler) ip = '127.0.0.1' port = randrange(1024, 49152) # Select random port for travis self.updater.start_webhook(ip, port, url_path='TOKEN', cert='./tests/test_updater.py', key='./tests/test_updater.py', webhook_url=None) 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(), Chat(1, "group", title="Test Group")) message.text = "Webhook Test" update = Update(1) update.message = message self._send_webhook_msg(ip, port, update.to_json(), 'TOKEN') sleep(1) self.assertEqual(self.received_message, 'Webhook Test') print("Test other webhook server functionalities...") response = self._send_webhook_msg(ip, port, None, 'webookhandler.py') self.assertEqual(b'', response.read()) self.assertEqual(200, response.code) response = self._send_webhook_msg( ip, port, None, 'webookhandler.py', get_method=lambda: 'HEAD') 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)
def test_get_saved_filter_and_proceed_no_user(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.model = MockModel c.get_saved_filter = lambda x: 1 mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text='saved_filter') message.chat = chat update = Update(1) update.message = message data = c.get_saved_filter_and_proceed(update, None) assert data is None
def test_webhook(self): self._setup_updater('', messages=0) d = self.updater.dispatcher handler = MessageHandler([], self.telegramHandlerTest) d.addHandler(handler) ip = '127.0.0.1' port = randrange(1024, 49152) # Select random port for travis self.updater.start_webhook(ip, port, url_path='TOKEN', cert='./tests/test_updater.py', key='./tests/test_updater.py', webhook_url=None) 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(), Chat(1, "group", title="Test Group")) message.text = "Webhook Test" update = Update(1) update.message = message self._send_webhook_msg(ip, port, update.to_json(), 'TOKEN') sleep(1) self.assertEqual(self.received_message, 'Webhook Test') print("Test other webhook server functionalities...") response = self._send_webhook_msg(ip, port, None, 'webookhandler.py') self.assertEqual(b'', response.read()) self.assertEqual(200, response.code) response = self._send_webhook_msg( ip, port, None, 'webookhandler.py', get_method=lambda: 'HEAD') 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)
def test_authorized_only_unauthorized(default_conf, mocker): mocker.patch.dict('freqtrade.rpc.telegram._CONF', default_conf) chat = Chat(0xdeadbeef, 0) update = Update(randint(1, 100)) update.message = Message(randint(1, 100), 0, datetime.utcnow(), chat) state = {'called': False} @authorized_only def dummy_handler(*args, **kwargs) -> None: state['called'] = True dummy_handler(MagicMock(), update) assert state['called'] is False
def test_get_saved_filter_and_proceed_no_filter_method(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.model = MockModel c.set_chat_id(1) mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text='unknown') message.chat = chat update.message = message with pytest.raises(SavedFilterNotFound): c.get_saved_filter_and_proceed(update, None)
def handle_lift(update: telegram.Update, job_queue): message = update.message assert isinstance(message, telegram.Message) reply_to = message.reply_to_message user_id = message.from_user.id if not isinstance(reply_to, telegram.Message): return error_message(message, job_queue, '需要回复一条消息来转换') elif reply_to.from_user.id == message.bot.id: return error_message(message, job_queue, '需要回复一条玩家发送的消息') elif reply_to.from_user.id == user_id or is_gm(message.chat_id, user_id): update.message = reply_to delete_message(update.message) return handle_message(message.bot, update, job_queue, lift=True) else: return error_message(message, job_queue, '你只能转换自己的消息,GM 能转换任何人的消息')
def test_authorized_only_unauthorized(default_conf, mocker, caplog) -> None: patch_exchange(mocker) chat = Chat(0xdeadbeef, 0) update = Update(randint(1, 100)) update.message = Message(randint(1, 100), 0, datetime.utcnow(), chat) default_conf['telegram']['enabled'] = False bot = FreqtradeBot(default_conf) patch_get_signal(bot, (True, False)) dummy = DummyCls(bot) dummy.dummy_handler(update=update, context=MagicMock()) assert dummy.state['called'] is False assert not log_has('Executing handler: dummy_handler for chat_id: 3735928559', caplog) assert log_has('Rejected unauthorized message from: 3735928559', caplog) assert not log_has('Exception occurred within Telegram module', caplog)
def test_cancel(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.set_chat_id(1) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat) message.chat = chat update.message = message data = c.cancel(update, None) assert mock.called assert mock.call_args[0] == ('``` End of conversation ```', ) assert data == ConversationHandler.END
def test_show_list_of_commands(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.set_chat_id(1) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text=WEEKS) message.chat = chat update.message = message data = c.show_list_of_commands(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == ConversationHandler.END
def test_show_mode_select(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.set_chat_id(1) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat) message.chat = chat update.message = message data = c.show_mode_select(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == TelegramConversation.STATUS.MODE_SELECTOR
def test_get_period_uom_show_quantity(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.set_chat_id(1) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text=WEEKS) message.chat = chat update.message = message data = c.get_period_uom_show_quantity(update, None) assert mock.called assert mock.call_args[0] != ( f'``` {TelegramConversation.EMPTY_RESULT} ```', ) assert data == TelegramConversation.STATUS.BUILD_PERIOD_QUANTITY assert c.query_period_uom == WEEKS
def test_get_aggregate_and_proceed_unknown(mocker): log = logging.getLogger() c = ConvTest(log, 'created_at', suffix='dev') c.set_query_period_uom(WEEKS) c.set_query_period_quantity(10) c.set_chat_id(1) mock = mocker.patch(TELEGRAM_REPLY_METHOD, return_value=None) update = Update(1) chat = Chat(1, 'user') message = Message(1, timezone.now(), chat=chat, text='unknown') message.chat = chat update.message = message data = c.get_aggregate_and_proceed(update, None) assert mock.called assert mock.call_args[0] == ('``` End of conversation ```', ) assert data == ConversationHandler.END
def command_accept_choice(self, bot: Bot, update: Update): query = update.callback_query update.message = query.message # because callback update doesn't have message at all chat_id = update.message.chat_id chosen_channel = self.chosen_channels.get(chat_id, None) if chosen_channel: chosen_channel.remove_commands_handlers(chat_id) chosen_channel: BaseChannel = self.channels[query.data] self.chosen_channels[chat_id] = chosen_channel chosen_channel.add_commands_handlers(chat_id) bot.edit_message_text( text=f'Chose {query.data} ({chosen_channel.channel_id}).', chat_id=query.message.chat_id, message_id=query.message.message_id) help = chosen_channel.help_text() update.message.reply_text('```\n' + help + '\n```', parse_mode=ParseMode.MARKDOWN)
def test_webhook_no_ssl(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addTelegramMessageHandler(self.telegramHandlerTest) ip = '127.0.0.1' port = randrange(1024, 49152) # Select random port for travis self.updater.start_webhook(ip, port) sleep(0.5) # Now, we send an update to the server via urlopen message = Message(1, User(1, "Tester 2"), datetime.now(), Chat(1, 'group', title="Test Group 2")) message.text = "Webhook Test 2" update = Update(1) update.message = message self._send_webhook_msg(ip, port, update.to_json()) sleep(1) self.assertEqual(self.received_message, 'Webhook Test 2')
def test_webhook_no_ssl(self): self._setup_updater('', messages=0) d = self.updater.dispatcher d.addTelegramMessageHandler( self.telegramHandlerTest) ip = '127.0.0.1' port = randrange(1024, 49152) # Select random port for travis self.updater.start_webhook(ip, port) sleep(0.5) # Now, we send an update to the server via urlopen message = Message(1, User(1, "Tester 2"), datetime.now(), Chat(1, 'group', title="Test Group 2")) message.text = "Webhook Test 2" update = Update(1) update.message = message self._send_webhook_msg(ip, port, update.to_json()) sleep(1) self.assertEqual(self.received_message, 'Webhook Test 2')
def test_webhook_no_ssl(self): print('Testing Webhook without SSL') self._setup_updater('', messages=0) 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) sleep(0.5) # Now, we send an update to the server via urlopen message = Message(1, User(1, "Tester 2"), datetime.now(), Chat(1, 'group', title="Test Group 2")) message.text = "Webhook Test 2" 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/' % port, data=payload, headers=header) urlopen(r) sleep(1) self.assertEqual(self.received_message, 'Webhook Test 2')
def test_effective_message_type(self): test_message = Message(message_id=1, from_user=None, date=None, chat=None) test_message.text = 'Test' assert helpers.effective_message_type(test_message) == 'text' test_message.text = None test_message.sticker = Sticker('sticker_id', 50, 50) assert helpers.effective_message_type(test_message) == 'sticker' test_message.sticker = None test_message.new_chat_members = [User(55, 'new_user', False)] assert helpers.effective_message_type(test_message) == 'new_chat_members' test_update = Update(1) test_message.text = 'Test' test_update.message = test_message assert helpers.effective_message_type(test_update) == 'text' empty_update = Update(2) assert helpers.effective_message_type(empty_update) is None
def mockUpdate(text): message = Message(0, None, None, None) message.text = text update = Update(0) update.message = message return update
def update(): _update = Update(0) _update.message = Message(0, 0, datetime.utcnow(), Chat(0, 0)) return _update