forked from elastic/connectors
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_onedrive.py
1264 lines (1116 loc) · 43.5 KB
/
test_onedrive.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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
# Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
# or more contributor license agreements. Licensed under the Elastic License 2.0;
# you may not use this file except in compliance with the Elastic License 2.0.
#
"""Tests the OneDrive source class methods"""
from contextlib import asynccontextmanager
from unittest.mock import ANY, AsyncMock, MagicMock, Mock, patch
import pytest
from aiohttp import StreamReader
from aiohttp.client_exceptions import ClientPayloadError, ClientResponseError
from connectors.filtering.validation import SyncRuleValidationResult
from connectors.protocol import Filter
from connectors.source import ConfigurableFieldValueError, DataSourceConfiguration
from connectors.sources.onedrive import (
AccessToken,
InternalServerError,
NotFound,
OneDriveAdvancedRulesValidator,
OneDriveClient,
OneDriveDataSource,
TokenRetrievalError,
)
from tests.commons import AsyncIterator
from tests.sources.support import create_source
ADVANCED_SNIPPET = "advanced_snippet"
EXPECTED_USERS = [
{
"mail": "[email protected]",
"id": "3fada5d6-125c-4aaa-bc23-09b5d301b2a7",
"createdDateTime": "2022-06-11T14:47:53Z",
"userPrincipalName": "[email protected]",
"transitiveMemberOf": [
{
"@odata.type": "#microsoft.graph.group",
"id": "e35d6159-f6c1-462c-a60c-11f29880e9c0",
}
],
},
{
"mail": "[email protected]",
"id": "8e083933-1720-4d2f-80d0-3976669b40ee",
"createdDateTime": "2022-06-11T14:47:53Z",
"userPrincipalName": "[email protected]",
"transitiveMemberOf": [
{
"@odata.type": "#microsoft.graph.group",
"id": "5010ad09-7ad0-48e7-8047-1ae0f6117a17",
}
],
},
]
RESPONSE_USERS = {
"value": [
{
"mail": "[email protected]",
"id": "3fada5d6-125c-4aaa-bc23-09b5d301b2a7",
"createdDateTime": "2022-06-11T14:47:53Z",
"userPrincipalName": "[email protected]",
"transitiveMemberOf": [
{
"@odata.type": "#microsoft.graph.group",
"id": "e35d6159-f6c1-462c-a60c-11f29880e9c0",
}
],
},
{
"mail": "[email protected]",
"id": "8e083933-1720-4d2f-80d0-3976669b40ee",
"createdDateTime": "2022-06-11T14:47:53Z",
"userPrincipalName": "[email protected]",
"transitiveMemberOf": [
{
"@odata.type": "#microsoft.graph.group",
"id": "5010ad09-7ad0-48e7-8047-1ae0f6117a17",
}
],
},
]
}
RESPONSE_FILES = {
"value": [
{
"createdDateTime": "2023-04-23T05:09:39Z",
"id": "01DABHRNV6Y2GOVW7725BZO354PWSELRRZ",
"lastModifiedDateTime": "2023-08-04T02:55:19Z",
"name": "root",
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents",
"parentReference": {"path": "root"},
"size": 206100,
},
{
"createdDateTime": "2023-05-01T09:09:19Z",
"eTag": '"{FF3F899A-2CBB-4D06-AE16-BBBBF5C35C4E},1"',
"id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"lastModifiedDateTime": "2023-05-01T09:09:19Z",
"name": "folder1",
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder1",
"cTag": '"c:{FF3F899A-2CBB-4D06-AE16-BBBBF5C35C4E},0"',
"parentReference": {"path": "root"},
"size": 10484,
},
{
"createdDateTime": "2023-05-01T09:09:31Z",
"eTag": '"{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"lastModifiedDateTime": "2023-05-01T09:10:21Z",
"name": "Document.docx",
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=Document.docx&action=default&mobileredirect=true",
"cTag": '"c:{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"size": 10484,
"parentReference": {"path": "root"},
"file": {
"mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
},
},
]
}
EXPECTED_FILES = [
{
"createdDateTime": "2023-05-01T09:09:19Z",
"eTag": '"{FF3F899A-2CBB-4D06-AE16-BBBBF5C35C4E},1"',
"id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"lastModifiedDateTime": "2023-05-01T09:09:19Z",
"name": "folder1",
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder1",
"cTag": '"c:{FF3F899A-2CBB-4D06-AE16-BBBBF5C35C4E},0"',
"parentReference": {"path": "root"},
"size": 10484,
},
{
"createdDateTime": "2023-05-01T09:09:31Z",
"eTag": '"{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"lastModifiedDateTime": "2023-05-01T09:10:21Z",
"name": "Document.docx",
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=Document.docx&action=default&mobileredirect=true",
"cTag": '"c:{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"size": 10484,
"parentReference": {"path": "root"},
"file": {
"mimeType": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
},
},
]
RESPONSE_USER1_FILES = [
{
"@microsoft.graph.downloadUrl": "https://example-download-url-item-3",
"createdDateTime": "2023-05-01T09:09:19Z",
"id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"lastModifiedDateTime": "2023-05-01T09:09:19Z",
"name": "folder3",
"eTag": '"{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"cTag": '"c:{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder1",
"parentReference": {"path": "/drive/root:/hello"},
"size": 10484,
},
{
"@microsoft.graph.downloadUrl": "https://example-download-url-item-1",
"createdDateTime": "2023-05-01T09:09:31Z",
"id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"lastModifiedDateTime": "2023-05-01T09:10:21Z",
"name": "doit.py",
"eTag": '"{2E301580-9Y39-4D32-A6D4-E34680133WE8},3"',
"cTag": '"c:{2E301580-9Y39-4D32-A6D4-E34680133WE8},3"',
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=doit.py&action=default&mobileredirect=true",
"parentReference": {"path": "/drive/root:/anc"},
"size": 10484,
"file": {"mimeType": "application/python"},
},
]
EXPECTED_USER1_FILES = [
{
"created_at": "2023-05-01T09:09:19Z",
"_id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"_timestamp": "2023-05-01T09:09:19Z",
"title": "folder3",
"type": "folder",
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder1",
"size": 10484,
},
{
"created_at": "2023-05-01T09:09:31Z",
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"title": "doit.py",
"type": "file",
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=doit.py&action=default&mobileredirect=true",
"size": 10484,
},
]
RESPONSE_USER2_FILES = [
{
"createdDateTime": "2023-05-01T09:09:19Z",
"id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"lastModifiedDateTime": "2023-05-01T09:09:19Z",
"name": "folder4",
"eTag": '"{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"cTag": '"c:{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder4",
"parentReference": {"path": "/drive/root:/dummy"},
"size": 10484,
},
{
"@microsoft.graph.downloadUrl": "https://example-download-url-item-3",
"createdDateTime": "2023-05-01T09:09:31Z",
"id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"lastModifiedDateTime": "2023-05-01T09:10:21Z",
"name": "mac.txt",
"eTag": '"{2E301580-9Y39-4D32-A6D4-E34680133WE8},3"',
"cTag": '"c:{2E301580-9Y39-4D32-A6D4-E34680133WE8},3"',
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/mac.txt?sourcedoc=34680133F84%7&file=mac.txt&action=default&mobileredirect=true",
"parentReference": {"path": "/drive/root:/hello/world"},
"size": 10484,
"file": {"mimeType": "plain/text"},
},
]
EXPECTED_USER2_FILES = [
{
"created_at": "2023-05-01T09:09:19Z",
"_id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"_timestamp": "2023-05-01T09:09:19Z",
"title": "folder4",
"type": "folder",
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder4",
"size": 10484,
},
{
"created_at": "2023-05-01T09:09:31Z",
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"title": "mac.txt",
"type": "file",
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/mac.txt?sourcedoc=34680133F84%7&file=mac.txt&action=default&mobileredirect=true",
"size": 10484,
},
]
MOCK_ATTACHMENT = {
"created_at": "2023-05-01T09:09:31Z",
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"title": "Document.docx",
"type": "file",
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=Document.docx&action=default&mobileredirect=true",
"size": 10484,
}
MOCK_ATTACHMENT_WITHOUT_EXTENSION = {
"created_at": "2023-05-01T09:09:31Z",
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"title": "Document",
"type": "file",
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=Document&action=default&mobileredirect=true",
"size": 10484,
}
MOCK_ATTACHMENT_WITH_LARGE_DATA = {
"created_at": "2023-05-01T09:09:31Z",
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"title": "Document.docx",
"type": "file",
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=Document.docx&action=default&mobileredirect=true",
"size": 23000000,
}
MOCK_ATTACHMENT_WITH_UNSUPPORTED_EXTENSION = {
"created_at": "2023-05-01T09:09:31Z",
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"title": "Document.xyz",
"type": "file",
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=Document.xyz&action=default&mobileredirect=true",
"size": 10484,
}
RESPONSE_CONTENT = "# This is the dummy file"
EXPECTED_CONTENT = {
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"_attachment": "IyBUaGlzIGlzIHRoZSBkdW1teSBmaWxl",
}
EXPECTED_CONTENT_EXTRACTED = {
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"body": RESPONSE_CONTENT,
}
EXPECTED_FILES_FOLDERS = {}
RESPONSE_PERMISSION1 = {
"grantedToV2": {
"user": {
"id": "user_id_1",
}
},
"grantedToIdentitiesV2": [
{
"user": {
"id": "user_id_2",
},
"group": {
"id": "group_id_1",
},
},
],
}
RESPONSE_PERMISSION2 = {
"grantedToV2": {
"user": {
"id": "user_id_3",
}
},
"grantedToIdentitiesV2": [
{
"user": {
"id": "user_id_4",
},
"group": {
"id": "group_id_2",
},
}
],
}
EXPECTED_USER1_FILES_PERMISSION = [
{
"type": "folder",
"title": "folder3",
"_id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"_timestamp": "2023-05-01T09:09:19Z",
"created_at": "2023-05-01T09:09:19Z",
"size": 10484,
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder1",
"_allow_access_control": [
"group:group_id_1",
"user_id:user_id_1",
"user_id:user_id_2",
],
},
{
"type": "file",
"title": "doit.py",
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"created_at": "2023-05-01T09:09:31Z",
"size": 10484,
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=doit.py&action=default&mobileredirect=true",
"_allow_access_control": [
"group:group_id_1",
"user_id:user_id_1",
"user_id:user_id_2",
],
},
]
EXPECTED_USER2_FILES_PERMISSION = [
{
"type": "folder",
"title": "folder4",
"_id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"_timestamp": "2023-05-01T09:09:19Z",
"created_at": "2023-05-01T09:09:19Z",
"size": 10484,
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder4",
"_allow_access_control": [
"group:group_id_2",
"user_id:user_id_3",
"user_id:user_id_4",
],
},
{
"type": "file",
"title": "mac.txt",
"_id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"_timestamp": "2023-05-01T09:10:21Z",
"created_at": "2023-05-01T09:09:31Z",
"size": 10484,
"url": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/mac.txt?sourcedoc=34680133F84%7&file=mac.txt&action=default&mobileredirect=true",
"_allow_access_control": [
"group:group_id_2",
"user_id:user_id_3",
"user_id:user_id_4",
],
},
]
RESPONSE_GROUPS = [{"name": "group1", "id": "123"}, {"name": "group2", "id": "234"}]
BATCHED_RESPONSE = {
"responses": [
{
"id": "123",
"body": {
"value": [
{
"@microsoft.graph.downloadUrl": "https://example-download-url-item-3",
"createdDateTime": "2023-05-01T09:09:19Z",
"id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"lastModifiedDateTime": "2023-05-01T09:09:19Z",
"name": "folder3",
"eTag": '"{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"cTag": '"c:{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder1",
"parentReference": {"path": "/drive/root:/hello"},
"size": 10484,
},
]
},
},
{
"id": "231",
"body": {
"@odata.nextLink": "https://graph.microsoft.com/v1.0/users/231/delta/next-page-token",
"value": [
{
"@microsoft.graph.downloadUrl": "https://example-download-url-item-1",
"createdDateTime": "2023-05-01T09:09:31Z",
"id": "01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"lastModifiedDateTime": "2023-05-01T09:10:21Z",
"name": "doit.py",
"eTag": '"{2E301580-9Y39-4D32-A6D4-E34680133WE8},3"',
"cTag": '"c:{2E301580-9Y39-4D32-A6D4-E34680133WE8},3"',
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/_layouts/15/Doc.aspx?sourcedoc=34680133F84%7&file=doit.py&action=default&mobileredirect=true",
"parentReference": {"path": "/drive/root:/anc"},
"size": 10484,
"file": {"mimeType": "application/python"},
},
],
},
},
]
}
NEXT_BATCH_RESPONSE = {
"responses": [
{
"id": "231",
"body": {
"value": [
{
"createdDateTime": "2023-05-01T09:09:19Z",
"id": "01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"lastModifiedDateTime": "2023-05-01T09:09:19Z",
"name": "folder4",
"eTag": '"{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"cTag": '"c:{2E301580-9B39-4D32-A6D4-E34680133F84},3"',
"webUrl": "https://w076v-my.sharepoint.com/personal/adel_w076v_onmicrosoft_com/Documents/folder4",
"parentReference": {"path": "/drive/root:/dummy"},
"size": 10484,
},
]
},
},
]
}
def token_retrieval_errors(message, error_code):
error = ClientResponseError(None, None)
error.status = error_code
error.message = message
return error
def get_stream_reader():
async_mock = AsyncMock()
async_mock.__aenter__ = AsyncMock(return_value=StreamReaderAsyncMock())
return async_mock
class JSONAsyncMock(AsyncMock):
def __init__(self, json, *args, **kwargs):
super().__init__(*args, **kwargs)
self._json = json
async def json(self):
return self._json
class StreamReaderAsyncMock(AsyncMock):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.content = StreamReader
def test_get_configuration():
config = DataSourceConfiguration(
config=OneDriveDataSource.get_default_configuration()
)
assert config["client_id"] == ""
@asynccontextmanager
async def create_onedrive_source(use_text_extraction_service=False):
async with create_source(
OneDriveDataSource,
client_id="foo",
client_secret="bar",
tenant_id="faa",
use_text_extraction_service=use_text_extraction_service,
) as source:
yield source
@pytest.mark.asyncio
@pytest.mark.parametrize(
"extras",
[
(
{
"client_id": "",
"client_secret": "",
"tenant_id": "",
}
),
],
)
async def test_validate_configuration_with_invalid_dependency_fields_raises_error(
extras,
):
async with create_source(OneDriveDataSource, **extras) as source:
with pytest.raises(ConfigurableFieldValueError):
await source.validate_config()
@pytest.mark.asyncio
async def test_close_with_client_session():
async with create_onedrive_source() as source:
source.client.access_token = "dummy"
await source.close()
assert not hasattr(source.client.__dict__, "session")
@pytest.mark.asyncio
async def test_set_access_token():
async with create_onedrive_source() as source:
mock_token = {"access_token": "msgraphtoken", "expires_in": "1234555"}
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(mock_token, 200)
)
with patch("aiohttp.request", return_value=async_response):
await source.client.token._set_access_token()
assert source.client.token.access_token == "msgraphtoken"
@pytest.mark.asyncio
async def test_ping_for_successful_connection():
async with create_onedrive_source() as source:
DUMMY_RESPONSE = {}
source.client.get = AsyncIterator([[DUMMY_RESPONSE]])
await source.ping()
@pytest.mark.asyncio
@patch("aiohttp.ClientSession.get")
async def test_ping_for_failed_connection_exception(mock_get):
async with create_onedrive_source() as source:
with patch.object(
OneDriveClient, "get", side_effect=Exception("Something went wrong")
):
with pytest.raises(Exception):
await source.ping()
@pytest.mark.asyncio
async def test_get_token_raises_correct_exception_when_400():
klass = OneDriveDataSource
config = DataSourceConfiguration(config=klass.get_default_configuration())
message = "Bad Request"
token = AccessToken(configuration=config)
with patch.object(
AccessToken,
"_set_access_token",
side_effect=token_retrieval_errors(message, 400),
):
with pytest.raises(TokenRetrievalError) as e:
await token.get()
assert e.match("Tenant ID")
assert e.match("Client ID")
@pytest.mark.asyncio
async def test_get_token_raises_correct_exception_when_401():
klass = OneDriveDataSource
config = DataSourceConfiguration(config=klass.get_default_configuration())
message = "Unauthorized"
token = AccessToken(configuration=config)
with patch.object(
AccessToken,
"_set_access_token",
side_effect=token_retrieval_errors(message, 401),
):
with pytest.raises(TokenRetrievalError) as e:
await token.get()
assert e.match("Client Secret")
@pytest.mark.asyncio
async def test_get_token_raises_correct_exception_when_any_other_status():
klass = OneDriveDataSource
config = DataSourceConfiguration(config=klass.get_default_configuration())
message = "Internal server error"
token = AccessToken(configuration=config)
with patch.object(
AccessToken,
"_set_access_token",
side_effect=token_retrieval_errors(message, 500),
):
with pytest.raises(TokenRetrievalError) as e:
await token.get()
assert e.match(message)
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_get_with_429_status():
initial_response = ClientResponseError(None, None)
initial_response.status = 429
initial_response.message = "rate-limited"
initial_response.headers = {"Retry-After": 0.1}
retried_response = AsyncMock()
payload = {"value": "Test rate limit"}
retried_response.__aenter__ = AsyncMock(return_value=JSONAsyncMock(payload))
async with create_onedrive_source() as source:
with patch.object(AccessToken, "get", return_value="abc"):
with patch(
"aiohttp.ClientSession.get",
side_effect=[initial_response, retried_response],
):
async for response in source.client.get(
url="http://localhost:1000/sample"
):
result = await response.json()
assert result == payload
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_get_with_429_status_without_retry_after_header():
initial_response = ClientResponseError(None, None)
initial_response.status = 429
initial_response.message = "rate-limited"
retried_response = AsyncMock()
payload = {"value": "Test rate limit"}
retried_response.__aenter__ = AsyncMock(return_value=JSONAsyncMock(payload))
with patch("connectors.sources.onedrive.DEFAULT_RETRY_SECONDS", 0.3):
async with create_onedrive_source() as source:
with patch.object(AccessToken, "get", return_value="abc"):
with patch(
"aiohttp.ClientSession.get",
side_effect=[initial_response, retried_response],
):
async for response in source.client.get(
url="http://localhost:1000/sample"
):
result = await response.json()
assert result == payload
@pytest.mark.asyncio
async def test_get_with_404_status():
error = ClientResponseError(None, None)
error.status = 404
async with create_onedrive_source() as source:
with patch.object(AccessToken, "get", return_value="abc"):
with patch(
"aiohttp.ClientSession.get",
side_effect=error,
):
with pytest.raises(NotFound):
async for response in source.client.get(
url="http://localhost:1000/err"
):
await response.json()
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_get_with_500_status():
error = ClientResponseError(None, None)
error.status = 500
async with create_onedrive_source() as source:
with patch.object(AccessToken, "get", return_value="abc"):
with patch(
"aiohttp.ClientSession.get",
side_effect=error,
):
with pytest.raises(InternalServerError):
async for response in source.client.get(
url="http://localhost:1000/err"
):
await response.json()
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_post_with_429_status():
initial_response = ClientPayloadError(None, None)
initial_response.status = 429
initial_response.message = "rate-limited"
initial_response.headers = {"Retry-After": 0.1}
retried_response = AsyncMock()
payload = {"value": "Test rate limit"}
retried_response.__aenter__ = AsyncMock(return_value=JSONAsyncMock(payload))
async with create_onedrive_source() as source:
with patch.object(AccessToken, "get", return_value="abc"):
with patch(
"aiohttp.ClientSession.post",
side_effect=[initial_response, retried_response],
):
async for response in source.client.post(
url="http://localhost:1000/sample"
):
result = await response.json()
assert result == payload
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_post_with_429_status_without_retry_after_header():
initial_response = ClientPayloadError(None, None)
initial_response.status = 429
initial_response.message = "rate-limited"
retried_response = AsyncMock()
payload = {"value": "Test rate limit"}
retried_response.__aenter__ = AsyncMock(return_value=JSONAsyncMock(payload))
with patch("connectors.sources.onedrive.DEFAULT_RETRY_SECONDS", 0.3):
async with create_onedrive_source() as source:
with patch.object(AccessToken, "get", return_value="abc"):
with patch(
"aiohttp.ClientSession.post",
side_effect=[initial_response, retried_response],
):
async for response in source.client.post(
url="http://localhost:1000/sample"
):
result = await response.json()
assert result == payload
@pytest.mark.asyncio
async def test_list_groups():
async with create_onedrive_source() as source:
with patch.object(
OneDriveClient,
"paginated_api_call",
return_value=AsyncIterator([RESPONSE_GROUPS]),
):
response = []
async for group in source.client.list_groups("user-1"):
response.append(group)
assert response == RESPONSE_GROUPS
@pytest.mark.asyncio
async def test_list_permissions():
async with create_onedrive_source() as source:
with patch.object(
OneDriveClient,
"paginated_api_call",
return_value=AsyncIterator([[RESPONSE_PERMISSION1]]),
):
async for permission in source.client.list_file_permission(
"user-1", "file-1"
):
assert permission == RESPONSE_PERMISSION1
@pytest.mark.asyncio
async def test_get_owned_files():
async with create_onedrive_source() as source:
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(RESPONSE_FILES)
)
response = []
with patch.object(AccessToken, "get", return_value="abc"):
with patch("aiohttp.ClientSession.get", return_value=async_response):
with patch.object(
OneDriveClient,
"list_users",
return_value=AsyncIterator([EXPECTED_USERS]),
) as user:
async for file, _ in source.client.get_owned_files(user["id"]):
response.append(file)
assert response == EXPECTED_FILES
@pytest.mark.asyncio
async def test_list_users():
async with create_onedrive_source() as source:
response = []
async_response = AsyncMock()
async_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(RESPONSE_USERS)
)
with patch.object(AccessToken, "get", return_value="abc"):
with patch("aiohttp.ClientSession.get", return_value=async_response):
async for user in source.client.list_users():
response.append(user)
assert response == EXPECTED_USERS
@pytest.mark.asyncio
@pytest.mark.parametrize(
"file, download_url, expected_content",
[
(MOCK_ATTACHMENT, "https://content1", EXPECTED_CONTENT),
(MOCK_ATTACHMENT_WITHOUT_EXTENSION, "https://content2", None),
(MOCK_ATTACHMENT_WITH_LARGE_DATA, "https://content3", None),
(MOCK_ATTACHMENT_WITH_UNSUPPORTED_EXTENSION, "https://content4", None),
],
)
async def test_get_content_when_is_downloadable_is_true(
file, download_url, expected_content
):
async with create_onedrive_source() as source:
with patch.object(AccessToken, "get", return_value="abc"):
with patch("aiohttp.ClientSession.get", return_value=get_stream_reader()):
with patch(
"aiohttp.StreamReader.iter_chunked",
return_value=AsyncIterator([bytes(RESPONSE_CONTENT, "utf-8")]),
):
response = await source.get_content(
file=file,
download_url=download_url,
doit=True,
)
assert response == expected_content
@pytest.mark.asyncio
async def test_get_content_with_extraction_service():
with patch(
"connectors.content_extraction.ContentExtraction.extract_text",
return_value=RESPONSE_CONTENT,
), patch(
"connectors.content_extraction.ContentExtraction.get_extraction_config",
return_value={"host": "http://localhost:8090"},
):
async with create_onedrive_source(use_text_extraction_service=True) as source:
with patch.object(AccessToken, "get", return_value="abc"):
with patch(
"aiohttp.ClientSession.get", return_value=get_stream_reader()
):
with patch(
"aiohttp.StreamReader.iter_chunked",
return_value=AsyncIterator([bytes(RESPONSE_CONTENT, "utf-8")]),
):
response = await source.get_content(
file=MOCK_ATTACHMENT,
download_url="https://content1",
doit=True,
)
assert response == EXPECTED_CONTENT_EXTRACTED
@pytest.mark.asyncio
async def test_lookup_request_by_id():
async with create_onedrive_source() as source:
requests = [
{"id": "1", "url": "user1/delta"},
{"id": "2", "url": "user2/delta"},
]
result = source.lookup_request_by_id(requests, "2")
assert result == requests[1]
@pytest.mark.asyncio
async def test_json_batching():
async_response, next_page_response = AsyncMock(), AsyncMock()
result = []
expected_result = [
"01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
"01DABHRNUACUYC4OM3GJG2NVHDI2ABGP4E",
"01DABHRNU2RE777OZMAZG24FV3XP24GXCO",
]
async_response.__aenter__ = AsyncMock(return_value=JSONAsyncMock(BATCHED_RESPONSE))
next_page_response.__aenter__ = AsyncMock(
return_value=JSONAsyncMock(NEXT_BATCH_RESPONSE)
)
async with create_onedrive_source() as source:
with patch.object(AccessToken, "get", return_value="abc"):
with patch(
"aiohttp.ClientSession.post",
side_effect=[async_response, next_page_response],
):
async for response in source.json_batching(
batched_apis=[
{"method": "GET", "id": "123", "url": "/users/user1/delta"},
{"method": "GET", "id": "231", "url": "/users/user2/delta"},
]
):
file = response.get("body", {}).get("value", [])
result.append(file[0].get("id"))
assert result == expected_result
@patch.object(OneDriveClient, "list_users", return_value=AsyncIterator(EXPECTED_USERS))
@patch.object(
OneDriveDataSource,
"json_batching",
side_effect=[
(
AsyncIterator(
[
({"body": {"value": RESPONSE_USER1_FILES}}),
({"body": {"value": RESPONSE_USER2_FILES}}),
],
)
)
],
)
@pytest.mark.asyncio
async def test_get_docs(users_patch, files_patch):
async with create_onedrive_source() as source:
expected_responses = [*EXPECTED_USER1_FILES, *EXPECTED_USER2_FILES]
source.get_content = AsyncMock(return_value=EXPECTED_CONTENT)
documents, downloads = [], []
async for item, content in source.get_docs():
documents.append(item)
if content:
downloads.append(content)
assert documents == expected_responses
assert len(downloads) == 2
@pytest.mark.parametrize(
"advanced_rules, expected_validation_result",
[
(
# valid: empty array should be valid
[],
SyncRuleValidationResult.valid_result(
SyncRuleValidationResult.ADVANCED_RULES
),
),
(
# valid: empty object should also be valid -> default value in Kibana
{},
SyncRuleValidationResult.valid_result(
SyncRuleValidationResult.ADVANCED_RULES
),
),
(
# valid: one custom query
[
{
"owners": ["[email protected]", "[email protected]"],