-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathtest_google_drive.py
2228 lines (2020 loc) · 76.9 KB
/
test_google_drive.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 Google Drive source class methods."""
import asyncio
import re
from contextlib import asynccontextmanager
from unittest import mock
from unittest.mock import patch
import pytest
from aiogoogle import Aiogoogle, HTTPError
from aiogoogle.auth.managers import ServiceAccountManager
from aiogoogle.models import Request, Response
from connectors.access_control import DLS_QUERY
from connectors.source import (
CURSOR_SYNC_TIMESTAMP,
ConfigurableFieldValueError,
DataSourceConfiguration,
)
from connectors.sources.google import GoogleServiceAccountClient
from connectors.sources.google_drive import (
RETRIES,
GoogleDriveDataSource,
SyncCursorEmpty,
)
from tests.commons import AsyncIterator
from tests.sources.support import create_source
SERVICE_ACCOUNT_CREDENTIALS = '{"project_id": "dummy123"}'
MORE_THAN_DEFAULT_FILE_SIZE_LIMIT = 10485760 + 1
@asynccontextmanager
async def create_gdrive_source(**kwargs):
async with create_source(
GoogleDriveDataSource,
service_account_credentials=SERVICE_ACCOUNT_CREDENTIALS,
use_document_level_security=False,
**kwargs,
) as source:
yield source
@pytest.mark.asyncio
async def test_empty_configuration():
"""Tests the validity of the configurations passed to the Google Drive source class."""
configuration = DataSourceConfiguration({"service_account_credentials": ""})
gd_object = GoogleDriveDataSource(configuration=configuration)
with pytest.raises(
ConfigurableFieldValueError,
match="Field validation errors: 'Service_account_credentials' cannot be empty.",
):
await gd_object.validate_config()
@pytest.mark.asyncio
async def test_raise_on_invalid_configuration():
"""Test if invalid configuration raises an expected Exception"""
configuration = DataSourceConfiguration(
{"service_account_credentials": "{'abc':'bcd','cd'}"}
)
gd_object = GoogleDriveDataSource(configuration=configuration)
with pytest.raises(
ConfigurableFieldValueError,
match="Google Drive service account is not a valid JSON",
):
await gd_object.validate_config()
@pytest.mark.asyncio
async def test_raise_on_invalid_email_configuration_misformatted_email():
"""Test if invalid configuration raises an expected Exception"""
configuration = DataSourceConfiguration(
{
"service_account_credentials": "{'abc':'bcd','cd'}",
"use_domain_wide_delegation_for_sync": True,
"google_workspace_admin_email_for_data_sync": None,
"google_workspace_email_for_shared_drives_sync": "",
}
)
gd_object = GoogleDriveDataSource(configuration=configuration)
with pytest.raises(
ConfigurableFieldValueError,
):
await gd_object._validate_google_workspace_email_for_shared_drives_sync()
@pytest.mark.asyncio
async def test_raise_on_invalid_email_configuration_empty_email():
"""Test if invalid configuration raises an expected Exception"""
configuration = DataSourceConfiguration(
{
"service_account_credentials": "{'abc':'bcd','cd'}",
"use_domain_wide_delegation_for_sync": True,
"google_workspace_admin_email_for_data_sync": "[email protected]",
"google_workspace_email_for_shared_drives_sync": "admin.com",
}
)
gd_object = GoogleDriveDataSource(configuration=configuration)
with pytest.raises(
ConfigurableFieldValueError,
):
await gd_object._validate_google_workspace_email_for_shared_drives_sync()
@pytest.mark.asyncio
async def test_ping_for_successful_connection():
"""Tests the ping functionality for ensuring connection to Google Drive."""
expected_response = {
"kind": "drive#about",
}
async with create_gdrive_source() as source:
as_service_account_response = asyncio.Future()
as_service_account_response.set_result(expected_response)
with mock.patch.object(
Aiogoogle, "as_service_account", return_value=as_service_account_response
):
await source.ping()
@patch("connectors.utils.time_to_sleep_between_retries", mock.Mock(return_value=0))
@pytest.mark.asyncio
async def test_ping_for_failed_connection():
"""Tests the ping functionality when connection can not be established to Google Drive."""
async with create_gdrive_source() as source:
with mock.patch.object(
Aiogoogle, "discover", side_effect=Exception("Something went wrong")
):
with pytest.raises(Exception):
await source.ping()
@pytest.mark.parametrize(
"files, expected_files",
[
(
[
{
"kind": "drive#fileList",
"incompleteSearch": False,
"files": [
{
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test.txt",
"parents": ["0APU6durKUAiqUk9PVA"],
"size": "28",
"modifiedTime": "2023-06-28T07:46:28.000Z",
"trashed": False,
}
],
}
],
[
(
{
"_id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": "28",
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": None,
"url": None,
"type": "file",
"trashed": False,
},
None,
)
],
)
],
)
@pytest.mark.asyncio
async def test_prepare_files(files, expected_files):
"""Tests the function which modifies the fetched files and maps the values to keys."""
async with create_gdrive_source() as source:
processed_files = []
async for file in source.prepare_files(
client=source.google_drive_client(),
files_page=files[0],
paths={},
seen_ids=set(),
):
processed_files.append(file)
assert processed_files == expected_files
@pytest.mark.parametrize(
"file, expected_file",
[
(
{
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test.txt",
"parents": ["0APU6durKUAiqUk9PVA"],
"size": "28",
"modifiedTime": "2023-06-28T07:46:28.000Z",
"trashed": False,
},
(
{
"_id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": "28",
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": None,
"url": None,
"type": "file",
"trashed": False,
},
None,
),
),
(
{
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test.txt",
"parents": ["0APU6durKUAiqUk9PVA"],
"size": None,
"modifiedTime": "2023-06-28T07:46:28.000Z",
"trashed": False,
},
(
{
"_id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": 0,
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": None,
"url": None,
"type": "file",
"trashed": False,
},
None,
),
),
(
{
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test.txt",
"parents": ["0APU6durKUAiqUk9PVA"],
"size": None,
"modifiedTime": "2023-06-28T07:46:28.000Z",
"trashed": False,
"owners": [
{
"displayName": "Test User",
"kind": "drive#user",
"emailAddress": "[email protected]",
"photoLink": "dummy_link",
}
],
},
(
{
"_id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": 0,
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": None,
"url": None,
"type": "file",
"author": "Test User",
"created_by": "Test User",
"created_by_email": "[email protected]",
"trashed": False,
},
None,
),
),
(
{
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test.txt",
"parents": ["folderId4"],
"size": None,
"modifiedTime": "2023-06-28T07:46:28.000Z",
"trashed": False,
"owners": [
{
"displayName": "Test User",
"kind": "drive#user",
"emailAddress": "[email protected]",
"photoLink": "dummy_link",
}
],
"lastModifyingUser": {
"displayName": "Test User 2",
"kind": "drive#user",
"emailAddress": "[email protected]",
"photoLink": "dummy_link",
},
},
(
{
"_id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": 0,
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": None,
"url": None,
"type": "file",
"author": "Test User",
"created_by": "Test User",
"created_by_email": "[email protected]",
"updated_by": "Test User 2",
"updated_by_email": "[email protected]",
"updated_by_photo_url": "dummy_link",
"path": "Drive3/Folder4/test.txt",
"trashed": False,
},
None,
),
),
(
{
"driveId": "sd1",
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test.txt",
"parents": ["0APU6durKUAiqUk9PVA"],
"size": "28",
"modifiedTime": "2023-06-28T07:46:28.000Z",
"trashed": True,
"trashedTime": "2023-06-28T12:46:28.000Z",
},
(
{
"_id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": "28",
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": None,
"url": None,
"type": "file",
"trashed": True,
"shared_drive": "SharedDrive",
},
"2023-06-28T12:46:28.000Z",
),
),
],
)
@pytest.mark.asyncio
async def test_prepare_file(file, expected_file):
"""Test the method that formats the file metadata from Google Drive API"""
async with create_gdrive_source() as source:
dummy_paths = {
"folderId4": {
"name": "Folder4",
"parents": ["driveId3"],
"path": "Drive3/Folder4",
},
"sd1": {
"name": "SharedDrive",
"parents": [],
"path": "SharedDrive",
},
}
actual_output = await source.prepare_file(
client=source.google_drive_client(), file=file, paths=dummy_paths
)
assert actual_output == expected_file
@pytest.mark.asyncio
async def test_list_drives():
"""Tests the method which lists the shared drives from Google Drive."""
async with create_gdrive_source() as source:
expected_response = {
"kind": "drive#driveList",
"drives": [
{
"id": "0ABHLjfsUwpHFUk9PVA",
"name": "Test Drive",
"kind": "drive#drive",
},
],
}
expected_drives_list = [
{
"kind": "drive#driveList",
"drives": [
{
"id": "0ABHLjfsUwpHFUk9PVA",
"name": "Test Drive",
"kind": "drive#drive",
},
],
}
]
dummy_url = "https://www.googleapis.com/drive/v3/drives"
expected_response_object = Response(
status_code=200,
url=dummy_url,
json=expected_response,
req=Request(method="GET", url=dummy_url),
)
with mock.patch.object(
Aiogoogle, "as_service_account", return_value=expected_response_object
):
with mock.patch.object(ServiceAccountManager, "refresh"):
drives_list = []
async for drive in source.google_drive_client().list_drives():
drives_list.append(drive)
assert drives_list == expected_drives_list
@pytest.mark.asyncio
async def test_list_folders():
"""Tests the method which lists the folders from Google Drive."""
async with create_gdrive_source() as source:
expected_response = {
"kind": "drive#fileList",
"files": [
{
"kind": "drive#file",
"mimeType": "application/vnd.google-apps.folder",
"id": "1kGzmOTZgherwS9ODxZNC-owji_QZGGRU",
"name": "test",
}
],
}
expected_folders_list = [
{
"kind": "drive#fileList",
"files": [
{
"kind": "drive#file",
"mimeType": "application/vnd.google-apps.folder",
"id": "1kGzmOTZgherwS9ODxZNC-owji_QZGGRU",
"name": "test",
}
],
}
]
dummy_url = "https://www.googleapis.com/drive/v3/files"
expected_response_object = Response(
status_code=200,
url=dummy_url,
json=expected_response,
req=Request(method="GET", url=dummy_url),
)
with mock.patch.object(
Aiogoogle, "as_service_account", return_value=expected_response_object
):
with mock.patch.object(ServiceAccountManager, "refresh"):
folders_list = []
async for folder in source.google_drive_client().list_folders():
folders_list.append(folder)
assert folders_list == expected_folders_list
@pytest.mark.asyncio
async def test_resolve_paths():
"""Test the method that builds a lookup between a folder id and its absolute path in Google Drive structure"""
drives = {
"driveId1": "Drive1",
"driveId2": "Drive2",
"driveId3": "Drive3",
}
drives_future = asyncio.Future()
drives_future.set_result(drives)
folders = {
"folderId1": {"name": "Folder1", "parents": ["driveId1"]},
"folderId2": {"name": "Folder2", "parents": ["folderId1"]},
"folderId3": {"name": "Folder3", "parents": ["folderId2"]},
"folderId4": {"name": "Folder4", "parents": ["driveId3"]},
}
expected_paths = {
"folderId1": {
"name": "Folder1",
"parents": ["driveId1"],
"path": "Drive1/Folder1",
},
"folderId2": {
"name": "Folder2",
"parents": ["folderId1"],
"path": "Drive1/Folder1/Folder2",
},
"folderId3": {
"name": "Folder3",
"parents": ["folderId2"],
"path": "Drive1/Folder1/Folder2/Folder3",
},
"folderId4": {
"name": "Folder4",
"parents": ["driveId3"],
"path": "Drive3/Folder4",
},
"driveId1": {"name": "Drive1", "parents": [], "path": "Drive1"},
"driveId2": {"name": "Drive2", "parents": [], "path": "Drive2"},
"driveId3": {"name": "Drive3", "parents": [], "path": "Drive3"},
}
folders_future = asyncio.Future()
folders_future.set_result(folders)
# Create a mock for the google drive client
mock_google_drive_client = mock.MagicMock()
# Setup return values for the client's methods
mock_google_drive_client.get_all_drives.return_value = drives_future
mock_google_drive_client.get_all_folders.return_value = folders_future
async with create_gdrive_source() as source:
source.google_drive_client = mock.MagicMock(
return_value=mock_google_drive_client
)
paths = await source.resolve_paths()
assert paths == expected_paths
@pytest.mark.asyncio
async def test_fetch_files():
"""Tests the method responsible to yield files from Google Drive."""
async with create_gdrive_source() as source:
expected_response = {
"kind": "drive#fileList",
"files": [
{
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test",
}
],
}
expected_files_list = [
{
"kind": "drive#fileList",
"files": [
{
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test",
}
],
}
]
dummy_url = "https://www.googleapis.com/drive/v3/files"
expected_response_object = Response(
status_code=200,
url=dummy_url,
json=expected_response,
req=Request(method="GET", url=dummy_url),
)
with mock.patch.object(
Aiogoogle, "as_service_account", return_value=expected_response_object
):
with mock.patch.object(ServiceAccountManager, "refresh"):
files_list = []
async for file in source.google_drive_client().list_folders():
files_list.append(file)
assert files_list == expected_files_list
@pytest.mark.asyncio
async def test_get_docs_with_domain_wide_delegation():
"""Tests the method responsible to yield files from Google Drive."""
async with create_gdrive_source(
google_workspace_admin_email_for_data_sync="[email protected]"
) as source:
source._get_google_workspace_admin_email = mock.MagicMock(
return_value="[email protected]"
)
source.google_admin_directory_client.users = mock.MagicMock(
return_value=AsyncIterator([{"primaryEmail": "[email protected]"}])
)
source._domain_wide_delegation_sync_enabled = mock.MagicMock(return_value=True)
expected_response = {
"kind": "drive#fileList",
"files": [
{
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test.txt",
"parents": ["0APU6durKUAiqUk9PVA"],
"size": "28",
"modifiedTime": "2023-06-28T07:46:28.000Z",
"trashed": False,
}
],
}
expected_file_document = {
"_id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": "28",
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": None,
"url": None,
"type": "file",
"trashed": False,
}
mock_gdrive_client = mock.MagicMock()
mock_gdrive_client.list_files_from_my_drive = mock.MagicMock(
return_value=AsyncIterator([expected_response])
)
mock_empty_response_future = asyncio.Future()
mock_empty_response_future.set_result({})
mock_gdrive_client.get_all_folders = mock.MagicMock(
return_value=mock_empty_response_future
)
mock_gdrive_client.get_all_drives = mock.MagicMock(
return_value=mock_empty_response_future
)
source.google_drive_client = mock.MagicMock(return_value=mock_gdrive_client)
async for file_document in source.get_docs():
assert file_document[0] == expected_file_document
@pytest.mark.asyncio
async def test_get_docs():
"""Tests the module responsible to fetch and yield files documents from Google Drive."""
async with create_gdrive_source() as source:
expected_response = {
"kind": "drive#fileList",
"files": [
{
"kind": "drive#file",
"mimeType": "text/plain",
"id": "id1",
"name": "test.txt",
"parents": ["0APU6durKUAiqUk9PVA"],
"size": "28",
"modifiedTime": "2023-06-28T07:46:28.000Z",
"trashed": False,
}
],
}
expected_file_document = {
"_id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": "28",
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": None,
"url": None,
"type": "file",
"trashed": False,
}
dummy_url = "https://www.googleapis.com/drive/v3/files"
expected_response_object = Response(
status_code=200,
url=dummy_url,
json=expected_response,
req=Request(method="GET", url=dummy_url),
)
with mock.patch.object(
Aiogoogle, "as_service_account", return_value=expected_response_object
):
with mock.patch.object(ServiceAccountManager, "refresh"):
async for file_document in source.get_docs():
assert file_document[0] == expected_file_document
@pytest.mark.asyncio
async def test_get_content():
"""Test the module responsible for fetching the content of the file if it is extractable."""
async with create_gdrive_source() as source:
file_document = {
"id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": 28,
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": "txt",
"url": None,
"type": "file",
}
expected_file_document = {
"_id": "id1",
"_timestamp": "2023-06-28T07:46:28.000Z",
"_attachment": "",
}
file_content_response = ""
with mock.patch.object(
Aiogoogle, "as_service_account", return_value=file_content_response
):
async with Aiogoogle(
service_account_creds=source.google_drive_client().service_account_credentials
) as google_client:
drive_client = await google_client.discover(
api_name="drive", api_version="v3"
)
drive_client.files = mock.MagicMock()
content = await source.get_content(
client=source.google_drive_client(),
file=file_document,
doit=True,
)
assert content == expected_file_document
@pytest.mark.asyncio
async def test_get_content_doit_false():
"""Test the module responsible for fetching the content of the file with `doit` set to False"""
async with create_gdrive_source() as source:
file_document = {
"id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": 28,
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "text/plain",
"file_extension": "txt",
"url": None,
"type": "file",
}
content = await source.get_content(
client=source.google_drive_client(),
file=file_document,
doit=False,
)
assert content is None
@pytest.mark.asyncio
async def test_get_content_google_workspace_called():
"""Test the method responsible for selecting right extraction method depending on MIME type"""
async with create_gdrive_source() as source:
timestamp = "1234"
file_document = {
"id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "Google docs test",
"size": 28,
"_timestamp": timestamp,
"mime_type": "application/vnd.google-apps.document",
"file_extension": None,
"url": None,
"type": "file",
}
expected_content = {
"_id": "id1",
"_timestamp": timestamp,
"_attachment": "Test content",
}
expected_content_future = asyncio.Future()
expected_content_future.set_result(expected_content)
source.get_google_workspace_content = mock.MagicMock(
return_value=expected_content_future
)
source.get_generic_file_content = mock.MagicMock()
drive_client = source.google_drive_client()
await source.get_content(
client=drive_client,
file=file_document,
timestamp=timestamp,
doit=True,
)
source.get_google_workspace_content.assert_called_once_with(
drive_client, file_document, timestamp=timestamp
)
source.get_generic_file_content.assert_not_called()
@pytest.mark.asyncio
async def test_get_content_generic_files_called():
"""Test the method responsible for selecting right extraction method depending on MIME type"""
async with create_gdrive_source() as source:
timestamp = "1234"
file_document = {
"id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "text.txt",
"size": 28,
"_timestamp": timestamp,
"mime_type": "text/plain",
"file_extension": "txt",
"url": None,
"type": "file",
}
expected_content = {
"_id": "id1",
"_timestamp": timestamp,
"_attachment": "Test content",
}
expected_content_future = asyncio.Future()
expected_content_future.set_result(expected_content)
source.get_google_workspace_content = mock.MagicMock()
source.get_generic_file_content = mock.MagicMock(
return_value=expected_content_future
)
drive_client = source.google_drive_client()
await source.get_content(
client=drive_client,
file=file_document,
timestamp=timestamp,
doit=True,
)
source.get_google_workspace_content.assert_not_called()
source.get_generic_file_content.assert_called_once_with(
drive_client, file_document, timestamp=timestamp
)
@pytest.mark.asyncio
async def test_get_google_workspace_content():
"""Test the module responsible for fetching the content of the Google Suite document."""
async with create_gdrive_source() as source:
file_document = {
"id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": 28,
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "application/vnd.google-apps.document",
"file_extension": None,
"url": None,
"type": "file",
}
expected_file_document = {
"_id": "id1",
"_timestamp": "2023-06-28T07:46:28.000Z",
"_attachment": "I love unit tests",
}
file_content_response = ("I love unit tests", None, 1234)
future_file_content_response = asyncio.Future()
future_file_content_response.set_result(file_content_response)
source._download_content = mock.MagicMock(
return_value=future_file_content_response
)
content = await source.get_content(
client=source.google_drive_client(),
file=file_document,
doit=True,
)
assert content == expected_file_document
@pytest.mark.asyncio
@patch(
"connectors.content_extraction.ContentExtraction._check_configured",
lambda *_: True,
)
async def test_get_google_workspace_content_with_text_extraction_enabled_adds_body():
"""Test the module responsible for fetching the content of the Google Suite document."""
with (
patch(
"connectors.content_extraction.ContentExtraction.extract_text",
return_value="I love unit tests",
),
patch(
"connectors.content_extraction.ContentExtraction.get_extraction_config",
return_value={"host": "http://localhost:8090"},
),
):
async with create_gdrive_source(use_text_extraction_service=True) as source:
file_document = {
"id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": 28,
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "application/vnd.google-apps.document",
"file_extension": None,
"url": None,
"type": "file",
}
expected_file_document = {
"_id": "id1",
"_timestamp": "2023-06-28T07:46:28.000Z",
"body": "I love unit tests",
}
file_content_response = (None, "I love unit tests", 1234)
future_file_content_response = asyncio.Future()
future_file_content_response.set_result(file_content_response)
source._download_content = mock.MagicMock(
return_value=future_file_content_response
)
content = await source.get_content(
client=source.google_drive_client(),
file=file_document,
doit=True,
)
assert content == expected_file_document
@pytest.mark.asyncio
async def test_get_google_workspace_content_size_limit():
"""Test the module responsible for fetching the content of the Google Suite document if its size
is above the limit."""
async with create_gdrive_source() as source:
file_document = {
"id": "id1",
"created_at": None,
"last_updated": "2023-06-28T07:46:28.000Z",
"name": "test.txt",
"size": 28,
"_timestamp": "2023-06-28T07:46:28.000Z",
"mime_type": "application/vnd.google-apps.document",
"file_extension": None,
"url": None,