-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathtest_google_cloud_storage.py
684 lines (606 loc) · 24.5 KB
/
test_google_cloud_storage.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
#
# 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 Cloud Storage source class methods."""
import asyncio
from contextlib import asynccontextmanager
from unittest import mock
from unittest.mock import Mock, patch
import pytest
from aiogoogle import Aiogoogle, HTTPError
from aiogoogle.auth.managers import ServiceAccountManager
from aiogoogle.models import Request, Response
from connectors.source import ConfigurableFieldValueError, DataSourceConfiguration
from connectors.sources.google_cloud_storage import GoogleCloudStorageDataSource
from tests.sources.support import create_source
SERVICE_ACCOUNT_CREDENTIALS = '{"project_id": "dummy123"}'
API_NAME = "storage"
API_VERSION = "v1"
@asynccontextmanager
async def create_gcs_source(use_text_extraction_service=False):
async with create_source(
GoogleCloudStorageDataSource,
service_account_credentials=SERVICE_ACCOUNT_CREDENTIALS,
retry_count=0,
use_text_extraction_service=use_text_extraction_service,
) as source:
yield source
@pytest.mark.asyncio
async def test_empty_configuration():
"""Tests the validity of the configurations passed to the Google Cloud source class."""
configuration = DataSourceConfiguration({"service_account_credentials": ""})
gcs_object = GoogleCloudStorageDataSource(configuration=configuration)
with pytest.raises(
ConfigurableFieldValueError,
match="Field validation errors: 'Service_account_credentials' cannot be empty.",
):
await gcs_object.validate_config()
@pytest.mark.asyncio
async def test_raise_on_invalid_configuration():
configuration = DataSourceConfiguration(
{"service_account_credentials": "{'abc':'bcd','cd'}"}
)
gcs_object = GoogleCloudStorageDataSource(configuration=configuration)
with pytest.raises(
ConfigurableFieldValueError,
match="Google Cloud Storage service account is not a valid JSON",
):
await gcs_object.validate_config()
@pytest.mark.asyncio
async def test_ping_for_successful_connection(catch_stdout):
"""Tests the ping functionality for ensuring connection to Google Cloud Storage."""
expected_response = {
"kind": "storage#serviceAccount",
"email_address": "[email protected]",
}
async with create_gcs_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()
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_ping_for_failed_connection(catch_stdout):
"""Tests the ping functionality when connection can not be established to Google Cloud Storage."""
async with create_gcs_source() as source:
with mock.patch.object(
Aiogoogle, "discover", side_effect=Exception("Something went wrong")
):
with pytest.raises(Exception):
await source.ping()
@pytest.mark.asyncio
@pytest.mark.parametrize(
"previous_documents_list, updated_documents_list",
[
(
[
{
"items": [
{
"id": "path_to_blob",
"updated": "2011-10-12T00:00:00Z",
"name": "path_to_blob",
}
]
},
{
"kind": "storage#buckets",
},
],
[
{
"_id": "path_to_blob",
"component_count": None,
"content_encoding": None,
"content_language": None,
"created_at": None,
"last_updated": "2011-10-12T00:00:00Z",
"metadata": None,
"name": "path_to_blob",
"size": None,
"storage_class": None,
"_timestamp": "2011-10-12T00:00:00Z",
"type": None,
"url": "https://console.cloud.google.com/storage/browser/_details/None/path_to_blob;tab=live_object?project=dummy123",
"version": None,
"bucket_name": None,
}
],
)
],
)
async def test_get_blob_document(previous_documents_list, updated_documents_list):
"""Tests the function which modifies the fetched blobs and maps the values to keys.
Args:
previous_documents_list (list): List of the blobs documents fetched from Google Cloud Storage.
updated_documents_list (list): List of the documents returned by the method.
"""
async with create_gcs_source() as source:
assert updated_documents_list == list(
source.get_blob_document(blobs=previous_documents_list[0])
)
@pytest.mark.asyncio
async def test_fetch_buckets():
"""Tests the method which lists the storage buckets available in Google Cloud Storage."""
async with create_gcs_source() as source:
expected_response = {
"kind": "storage#objects",
"items": [
{
"kind": "storage#object",
"id": "bucket_1",
"updated": "2011-10-12T00:00:00Z",
"name": "bucket_1",
}
],
}
expected_bucket_list = [
{
"kind": "storage#objects",
"items": [
{
"kind": "storage#object",
"id": "bucket_1",
"updated": "2011-10-12T00:00:00Z",
"name": "bucket_1",
}
],
}
]
dummy_url = "https://dummy.gcs.com/buckets/b1/objects"
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"):
bucket_list = []
async for bucket in source.fetch_buckets(["*"]):
bucket_list.append(bucket)
assert bucket_list == expected_bucket_list
@pytest.mark.asyncio
async def test_fetch_blobs():
"""Tests the method responsible to yield blobs from Google Cloud Storage bucket."""
async with create_gcs_source() as source:
expected_bucket_response = {
"kind": "storage#objects",
"items": [
{
"kind": "storage#object",
"id": "bucket_1",
"updated": "2011-10-12T00:01:00Z",
"name": "bucket_1",
}
],
}
dummy_blob_response = {
"kind": "storage#objects",
"items": [
{
"kind": "storage#object",
"id": "bucket_1/blob_1/123123123",
"updated": "2011-10-12T00:01:00Z",
"name": "blob_1",
}
],
}
dummy_url = "https://dummy.gcs.com/buckets/b1/objects"
expected_response_object = Response(
status_code=200,
url=dummy_url,
json=dummy_blob_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 blob_result in source.fetch_blobs(
buckets=expected_bucket_response
):
assert blob_result == dummy_blob_response
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_fetch_blobs_negative():
"""Tests the method responsible to yield blobs(negative) from Google Cloud Storage bucket."""
bucket_response = {
"kind": "storage#objects",
"items": [
{
"kind": "storage#object",
"id": "bucket_1",
"updated": "2011-10-12T00:01:00Z",
"name": "bucket_1",
}
],
}
async with create_gcs_source() as source:
with mock.patch.object(
Aiogoogle,
"discover",
side_effect=HTTPError("Something Went Wrong", res=mock.MagicMock()),
):
async for blob_result in source.fetch_blobs(buckets=bucket_response):
assert blob_result is None
@pytest.mark.asyncio
async def test_get_docs():
"""Tests the module responsible to fetch and yield blobs documents from Google Cloud Storage."""
async with create_gcs_source() as source:
source.configuration.get_field("buckets").value = ["*"]
expected_response = {
"kind": "storage#objects",
"items": [
{
"kind": "storage#object",
"id": "bucket_1/blob_1/123123123",
"updated": "2011-10-12T00:01:00Z",
"name": "blob_1",
}
],
}
expected_blob_document = {
"_id": "bucket_1/blob_1/123123123",
"component_count": None,
"content_encoding": None,
"content_language": None,
"created_at": None,
"last_updated": "2011-10-12T00:01:00Z",
"metadata": None,
"name": "blob_1",
"size": None,
"storage_class": None,
"_timestamp": "2011-10-12T00:01:00Z",
"type": None,
"url": "https://console.cloud.google.com/storage/browser/_details/None/blob_1;tab=live_object?project=dummy123",
"version": None,
"bucket_name": None,
}
dummy_url = "https://dummy.gcs.com/buckets/b1/objects"
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 blob_document in source.get_docs():
assert blob_document[0] == expected_blob_document
@pytest.mark.asyncio
async def test_get_docs_with_specific_bucket():
"""Tests the module responsible to fetch and yield blobs documents from Google Cloud Storage."""
async with create_gcs_source() as source:
source.configuration.get_field("buckets").value = ["test_bucket"]
expected_response = {
"kind": "storage#objects",
"items": [
{
"kind": "storage#object",
"id": "bucket_1/blob_1/123123123",
"updated": "2011-10-12T00:01:00Z",
"name": "blob_1",
}
],
}
expected_blob_document = {
"_id": "bucket_1/blob_1/123123123",
"component_count": None,
"content_encoding": None,
"content_language": None,
"created_at": None,
"last_updated": "2011-10-12T00:01:00Z",
"metadata": None,
"name": "blob_1",
"size": None,
"storage_class": None,
"_timestamp": "2011-10-12T00:01:00Z",
"type": None,
"url": "https://console.cloud.google.com/storage/browser/_details/None/blob_1;tab=live_object?project=dummy123",
"version": None,
"bucket_name": None,
}
dummy_url = "https://dummy.gcs.com/buckets/b1/objects"
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 blob_document in source.get_docs():
assert blob_document[0] == expected_blob_document
@pytest.mark.asyncio
async def test_get_docs_when_no_buckets_present():
"""Tests the module responsible to fetch and yield blobs documents from Google Cloud Storage. When
Cloud storage does not have any buckets.
"""
async with create_gcs_source() as source:
expected_response = {
"kind": "storage#objects",
}
dummy_url = "https://dummy.gcs.com/buckets/b1/objects"
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 blob_document in source.get_docs():
assert blob_document[0] is None
@pytest.mark.asyncio
@pytest.mark.parametrize(
"blob_document, expected_blob_document",
[
(
{
"id": "bucket_1/blob_1/123123123",
"component_count": None,
"content_encoding": None,
"content_language": None,
"created_at": None,
"last_updated": "2011-10-12T00:01:00Z",
"metadata": None,
"name": "blob_1.txt",
"size": "15",
"storage_class": None,
"_timestamp": "2011-10-12T00:01:00Z",
"type": None,
"url": "https://console.cloud.google.com/storage/browser/_details/bucket_1/blob_1;tab=live_object?project=dummy123",
"version": None,
"bucket_name": "bucket_1",
},
{
"_id": "bucket_1/blob_1/123123123",
"_timestamp": "2011-10-12T00:01:00Z",
"_attachment": "",
},
),
(
{
"id": "bucket_1/demo_folder/blob_2/321321321",
"component_count": None,
"content_encoding": None,
"content_language": None,
"created_at": None,
"last_updated": "2011-10-12T00:01:00Z",
"metadata": None,
"name": "demo_folder/blob_2.txt",
"size": "15",
"storage_class": None,
"_timestamp": "2011-10-12T00:01:00Z",
"type": None,
"url": "https://console.cloud.google.com/storage/browser/_details/bucket_1/blob_1;tab=live_object?project=dummy123",
"version": None,
"bucket_name": "bucket_1",
},
{
"_id": "bucket_1/demo_folder/blob_2/321321321",
"_timestamp": "2011-10-12T00:01:00Z",
"_attachment": "",
},
),
],
)
async def test_get_content(blob_document, expected_blob_document):
"""Test the module responsible for fetching the content of the file if it is extractable."""
async with create_gcs_source() as source:
blob_content_response = ""
with mock.patch.object(
Aiogoogle, "as_service_account", return_value=blob_content_response
):
async with Aiogoogle(
service_account_creds=source._google_storage_client.service_account_credentials
) as google_client:
storage_client = await google_client.discover(
api_name=API_NAME, api_version=API_VERSION
)
storage_client.objects = mock.MagicMock()
content = await source.get_content(
blob=blob_document,
doit=True,
)
assert content == expected_blob_document
@pytest.mark.asyncio
@patch(
"connectors.content_extraction.ContentExtraction._check_configured",
lambda *_: True,
)
async def test_get_content_with_text_extraction_enabled_adds_body():
"""Test the module responsible for fetching the content of the file if it is extractable."""
with (
patch(
"connectors.content_extraction.ContentExtraction.extract_text",
return_value="file content",
),
patch(
"connectors.content_extraction.ContentExtraction.get_extraction_config",
return_value={"host": "http://localhost:8090"},
),
):
async with create_gcs_source(use_text_extraction_service=True) as source:
blob_document = {
"id": "bucket_1/blob_1/123123123",
"component_count": None,
"content_encoding": None,
"content_language": None,
"created_at": None,
"last_updated": "2011-10-12T00:01:00Z",
"metadata": None,
"name": "blob_1.txt",
"size": "15",
"storage_class": None,
"_timestamp": "2011-10-12T00:01:00Z",
"type": None,
"url": "https://console.cloud.google.com/storage/browser/_details/bucket_1/blob_1;tab=live_object?project=dummy123",
"version": None,
"bucket_name": "bucket_1",
}
expected_blob_document = {
"_id": "bucket_1/blob_1/123123123",
"_timestamp": "2011-10-12T00:01:00Z",
"body": "file content",
}
blob_content_response = ""
with mock.patch.object(
Aiogoogle, "as_service_account", return_value=blob_content_response
):
async with Aiogoogle(
service_account_creds=source._google_storage_client.service_account_credentials
) as google_client:
storage_client = await google_client.discover(
api_name=API_NAME, api_version=API_VERSION
)
storage_client.objects = mock.MagicMock()
content = await source.get_content(
blob=blob_document,
doit=True,
)
assert content == expected_blob_document
@pytest.mark.asyncio
async def test_get_content_with_upper_extension():
"""Test the module responsible for fetching the content of the file if it is extractable."""
async with create_gcs_source() as source:
blob_document = {
"id": "bucket_1/blob_1/123123123",
"component_count": None,
"content_encoding": None,
"content_language": None,
"created_at": None,
"last_updated": "2011-10-12T00:01:00Z",
"metadata": None,
"name": "blob_1.TXT",
"size": "15",
"storage_class": None,
"_timestamp": "2011-10-12T00:01:00Z",
"type": None,
"url": "https://console.cloud.google.com/storage/browser/_details/bucket_1/blob_1;tab=live_object?project=dummy123",
"version": None,
"bucket_name": "bucket_1",
}
expected_blob_document = {
"_id": "bucket_1/blob_1/123123123",
"_timestamp": "2011-10-12T00:01:00Z",
"_attachment": "",
}
blob_content_response = ""
with mock.patch.object(
Aiogoogle, "as_service_account", return_value=blob_content_response
):
async with Aiogoogle(
service_account_creds=source._google_storage_client.service_account_credentials
) as google_client:
storage_client = await google_client.discover(
api_name=API_NAME, api_version=API_VERSION
)
storage_client.objects = mock.MagicMock()
content = await source.get_content(
blob=blob_document,
doit=True,
)
assert content == expected_blob_document
@pytest.mark.asyncio
async def test_get_content_when_type_not_supported():
"""Test the module responsible for fetching the content of the file if it is not extractable or doit is not true."""
async with create_gcs_source() as source:
blob_document = {
"_id": "bucket_1/blob_1/123123123",
"component_count": None,
"content_encoding": None,
"content_language": None,
"created_at": None,
"last_updated": "2011-10-12T00:01:00Z",
"metadata": None,
"name": "blob_1.cc",
"size": "15",
"storage_class": None,
"_timestamp": "2011-10-12T00:01:00Z",
"type": None,
"url": "https://console.cloud.google.com/storage/browser/_details/None/blob_1;tab=live_object?project=dummy123",
"version": None,
"bucket_name": None,
}
async with Aiogoogle(
service_account_creds=source._google_storage_client.service_account_credentials
) as google_client:
storage_client = await google_client.discover(
api_name=API_NAME, api_version=API_VERSION
)
storage_client.objects = mock.MagicMock()
content = await source.get_content(
blob=blob_document,
doit=True,
)
assert content is None
content = await source.get_content(
blob=blob_document,
)
assert content is None
@pytest.mark.asyncio
async def test_get_content_when_file_size_is_large(catch_stdout):
"""Test the module responsible for fetching the content of the file if it is not extractable or doit is not true."""
async with create_gcs_source() as source:
blob_document = {
"_id": "bucket_1/blob_1/123123123",
"component_count": None,
"content_encoding": None,
"content_language": None,
"created_at": None,
"last_updated": "2011-10-12T00:01:00Z",
"metadata": None,
"name": "blob_1.txt",
"size": 10000000000000,
"storage_class": None,
"_timestamp": "2011-10-12T00:01:00Z",
"type": None,
"url": "https://console.cloud.google.com/storage/browser/_details/None/blob_1;tab=live_object?project=dummy123",
"version": None,
"bucket_name": None,
}
async with Aiogoogle(
service_account_creds=source._google_storage_client.service_account_credentials
) as google_client:
storage_client = await google_client.discover(
api_name=API_NAME, api_version=API_VERSION
)
storage_client.objects = mock.MagicMock()
content = await source.get_content(
blob=blob_document,
doit=True,
)
assert content is None
content = await source.get_content(
blob=blob_document,
)
assert content is None
@pytest.mark.asyncio
@patch("connectors.utils.time_to_sleep_between_retries", Mock(return_value=0))
async def test_api_call_for_attribute_error(catch_stdout):
"""Tests the api_call method when resource attribute is not present in the getattr."""
async with create_gcs_source() as source:
with mock.patch.object(Aiogoogle, "discover", side_effect=AttributeError):
with pytest.raises(AttributeError):
async for resp in source._google_storage_client.api_call(
resource="buckets_dummy",
method="list",
full_response=True,
project=source._google_storage_client.user_project_id,
userProject=source._google_storage_client.user_project_id,
):
assert resp is not None