-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtests.py
653 lines (511 loc) · 18.2 KB
/
tests.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
"""
Unit tests for the functions and classes implemented for the DogPicsBot.
@author Andrés Ignacio Torres <[email protected]>
"""
from dataclasses import dataclass, field
from random import randint
from typing import List, Optional, Tuple
import pytest
from bot import (
DOG_SOUNDS,
DOGS_API_BREED_LIST_URL,
DOGS_API_DOG_PICTURE_URL,
FOX_SOUNDS,
RANDOMFOX_API_URL,
TELEGRAM_CHAT_TYPE_GROUP,
WOLF_PICTURES,
DogPicsBot,
)
# Mocking Telegram's API
@dataclass
class MockApplication:
"""
Mock class to bypass Telegram's application on tests.
"""
_token: str = ""
handler_names: List[str] = field(default_factory=list)
def build(self):
"""
Fakes the process in which a Telegram bot is built.
"""
return self
def token(self, _token: str):
"""
Fakes the process in which a Telegram bot's token is set.
"""
self._token = _token
return self
@staticmethod
def builder():
"""
Fakes the process in which a Telegram bot's builder is set.
"""
return MockApplication()
def add_handler(self, handler):
"""
Fakes the process in which a new handler is added to a Telegram
bot's dispatcher. Instead, stores the name of the new handler
on an instance level for further checks on tests.
"""
self.handler_names.append(str(handler.__class__))
def run_polling(self):
"""
Fakes the call to Telegram's application's start_polling, but in reality
does nothing.
"""
return
@dataclass
class MockChat:
"""
Mocks the information contained in Telegram's Chat class for tests.
"""
type: str
@dataclass
class MockSticker:
"""
Mocks the information contained in Telegram's Sticker class for tests.
"""
emoji: Optional[str] = None
@dataclass
class MockMessage:
"""
Mocks the information contained in Telegram's Message class for tests.
"""
message_id: int
chat_id: int
chat: MockChat
text: str
sticker: Optional[MockSticker] = None
@dataclass
class MockUpdate:
"""
Mocks the information contained in Telegram's Update class for tests.
"""
chat: MockChat
message: MockMessage
@dataclass
class MockContextBot:
"""
Mocks Telegram's context bot for tests. This class handles most of the
logic in charge of sending messages and photos through a Telegram bot.
"""
# tuple of (intended_chat_id, sent_message)
messages: List[Tuple[int, str]] = field(default_factory=list)
# tuple of (intended_chat_id, intented_reply_to_message_id, photo, caption)
photos: List[Tuple[int, int, str, str]] = field(default_factory=list)
async def send_message(self, chat_id, text):
"""
Pretends that a message is sent, instead stores it on an instance
level for further checks on tests.
"""
self.messages.append((chat_id, text))
async def send_photo(self, chat_id, reply_to_message_id, photo, caption):
"""
Pretends that a message with a photo is sent, instead stores it
on an instance level for further checks on tests.
"""
self.photos.append((chat_id, reply_to_message_id, photo, caption))
@dataclass
class MockContext:
"""
Mocks Telegram's Context class for tests.
"""
bot: MockContextBot
@dataclass
class MockResponse:
"""
Mock class to use instead of `requests` own response, to
avoid making live requests during tests.
"""
url: str
timeout: int
def json(self):
"""
Return a dictionary with test data, depending on the instance url
"""
if self.url == DOGS_API_DOG_PICTURE_URL:
return {"message": "https://dog.pics/dog.png"}
if self.url == RANDOMFOX_API_URL:
return {"image": "https://fox.pics/fox.png"}
if self.url == DOGS_API_BREED_LIST_URL:
return {
"message": {
"pug": [],
"collie": ["border"],
"dalmatian": [],
}
}
if "breed" in self.url:
return {"message": "https://dog.pics/specific-breed/dog.png"}
raise NotImplementedError("Test case not yet covered in `MockResponse`")
def get_mock_bot(monkeypatch: pytest.MonkeyPatch):
"""
Helper function that initializes and returns a mocked instance of the
DogPicsBot class, that can be safely used for tests.
"""
monkeypatch.setenv("DPB_TG_TOKEN", "TEST_TOKEN_-_INVALID")
monkeypatch.setattr("bot.Application", MockApplication)
monkeypatch.setattr("requests.get", MockResponse)
return DogPicsBot()
def get_mock_update(
message="This is a message",
chat_type=TELEGRAM_CHAT_TYPE_GROUP,
is_sticker=False,
emoji=None,
):
"""
Given chat and message information, returns an instance of MockUpdate.
"""
chat = MockChat(type=chat_type)
return MockUpdate(
message=MockMessage(
message_id=randint(0, 100000),
chat_id=randint(0, 100000),
chat=chat,
text=message,
sticker=MockSticker(emoji=emoji) if is_sticker else None,
),
chat=chat,
)
def get_mock_context():
"""
Returns a properly created instance of MockContext.
"""
return MockContext(bot=MockContextBot())
# Code of actual tests
async def test_get_random_dog_sound(monkeypatch: pytest.MonkeyPatch):
"""
Unit test to verify that the bot is able to generate a random
caption if needed.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
# repeating the test several times
test_iterations = max(len(DOG_SOUNDS) * 5, 25)
for _ in range(test_iterations):
assert bot.get_random_dog_sound() in DOG_SOUNDS
async def test_get_random_fox_sound(monkeypatch: pytest.MonkeyPatch):
"""
Unit test to verify that the bot is able to generate a random
caption if needed.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
# repeating the test several times
test_iterations = max(len(FOX_SOUNDS) * 5, 25)
for _ in range(test_iterations):
assert bot.get_random_fox_sound() in FOX_SOUNDS
async def test_get_random_wolf_picture(monkeypatch: pytest.MonkeyPatch):
"""
Unit test to verify that the bot is able to generate a random
wolf picture if needed.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
# repeating the test several times
test_iterations = max(len(WOLF_PICTURES) * 5, 25)
for _ in range(test_iterations):
assert bot.get_random_wolf_picture() in WOLF_PICTURES
async def test_show_help(monkeypatch: pytest.MonkeyPatch):
"""
Unit test to verify that the bot is sending the proper help information
when needed.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
update = get_mock_update()
context = get_mock_context()
# context is empty
assert len(context.bot.messages) == 0
await bot.show_help(update, context)
# one message sent through context
assert len(context.bot.messages) == 1
# the tuple contains the chat_id and the message, we only care about
# the message on this test
_, sent_message = context.bot.messages[0]
expected_message = "If you want a dog picture, send me a message or use the /dog command."
assert expected_message in sent_message
async def test_handle_text_messages_for_private_message(monkeypatch: pytest.MonkeyPatch):
"""
Unit test to make sure that the bot always replies with a dog picture
if messaged on a private (non-group) chat
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
update = get_mock_update(chat_type="private")
context = get_mock_context()
# context is empty of sent photos
assert len(context.bot.photos) == 0
await bot.handle_text_messages(update, context)
# one picture sent through context
assert len(context.bot.photos) == 1
# contains the chat_id, original message id, photo url and caption
chat_id, reply_to_message_id, photo_url, caption = context.bot.photos[0]
assert chat_id == update.message.chat_id
assert reply_to_message_id == update.message.message_id
assert photo_url == "https://dog.pics/dog.png"
assert caption in DOG_SOUNDS
@pytest.mark.parametrize(
"dog_message",
[
"I really like dogs",
"Dogs go woof",
"woof woof",
"I have a new pup",
"I have a new pupper",
"tengo un perro",
"mira mi lomito",
"look a doggo",
"look! a! doggo!",
"puppy!",
"woof!",
"pooch!",
],
)
async def test_handle_text_messages_for_group_message_with_dogs(
monkeypatch: pytest.MonkeyPatch, dog_message: str
):
"""
Unit test to verify that the bot properly sends a dog picture if
a message that contains a dog reference is sent to a group chat.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
update = get_mock_update(chat_type=TELEGRAM_CHAT_TYPE_GROUP, message=dog_message)
context = get_mock_context()
# context is empty of sent photos
assert len(context.bot.photos) == 0
await bot.handle_text_messages(update, context)
# one picture sent through context
assert len(context.bot.photos) == 1
# contains the chat_id, original message id, photo url and caption
chat_id, reply_to_message_id, photo_url, caption = context.bot.photos[0]
assert chat_id == update.message.chat_id
assert reply_to_message_id == update.message.message_id
assert photo_url == "https://dog.pics/dog.png"
assert caption in DOG_SOUNDS
async def test_handle_text_messages_for_group_message_without_dogs(monkeypatch: pytest.MonkeyPatch):
"""
Unit test to verify that the bot does not send a dog picture if
a message sent to a group chat doesn't contain a dog reference.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
update = get_mock_update(
chat_type=TELEGRAM_CHAT_TYPE_GROUP,
message="I really like plants",
)
context = get_mock_context()
# context is empty of sent photos
assert len(context.bot.photos) == 0
await bot.handle_text_messages(update, context)
# context is still empty!
assert len(context.bot.photos) == 0
@pytest.mark.parametrize(
"sad_message",
[
"sad",
"i'm really sad right now",
"😢",
"😭😓",
"She left me 💔",
"I'm not gonna make it 😞",
"mano, estoy triste",
"estoy despechado",
"ando deprimido",
"tengo tusa",
],
)
async def test_handle_text_messages_for_sad_message(
monkeypatch: pytest.MonkeyPatch, sad_message: str
):
"""
Unit test to verify that, in the presence of a sad trigger within a
message, the bot replies with a dog picture and a particular caption.
"""
for probability in [0.0, 1.0]:
# we're either testing with a 100% probability or a 0% probability
# so we can assert the outcome of the test
should_send: bool = probability == 1.0
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
bot.sad_message_response_probability = probability
update = get_mock_update(message=sad_message)
context = get_mock_context()
# context is empty of sent photos
assert len(context.bot.photos) == 0
await bot.handle_text_messages(update, context)
if should_send:
# one picture sent through context
assert len(context.bot.photos) == 1
# contains the chat_id, original message id, photo url and caption
chat_id, reply_to_message_id, photo_url, caption = context.bot.photos[0]
assert chat_id == update.message.chat_id
assert reply_to_message_id == update.message.message_id
assert photo_url == "https://dog.pics/dog.png"
assert caption == "Don't be sad, have a cute dog!"
else:
assert len(context.bot.photos) == 0
@pytest.mark.parametrize(
"msg",
[
"i have a pug at home",
"i have two pugs at home",
"this is pugtastic!",
],
)
async def test_handle_text_messages_for_breed_message(monkeypatch: pytest.MonkeyPatch, msg: str):
"""
Unit test to verify that, in the presence of a breed name within a
message, the bot replies with a specific dog picture and a generic caption.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
update = get_mock_update(message=msg)
context = get_mock_context()
# context is empty of sent photos
assert len(context.bot.photos) == 0
await bot.handle_text_messages(update, context)
# one picture sent through context
assert len(context.bot.photos) == 1
# contains the chat_id, original message id, photo url and caption
chat_id, reply_to_message_id, photo_url, caption = context.bot.photos[0]
assert chat_id == update.message.chat_id
assert reply_to_message_id == update.message.message_id
assert photo_url == "https://dog.pics/specific-breed/dog.png"
assert caption in DOG_SOUNDS
@pytest.mark.parametrize(
"dog_emoji",
[
"🐶",
"🐕",
"🐩",
"🌭",
],
)
async def test_handle_text_messages_for_dog_sticker(
monkeypatch: pytest.MonkeyPatch, dog_emoji: str
):
"""
Unit test to verify that, in the presence of a sticker associated to a
dog emoji, the bot replies with a random dog picture and a generic caption
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
update = get_mock_update(is_sticker=True, emoji=dog_emoji)
context = get_mock_context()
# context is empty of sent photos
assert len(context.bot.photos) == 0
await bot.handle_stickers(update, context)
# one picture sent through context
assert len(context.bot.photos) == 1
# contains the chat_id, original message id, photo url and caption
chat_id, reply_to_message_id, photo_url, caption = context.bot.photos[0]
assert chat_id == update.message.chat_id
assert reply_to_message_id == update.message.message_id
assert photo_url == "https://dog.pics/dog.png"
assert caption in DOG_SOUNDS
@pytest.mark.parametrize(
"fox_message",
[
"🦊",
"me gusta mucho este animal 🦊",
"foxes are the best",
"i saw a fennec the other day",
"do you have a fox?",
"mira un zorro!",
],
)
async def test_handle_text_messages_for_fox_reference(
monkeypatch: pytest.MonkeyPatch, fox_message: str
):
"""
Unit test to verify that, in the presence of a message with a fox
reference, the bot replies with a random fox picture and a specific
caption.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
update = get_mock_update(message=fox_message)
context = get_mock_context()
# context is empty of sent photos
assert len(context.bot.photos) == 0
await bot.handle_text_messages(update, context)
# one picture sent through context
assert len(context.bot.photos) == 1
# contains the chat_id, original message id, photo url and caption
chat_id, reply_to_message_id, photo_url, caption = context.bot.photos[0]
assert chat_id == update.message.chat_id
assert reply_to_message_id == update.message.message_id
assert photo_url == "https://fox.pics/fox.png"
assert caption in FOX_SOUNDS
@pytest.mark.parametrize(
"wolf_message",
[
"🐺",
"me gusta mucho este animal 🐺",
"wolves are the best",
"is that a wolf?",
"¡mira un lobo!",
"howl howl howl!",
],
)
async def test_handle_text_messages_for_wolf_reference(
monkeypatch: pytest.MonkeyPatch, wolf_message: str
):
"""
Unit test to verify that, in the presence of a message with a wolf
reference, the bot replies with a random wolf picture and a specific
caption.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
update = get_mock_update(message=wolf_message)
context = get_mock_context()
# context is empty of sent photos
assert len(context.bot.photos) == 0
await bot.handle_text_messages(update, context)
# one picture sent through context
assert len(context.bot.photos) == 1
# contains the chat_id, original message id, photo url and caption
chat_id, reply_to_message_id, photo_url, caption = context.bot.photos[0]
assert chat_id == update.message.chat_id
assert reply_to_message_id == update.message.message_id
assert photo_url in WOLF_PICTURES
assert caption == "Howl!"
async def test_bot_fails_without_telegram_bot_token_in_environment(monkeypatch: pytest.MonkeyPatch):
"""
Unit test to verify that the bot properly raises an exception if
it's initialized in an environment that doesn't have a proper
Telegram Bot token set up as an env var.
"""
monkeypatch.setenv("DPB_TG_TOKEN", "")
with pytest.raises(RuntimeError, match="FATAL: No token was found."):
DogPicsBot()
async def test_run_bot(monkeypatch: pytest.MonkeyPatch):
"""
Unit test to verify that all expected bot handlers are initialized
properly when calling the `run_bot` method.
"""
# instantiating mock bot
bot = get_mock_bot(monkeypatch)
assert len(bot.application.handler_names) == 0
bot.run_bot()
# ? we're actually only checking that we got the right amount
# ? of handlers, and that their underlining classes are
# ? added in order; we might be able to actually check names or more
# ? information with either some introspection or attribute checks,
# ? but it might not be needed for now
assert len(bot.application.handler_names) == 5
assert bot.application.handler_names == [
# /start
"<class 'telegram.ext._handlers.commandhandler.CommandHandler'>",
# /help
"<class 'telegram.ext._handlers.commandhandler.CommandHandler'>",
# /dog
"<class 'telegram.ext._handlers.commandhandler.CommandHandler'>",
# text messages
"<class 'telegram.ext._handlers.messagehandler.MessageHandler'>",
# stickers
"<class 'telegram.ext._handlers.messagehandler.MessageHandler'>",
]