1# ruff: noqa: PT009
2import re
3import unittest
4from uuid import uuid4
5
6from telegram import InlineQueryResultArticle, InputTextMessageContent
7from telegram.constants import ParseMode
8from telegram.ext import InlineQueryHandler, Updater
9
10from ptbtest import InlineQueryGenerator, Mockbot
11
12"""
13This is an example to show how the ptbtest suite can be used.
14This example follows the timerbot example at:
15https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/inlinebot.py
16We will skip the start and help callbacks and focus on the inline query.
17
18"""
19
20
21class TestInlineBot(unittest.TestCase):
22 def setUp(self):
23 # For use within the tests we nee some stuff. Starting with a Mockbot
24 self.bot = Mockbot()
25 # And an InlineQueryGenerator and updater (for use with the bot.)
26 self.iqg = InlineQueryGenerator(self.bot)
27 self.updater = Updater(bot=self.bot)
28
29 def test_inline_bot(self):
30 # create some handlers and add them
31 def escape_markdown(text):
32 """Helper function to escape telegram markup symbols"""
33 escape_chars = r"\*_`\["
34 return re.sub(r"([%s])" % escape_chars, r"\\\1", text) # noqa: UP031
35
36 def inlinequery(update):
37 query = update.inline_query.query
38 results = []
39
40 results.append(
41 InlineQueryResultArticle(
42 id=uuid4(), title="Caps", input_message_content=InputTextMessageContent(query.upper())
43 )
44 )
45 results.append(
46 InlineQueryResultArticle(
47 id=uuid4(),
48 title="Bold",
49 input_message_content=InputTextMessageContent(
50 f"*{escape_markdown(query)}*", parse_mode=ParseMode.MARKDOWN
51 ),
52 )
53 )
54 results.append(
55 InlineQueryResultArticle(
56 id=uuid4(),
57 title="Italic",
58 input_message_content=InputTextMessageContent(
59 f"_{escape_markdown(query)}_", parse_mode=ParseMode.MARKDOWN
60 ),
61 )
62 )
63 update.inline_query.answer(results)
64
65 dp = self.updater.dispatcher
66 dp.add_handler(InlineQueryHandler(inlinequery))
67 self.updater.start_polling()
68
69 # Now test the handler
70 u1 = self.iqg.get_inline_query(query="test data")
71 self.bot.insert_update(u1)
72
73 data = self.bot.sent_messages[-1]
74 self.assertEqual(len(data["results"]), 3)
75 results = data["results"]
76 self.assertEqual(results[0]["title"], "Caps")
77 self.assertEqual(results[0]["input_message_content"]["message_text"], "TEST DATA")
78 self.assertEqual(results[1]["title"], "Bold")
79 self.assertEqual(results[1]["input_message_content"]["message_text"], "*test data*")
80 self.assertEqual(results[2]["title"], "Italic")
81 self.assertEqual(results[2]["input_message_content"]["message_text"], "_test data_")
82
83 self.updater.stop()
84
85
86if __name__ == "__main__":
87 unittest.main()