forked from chaoss/grimoirelab-perceval
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathtest_slack.py
954 lines (760 loc) · 35.1 KB
/
test_slack.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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2020 Bitergia
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
# Santiago Dueñas <[email protected]>
# Valerio Cosentino <[email protected]>
# Miguel Ángel Fernández <[email protected]>
# Harshal Mittal <[email protected]>
#
import copy
import datetime
import dateutil
import httpretty
import os
import unittest
import unittest.mock
from perceval.backend import BackendCommandArgumentParser
from perceval.utils import DEFAULT_DATETIME
from perceval.backends.core.slack import (logger,
Slack,
SlackClient,
SlackClientError,
SlackCommand)
from base import TestCaseBackendArchive
SLACK_API_URL = 'https://slack.com/api/'
SLACK_CHANNEL_INFO_URL = SLACK_API_URL + SlackClient.RCONVERSATION_INFO
SLACK_CHANNEL_HISTORY_URL = SLACK_API_URL + SlackClient.RCONVERSATION_HISTORY
SLACK_CONVERSATION_MEMBERS = SLACK_API_URL + SlackClient.RCONVERSATION_MEMBERS
SLACK_USER_INFO_URL = SLACK_API_URL + SlackClient.RUSER_INFO
def read_file(filename, mode='r'):
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), filename), mode) as f:
content = f.read()
return content
def setup_http_server(archived_channel=False):
"""Setup a mock HTTP server"""
http_requests = []
channel_error = read_file('data/slack/slack_error.json', 'rb')
channel_empty = read_file('data/slack/slack_history_empty.json', 'rb')
if archived_channel:
channel_info = read_file('data/slack/slack_info_archived.json', 'rb')
else:
channel_info = read_file('data/slack/slack_info.json', 'rb')
conversation_members_1 = read_file('data/slack/slack_members1.json', 'rb')
conversation_members_2 = read_file('data/slack/slack_members2.json', 'rb')
channel_history = read_file('data/slack/slack_history.json', 'rb')
channel_history_next = read_file('data/slack/slack_history_next.json', 'rb')
channel_history_date = read_file('data/slack/slack_history_20150323.json', 'rb')
user_U0001 = read_file('data/slack/slack_user_U0001.json', 'rb')
user_U0002 = read_file('data/slack/slack_user_U0002.json', 'rb')
user_U0003 = read_file('data/slack/slack_user_U0003.json', 'rb')
def request_callback(method, uri, headers):
last_request = httpretty.last_request()
params = last_request.querystring
status = 200
if uri.startswith(SLACK_CHANNEL_INFO_URL):
body = channel_info
elif uri.startswith(SLACK_CHANNEL_HISTORY_URL):
if params['channel'][0] != 'C011DUKE8':
body = channel_error
elif 'latest' not in params:
body = channel_history
elif (params['oldest'][0] == '0.999990' and
params['latest'][0] == '1427135733.000068'):
body = channel_history_next
elif (params['oldest'][0] == '0' and
params['latest'][0] == '1483228800.000000'):
body = channel_history
elif (params['oldest'][0] == '0' and
params['latest'][0] == '1427135733.000068'):
body = channel_history_next
elif (params['oldest'][0] == '1427135740.000059' and
params['latest'][0] == '1483228800.000000'):
body = channel_history_date
elif (params['oldest'][0] == '1451606399.999990' and
params['latest'][0] == '1483228800.000000'):
body = channel_empty
else:
raise Exception
elif uri.startswith(SLACK_USER_INFO_URL):
if params['user'][0] == 'U0001':
body = user_U0001
elif params['user'][0] == 'U0002':
body = user_U0002
else:
body = user_U0003
elif uri.startswith(SLACK_CONVERSATION_MEMBERS):
if 'cursor' not in params:
body = conversation_members_1
else:
body = conversation_members_2
else:
raise
http_requests.append(last_request)
return status, headers, body
httpretty.register_uri(httpretty.GET,
SLACK_CHANNEL_INFO_URL,
responses=[
httpretty.Response(body=request_callback)
])
httpretty.register_uri(httpretty.GET,
SLACK_CHANNEL_HISTORY_URL,
responses=[
httpretty.Response(body=request_callback)
for _ in range(1)
])
httpretty.register_uri(httpretty.GET,
SLACK_USER_INFO_URL,
responses=[
httpretty.Response(body=request_callback)
])
httpretty.register_uri(httpretty.GET,
SLACK_CONVERSATION_MEMBERS,
responses=[
httpretty.Response(body=request_callback)
])
return http_requests
class TestSlackBackend(unittest.TestCase):
"""Slack backend tests"""
def test_initialization(self):
"""Test whether attributes are initializated"""
slack = Slack('C011DUKE8', 'aaaa', max_items=5, tag='test')
self.assertEqual(slack.origin, 'https://slack.com/C011DUKE8')
self.assertEqual(slack.tag, 'test')
self.assertEqual(slack.channel, 'C011DUKE8')
self.assertEqual(slack.max_items, 5)
self.assertIsNone(slack.client)
self.assertTrue(slack.ssl_verify)
# When tag is empty or None it will be set to
# the value in URL
slack = Slack('C011DUKE8', 'aaaa', ssl_verify=False)
self.assertEqual(slack.origin, 'https://slack.com/C011DUKE8')
self.assertEqual(slack.tag, 'https://slack.com/C011DUKE8')
self.assertFalse(slack.ssl_verify)
slack = Slack('C011DUKE8', 'aaaa', tag='')
self.assertEqual(slack.origin, 'https://slack.com/C011DUKE8')
self.assertEqual(slack.tag, 'https://slack.com/C011DUKE8')
def test_has_archiving(self):
"""Test if it returns True when has_archiving is called"""
self.assertEqual(Slack.has_archiving(), True)
def test_has_resuming(self):
"""Test if it returns False when has_resuming is called"""
self.assertEqual(Slack.has_resuming(), False)
@httpretty.activate
@unittest.mock.patch('perceval.backends.core.slack.datetime_utcnow')
def test_fetch(self, mock_utcnow):
"""Test if it fetches a list of messages"""
mock_utcnow.return_value = datetime.datetime(2017, 1, 1,
tzinfo=dateutil.tz.tzutc())
http_requests = setup_http_server()
slack = Slack('C011DUKE8', 'aaaa', max_items=5)
messages = [msg for msg in slack.fetch(from_date=None)]
expected = [
("<@U0003|dizquierdo> commented on <@U0002|acs> file>: Thanks.",
'cc2338c23bf5293308d596629c598cd5ec37d14b',
1486999900.000000, '[email protected]', 'test channel'),
("There are no events this week.",
'b48fd01f4e010597091b7e44cecfb6074f56a1a6',
1486969200.000136, 'B0001', 'test channel'),
("<@U0003|dizquierdo> has joined the channel",
'bb95a1facf7d61baaf57322f3d6b6d2d45af8aeb',
1427799888.0, '[email protected]', 'test channel'),
("tengo el m\u00f3vil",
'f8668de6fadeb5730e0a80d4c8e5d3f8d175f4d5',
1427135890.000071, '[email protected]', 'test channel'),
("hey acs",
'29c2942a704c4e0b067daeb76edb2f826376cecf',
1427135835.000070, '[email protected]', 'test channel'),
("¿vale?",
'757e88ea008db0fff739dd261179219aedb84a95',
1427135740.000069, '[email protected]', 'test channel'),
("jsmanrique: tenemos que dar m\u00e9tricas super chulas",
'e92555381bc431a53c0b594fc118850eafd6e212',
1427135733.000068, '[email protected]', 'test channel'),
("hi!",
'b92892e7b65add0e83d0839de20b2375a42014e8',
1427135689.000067, '[email protected]', 'test channel'),
("hi!",
'e59d9ca0d9a2ba1c747dc60a0904edd22d69e20e',
1427135634.000066, '[email protected]', 'test channel')
]
self.assertEqual(len(messages), len(expected))
for x in range(len(messages)):
message = messages[x]
expc = expected[x]
self.assertEqual(message['data']['text'], expc[0])
self.assertEqual(message['uuid'], expc[1])
self.assertEqual(message['origin'], 'https://slack.com/C011DUKE8')
self.assertEqual(message['updated_on'], expc[2])
self.assertEqual(message['category'], 'message')
self.assertEqual(message['tag'], 'https://slack.com/C011DUKE8')
# The second message was sent by a bot
if x == 1:
self.assertEqual(message['data']['bot_id'], expc[3])
else:
self.assertEqual(message['data']['user_data']['profile']['email'], expc[3])
self.assertEqual(message['data']['channel_info']['name'], expc[4])
self.assertEqual(message['data']['channel_info']['num_members'], 164)
# Check requests
expected = [
{
'channel': ['C011DUKE8']
},
{
'channel': ['C011DUKE8']
},
{
'channel': ['C011DUKE8'],
'cursor': ['dXNlcl9pZDpVNEMwUTZGQTc=']
},
{
'channel': ['C011DUKE8'],
'oldest': ['0'],
'latest': ['1483228800.000000'],
'count': ['5']
},
{
'user': ['U0003']
},
{
'user': ['U0002']
},
{
'user': ['U0001']
},
{
'channel': ['C011DUKE8'],
'oldest': ['0'],
'latest': ['1427135733.000068'],
'count': ['5']
}
]
self.assertEqual(len(http_requests), len(expected))
for i in range(len(expected)):
self.assertIn((SlackClient.AUTHORIZATION_HEADER, 'Bearer aaaa'), http_requests[i].headers._headers)
self.assertDictEqual(http_requests[i].querystring, expected[i])
@httpretty.activate
@unittest.mock.patch('perceval.backends.core.slack.datetime_utcnow')
def test_search_fields(self, mock_utcnow):
"""Test whether the search_fields is properly set"""
mock_utcnow.return_value = datetime.datetime(2017, 1, 1,
tzinfo=dateutil.tz.tzutc())
setup_http_server()
slack = Slack('C011DUKE8', 'aaaa', max_items=5)
messages = [msg for msg in slack.fetch(from_date=None)]
message = messages[0]
self.assertEqual(slack.metadata_id(message['data']), message['search_fields']['item_id'])
self.assertEqual(message['data']['channel_info']['name'], 'test channel')
self.assertEqual(message['data']['channel_info']['name'], message['search_fields']['channel_name'])
self.assertEqual(message['data']['channel_info']['id'], 'C011DUKE8')
self.assertEqual(message['data']['channel_info']['id'], message['search_fields']['channel_id'])
message = messages[1]
self.assertEqual(slack.metadata_id(message['data']), message['search_fields']['item_id'])
self.assertEqual(message['data']['channel_info']['name'], 'test channel')
self.assertEqual(message['data']['channel_info']['name'], message['search_fields']['channel_name'])
self.assertEqual(message['data']['channel_info']['id'], 'C011DUKE8')
self.assertEqual(message['data']['channel_info']['id'], message['search_fields']['channel_id'])
message = messages[2]
self.assertEqual(slack.metadata_id(message['data']), message['search_fields']['item_id'])
self.assertEqual(message['data']['channel_info']['name'], 'test channel')
self.assertEqual(message['data']['channel_info']['name'], message['search_fields']['channel_name'])
self.assertEqual(message['data']['channel_info']['id'], 'C011DUKE8')
self.assertEqual(message['data']['channel_info']['id'], message['search_fields']['channel_id'])
@httpretty.activate
@unittest.mock.patch('perceval.backends.core.slack.datetime_utcnow')
def test_fetch_archived_channel(self, mock_utcnow):
"""Test if it fetches a list of messages from an archived channel"""
mock_utcnow.return_value = datetime.datetime(2017, 1, 1,
tzinfo=dateutil.tz.tzutc())
http_requests = setup_http_server(archived_channel=True)
slack = Slack('C011DUKE8', 'aaaa', max_items=5)
with self.assertLogs(logger, level='WARNING') as cm:
messages = [msg for msg in slack.fetch(from_date=None)]
self.assertEqual(cm.output[0], 'WARNING:perceval.backends.core.slack:'
'channel_info.num_members is None for archived channels C011DUKE8')
expected = [
("<@U0003|dizquierdo> commented on <@U0002|acs> file>: Thanks.",
'cc2338c23bf5293308d596629c598cd5ec37d14b',
1486999900.000000, '[email protected]', 'test channel'),
("There are no events this week.",
'b48fd01f4e010597091b7e44cecfb6074f56a1a6',
1486969200.000136, 'B0001', 'test channel'),
("<@U0003|dizquierdo> has joined the channel",
'bb95a1facf7d61baaf57322f3d6b6d2d45af8aeb',
1427799888.0, '[email protected]', 'test channel'),
("tengo el m\u00f3vil",
'f8668de6fadeb5730e0a80d4c8e5d3f8d175f4d5',
1427135890.000071, '[email protected]', 'test channel'),
("hey acs",
'29c2942a704c4e0b067daeb76edb2f826376cecf',
1427135835.000070, '[email protected]', 'test channel'),
("¿vale?",
'757e88ea008db0fff739dd261179219aedb84a95',
1427135740.000069, '[email protected]', 'test channel'),
("jsmanrique: tenemos que dar m\u00e9tricas super chulas",
'e92555381bc431a53c0b594fc118850eafd6e212',
1427135733.000068, '[email protected]', 'test channel'),
("hi!",
'b92892e7b65add0e83d0839de20b2375a42014e8',
1427135689.000067, '[email protected]', 'test channel'),
("hi!",
'e59d9ca0d9a2ba1c747dc60a0904edd22d69e20e',
1427135634.000066, '[email protected]', 'test channel')
]
self.assertEqual(len(messages), len(expected))
for x in range(len(messages)):
message = messages[x]
expc = expected[x]
self.assertEqual(message['data']['text'], expc[0])
self.assertEqual(message['uuid'], expc[1])
self.assertEqual(message['origin'], 'https://slack.com/C011DUKE8')
self.assertEqual(message['updated_on'], expc[2])
self.assertEqual(message['category'], 'message')
self.assertEqual(message['tag'], 'https://slack.com/C011DUKE8')
# The second message was sent by a bot
if x == 1:
self.assertEqual(message['data']['bot_id'], expc[3])
else:
self.assertEqual(message['data']['user_data']['profile']['email'], expc[3])
self.assertEqual(message['data']['channel_info']['name'], expc[4])
self.assertIsNone(message['data']['channel_info']['num_members'])
# Check requests
expected = [
{
'channel': ['C011DUKE8']
},
{
'channel': ['C011DUKE8'],
'oldest': ['0'],
'latest': ['1483228800.000000'],
'count': ['5']
},
{
'user': ['U0003']
},
{
'user': ['U0002']
},
{
'user': ['U0001']
},
{
'channel': ['C011DUKE8'],
'oldest': ['0'],
'latest': ['1427135733.000068'],
'count': ['5']
}
]
self.assertEqual(len(http_requests), len(expected))
for i in range(len(expected)):
self.assertIn((SlackClient.AUTHORIZATION_HEADER, 'Bearer aaaa'), http_requests[i].headers._headers)
self.assertDictEqual(http_requests[i].querystring, expected[i])
@httpretty.activate
@unittest.mock.patch('perceval.backends.core.slack.datetime_utcnow')
def test_fetch_from_date(self, mock_utcnow):
"""Test if it fetches a list of messages since a given date"""
mock_utcnow.return_value = datetime.datetime(2017, 1, 1,
tzinfo=dateutil.tz.tzutc())
http_requests = setup_http_server()
from_date = datetime.datetime(2015, 3, 23, 18, 35, 40, 69,
tzinfo=dateutil.tz.tzutc())
slack = Slack('C011DUKE8', 'aaaa', max_items=5)
messages = [msg for msg in slack.fetch(from_date=from_date)]
expected = [
("There are no events this week.",
'b48fd01f4e010597091b7e44cecfb6074f56a1a6',
1486969200.000136, 'B0001', 'test channel'),
("hey hey!",
'141392fe7515c0710bc4b3d1da82f1d4bec311f4',
1486949200.000069, None, 'test channel'),
("<@U0003|dizquierdo> has joined the channel",
'bb95a1facf7d61baaf57322f3d6b6d2d45af8aeb',
1427799888.0, '[email protected]', 'test channel'),
("tengo el m\u00f3vil",
'f8668de6fadeb5730e0a80d4c8e5d3f8d175f4d5',
1427135890.000071, '[email protected]', 'test channel'),
("hey acs",
'29c2942a704c4e0b067daeb76edb2f826376cecf',
1427135835.000070, '[email protected]', 'test channel')
]
self.assertEqual(len(messages), len(expected))
for x in range(len(messages)):
message = messages[x]
expc = expected[x]
self.assertEqual(message['data']['text'], expc[0])
self.assertEqual(message['uuid'], expc[1])
self.assertEqual(message['origin'], 'https://slack.com/C011DUKE8')
self.assertEqual(message['updated_on'], expc[2])
self.assertEqual(message['category'], 'message')
self.assertEqual(message['tag'], 'https://slack.com/C011DUKE8')
# The first message was sent by a bot
if x == 0:
self.assertEqual(message['data']['bot_id'], expc[3])
elif x == 1:
self.assertNotIn('bot_id', message['data'])
self.assertNotIn('user_data', message['data'])
else:
self.assertEqual(message['data']['user_data']['profile']['email'], expc[3])
self.assertEqual(message['data']['channel_info']['name'], expc[4])
self.assertEqual(message['data']['channel_info']['num_members'], 164)
# Check requests
expected = [
{
'channel': ['C011DUKE8']
},
{
'channel': ['C011DUKE8']
},
{
'channel': ['C011DUKE8'],
'cursor': ['dXNlcl9pZDpVNEMwUTZGQTc=']
},
{
'channel': ['C011DUKE8'],
'oldest': ['1427135740.000059'],
'latest': ['1483228800.000000'],
'count': ['5']
},
{
'user': ['U0003']
},
{
'user': ['U0002']
}
]
self.assertEqual(len(http_requests), len(expected))
for i in range(len(expected)):
self.assertIn((SlackClient.AUTHORIZATION_HEADER, 'Bearer aaaa'), http_requests[i].headers._headers)
self.assertDictEqual(http_requests[i].querystring, expected[i])
@httpretty.activate
@unittest.mock.patch('perceval.backends.core.slack.datetime_utcnow')
def test_fetch_empty(self, mock_utcnow):
"""Test if nothing is returned when there are no messages"""
mock_utcnow.return_value = datetime.datetime(2017, 1, 1,
tzinfo=dateutil.tz.tzutc())
http_requests = setup_http_server()
from_date = datetime.datetime(2016, 1, 1,
tzinfo=dateutil.tz.tzutc())
slack = Slack('C011DUKE8', 'aaaa', max_items=5)
messages = [msg for msg in slack.fetch(from_date=from_date)]
self.assertEqual(len(messages), 0)
# Check requests
expected = [
{
'channel': ['C011DUKE8']
},
{
'channel': ['C011DUKE8']
},
{
'channel': ['C011DUKE8'],
'cursor': ['dXNlcl9pZDpVNEMwUTZGQTc=']
},
{
'channel': ['C011DUKE8'],
'oldest': ['1451606399.999990'],
'latest': ['1483228800.000000'],
'count': ['5']
}
]
self.assertEqual(len(http_requests), len(expected))
for i in range(len(expected)):
self.assertIn((SlackClient.AUTHORIZATION_HEADER, 'Bearer aaaa'), http_requests[i].headers._headers)
self.assertDictEqual(http_requests[i].querystring, expected[i])
def test_parse_channel_info(self):
"""Test if it parses a channel info JSON stream"""
raw_json = read_file('data/slack/slack_info.json')
user = Slack.parse_channel_info(raw_json)
self.assertEqual(user['id'], 'C011DUKE8')
self.assertEqual(user['name'], 'test channel')
def test_parse_history(self):
"""Test if it parses a channel history JSON stream"""
raw_json = read_file('data/slack/slack_history.json')
items, has_more = Slack.parse_history(raw_json)
results = [item for item in items]
self.assertEqual(len(results), 7)
self.assertEqual(results[0]['ts'], '1486999900.000000')
self.assertEqual(results[1]['ts'], '1486969200.000136')
self.assertEqual(results[2]['ts'], '1427799888.000000')
self.assertEqual(results[3]['ts'], '1427135890.000071')
self.assertEqual(results[4]['ts'], '1427135835.000070')
self.assertEqual(results[5]['ts'], '1427135740.000069')
self.assertEqual(results[6]['ts'], '1427135733.000068')
self.assertEqual(has_more, True)
# Parse a file without results
raw_json = read_file('data/slack/slack_history_empty.json')
items, has_more = Slack.parse_history(raw_json)
results = [item for item in items]
self.assertEqual(len(results), 0)
self.assertEqual(has_more, False)
def test_parse_user(self):
"""Test if it parses a user info JSON stream"""
raw_json = read_file('data/slack/slack_user_U0001.json')
user = Slack.parse_user(raw_json)
self.assertEqual(user['id'], 'U0001')
self.assertEqual(user['name'], 'acs')
self.assertEqual(user['profile']['email'], '[email protected]')
class TestSlackBackendArchive(TestCaseBackendArchive):
"""Slack backend tests using an archive"""
def setUp(self):
super().setUp()
self.backend_write_archive = Slack('C011DUKE8', 'aaaa', max_items=5, archive=self.archive)
self.backend_read_archive = Slack('C011DUKE8', 'bbbb', max_items=5, archive=self.archive)
@httpretty.activate
@unittest.mock.patch('perceval.backends.core.slack.datetime_utcnow')
def test_fetch_from_archive(self, mock_utcnow):
"""Test if it fetches a list of messages from archive"""
mock_utcnow.return_value = datetime.datetime(2017, 1, 1,
tzinfo=dateutil.tz.tzutc())
setup_http_server()
self._test_fetch_from_archive(from_date=None)
@httpretty.activate
@unittest.mock.patch('perceval.backends.core.slack.datetime_utcnow')
def test_fetch_from_date_from_archive(self, mock_utcnow):
"""Test if it fetches a list of messages since a given date from archive"""
mock_utcnow.return_value = datetime.datetime(2017, 1, 1,
tzinfo=dateutil.tz.tzutc())
setup_http_server()
from_date = datetime.datetime(2015, 3, 23, 18, 35, 40, 69,
tzinfo=dateutil.tz.tzutc())
self._test_fetch_from_archive(from_date=from_date)
@httpretty.activate
@unittest.mock.patch('perceval.backends.core.slack.datetime_utcnow')
def test_fetch_empty_from_archive(self, mock_utcnow):
"""Test if nothing is returned when there are no messages from archive"""
mock_utcnow.return_value = datetime.datetime(2017, 1, 1,
tzinfo=dateutil.tz.tzutc())
setup_http_server()
from_date = datetime.datetime(2016, 1, 1,
tzinfo=dateutil.tz.tzutc())
self._test_fetch_from_archive(from_date=from_date)
class TestSlackClient(unittest.TestCase):
"""Slack API client tests.
These tests not check the body of the response, only if the call
was well formed and if a response was obtained. Due to this, take
into account that the body returned on each request might not
match with the parameters from the request.
"""
def test_init(self):
"""Test initialization"""
client = SlackClient('aaaa', max_items=5)
self.assertEqual(client.api_token, 'aaaa')
self.assertEqual(client.max_items, 5)
self.assertTrue(client.ssl_verify)
client = SlackClient('aaaa', max_items=5, ssl_verify=False)
self.assertEqual(client.api_token, 'aaaa')
self.assertEqual(client.max_items, 5)
self.assertFalse(client.ssl_verify)
@httpretty.activate
def test_conversation_members(self):
"""Test conversation members API call"""
http_requests = setup_http_server()
client = SlackClient('aaaa', max_items=5)
num_members = client.conversation_members('C011DUKE8')
self.assertEqual(num_members, 164)
expected = [
{
'channel': ['C011DUKE8']
},
{
'channel': ['C011DUKE8'],
'cursor': ['dXNlcl9pZDpVNEMwUTZGQTc=']
}]
self.assertEqual(len(http_requests), 2)
req = http_requests[0]
self.assertEqual(req.method, 'GET')
self.assertRegex(req.path, SlackClient.RCONVERSATION_MEMBERS)
for i in range(len(expected)):
self.assertIn((SlackClient.AUTHORIZATION_HEADER, 'Bearer aaaa'), http_requests[i].headers._headers)
self.assertDictEqual(http_requests[i].querystring, expected[i])
@httpretty.activate
def test_channel_info(self):
"""Test channel info API call"""
http_requests = setup_http_server()
client = SlackClient('aaaa', max_items=5)
_ = client.channel_info('C011DUKE8')
expected = {
'channel': ['C011DUKE8']
}
self.assertEqual(len(http_requests), 1)
req = http_requests[0]
self.assertEqual(req.method, 'GET')
self.assertRegex(req.path, SlackClient.RCONVERSATION_INFO)
self.assertDictEqual(req.querystring, expected)
self.assertIn((SlackClient.AUTHORIZATION_HEADER, 'Bearer aaaa'), req.headers._headers)
@httpretty.activate
def test_history(self):
"""Test channel history API call"""
http_requests = setup_http_server()
client = SlackClient('aaaa', max_items=5)
# Call API
_ = client.history('C011DUKE8',
oldest=1, latest=1427135733.000068)
expected = {
'channel': ['C011DUKE8'],
'oldest': ['0.999990'],
'latest': ['1427135733.000068'],
'count': ['5']
}
self.assertEqual(len(http_requests), 1)
req = http_requests[0]
self.assertEqual(req.method, 'GET')
self.assertRegex(req.path, SlackClient.RCONVERSATION_HISTORY)
self.assertDictEqual(req.querystring, expected)
self.assertIn((SlackClient.AUTHORIZATION_HEADER, 'Bearer aaaa'), req.headers._headers)
@httpretty.activate
def test_history_format_latest(self):
"""Test channel history API call with latest timestamp longer than 6 decimals"""
http_requests = setup_http_server()
client = SlackClient('aaaa', max_items=5)
# Call API
_ = client.history('C011DUKE8',
oldest=1, latest=1427135733.00006771)
expected = {
'channel': ['C011DUKE8'],
'oldest': ['0.999990'],
'latest': ['1427135733.000068'],
'count': ['5']
}
self.assertEqual(len(http_requests), 1)
req = http_requests[0]
self.assertEqual(req.method, 'GET')
self.assertRegex(req.path, SlackClient.RCONVERSATION_HISTORY)
self.assertDictEqual(req.querystring, expected)
self.assertIn((SlackClient.AUTHORIZATION_HEADER, 'Bearer aaaa'), req.headers._headers)
@httpretty.activate
def test_user(self):
"""Test user info API call"""
http_requests = setup_http_server()
client = SlackClient('aaaa', max_items=5)
# Call API
_ = client.user('U0001')
expected = {
'user': ['U0001']
}
self.assertEqual(len(http_requests), 1)
req = http_requests[0]
self.assertEqual(req.method, 'GET')
self.assertRegex(req.path, SlackClient.RUSER_INFO)
self.assertDictEqual(req.querystring, expected)
self.assertIn((SlackClient.AUTHORIZATION_HEADER, 'Bearer aaaa'), req.headers._headers)
@httpretty.activate
def test_slack_error(self):
"""Test if an exception is raised when an error is returned by the server"""
setup_http_server()
client = SlackClient('aaaa', max_items=5)
with self.assertRaises(SlackClientError):
_ = client.history('CH0')
def test_sanitize_for_archive(self):
"""Test whether the sanitize method works properly"""
url = "http://example.com"
headers = {
SlackClient.AUTHORIZATION_HEADER: 'Bear aaaa'
}
payload = {
'channel': 'C011DUKE8'
}
s_url, s_headers, s_payload = SlackClient.sanitize_for_archive(url, copy.deepcopy(headers), payload)
headers.pop(SlackClient.AUTHORIZATION_HEADER)
self.assertEqual(url, s_url)
self.assertEqual(headers, s_headers)
self.assertEqual(payload, s_payload)
@httpretty.activate
def test_private_user(self):
user_U0004 = read_file('data/slack/slack_user_U0004_private.json', 'rb')
httpretty.register_uri(httpretty.GET,
SLACK_USER_INFO_URL + "?user=U0004",
body=user_U0004)
client = SlackClient('aaaa', max_items=5)
# Call API
user = client.user('U0004')
self.assertEqual(user, '{"ok":false,"user":null}')
def test_metadata_id(self):
client = Slack('CHANNEL', 'TOKEN')
# When 'user', 'bot_id', 'comment', or 'username' do not exist.
item = {
'type': 'message',
'text': 'A file was commented on',
'ts': '1529335169.000726',
'channel_info': {
'id': 'CHANNEL',
'name': 'test',
'is_channel': True,
'num_members': 4
}
}
metadata_id = client.metadata_id(item)
expected_id = item['ts']
self.assertEqual(metadata_id, expected_id)
# With 'username'
item['username'] = "username"
metadata_id = client.metadata_id(item)
expected_id = item['ts'] + item['username']
self.assertEqual(metadata_id, expected_id)
# With 'bot_id'
item['bot_id'] = "1"
metadata_id = client.metadata_id(item)
expected_id = item['ts'] + item['bot_id']
self.assertEqual(metadata_id, expected_id)
# With 'comment'
item['comment'] = {"user": "user"}
metadata_id = client.metadata_id(item)
expected_id = item['ts'] + item['comment']['user']
self.assertEqual(metadata_id, expected_id)
# With 'user'
item['user'] = "user"
metadata_id = client.metadata_id(item)
expected_id = item['ts'] + item['user']
self.assertEqual(metadata_id, expected_id)
class TestSlackCommand(unittest.TestCase):
"""SlackCommand unit tests"""
def test_backend_class(self):
"""Test if the backend class is Slack"""
self.assertIs(SlackCommand.BACKEND, Slack)
def test_setup_cmd_parser(self):
"""Test if it parser object is correctly initialized"""
parser = SlackCommand.setup_cmd_parser()
self.assertIsInstance(parser, BackendCommandArgumentParser)
self.assertEqual(parser._backend, Slack)
args = ['--tag', 'test', '--no-archive',
'--api-token', 'abcdefgh',
'--from-date', '1970-01-01',
'--max-items', '10',
'C001']
parsed_args = parser.parse(*args)
self.assertEqual(parsed_args.channel, 'C001')
self.assertEqual(parsed_args.tag, 'test')
self.assertEqual(parsed_args.from_date, DEFAULT_DATETIME)
self.assertTrue(parsed_args.no_archive)
self.assertTrue(parsed_args.ssl_verify)
self.assertEqual(parsed_args.api_token, 'abcdefgh')
self.assertEqual(parsed_args.max_items, 10)
args = ['--tag', 'test', '--no-ssl-verify',
'--api-token', 'abcdefgh',
'--from-date', '1970-01-01',
'--max-items', '10',
'C001']
parsed_args = parser.parse(*args)
self.assertEqual(parsed_args.channel, 'C001')
self.assertEqual(parsed_args.tag, 'test')
self.assertEqual(parsed_args.from_date, DEFAULT_DATETIME)
self.assertFalse(parsed_args.ssl_verify)
self.assertEqual(parsed_args.api_token, 'abcdefgh')
self.assertEqual(parsed_args.max_items, 10)
if __name__ == "__main__":
unittest.main(warnings='ignore')