-
Notifications
You must be signed in to change notification settings - Fork 151
/
test_system.py
2504 lines (1993 loc) · 92.4 KB
/
test_system.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 2014 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import base64
import datetime
import gzip
import hashlib
import io
import os
import re
import tempfile
import time
import unittest
import mock
import requests
import six
from google.cloud import exceptions
from google.cloud import iam_credentials_v1
from google.cloud import storage
from google.cloud.storage._helpers import _base64_md5hash
from google.cloud.storage.bucket import LifecycleRuleDelete
from google.cloud.storage.bucket import LifecycleRuleSetStorageClass
from google.cloud import kms
from google import resumable_media
import google.auth
import google.api_core
from google.api_core import path_template
import google.oauth2
from test_utils.retry import RetryErrors
from test_utils.system import unique_resource_id
from test_utils.vpcsc_config import vpcsc_config
USER_PROJECT = os.environ.get("GOOGLE_CLOUD_TESTS_USER_PROJECT")
DIRNAME = os.path.realpath(os.path.dirname(__file__))
DATA_DIRNAME = os.path.abspath(os.path.join(DIRNAME, "..", "data"))
def _bad_copy(bad_request):
"""Predicate: pass only exceptions for a failed copyTo."""
err_msg = bad_request.message
return err_msg.startswith("No file found in request. (POST") and "copyTo" in err_msg
retry_429 = RetryErrors(exceptions.TooManyRequests, max_tries=6)
retry_429_harder = RetryErrors(exceptions.TooManyRequests, max_tries=10)
retry_429_503 = RetryErrors(
[exceptions.TooManyRequests, exceptions.ServiceUnavailable], max_tries=6
)
retry_bad_copy = RetryErrors(exceptions.BadRequest, error_predicate=_bad_copy)
def _empty_bucket(bucket):
"""Empty a bucket of all existing blobs (including multiple versions)."""
for blob in list(bucket.list_blobs(versions=True)):
try:
blob.delete()
except exceptions.NotFound:
pass
class Config(object):
"""Run-time configuration to be modified at set-up.
This is a mutable stand-in to allow test set-up to modify
global state.
"""
CLIENT = None
TEST_BUCKET = None
def setUpModule():
Config.CLIENT = storage.Client()
bucket_name = "new" + unique_resource_id()
# In the **very** rare case the bucket name is reserved, this
# fails with a ConnectionError.
Config.TEST_BUCKET = Config.CLIENT.bucket(bucket_name)
Config.TEST_BUCKET.versioning_enabled = True
retry_429_503(Config.TEST_BUCKET.create)()
def tearDownModule():
errors = (exceptions.Conflict, exceptions.TooManyRequests)
retry = RetryErrors(errors, max_tries=15)
retry(_empty_bucket)(Config.TEST_BUCKET)
retry(Config.TEST_BUCKET.delete)(force=True)
class TestClient(unittest.TestCase):
def setUp(self):
self.case_hmac_keys_to_delete = []
def tearDown(self):
from google.cloud.storage.hmac_key import HMACKeyMetadata
for hmac_key in self.case_hmac_keys_to_delete:
if hmac_key.state == HMACKeyMetadata.ACTIVE_STATE:
hmac_key.state = HMACKeyMetadata.INACTIVE_STATE
hmac_key.update()
if hmac_key.state == HMACKeyMetadata.INACTIVE_STATE:
retry_429_harder(hmac_key.delete)()
def test_get_service_account_email(self):
domain = "gs-project-accounts.iam.gserviceaccount.com"
email = Config.CLIENT.get_service_account_email()
new_style = re.compile(r"service-(?P<projnum>[^@]+)@" + domain)
old_style = re.compile(r"{}@{}".format(Config.CLIENT.project, domain))
patterns = [new_style, old_style]
matches = [pattern.match(email) for pattern in patterns]
self.assertTrue(any(match for match in matches if match is not None))
def test_hmac_key_crud(self):
from google.cloud.storage.hmac_key import HMACKeyMetadata
credentials = Config.CLIENT._credentials
email = credentials.service_account_email
before_keys = set(Config.CLIENT.list_hmac_keys())
metadata, secret = Config.CLIENT.create_hmac_key(email)
self.case_hmac_keys_to_delete.append(metadata)
self.assertIsInstance(secret, six.text_type)
self.assertEqual(len(secret), 40)
after_keys = set(Config.CLIENT.list_hmac_keys())
self.assertFalse(metadata in before_keys)
self.assertTrue(metadata in after_keys)
another = HMACKeyMetadata(Config.CLIENT)
another._properties["accessId"] = "nonesuch"
self.assertFalse(another.exists())
another._properties["accessId"] = metadata.access_id
self.assertTrue(another.exists())
another.reload()
self.assertEqual(another._properties, metadata._properties)
metadata.state = HMACKeyMetadata.INACTIVE_STATE
metadata.update()
metadata.delete()
self.case_hmac_keys_to_delete.remove(metadata)
class TestStorageBuckets(unittest.TestCase):
def setUp(self):
self.case_buckets_to_delete = []
def tearDown(self):
for bucket_name in self.case_buckets_to_delete:
bucket = Config.CLIENT.bucket(bucket_name)
retry_429_harder(bucket.delete)()
def test_create_bucket(self):
new_bucket_name = "a-new-bucket" + unique_resource_id("-")
self.assertRaises(
exceptions.NotFound, Config.CLIENT.get_bucket, new_bucket_name
)
created = retry_429_503(Config.CLIENT.create_bucket)(new_bucket_name)
self.case_buckets_to_delete.append(new_bucket_name)
self.assertEqual(created.name, new_bucket_name)
def test_bucket_create_w_alt_storage_class(self):
from google.cloud.storage import constants
new_bucket_name = "bucket-w-archive" + unique_resource_id("-")
self.assertRaises(
exceptions.NotFound, Config.CLIENT.get_bucket, new_bucket_name
)
bucket = Config.CLIENT.bucket(new_bucket_name)
bucket.storage_class = constants.ARCHIVE_STORAGE_CLASS
retry_429_503(bucket.create)()
self.case_buckets_to_delete.append(new_bucket_name)
created = Config.CLIENT.get_bucket(new_bucket_name)
self.assertEqual(created.storage_class, constants.ARCHIVE_STORAGE_CLASS)
def test_lifecycle_rules(self):
import datetime
from google.cloud.storage import constants
new_bucket_name = "w-lifcycle-rules" + unique_resource_id("-")
custom_time_before = datetime.date(2018, 8, 1)
noncurrent_before = datetime.date(2018, 8, 1)
self.assertRaises(
exceptions.NotFound, Config.CLIENT.get_bucket, new_bucket_name
)
bucket = Config.CLIENT.bucket(new_bucket_name)
bucket.add_lifecycle_delete_rule(
age=42,
number_of_newer_versions=3,
days_since_custom_time=2,
custom_time_before=custom_time_before,
days_since_noncurrent_time=2,
noncurrent_time_before=noncurrent_before,
)
bucket.add_lifecycle_set_storage_class_rule(
constants.COLDLINE_STORAGE_CLASS,
is_live=False,
matches_storage_class=[constants.NEARLINE_STORAGE_CLASS],
)
expected_rules = [
LifecycleRuleDelete(
age=42,
number_of_newer_versions=3,
days_since_custom_time=2,
custom_time_before=custom_time_before,
days_since_noncurrent_time=2,
noncurrent_time_before=noncurrent_before,
),
LifecycleRuleSetStorageClass(
constants.COLDLINE_STORAGE_CLASS,
is_live=False,
matches_storage_class=[constants.NEARLINE_STORAGE_CLASS],
),
]
retry_429_503(bucket.create)(location="us")
self.case_buckets_to_delete.append(new_bucket_name)
self.assertEqual(bucket.name, new_bucket_name)
self.assertEqual(list(bucket.lifecycle_rules), expected_rules)
bucket.clear_lifecyle_rules()
bucket.patch()
self.assertEqual(list(bucket.lifecycle_rules), [])
def test_list_buckets(self):
buckets_to_create = [
"new" + unique_resource_id(),
"newer" + unique_resource_id(),
"newest" + unique_resource_id(),
]
created_buckets = []
for bucket_name in buckets_to_create:
bucket = Config.CLIENT.bucket(bucket_name)
retry_429_503(bucket.create)()
self.case_buckets_to_delete.append(bucket_name)
# Retrieve the buckets.
all_buckets = Config.CLIENT.list_buckets()
created_buckets = [
bucket for bucket in all_buckets if bucket.name in buckets_to_create
]
self.assertEqual(len(created_buckets), len(buckets_to_create))
def test_bucket_update_labels(self):
bucket_name = "update-labels" + unique_resource_id("-")
bucket = retry_429_503(Config.CLIENT.create_bucket)(bucket_name)
self.case_buckets_to_delete.append(bucket_name)
self.assertTrue(bucket.exists())
updated_labels = {"test-label": "label-value"}
bucket.labels = updated_labels
bucket.update()
self.assertEqual(bucket.labels, updated_labels)
new_labels = {"another-label": "another-value"}
bucket.labels = new_labels
bucket.patch()
self.assertEqual(bucket.labels, new_labels)
bucket.labels = {}
bucket.update()
self.assertEqual(bucket.labels, {})
def test_get_set_iam_policy(self):
import pytest
from google.cloud.storage.iam import STORAGE_OBJECT_VIEWER_ROLE
from google.api_core.exceptions import BadRequest, PreconditionFailed
bucket_name = "iam-policy" + unique_resource_id("-")
bucket = retry_429_503(Config.CLIENT.create_bucket)(bucket_name)
self.case_buckets_to_delete.append(bucket_name)
self.assertTrue(bucket.exists())
policy_no_version = bucket.get_iam_policy()
self.assertEqual(policy_no_version.version, 1)
policy = bucket.get_iam_policy(requested_policy_version=3)
self.assertEqual(policy, policy_no_version)
member = "serviceAccount:{}".format(Config.CLIENT.get_service_account_email())
BINDING_W_CONDITION = {
"role": STORAGE_OBJECT_VIEWER_ROLE,
"members": {member},
"condition": {
"title": "always-true",
"description": "test condition always-true",
"expression": "true",
},
}
policy.bindings.append(BINDING_W_CONDITION)
with pytest.raises(
PreconditionFailed, match="enable uniform bucket-level access"
):
bucket.set_iam_policy(policy)
bucket.iam_configuration.uniform_bucket_level_access_enabled = True
bucket.patch()
policy = bucket.get_iam_policy(requested_policy_version=3)
policy.bindings.append(BINDING_W_CONDITION)
with pytest.raises(BadRequest, match="at least 3"):
bucket.set_iam_policy(policy)
policy.version = 3
returned_policy = bucket.set_iam_policy(policy)
self.assertEqual(returned_policy.version, 3)
self.assertEqual(returned_policy.bindings, policy.bindings)
fetched_policy = bucket.get_iam_policy(requested_policy_version=3)
self.assertEqual(fetched_policy.bindings, returned_policy.bindings)
@unittest.skipUnless(USER_PROJECT, "USER_PROJECT not set in environment.")
def test_crud_bucket_with_requester_pays(self):
new_bucket_name = "w-requester-pays" + unique_resource_id("-")
created = retry_429_503(Config.CLIENT.create_bucket)(
new_bucket_name, requester_pays=True
)
self.case_buckets_to_delete.append(new_bucket_name)
self.assertEqual(created.name, new_bucket_name)
self.assertTrue(created.requester_pays)
with_user_project = Config.CLIENT.bucket(
new_bucket_name, user_project=USER_PROJECT
)
# Bucket will be deleted in-line below.
self.case_buckets_to_delete.remove(new_bucket_name)
try:
# Exercise 'buckets.get' w/ userProject.
self.assertTrue(with_user_project.exists())
with_user_project.reload()
self.assertTrue(with_user_project.requester_pays)
# Exercise 'buckets.patch' w/ userProject.
with_user_project.configure_website(
main_page_suffix="index.html", not_found_page="404.html"
)
with_user_project.patch()
self.assertEqual(
with_user_project._properties["website"],
{"mainPageSuffix": "index.html", "notFoundPage": "404.html"},
)
# Exercise 'buckets.update' w/ userProject.
new_labels = {"another-label": "another-value"}
with_user_project.labels = new_labels
with_user_project.update()
self.assertEqual(with_user_project.labels, new_labels)
finally:
# Exercise 'buckets.delete' w/ userProject.
with_user_project.delete()
@unittest.skipUnless(USER_PROJECT, "USER_PROJECT not set in environment.")
def test_bucket_acls_iam_with_user_project(self):
new_bucket_name = "acl-w-user-project" + unique_resource_id("-")
retry_429_503(Config.CLIENT.create_bucket)(new_bucket_name, requester_pays=True)
self.case_buckets_to_delete.append(new_bucket_name)
with_user_project = Config.CLIENT.bucket(
new_bucket_name, user_project=USER_PROJECT
)
# Exercise bucket ACL w/ userProject
acl = with_user_project.acl
acl.reload()
acl.all().grant_read()
acl.save()
self.assertIn("READER", acl.all().get_roles())
del acl.entities["allUsers"]
acl.save()
self.assertFalse(acl.has_entity("allUsers"))
# Exercise default object ACL w/ userProject
doa = with_user_project.default_object_acl
doa.reload()
doa.all().grant_read()
doa.save()
self.assertIn("READER", doa.all().get_roles())
# Exercise IAM w/ userProject
test_permissions = ["storage.buckets.get"]
self.assertEqual(
with_user_project.test_iam_permissions(test_permissions), test_permissions
)
policy = with_user_project.get_iam_policy()
viewers = policy.setdefault("roles/storage.objectViewer", set())
viewers.add(policy.all_users())
with_user_project.set_iam_policy(policy)
@unittest.skipUnless(USER_PROJECT, "USER_PROJECT not set in environment.")
def test_copy_existing_file_with_user_project(self):
new_bucket_name = "copy-w-requester-pays" + unique_resource_id("-")
created = retry_429_503(Config.CLIENT.create_bucket)(
new_bucket_name, requester_pays=True
)
self.case_buckets_to_delete.append(new_bucket_name)
self.assertEqual(created.name, new_bucket_name)
self.assertTrue(created.requester_pays)
to_delete = []
blob = storage.Blob("simple", bucket=created)
blob.upload_from_string(b"DEADBEEF")
to_delete.append(blob)
try:
with_user_project = Config.CLIENT.bucket(
new_bucket_name, user_project=USER_PROJECT
)
new_blob = retry_bad_copy(with_user_project.copy_blob)(
blob, with_user_project, "simple-copy"
)
to_delete.append(new_blob)
base_contents = blob.download_as_bytes()
copied_contents = new_blob.download_as_bytes()
self.assertEqual(base_contents, copied_contents)
finally:
for blob in to_delete:
retry_429_harder(blob.delete)()
def test_copy_file_with_generation_match(self):
new_bucket_name = "generation-match" + unique_resource_id("-")
created = retry_429_503(Config.CLIENT.create_bucket)(
new_bucket_name, requester_pays=True
)
self.case_buckets_to_delete.append(new_bucket_name)
self.assertEqual(created.name, new_bucket_name)
to_delete = []
blob = storage.Blob("simple", bucket=created)
blob.upload_from_string(b"DEADBEEF")
to_delete.append(blob)
try:
dest_bucket = Config.CLIENT.bucket(new_bucket_name)
new_blob = dest_bucket.copy_blob(
blob,
dest_bucket,
"simple-copy",
if_source_generation_match=blob.generation,
)
to_delete.append(new_blob)
base_contents = blob.download_as_bytes()
copied_contents = new_blob.download_as_bytes()
self.assertEqual(base_contents, copied_contents)
finally:
for blob in to_delete:
retry_429_harder(blob.delete)()
def test_copy_file_with_metageneration_match(self):
new_bucket_name = "generation-match" + unique_resource_id("-")
created = retry_429_503(Config.CLIENT.create_bucket)(
new_bucket_name, requester_pays=True
)
self.case_buckets_to_delete.append(new_bucket_name)
self.assertEqual(created.name, new_bucket_name)
to_delete = []
blob = storage.Blob("simple", bucket=created)
blob.upload_from_string(b"DEADBEEF")
to_delete.append(blob)
try:
dest_bucket = Config.CLIENT.bucket(new_bucket_name)
new_blob = dest_bucket.copy_blob(
blob,
dest_bucket,
"simple-copy",
if_source_metageneration_match=blob.metageneration,
)
to_delete.append(new_blob)
base_contents = blob.download_as_bytes()
copied_contents = new_blob.download_as_bytes()
self.assertEqual(base_contents, copied_contents)
finally:
for blob in to_delete:
retry_429_harder(blob.delete)()
@unittest.skipUnless(USER_PROJECT, "USER_PROJECT not set in environment.")
def test_bucket_get_blob_with_user_project(self):
new_bucket_name = "w-requester-pays" + unique_resource_id("-")
data = b"DEADBEEF"
created = retry_429_503(Config.CLIENT.create_bucket)(
new_bucket_name, requester_pays=True
)
self.case_buckets_to_delete.append(new_bucket_name)
self.assertEqual(created.name, new_bucket_name)
self.assertTrue(created.requester_pays)
with_user_project = Config.CLIENT.bucket(
new_bucket_name, user_project=USER_PROJECT
)
self.assertIsNone(with_user_project.get_blob("nonesuch"))
to_add = created.blob("blob-name")
to_add.upload_from_string(data)
try:
found = with_user_project.get_blob("blob-name")
self.assertEqual(found.download_as_bytes(), data)
finally:
to_add.delete()
class TestStorageFiles(unittest.TestCase):
FILES = {
"logo": {"path": DATA_DIRNAME + "/CloudPlatform_128px_Retina.png"},
"big": {"path": DATA_DIRNAME + "/five-point-one-mb-file.zip"},
"simple": {"path": DATA_DIRNAME + "/simple.txt"},
}
@classmethod
def setUpClass(cls):
super(TestStorageFiles, cls).setUpClass()
for file_data in cls.FILES.values():
with open(file_data["path"], "rb") as file_obj:
file_data["hash"] = _base64_md5hash(file_obj)
cls.bucket = Config.TEST_BUCKET
def setUp(self):
self.case_blobs_to_delete = []
def tearDown(self):
errors = (exceptions.TooManyRequests, exceptions.ServiceUnavailable)
retry = RetryErrors(errors, max_tries=6)
for blob in self.case_blobs_to_delete:
retry(blob.delete)()
class TestStorageWriteFiles(TestStorageFiles):
ENCRYPTION_KEY = "b23ff11bba187db8c37077e6af3b25b8"
def test_large_file_write_from_stream(self):
blob = self.bucket.blob("LargeFile")
file_data = self.FILES["big"]
with open(file_data["path"], "rb") as file_obj:
blob.upload_from_file(file_obj)
self.case_blobs_to_delete.append(blob)
md5_hash = blob.md5_hash
if not isinstance(md5_hash, six.binary_type):
md5_hash = md5_hash.encode("utf-8")
self.assertEqual(md5_hash, file_data["hash"])
def test_large_file_write_from_stream_with_checksum(self):
blob = self.bucket.blob("LargeFile")
file_data = self.FILES["big"]
with open(file_data["path"], "rb") as file_obj:
blob.upload_from_file(file_obj, checksum="crc32c")
self.case_blobs_to_delete.append(blob)
md5_hash = blob.md5_hash
if not isinstance(md5_hash, six.binary_type):
md5_hash = md5_hash.encode("utf-8")
self.assertEqual(md5_hash, file_data["hash"])
def test_large_file_write_from_stream_with_failed_checksum(self):
blob = self.bucket.blob("LargeFile")
file_data = self.FILES["big"]
# Intercept the digest processing at the last stage and replace it with garbage.
# This is done with a patch to monkey-patch the resumable media library's checksum
# processing; it does not mock a remote interface like a unit test would. The
# remote API is still exercised.
with open(file_data["path"], "rb") as file_obj:
with mock.patch(
"google.resumable_media._helpers.prepare_checksum_digest",
return_value="FFFFFF==",
):
with self.assertRaises(resumable_media.DataCorruption):
blob.upload_from_file(file_obj, checksum="crc32c")
self.assertFalse(blob.exists())
def test_large_encrypted_file_write_from_stream(self):
blob = self.bucket.blob("LargeFile", encryption_key=self.ENCRYPTION_KEY)
file_data = self.FILES["big"]
with open(file_data["path"], "rb") as file_obj:
blob.upload_from_file(file_obj)
self.case_blobs_to_delete.append(blob)
md5_hash = blob.md5_hash
if not isinstance(md5_hash, six.binary_type):
md5_hash = md5_hash.encode("utf-8")
self.assertEqual(md5_hash, file_data["hash"])
with tempfile.NamedTemporaryFile() as temp_f:
with open(temp_f.name, "wb") as file_obj:
blob.download_to_file(file_obj)
with open(temp_f.name, "rb") as file_obj:
md5_temp_hash = _base64_md5hash(file_obj)
self.assertEqual(md5_temp_hash, file_data["hash"])
def test_small_file_write_from_filename(self):
blob = self.bucket.blob("SmallFile")
file_data = self.FILES["simple"]
blob.upload_from_filename(file_data["path"])
self.case_blobs_to_delete.append(blob)
md5_hash = blob.md5_hash
if not isinstance(md5_hash, six.binary_type):
md5_hash = md5_hash.encode("utf-8")
self.assertEqual(md5_hash, file_data["hash"])
def test_small_file_write_from_filename_with_checksum(self):
blob = self.bucket.blob("SmallFile")
file_data = self.FILES["simple"]
blob.upload_from_filename(file_data["path"], checksum="crc32c")
self.case_blobs_to_delete.append(blob)
md5_hash = blob.md5_hash
if not isinstance(md5_hash, six.binary_type):
md5_hash = md5_hash.encode("utf-8")
self.assertEqual(md5_hash, file_data["hash"])
def test_small_file_write_from_filename_with_failed_checksum(self):
blob = self.bucket.blob("SmallFile")
file_data = self.FILES["simple"]
# Intercept the digest processing at the last stage and replace it with garbage
with mock.patch(
"google.resumable_media._helpers.prepare_checksum_digest",
return_value="FFFFFF==",
):
with self.assertRaises(google.api_core.exceptions.BadRequest):
blob.upload_from_filename(file_data["path"], checksum="crc32c")
self.assertFalse(blob.exists())
@unittest.skipUnless(USER_PROJECT, "USER_PROJECT not set in environment.")
def test_crud_blob_w_user_project(self):
with_user_project = Config.CLIENT.bucket(
self.bucket.name, user_project=USER_PROJECT
)
blob = with_user_project.blob("SmallFile")
file_data = self.FILES["simple"]
with open(file_data["path"], mode="rb") as to_read:
file_contents = to_read.read()
# Exercise 'objects.insert' w/ userProject.
blob.upload_from_filename(file_data["path"])
gen0 = blob.generation
# Upload a second generation of the blob
blob.upload_from_string(b"gen1")
gen1 = blob.generation
blob0 = with_user_project.blob("SmallFile", generation=gen0)
blob1 = with_user_project.blob("SmallFile", generation=gen1)
# Exercise 'objects.get' w/ generation
self.assertEqual(with_user_project.get_blob(blob.name).generation, gen1)
self.assertEqual(
with_user_project.get_blob(blob.name, generation=gen0).generation, gen0
)
try:
# Exercise 'objects.get' (metadata) w/ userProject.
self.assertTrue(blob.exists())
blob.reload()
# Exercise 'objects.get' (media) w/ userProject.
self.assertEqual(blob0.download_as_bytes(), file_contents)
self.assertEqual(blob1.download_as_bytes(), b"gen1")
# Exercise 'objects.patch' w/ userProject.
blob0.content_language = "en"
blob0.patch()
self.assertEqual(blob0.content_language, "en")
self.assertIsNone(blob1.content_language)
# Exercise 'objects.update' w/ userProject.
metadata = {"foo": "Foo", "bar": "Bar"}
blob0.metadata = metadata
blob0.update()
self.assertEqual(blob0.metadata, metadata)
self.assertIsNone(blob1.metadata)
finally:
# Exercise 'objects.delete' (metadata) w/ userProject.
blobs = with_user_project.list_blobs(prefix=blob.name, versions=True)
self.assertEqual([each.generation for each in blobs], [gen0, gen1])
blob0.delete()
blobs = with_user_project.list_blobs(prefix=blob.name, versions=True)
self.assertEqual([each.generation for each in blobs], [gen1])
blob1.delete()
def test_crud_blob_w_generation_match(self):
WRONG_GENERATION_NUMBER = 6
WRONG_METAGENERATION_NUMBER = 9
bucket = Config.CLIENT.bucket(self.bucket.name)
blob = bucket.blob("SmallFile")
file_data = self.FILES["simple"]
with open(file_data["path"], mode="rb") as to_read:
file_contents = to_read.read()
blob.upload_from_filename(file_data["path"])
gen0 = blob.generation
# Upload a second generation of the blob
blob.upload_from_string(b"gen1")
gen1 = blob.generation
blob0 = bucket.blob("SmallFile", generation=gen0)
blob1 = bucket.blob("SmallFile", generation=gen1)
try:
# Exercise 'objects.get' (metadata) w/ generation match.
with self.assertRaises(google.api_core.exceptions.PreconditionFailed):
blob.exists(if_generation_match=WRONG_GENERATION_NUMBER)
self.assertTrue(blob.exists(if_generation_match=gen1))
with self.assertRaises(google.api_core.exceptions.PreconditionFailed):
blob.reload(if_metageneration_match=WRONG_METAGENERATION_NUMBER)
blob.reload(if_generation_match=gen1)
# Exercise 'objects.get' (media) w/ generation match.
self.assertEqual(
blob0.download_as_bytes(if_generation_match=gen0), file_contents
)
self.assertEqual(
blob1.download_as_bytes(if_generation_not_match=gen0), b"gen1"
)
# Exercise 'objects.patch' w/ generation match.
blob0.content_language = "en"
blob0.patch(if_generation_match=gen0)
self.assertEqual(blob0.content_language, "en")
self.assertIsNone(blob1.content_language)
# Exercise 'objects.update' w/ generation match.
metadata = {"foo": "Foo", "bar": "Bar"}
blob0.metadata = metadata
blob0.update(if_generation_match=gen0)
self.assertEqual(blob0.metadata, metadata)
self.assertIsNone(blob1.metadata)
finally:
# Exercise 'objects.delete' (metadata) w/ generation match.
with self.assertRaises(google.api_core.exceptions.PreconditionFailed):
blob0.delete(if_metageneration_match=WRONG_METAGENERATION_NUMBER)
blob0.delete(if_generation_match=gen0)
blob1.delete(if_metageneration_not_match=WRONG_METAGENERATION_NUMBER)
@unittest.skipUnless(USER_PROJECT, "USER_PROJECT not set in environment.")
def test_blob_acl_w_user_project(self):
with_user_project = Config.CLIENT.bucket(
self.bucket.name, user_project=USER_PROJECT
)
blob = with_user_project.blob("SmallFile")
file_data = self.FILES["simple"]
blob.upload_from_filename(file_data["path"])
self.case_blobs_to_delete.append(blob)
# Exercise bucket ACL w/ userProject
acl = blob.acl
acl.reload()
acl.all().grant_read()
acl.save()
self.assertIn("READER", acl.all().get_roles())
del acl.entities["allUsers"]
acl.save()
self.assertFalse(acl.has_entity("allUsers"))
def test_upload_blob_acl(self):
control = self.bucket.blob("logo")
control_data = self.FILES["logo"]
blob = self.bucket.blob("SmallFile")
file_data = self.FILES["simple"]
try:
control.upload_from_filename(control_data["path"])
blob.upload_from_filename(file_data["path"], predefined_acl="publicRead")
finally:
self.case_blobs_to_delete.append(blob)
self.case_blobs_to_delete.append(control)
control_acl = control.acl
self.assertNotIn("READER", control_acl.all().get_roles())
acl = blob.acl
self.assertIn("READER", acl.all().get_roles())
acl.all().revoke_read()
self.assertSequenceEqual(acl.all().get_roles(), set([]))
self.assertEqual(control_acl.all().get_roles(), acl.all().get_roles())
def test_write_metadata(self):
filename = self.FILES["logo"]["path"]
blob_name = os.path.basename(filename)
blob = storage.Blob(blob_name, bucket=self.bucket)
blob.upload_from_filename(filename)
self.case_blobs_to_delete.append(blob)
# NOTE: This should not be necessary. We should be able to pass
# it in to upload_file and also to upload_from_string.
blob.content_type = "image/png"
self.assertEqual(blob.content_type, "image/png")
def test_direct_write_and_read_into_file(self):
blob = self.bucket.blob("MyBuffer")
file_contents = b"Hello World"
blob.upload_from_string(file_contents)
self.case_blobs_to_delete.append(blob)
same_blob = self.bucket.blob("MyBuffer")
same_blob.reload() # Initialize properties.
with tempfile.NamedTemporaryFile() as temp_f:
with open(temp_f.name, "wb") as file_obj:
same_blob.download_to_file(file_obj)
with open(temp_f.name, "rb") as file_obj:
stored_contents = file_obj.read()
self.assertEqual(file_contents, stored_contents)
def test_download_w_generation_match(self):
WRONG_GENERATION_NUMBER = 6
blob = self.bucket.blob("MyBuffer")
file_contents = b"Hello World"
blob.upload_from_string(file_contents)
self.case_blobs_to_delete.append(blob)
same_blob = self.bucket.blob("MyBuffer")
same_blob.reload() # Initialize properties.
with tempfile.NamedTemporaryFile() as temp_f:
with open(temp_f.name, "wb") as file_obj:
with self.assertRaises(google.api_core.exceptions.PreconditionFailed):
same_blob.download_to_file(
file_obj, if_generation_match=WRONG_GENERATION_NUMBER
)
same_blob.download_to_file(
file_obj,
if_generation_match=blob.generation,
if_metageneration_match=blob.metageneration,
)
with open(temp_f.name, "rb") as file_obj:
stored_contents = file_obj.read()
self.assertEqual(file_contents, stored_contents)
def test_download_w_failed_crc32c_checksum(self):
blob = self.bucket.blob("FailedChecksumBlob")
file_contents = b"Hello World"
blob.upload_from_string(file_contents)
self.case_blobs_to_delete.append(blob)
with tempfile.NamedTemporaryFile() as temp_f:
# Intercept the digest processing at the last stage and replace it with garbage.
# This is done with a patch to monkey-patch the resumable media library's checksum
# processing; it does not mock a remote interface like a unit test would. The
# remote API is still exercised.
with mock.patch(
"google.resumable_media._helpers.prepare_checksum_digest",
return_value="FFFFFF==",
):
with self.assertRaises(resumable_media.DataCorruption):
blob.download_to_filename(temp_f.name, checksum="crc32c")
# Confirm the file was deleted on failure
self.assertFalse(os.path.isfile(temp_f.name))
# Now download with checksumming turned off
blob.download_to_filename(temp_f.name, checksum=None)
with open(temp_f.name, "rb") as file_obj:
stored_contents = file_obj.read()
self.assertEqual(file_contents, stored_contents)
def test_copy_existing_file(self):
filename = self.FILES["logo"]["path"]
blob = storage.Blob("CloudLogo", bucket=self.bucket)
blob.upload_from_filename(filename)
self.case_blobs_to_delete.append(blob)
new_blob = retry_bad_copy(self.bucket.copy_blob)(
blob, self.bucket, "CloudLogoCopy"
)
self.case_blobs_to_delete.append(new_blob)
base_contents = blob.download_as_bytes()
copied_contents = new_blob.download_as_bytes()
self.assertEqual(base_contents, copied_contents)
def test_download_blob_w_uri(self):
blob = self.bucket.blob("MyBuffer")
file_contents = b"Hello World"
blob.upload_from_string(file_contents)
self.case_blobs_to_delete.append(blob)
with tempfile.NamedTemporaryFile() as temp_f:
with open(temp_f.name, "wb") as file_obj:
Config.CLIENT.download_blob_to_file(
"gs://" + self.bucket.name + "/MyBuffer", file_obj
)
with open(temp_f.name, "rb") as file_obj:
stored_contents = file_obj.read()
self.assertEqual(file_contents, stored_contents)
def test_download_blob_as_text(self):
blob = self.bucket.blob("MyBuffer")
file_contents = "Hello World"
blob.upload_from_string(file_contents)
self.case_blobs_to_delete.append(blob)
stored_contents = blob.download_as_text()
self.assertEqual(file_contents, stored_contents)
def test_upload_gzip_encoded_download_raw(self):
payload = b"DEADBEEF" * 1000
raw_stream = io.BytesIO()
with gzip.GzipFile(fileobj=raw_stream, mode="wb") as gzip_stream:
gzip_stream.write(payload)
zipped = raw_stream.getvalue()
blob = self.bucket.blob("test_gzipped.gz")
blob.content_encoding = "gzip"
blob.upload_from_file(raw_stream, rewind=True)
expanded = blob.download_as_bytes()
self.assertEqual(expanded, payload)
raw = blob.download_as_bytes(raw_download=True)
self.assertEqual(raw, zipped)
def test_resumable_upload_with_generation_match(self):
blob = self.bucket.blob("LargeFile")
# uploading the file
file_data = self.FILES["big"]
with open(file_data["path"], "rb") as file_obj:
blob.upload_from_file(file_obj)
self.case_blobs_to_delete.append(blob)
# reuploading with correct generations numbers
with open(file_data["path"], "rb") as file_obj:
blob.upload_from_file(
file_obj,
if_generation_match=blob.generation,