forked from slackapi/bolt-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_events.py
More file actions
659 lines (578 loc) · 23 KB
/
test_events.py
File metadata and controls
659 lines (578 loc) · 23 KB
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
654
655
656
657
658
659
import asyncio
import json
import re
from random import random
from time import time
import pytest
from slack_sdk.signature import SignatureVerifier
from slack_sdk.web.async_client import AsyncWebClient
from slack_bolt.app.async_app import AsyncApp
from slack_bolt.context.say.async_say import AsyncSay
from slack_bolt.request.async_request import AsyncBoltRequest
from tests.mock_web_api_server import (
setup_mock_web_api_server,
cleanup_mock_web_api_server,
assert_auth_test_count_async,
)
from tests.utils import remove_os_env_temporarily, restore_os_env
class TestAsyncEvents:
signing_secret = "secret"
valid_token = "xoxb-valid"
mock_api_server_base_url = "http://localhost:8888"
signature_verifier = SignatureVerifier(signing_secret)
web_client = AsyncWebClient(
token=valid_token,
base_url=mock_api_server_base_url,
)
@pytest.fixture
def event_loop(self):
old_os_env = remove_os_env_temporarily()
try:
setup_mock_web_api_server(self)
loop = asyncio.get_event_loop()
yield loop
loop.close()
cleanup_mock_web_api_server(self)
finally:
restore_os_env(old_os_env)
def generate_signature(self, body: str, timestamp: str):
return self.signature_verifier.generate_signature(
body=body,
timestamp=timestamp,
)
def build_headers(self, timestamp: str, body: str):
return {
"content-type": ["application/json"],
"x-slack-signature": [self.generate_signature(body, timestamp)],
"x-slack-request-timestamp": [timestamp],
}
def build_valid_app_mention_request(self) -> AsyncBoltRequest:
timestamp, body = str(int(time())), json.dumps(app_mention_body)
return AsyncBoltRequest(body=body, headers=self.build_headers(timestamp, body))
@pytest.mark.asyncio
async def test_mock_server_is_running(self):
resp = await self.web_client.api_test()
assert resp != None
@pytest.mark.asyncio
async def test_app_mention(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
)
app.event("app_mention")(whats_up)
request = self.build_valid_app_mention_request()
response = await app.async_dispatch(request)
assert response.status == 200
await assert_auth_test_count_async(self, 1)
await asyncio.sleep(1) # wait a bit after auto ack()
assert self.mock_received_requests["/chat.postMessage"] == 1
@pytest.mark.asyncio
async def test_process_before_response(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
process_before_response=True,
)
app.event("app_mention")(whats_up)
request = self.build_valid_app_mention_request()
response = await app.async_dispatch(request)
assert response.status == 200
await assert_auth_test_count_async(self, 1)
# no sleep here
assert self.mock_received_requests["/chat.postMessage"] == 1
@pytest.mark.asyncio
async def test_middleware_skip(self):
app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret)
app.event("app_mention", middleware=[skip_middleware])(whats_up)
request = self.build_valid_app_mention_request()
response = await app.async_dispatch(request)
assert response.status == 404
await assert_auth_test_count_async(self, 1)
@pytest.mark.asyncio
async def test_simultaneous_requests(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
)
app.event("app_mention")(random_sleeper)
request = self.build_valid_app_mention_request()
times = 10
tasks = []
for i in range(times):
tasks.append(asyncio.ensure_future(app.async_dispatch(request)))
await asyncio.sleep(5)
# Verifies all the tasks have been completed with 200 OK
assert sum([t.result().status for t in tasks if t.done()]) == 200 * times
assert self.mock_received_requests["/auth.test"] == times
assert self.mock_received_requests["/chat.postMessage"] == times
def build_valid_reaction_added_request(self) -> AsyncBoltRequest:
timestamp, body = str(int(time())), json.dumps(reaction_added_body)
return AsyncBoltRequest(body=body, headers=self.build_headers(timestamp, body))
@pytest.mark.asyncio
async def test_reaction_added(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
)
app.event("reaction_added")(whats_up)
request = self.build_valid_reaction_added_request()
response = await app.async_dispatch(request)
assert response.status == 200
await assert_auth_test_count_async(self, 1)
await asyncio.sleep(1) # wait a bit after auto ack()
assert self.mock_received_requests["/chat.postMessage"] == 1
@pytest.mark.asyncio
async def test_stable_auto_ack(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
)
app.event("reaction_added")(always_failing)
for _ in range(10):
request = self.build_valid_reaction_added_request()
response = await app.async_dispatch(request)
assert response.status == 200
@pytest.mark.asyncio
async def test_self_events(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
)
app.event("reaction_added")(whats_up)
self_event = {
"token": "verification_token",
"team_id": "T111",
"enterprise_id": "E111",
"api_app_id": "A111",
"event": {
"type": "reaction_added",
"user": "W23456789", # bot_user_id
"item": {
"type": "message",
"channel": "C111",
"ts": "1599529504.000400",
},
"reaction": "heart_eyes",
"item_user": "W111",
"event_ts": "1599616881.000800",
},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1599616881,
"authed_users": ["W111"],
}
timestamp, body = str(int(time())), json.dumps(self_event)
request = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
await assert_auth_test_count_async(self, 1)
await asyncio.sleep(1) # wait a bit after auto ack()
# The listener should not be executed
assert self.mock_received_requests.get("/chat.postMessage") is None
@pytest.mark.asyncio
async def test_self_joined_left_events(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
)
app.event("reaction_added")(whats_up)
join_event_body = {
"token": "verification_token",
"team_id": "T111",
"enterprise_id": "E111",
"api_app_id": "A111",
"event": {
"type": "member_joined_channel",
"user": "W23456789", # bot_user_id
"channel": "C111",
"channel_type": "C",
"team": "T111",
"inviter": "U222",
},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1599616881,
"authed_users": ["W111"],
}
left_event_body = {
"token": "verification_token",
"team_id": "T111",
"enterprise_id": "E111",
"api_app_id": "A111",
"event": {
"type": "member_left_channel",
"user": "W23456789", # bot_user_id
"channel": "C111",
"channel_type": "C",
"team": "T111",
},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1599616881,
"authed_users": ["W111"],
}
@app.event("member_joined_channel")
async def handle_member_joined_channel(say):
await say("What's up?")
@app.event("member_left_channel")
async def handle_member_left_channel(say):
await say("What's up?")
timestamp, body = str(int(time())), json.dumps(join_event_body)
request = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
await assert_auth_test_count_async(self, 1)
timestamp, body = str(int(time())), json.dumps(left_event_body)
request = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
await asyncio.sleep(1) # wait a bit after auto ack()
# The listeners should be executed
assert self.mock_received_requests.get("/chat.postMessage") == 2
@pytest.mark.asyncio
async def test_joined_left_events(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
)
app.event("reaction_added")(whats_up)
join_event_body = {
"token": "verification_token",
"team_id": "T111",
"enterprise_id": "E111",
"api_app_id": "A111",
"event": {
"type": "member_joined_channel",
"user": "W111", # other user
"channel": "C111",
"channel_type": "C",
"team": "T111",
"inviter": "U222",
},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1599616881,
"authed_users": ["W111"],
}
left_event_body = {
"token": "verification_token",
"team_id": "T111",
"enterprise_id": "E111",
"api_app_id": "A111",
"event": {
"type": "member_left_channel",
"user": "W111", # other user
"channel": "C111",
"channel_type": "C",
"team": "T111",
},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1599616881,
"authed_users": ["W111"],
}
@app.event("member_joined_channel")
async def handle_member_joined_channel(say):
await say("What's up?")
@app.event("member_left_channel")
async def handle_member_left_channel(say):
await say("What's up?")
timestamp, body = str(int(time())), json.dumps(join_event_body)
request = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
await assert_auth_test_count_async(self, 1)
timestamp, body = str(int(time())), json.dumps(left_event_body)
request = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
await asyncio.sleep(1) # wait a bit after auto ack()
# The listeners should be executed
assert self.mock_received_requests.get("/chat.postMessage") == 2
@pytest.mark.asyncio
async def test_uninstallation_and_revokes(self):
app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret)
app._client = AsyncWebClient(
token="uninstalled-revoked", base_url=self.mock_api_server_base_url
)
@app.event("app_uninstalled")
async def handler1(say: AsyncSay):
await say(channel="C111", text="What's up?")
@app.event("tokens_revoked")
async def handler2(say: AsyncSay):
await say(channel="C111", text="What's up?")
app_uninstalled_body = {
"token": "verification_token",
"team_id": "T111",
"enterprise_id": "E111",
"api_app_id": "A111",
"event": {"type": "app_uninstalled"},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1599616881,
}
timestamp, body = str(int(time())), json.dumps(app_uninstalled_body)
request: AsyncBoltRequest = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
tokens_revoked_body = {
"token": "verification_token",
"team_id": "T111",
"enterprise_id": "E111",
"api_app_id": "A111",
"event": {
"type": "tokens_revoked",
"tokens": {"oauth": ["UXXXXXXXX"], "bot": ["UXXXXXXXX"]},
},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1599616881,
}
timestamp, body = str(int(time())), json.dumps(tokens_revoked_body)
request: AsyncBoltRequest = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
# AsyncApp doesn't call auth.test when booting
assert self.mock_received_requests.get("/auth.test") is None
await asyncio.sleep(1) # wait a bit after auto ack()
assert self.mock_received_requests["/chat.postMessage"] == 2
message_file_share_body = {
"token": "verification-token",
"team_id": "T111",
"api_app_id": "A111",
"event": {
"type": "message",
"text": "Here is your file!",
"files": [
{
"id": "F111",
"created": 1610493713,
"timestamp": 1610493713,
"name": "test.png",
"title": "test.png",
"mimetype": "image/png",
"filetype": "png",
"pretty_type": "PNG",
"user": "U111",
"editable": False,
"size": 42706,
"mode": "hosted",
"is_external": False,
"external_type": "",
"is_public": False,
"public_url_shared": False,
"display_as_bot": False,
"username": "",
"url_private": "https://files.slack.com/files-pri/T111-F111/test.png",
"url_private_download": "https://files.slack.com/files-pri/T111-F111/download/test.png",
"thumb_64": "https://files.slack.com/files-tmb/T111-F111-8d3f9a6d4b/test_64.png",
"thumb_80": "https://files.slack.com/files-tmb/T111-F111-8d3f9a6d4b/test_80.png",
"thumb_360": "https://files.slack.com/files-tmb/T111-F111-8d3f9a6d4b/test_360.png",
"thumb_360_w": 358,
"thumb_360_h": 360,
"thumb_480": "https://files.slack.com/files-tmb/T111-F111-8d3f9a6d4b/test_480.png",
"thumb_480_w": 477,
"thumb_480_h": 480,
"thumb_160": "https://files.slack.com/files-tmb/T111-F111-8d3f9a6d4b/test_160.png",
"thumb_720": "https://files.slack.com/files-tmb/T111-F111-8d3f9a6d4b/test_720.png",
"thumb_720_w": 716,
"thumb_720_h": 720,
"original_w": 736,
"original_h": 740,
"thumb_tiny": "xxx",
"permalink": "https://xxx.slack.com/files/U111/F111/test.png",
"permalink_public": "https://slack-files.com/T111-F111-3e534ef8ca",
"has_rich_preview": False,
}
],
"upload": False,
"blocks": [
{
"type": "rich_text",
"block_id": "gvM",
"elements": [
{
"type": "rich_text_section",
"elements": [
{"type": "text", "text": "Here is your file!"}
],
}
],
}
],
"user": "U111",
"display_as_bot": False,
"ts": "1610493715.001000",
"channel": "G111",
"subtype": "file_share",
"event_ts": "1610493715.001000",
"channel_type": "group",
},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1610493715,
"authorizations": [
{
"enterprise_id": None,
"team_id": "T111",
"user_id": "U111",
"is_bot": True,
"is_enterprise_install": False,
}
],
"is_ext_shared_channel": False,
"event_context": "1-message-T111-G111",
}
@pytest.mark.asyncio
async def test_message_subtypes_0(self):
app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret)
app._client = AsyncWebClient(
token="uninstalled-revoked", base_url=self.mock_api_server_base_url
)
@app.event({"type": "message", "subtype": "file_share"})
async def handler1(event):
assert event["subtype"] == "file_share"
timestamp, body = str(int(time())), json.dumps(self.message_file_share_body)
request: AsyncBoltRequest = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
@pytest.mark.asyncio
async def test_message_subtypes_1(self):
app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret)
app._client = AsyncWebClient(
token="uninstalled-revoked", base_url=self.mock_api_server_base_url
)
@app.event({"type": "message", "subtype": re.compile("file_.+")})
async def handler1(event):
assert event["subtype"] == "file_share"
timestamp, body = str(int(time())), json.dumps(self.message_file_share_body)
request: AsyncBoltRequest = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
@pytest.mark.asyncio
async def test_message_subtypes_2(self):
app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret)
app._client = AsyncWebClient(
token="uninstalled-revoked", base_url=self.mock_api_server_base_url
)
@app.event({"type": "message", "subtype": ["file_share"]})
async def handler1(event):
assert event["subtype"] == "file_share"
timestamp, body = str(int(time())), json.dumps(self.message_file_share_body)
request: AsyncBoltRequest = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
@pytest.mark.asyncio
async def test_message_subtypes_3(self):
app = AsyncApp(client=self.web_client, signing_secret=self.signing_secret)
app._client = AsyncWebClient(
token="uninstalled-revoked", base_url=self.mock_api_server_base_url
)
@app.event("message")
async def handler1(event):
assert event["subtype"] == "file_share"
timestamp, body = str(int(time())), json.dumps(self.message_file_share_body)
request: AsyncBoltRequest = AsyncBoltRequest(
body=body, headers=self.build_headers(timestamp, body)
)
response = await app.async_dispatch(request)
assert response.status == 200
# https://github.com/slackapi/bolt-python/issues/199
@pytest.mark.asyncio
async def test_invalid_message_events(self):
app = AsyncApp(
client=self.web_client,
signing_secret=self.signing_secret,
)
async def handle():
pass
# valid
app.event("message")(handle)
with pytest.raises(ValueError):
app.event("message.channels")(handle)
with pytest.raises(ValueError):
app.event("message.groups")(handle)
with pytest.raises(ValueError):
app.event("message.im")(handle)
with pytest.raises(ValueError):
app.event("message.mpim")(handle)
with pytest.raises(ValueError):
app.event(re.compile("message\\..*"))(handle)
with pytest.raises(ValueError):
app.event({"type": "message.channels"})(handle)
with pytest.raises(ValueError):
app.event({"type": re.compile("message\\..*")})(handle)
app_mention_body = {
"token": "verification_token",
"team_id": "T111",
"enterprise_id": "E111",
"api_app_id": "A111",
"event": {
"client_msg_id": "9cbd4c5b-7ddf-4ede-b479-ad21fca66d63",
"type": "app_mention",
"text": "<@W111> Hi there!",
"user": "W222",
"ts": "1595926230.009600",
"team": "T111",
"channel": "C111",
"event_ts": "1595926230.009600",
},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1595926230,
"authed_users": ["W111"],
}
reaction_added_body = {
"token": "verification_token",
"team_id": "T111",
"enterprise_id": "E111",
"api_app_id": "A111",
"event": {
"type": "reaction_added",
"user": "W111",
"item": {"type": "message", "channel": "C111", "ts": "1599529504.000400"},
"reaction": "heart_eyes",
"item_user": "W111",
"event_ts": "1599616881.000800",
},
"type": "event_callback",
"event_id": "Ev111",
"event_time": 1599616881,
"authed_users": ["W111"],
}
async def random_sleeper(body, say, payload, event):
assert body == app_mention_body
assert body["event"] == payload
assert payload == event
seconds = random() + 2 # 2-3 seconds
await asyncio.sleep(seconds)
await say(f"Sending this message after sleeping for {seconds} seconds")
async def whats_up(body, say, payload, event):
assert body["event"] == payload
assert payload == event
await say("What's up?")
async def skip_middleware(req, resp, next):
# return next()
pass
async def always_failing():
raise Exception("Something wrong!")