-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
test_blob.py
3322 lines (2806 loc) · 124 KB
/
test_blob.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 hashlib
import io
import json
import os
import tempfile
import unittest
import mock
import pytest
import six
from six.moves import http_client
def _make_credentials():
import google.auth.credentials
return mock.Mock(spec=google.auth.credentials.Credentials)
class Test_Blob(unittest.TestCase):
@staticmethod
def _make_one(*args, **kw):
from google.cloud.storage.blob import Blob
properties = kw.pop("properties", {})
blob = Blob(*args, **kw)
blob._properties.update(properties)
return blob
def test_ctor_wo_encryption_key(self):
BLOB_NAME = "blob-name"
bucket = _Bucket()
properties = {"key": "value"}
blob = self._make_one(BLOB_NAME, bucket=bucket, properties=properties)
self.assertIs(blob.bucket, bucket)
self.assertEqual(blob.name, BLOB_NAME)
self.assertEqual(blob._properties, properties)
self.assertFalse(blob._acl.loaded)
self.assertIs(blob._acl.blob, blob)
self.assertEqual(blob._encryption_key, None)
self.assertEqual(blob.kms_key_name, None)
def test_ctor_with_encoded_unicode(self):
blob_name = b"wet \xe2\x9b\xb5"
blob = self._make_one(blob_name, bucket=None)
unicode_name = u"wet \N{sailboat}"
self.assertNotIsInstance(blob.name, bytes)
self.assertIsInstance(blob.name, six.text_type)
self.assertEqual(blob.name, unicode_name)
def test_ctor_w_encryption_key(self):
KEY = b"01234567890123456789012345678901" # 32 bytes
BLOB_NAME = "blob-name"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket, encryption_key=KEY)
self.assertEqual(blob._encryption_key, KEY)
self.assertEqual(blob.kms_key_name, None)
def test_ctor_w_kms_key_name_and_encryption_key(self):
KEY = b"01234567890123456789012345678901" # 32 bytes
KMS_RESOURCE = (
"projects/test-project-123/"
"locations/us/"
"keyRings/test-ring/"
"cryptoKeys/test-key"
)
BLOB_NAME = "blob-name"
bucket = _Bucket()
with self.assertRaises(ValueError):
self._make_one(
BLOB_NAME, bucket=bucket, encryption_key=KEY, kms_key_name=KMS_RESOURCE
)
def test_ctor_w_kms_key_name(self):
KMS_RESOURCE = (
"projects/test-project-123/"
"locations/us/"
"keyRings/test-ring/"
"cryptoKeys/test-key"
)
BLOB_NAME = "blob-name"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket, kms_key_name=KMS_RESOURCE)
self.assertEqual(blob._encryption_key, None)
self.assertEqual(blob.kms_key_name, KMS_RESOURCE)
def test_ctor_with_generation(self):
BLOB_NAME = "blob-name"
GENERATION = 12345
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket, generation=GENERATION)
self.assertEqual(blob.generation, GENERATION)
def _set_properties_helper(self, kms_key_name=None):
import datetime
from google.cloud._helpers import UTC
from google.cloud._helpers import _RFC3339_MICROS
now = datetime.datetime.utcnow().replace(tzinfo=UTC)
NOW = now.strftime(_RFC3339_MICROS)
BLOB_NAME = "blob-name"
GENERATION = 12345
BLOB_ID = "name/{}/{}".format(BLOB_NAME, GENERATION)
SELF_LINK = "http://example.com/self/"
METAGENERATION = 23456
SIZE = 12345
MD5_HASH = "DEADBEEF"
MEDIA_LINK = "http://example.com/media/"
ENTITY = "project-owner-12345"
ENTITY_ID = "23456"
CRC32C = "FACE0DAC"
COMPONENT_COUNT = 2
ETAG = "ETAG"
resource = {
"id": BLOB_ID,
"selfLink": SELF_LINK,
"generation": GENERATION,
"metageneration": METAGENERATION,
"contentType": "text/plain",
"timeCreated": NOW,
"updated": NOW,
"timeDeleted": NOW,
"storageClass": "NEARLINE",
"timeStorageClassUpdated": NOW,
"size": SIZE,
"md5Hash": MD5_HASH,
"mediaLink": MEDIA_LINK,
"contentEncoding": "gzip",
"contentDisposition": "inline",
"contentLanguage": "en-US",
"cacheControl": "private",
"metadata": {"foo": "Foo"},
"owner": {"entity": ENTITY, "entityId": ENTITY_ID},
"crc32c": CRC32C,
"componentCount": COMPONENT_COUNT,
"etag": ETAG,
}
if kms_key_name is not None:
resource["kmsKeyName"] = kms_key_name
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket)
blob._set_properties(resource)
self.assertEqual(blob.id, BLOB_ID)
self.assertEqual(blob.self_link, SELF_LINK)
self.assertEqual(blob.generation, GENERATION)
self.assertEqual(blob.metageneration, METAGENERATION)
self.assertEqual(blob.content_type, "text/plain")
self.assertEqual(blob.time_created, now)
self.assertEqual(blob.updated, now)
self.assertEqual(blob.time_deleted, now)
self.assertEqual(blob.storage_class, "NEARLINE")
self.assertEqual(blob.size, SIZE)
self.assertEqual(blob.md5_hash, MD5_HASH)
self.assertEqual(blob.media_link, MEDIA_LINK)
self.assertEqual(blob.content_encoding, "gzip")
self.assertEqual(blob.content_disposition, "inline")
self.assertEqual(blob.content_language, "en-US")
self.assertEqual(blob.cache_control, "private")
self.assertEqual(blob.metadata, {"foo": "Foo"})
self.assertEqual(blob.owner, {"entity": ENTITY, "entityId": ENTITY_ID})
self.assertEqual(blob.crc32c, CRC32C)
self.assertEqual(blob.component_count, COMPONENT_COUNT)
self.assertEqual(blob.etag, ETAG)
if kms_key_name is not None:
self.assertEqual(blob.kms_key_name, kms_key_name)
else:
self.assertIsNone(blob.kms_key_name)
def test__set_properties_wo_kms_key_name(self):
self._set_properties_helper()
def test__set_properties_w_kms_key_name(self):
kms_resource = (
"projects/test-project-123/"
"locations/us/"
"keyRings/test-ring/"
"cryptoKeys/test-key"
)
self._set_properties_helper(kms_key_name=kms_resource)
def test_chunk_size_ctor(self):
from google.cloud.storage.blob import Blob
BLOB_NAME = "blob-name"
BUCKET = object()
chunk_size = 10 * Blob._CHUNK_SIZE_MULTIPLE
blob = self._make_one(BLOB_NAME, bucket=BUCKET, chunk_size=chunk_size)
self.assertEqual(blob._chunk_size, chunk_size)
def test_chunk_size_getter(self):
BLOB_NAME = "blob-name"
BUCKET = object()
blob = self._make_one(BLOB_NAME, bucket=BUCKET)
self.assertIsNone(blob.chunk_size)
VALUE = object()
blob._chunk_size = VALUE
self.assertIs(blob.chunk_size, VALUE)
def test_chunk_size_setter(self):
BLOB_NAME = "blob-name"
BUCKET = object()
blob = self._make_one(BLOB_NAME, bucket=BUCKET)
self.assertIsNone(blob._chunk_size)
blob._CHUNK_SIZE_MULTIPLE = 10
blob.chunk_size = 20
self.assertEqual(blob._chunk_size, 20)
def test_chunk_size_setter_bad_value(self):
BLOB_NAME = "blob-name"
BUCKET = object()
blob = self._make_one(BLOB_NAME, bucket=BUCKET)
self.assertIsNone(blob._chunk_size)
blob._CHUNK_SIZE_MULTIPLE = 10
with self.assertRaises(ValueError):
blob.chunk_size = 11
def test_acl_property(self):
from google.cloud.storage.acl import ObjectACL
fake_bucket = _Bucket()
blob = self._make_one(u"name", bucket=fake_bucket)
acl = blob.acl
self.assertIsInstance(acl, ObjectACL)
self.assertIs(acl, blob._acl)
def test_path_bad_bucket(self):
fake_bucket = object()
name = u"blob-name"
blob = self._make_one(name, bucket=fake_bucket)
self.assertRaises(AttributeError, getattr, blob, "path")
def test_path_no_name(self):
bucket = _Bucket()
blob = self._make_one(u"", bucket=bucket)
self.assertRaises(ValueError, getattr, blob, "path")
def test_path_normal(self):
BLOB_NAME = "blob-name"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket)
self.assertEqual(blob.path, "/b/name/o/%s" % BLOB_NAME)
def test_path_w_slash_in_name(self):
BLOB_NAME = "parent/child"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket)
self.assertEqual(blob.path, "/b/name/o/parent%2Fchild")
def test_path_with_non_ascii(self):
blob_name = u"Caf\xe9"
bucket = _Bucket()
blob = self._make_one(blob_name, bucket=bucket)
self.assertEqual(blob.path, "/b/name/o/Caf%C3%A9")
def test_bucket_readonly_property(self):
blob_name = "BLOB"
bucket = _Bucket()
other = _Bucket()
blob = self._make_one(blob_name, bucket=bucket)
with self.assertRaises(AttributeError):
blob.bucket = other
def test_client(self):
blob_name = "BLOB"
bucket = _Bucket()
blob = self._make_one(blob_name, bucket=bucket)
self.assertIs(blob.client, bucket.client)
def test_user_project(self):
user_project = "user-project-123"
blob_name = "BLOB"
bucket = _Bucket(user_project=user_project)
blob = self._make_one(blob_name, bucket=bucket)
self.assertEqual(blob.user_project, user_project)
def test__encryption_headers_wo_encryption_key(self):
BLOB_NAME = "blob-name"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket)
expected = {}
self.assertEqual(blob._encryption_headers(), expected)
def test__encryption_headers_w_encryption_key(self):
key = b"aa426195405adee2c8081bb9e7e74b19"
header_key_value = "YWE0MjYxOTU0MDVhZGVlMmM4MDgxYmI5ZTdlNzRiMTk="
header_key_hash_value = "V3Kwe46nKc3xLv96+iJ707YfZfFvlObta8TQcx2gpm0="
BLOB_NAME = "blob-name"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket, encryption_key=key)
expected = {
"X-Goog-Encryption-Algorithm": "AES256",
"X-Goog-Encryption-Key": header_key_value,
"X-Goog-Encryption-Key-Sha256": header_key_hash_value,
}
self.assertEqual(blob._encryption_headers(), expected)
def test__query_params_default(self):
BLOB_NAME = "blob-name"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket)
self.assertEqual(blob._query_params, {})
def test__query_params_w_user_project(self):
user_project = "user-project-123"
BLOB_NAME = "BLOB"
bucket = _Bucket(user_project=user_project)
blob = self._make_one(BLOB_NAME, bucket=bucket)
self.assertEqual(blob._query_params, {"userProject": user_project})
def test__query_params_w_generation(self):
generation = 123456
BLOB_NAME = "BLOB"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket, generation=generation)
self.assertEqual(blob._query_params, {"generation": generation})
def test_public_url(self):
BLOB_NAME = "blob-name"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket)
self.assertEqual(
blob.public_url, "https://storage.googleapis.com/name/%s" % BLOB_NAME
)
def test_public_url_w_slash_in_name(self):
BLOB_NAME = "parent/child"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket)
self.assertEqual(
blob.public_url, "https://storage.googleapis.com/name/parent/child"
)
def test_public_url_w_tilde_in_name(self):
BLOB_NAME = "foo~bar"
bucket = _Bucket()
blob = self._make_one(BLOB_NAME, bucket=bucket)
self.assertEqual(blob.public_url, "https://storage.googleapis.com/name/foo~bar")
def test_public_url_with_non_ascii(self):
blob_name = u"winter \N{snowman}"
bucket = _Bucket()
blob = self._make_one(blob_name, bucket=bucket)
expected_url = "https://storage.googleapis.com/name/winter%20%E2%98%83"
self.assertEqual(blob.public_url, expected_url)
def test_generate_signed_url_w_invalid_version(self):
BLOB_NAME = "blob-name"
EXPIRATION = "2014-10-16T20:34:37.000Z"
connection = _Connection()
client = _Client(connection)
bucket = _Bucket(client)
blob = self._make_one(BLOB_NAME, bucket=bucket)
with self.assertRaises(ValueError):
blob.generate_signed_url(EXPIRATION, version="nonesuch")
def _generate_signed_url_helper(
self,
version=None,
blob_name="blob-name",
api_access_endpoint=None,
method="GET",
content_md5=None,
content_type=None,
response_type=None,
response_disposition=None,
generation=None,
headers=None,
query_parameters=None,
credentials=None,
expiration=None,
encryption_key=None,
):
from six.moves.urllib import parse
from google.cloud._helpers import UTC
from google.cloud.storage.blob import _API_ACCESS_ENDPOINT
from google.cloud.storage.blob import _get_encryption_headers
api_access_endpoint = api_access_endpoint or _API_ACCESS_ENDPOINT
delta = datetime.timedelta(hours=1)
if expiration is None:
expiration = datetime.datetime.utcnow().replace(tzinfo=UTC) + delta
connection = _Connection()
client = _Client(connection)
bucket = _Bucket(client)
blob = self._make_one(blob_name, bucket=bucket, encryption_key=encryption_key)
if version is None:
effective_version = "v2"
else:
effective_version = version
to_patch = "google.cloud.storage.blob.generate_signed_url_{}".format(
effective_version
)
with mock.patch(to_patch) as signer:
signed_uri = blob.generate_signed_url(
expiration=expiration,
api_access_endpoint=api_access_endpoint,
method=method,
credentials=credentials,
content_md5=content_md5,
content_type=content_type,
response_type=response_type,
response_disposition=response_disposition,
generation=generation,
headers=headers,
query_parameters=query_parameters,
version=version,
)
self.assertEqual(signed_uri, signer.return_value)
if credentials is None:
expected_creds = _Connection.credentials
else:
expected_creds = credentials
encoded_name = blob_name.encode("utf-8")
expected_resource = "/name/{}".format(parse.quote(encoded_name, safe=b"/~"))
if encryption_key is not None:
expected_headers = headers or {}
if effective_version == "v2":
expected_headers["X-Goog-Encryption-Algorithm"] = "AES256"
else:
expected_headers.update(_get_encryption_headers(encryption_key))
else:
expected_headers = headers
expected_kwargs = {
"resource": expected_resource,
"expiration": expiration,
"api_access_endpoint": api_access_endpoint,
"method": method.upper(),
"content_md5": content_md5,
"content_type": content_type,
"response_type": response_type,
"response_disposition": response_disposition,
"generation": generation,
"headers": expected_headers,
"query_parameters": query_parameters,
}
signer.assert_called_once_with(expected_creds, **expected_kwargs)
def test_generate_signed_url_no_version_passed_warning(self):
self._generate_signed_url_helper()
def _generate_signed_url_v2_helper(self, **kw):
version = "v2"
self._generate_signed_url_helper(version, **kw)
def test_generate_signed_url_v2_w_defaults(self):
self._generate_signed_url_v2_helper()
def test_generate_signed_url_v2_w_expiration(self):
from google.cloud._helpers import UTC
expiration = datetime.datetime.utcnow().replace(tzinfo=UTC)
self._generate_signed_url_v2_helper(expiration=expiration)
def test_generate_signed_url_v2_w_non_ascii_name(self):
BLOB_NAME = u"\u0410\u043a\u043a\u043e\u0440\u0434\u044b.txt"
self._generate_signed_url_v2_helper(blob_name=BLOB_NAME)
def test_generate_signed_url_v2_w_slash_in_name(self):
BLOB_NAME = "parent/child"
self._generate_signed_url_v2_helper(blob_name=BLOB_NAME)
def test_generate_signed_url_v2_w_tilde_in_name(self):
BLOB_NAME = "foo~bar"
self._generate_signed_url_v2_helper(blob_name=BLOB_NAME)
def test_generate_signed_url_v2_w_endpoint(self):
self._generate_signed_url_v2_helper(
api_access_endpoint="https://api.example.com/v1"
)
def test_generate_signed_url_v2_w_method(self):
self._generate_signed_url_v2_helper(method="POST")
def test_generate_signed_url_v2_w_lowercase_method(self):
self._generate_signed_url_v2_helper(method="get")
def test_generate_signed_url_v2_w_content_md5(self):
self._generate_signed_url_v2_helper(content_md5="FACEDACE")
def test_generate_signed_url_v2_w_content_type(self):
self._generate_signed_url_v2_helper(content_type="text.html")
def test_generate_signed_url_v2_w_response_type(self):
self._generate_signed_url_v2_helper(response_type="text.html")
def test_generate_signed_url_v2_w_response_disposition(self):
self._generate_signed_url_v2_helper(response_disposition="inline")
def test_generate_signed_url_v2_w_generation(self):
self._generate_signed_url_v2_helper(generation=12345)
def test_generate_signed_url_v2_w_headers(self):
self._generate_signed_url_v2_helper(headers={"x-goog-foo": "bar"})
def test_generate_signed_url_v2_w_csek(self):
self._generate_signed_url_v2_helper(encryption_key=os.urandom(32))
def test_generate_signed_url_v2_w_csek_and_headers(self):
self._generate_signed_url_v2_helper(
encryption_key=os.urandom(32), headers={"x-goog-foo": "bar"}
)
def test_generate_signed_url_v2_w_credentials(self):
credentials = object()
self._generate_signed_url_v2_helper(credentials=credentials)
def _generate_signed_url_v4_helper(self, **kw):
version = "v4"
self._generate_signed_url_helper(version, **kw)
def test_generate_signed_url_v4_w_defaults(self):
self._generate_signed_url_v4_helper()
def test_generate_signed_url_v4_w_non_ascii_name(self):
BLOB_NAME = u"\u0410\u043a\u043a\u043e\u0440\u0434\u044b.txt"
self._generate_signed_url_v4_helper(blob_name=BLOB_NAME)
def test_generate_signed_url_v4_w_slash_in_name(self):
BLOB_NAME = "parent/child"
self._generate_signed_url_v4_helper(blob_name=BLOB_NAME)
def test_generate_signed_url_v4_w_tilde_in_name(self):
BLOB_NAME = "foo~bar"
self._generate_signed_url_v4_helper(blob_name=BLOB_NAME)
def test_generate_signed_url_v4_w_endpoint(self):
self._generate_signed_url_v4_helper(
api_access_endpoint="https://api.example.com/v1"
)
def test_generate_signed_url_v4_w_method(self):
self._generate_signed_url_v4_helper(method="POST")
def test_generate_signed_url_v4_w_lowercase_method(self):
self._generate_signed_url_v4_helper(method="get")
def test_generate_signed_url_v4_w_content_md5(self):
self._generate_signed_url_v4_helper(content_md5="FACEDACE")
def test_generate_signed_url_v4_w_content_type(self):
self._generate_signed_url_v4_helper(content_type="text.html")
def test_generate_signed_url_v4_w_response_type(self):
self._generate_signed_url_v4_helper(response_type="text.html")
def test_generate_signed_url_v4_w_response_disposition(self):
self._generate_signed_url_v4_helper(response_disposition="inline")
def test_generate_signed_url_v4_w_generation(self):
self._generate_signed_url_v4_helper(generation=12345)
def test_generate_signed_url_v4_w_headers(self):
self._generate_signed_url_v4_helper(headers={"x-goog-foo": "bar"})
def test_generate_signed_url_v4_w_csek(self):
self._generate_signed_url_v4_helper(encryption_key=os.urandom(32))
def test_generate_signed_url_v4_w_csek_and_headers(self):
self._generate_signed_url_v4_helper(
encryption_key=os.urandom(32), headers={"x-goog-foo": "bar"}
)
def test_generate_signed_url_v4_w_credentials(self):
credentials = object()
self._generate_signed_url_v4_helper(credentials=credentials)
def test_exists_miss(self):
NONESUCH = "nonesuch"
not_found_response = ({"status": http_client.NOT_FOUND}, b"")
connection = _Connection(not_found_response)
client = _Client(connection)
bucket = _Bucket(client)
blob = self._make_one(NONESUCH, bucket=bucket)
self.assertFalse(blob.exists())
self.assertEqual(len(connection._requested), 1)
self.assertEqual(
connection._requested[0],
{
"method": "GET",
"path": "/b/name/o/{}".format(NONESUCH),
"query_params": {"fields": "name"},
"_target_object": None,
},
)
def test_exists_hit_w_user_project(self):
BLOB_NAME = "blob-name"
USER_PROJECT = "user-project-123"
found_response = ({"status": http_client.OK}, b"")
connection = _Connection(found_response)
client = _Client(connection)
bucket = _Bucket(client, user_project=USER_PROJECT)
blob = self._make_one(BLOB_NAME, bucket=bucket)
bucket._blobs[BLOB_NAME] = 1
self.assertTrue(blob.exists())
self.assertEqual(len(connection._requested), 1)
self.assertEqual(
connection._requested[0],
{
"method": "GET",
"path": "/b/name/o/{}".format(BLOB_NAME),
"query_params": {"fields": "name", "userProject": USER_PROJECT},
"_target_object": None,
},
)
def test_exists_hit_w_generation(self):
BLOB_NAME = "blob-name"
GENERATION = 123456
found_response = ({"status": http_client.OK}, b"")
connection = _Connection(found_response)
client = _Client(connection)
bucket = _Bucket(client)
blob = self._make_one(BLOB_NAME, bucket=bucket, generation=GENERATION)
bucket._blobs[BLOB_NAME] = 1
self.assertTrue(blob.exists())
self.assertEqual(len(connection._requested), 1)
self.assertEqual(
connection._requested[0],
{
"method": "GET",
"path": "/b/name/o/{}".format(BLOB_NAME),
"query_params": {"fields": "name", "generation": GENERATION},
"_target_object": None,
},
)
def test_delete_wo_generation(self):
BLOB_NAME = "blob-name"
not_found_response = ({"status": http_client.NOT_FOUND}, b"")
connection = _Connection(not_found_response)
client = _Client(connection)
bucket = _Bucket(client)
blob = self._make_one(BLOB_NAME, bucket=bucket)
bucket._blobs[BLOB_NAME] = 1
blob.delete()
self.assertFalse(blob.exists())
self.assertEqual(bucket._deleted, [(BLOB_NAME, None, None)])
def test_delete_w_generation(self):
BLOB_NAME = "blob-name"
GENERATION = 123456
not_found_response = ({"status": http_client.NOT_FOUND}, b"")
connection = _Connection(not_found_response)
client = _Client(connection)
bucket = _Bucket(client)
blob = self._make_one(BLOB_NAME, bucket=bucket, generation=GENERATION)
bucket._blobs[BLOB_NAME] = 1
blob.delete()
self.assertFalse(blob.exists())
self.assertEqual(bucket._deleted, [(BLOB_NAME, None, GENERATION)])
def test__get_transport(self):
client = mock.Mock(spec=[u"_credentials", "_http"])
client._http = mock.sentinel.transport
blob = self._make_one(u"blob-name", bucket=None)
transport = blob._get_transport(client)
self.assertIs(transport, mock.sentinel.transport)
def test__get_download_url_with_media_link(self):
blob_name = "something.txt"
bucket = _Bucket(name="IRRELEVANT")
blob = self._make_one(blob_name, bucket=bucket)
media_link = "http://test.invalid"
# Set the media link on the blob
blob._properties["mediaLink"] = media_link
download_url = blob._get_download_url()
self.assertEqual(download_url, media_link)
def test__get_download_url_with_media_link_w_user_project(self):
blob_name = "something.txt"
user_project = "user-project-123"
bucket = _Bucket(name="IRRELEVANT", user_project=user_project)
blob = self._make_one(blob_name, bucket=bucket)
media_link = "http://test.invalid"
# Set the media link on the blob
blob._properties["mediaLink"] = media_link
download_url = blob._get_download_url()
self.assertEqual(
download_url, "{}?userProject={}".format(media_link, user_project)
)
def test__get_download_url_on_the_fly(self):
blob_name = "bzzz-fly.txt"
bucket = _Bucket(name="buhkit")
blob = self._make_one(blob_name, bucket=bucket)
self.assertIsNone(blob.media_link)
download_url = blob._get_download_url()
expected_url = (
"https://storage.googleapis.com/download/storage/v1/b/"
"buhkit/o/bzzz-fly.txt?alt=media"
)
self.assertEqual(download_url, expected_url)
def test__get_download_url_on_the_fly_with_generation(self):
blob_name = "pretend.txt"
bucket = _Bucket(name="fictional")
blob = self._make_one(blob_name, bucket=bucket)
generation = 1493058489532987
# Set the media link on the blob
blob._properties["generation"] = str(generation)
self.assertIsNone(blob.media_link)
download_url = blob._get_download_url()
expected_url = (
"https://storage.googleapis.com/download/storage/v1/b/"
"fictional/o/pretend.txt?alt=media&generation=1493058489532987"
)
self.assertEqual(download_url, expected_url)
def test__get_download_url_on_the_fly_with_user_project(self):
blob_name = "pretend.txt"
user_project = "user-project-123"
bucket = _Bucket(name="fictional", user_project=user_project)
blob = self._make_one(blob_name, bucket=bucket)
self.assertIsNone(blob.media_link)
download_url = blob._get_download_url()
expected_url = (
"https://storage.googleapis.com/download/storage/v1/b/"
"fictional/o/pretend.txt?alt=media&userProject={}".format(user_project)
)
self.assertEqual(download_url, expected_url)
def test__get_download_url_on_the_fly_with_kms_key_name(self):
kms_resource = (
"projects/test-project-123/"
"locations/us/"
"keyRings/test-ring/"
"cryptoKeys/test-key"
)
blob_name = "bzzz-fly.txt"
bucket = _Bucket(name="buhkit")
blob = self._make_one(blob_name, bucket=bucket, kms_key_name=kms_resource)
self.assertIsNone(blob.media_link)
download_url = blob._get_download_url()
expected_url = (
"https://storage.googleapis.com/download/storage/v1/b/"
"buhkit/o/bzzz-fly.txt?alt=media"
)
self.assertEqual(download_url, expected_url)
@staticmethod
def _mock_requests_response(status_code, headers, content=b""):
import requests
response = requests.Response()
response.status_code = status_code
response.headers.update(headers)
response.raw = None
response._content = content
response.request = requests.Request("POST", "http://example.com").prepare()
return response
def _do_download_helper_wo_chunks(self, w_range, raw_download):
blob_name = "blob-name"
client = mock.Mock()
bucket = _Bucket(client)
blob = self._make_one(blob_name, bucket=bucket)
self.assertIsNone(blob.chunk_size)
transport = object()
file_obj = io.BytesIO()
download_url = "http://test.invalid"
headers = {}
if raw_download:
patch = mock.patch("google.cloud.storage.blob.RawDownload")
else:
patch = mock.patch("google.cloud.storage.blob.Download")
with patch as patched:
if w_range:
blob._do_download(
transport,
file_obj,
download_url,
headers,
start=1,
end=3,
raw_download=raw_download,
)
else:
blob._do_download(
transport,
file_obj,
download_url,
headers,
raw_download=raw_download,
)
if w_range:
patched.assert_called_once_with(
download_url, stream=file_obj, headers=headers, start=1, end=3
)
else:
patched.assert_called_once_with(
download_url, stream=file_obj, headers=headers, start=None, end=None
)
patched.return_value.consume.assert_called_once_with(transport)
def test__do_download_wo_chunks_wo_range_wo_raw(self):
self._do_download_helper_wo_chunks(w_range=False, raw_download=False)
def test__do_download_wo_chunks_w_range_wo_raw(self):
self._do_download_helper_wo_chunks(w_range=True, raw_download=False)
def test__do_download_wo_chunks_wo_range_w_raw(self):
self._do_download_helper_wo_chunks(w_range=False, raw_download=True)
def test__do_download_wo_chunks_w_range_w_raw(self):
self._do_download_helper_wo_chunks(w_range=True, raw_download=True)
def _do_download_helper_w_chunks(self, w_range, raw_download):
blob_name = "blob-name"
client = mock.Mock(_credentials=_make_credentials(), spec=["_credentials"])
bucket = _Bucket(client)
blob = self._make_one(blob_name, bucket=bucket)
blob._CHUNK_SIZE_MULTIPLE = 1
chunk_size = blob.chunk_size = 3
transport = object()
file_obj = io.BytesIO()
download_url = "http://test.invalid"
headers = {}
download = mock.Mock(finished=False, spec=["finished", "consume_next_chunk"])
def side_effect(_):
download.finished = True
download.consume_next_chunk.side_effect = side_effect
if raw_download:
patch = mock.patch("google.cloud.storage.blob.RawChunkedDownload")
else:
patch = mock.patch("google.cloud.storage.blob.ChunkedDownload")
with patch as patched:
patched.return_value = download
if w_range:
blob._do_download(
transport,
file_obj,
download_url,
headers,
start=1,
end=3,
raw_download=raw_download,
)
else:
blob._do_download(
transport,
file_obj,
download_url,
headers,
raw_download=raw_download,
)
if w_range:
patched.assert_called_once_with(
download_url, chunk_size, file_obj, headers=headers, start=1, end=3
)
else:
patched.assert_called_once_with(
download_url, chunk_size, file_obj, headers=headers, start=0, end=None
)
download.consume_next_chunk.assert_called_once_with(transport)
def test__do_download_w_chunks_wo_range_wo_raw(self):
self._do_download_helper_w_chunks(w_range=False, raw_download=False)
def test__do_download_w_chunks_w_range_wo_raw(self):
self._do_download_helper_w_chunks(w_range=True, raw_download=False)
def test__do_download_w_chunks_wo_range_w_raw(self):
self._do_download_helper_w_chunks(w_range=False, raw_download=True)
def test__do_download_w_chunks_w_range_w_raw(self):
self._do_download_helper_w_chunks(w_range=True, raw_download=True)
def test_download_to_file_with_failure(self):
import requests
from google.resumable_media import InvalidResponse
from google.cloud import exceptions
raw_response = requests.Response()
raw_response.status_code = http_client.NOT_FOUND
raw_request = requests.Request("GET", "http://example.com")
raw_response.request = raw_request.prepare()
grmp_response = InvalidResponse(raw_response)
blob_name = "blob-name"
media_link = "http://test.invalid"
client = mock.Mock(spec=[u"_http"])
bucket = _Bucket(client)
blob = self._make_one(blob_name, bucket=bucket)
blob._properties["mediaLink"] = media_link
blob._do_download = mock.Mock()
blob._do_download.side_effect = grmp_response
file_obj = io.BytesIO()
with self.assertRaises(exceptions.NotFound):
blob.download_to_file(file_obj)
self.assertEqual(file_obj.tell(), 0)
headers = {"accept-encoding": "gzip"}
blob._do_download.assert_called_once_with(
client._http, file_obj, media_link, headers, None, None, False
)
def test_download_to_file_wo_media_link(self):
blob_name = "blob-name"
client = mock.Mock(spec=[u"_http"])
bucket = _Bucket(client)
blob = self._make_one(blob_name, bucket=bucket)
blob._do_download = mock.Mock()
file_obj = io.BytesIO()
blob.download_to_file(file_obj)
# Make sure the media link is still unknown.
self.assertIsNone(blob.media_link)
expected_url = (
"https://storage.googleapis.com/download/storage/v1/b/"
"name/o/blob-name?alt=media"
)
headers = {"accept-encoding": "gzip"}
blob._do_download.assert_called_once_with(
client._http, file_obj, expected_url, headers, None, None, False
)
def _download_to_file_helper(self, use_chunks, raw_download):
blob_name = "blob-name"
client = mock.Mock(spec=[u"_http"])
bucket = _Bucket(client)
media_link = "http://example.com/media/"
properties = {"mediaLink": media_link}
blob = self._make_one(blob_name, bucket=bucket, properties=properties)
if use_chunks:
blob._CHUNK_SIZE_MULTIPLE = 1
blob.chunk_size = 3
blob._do_download = mock.Mock()
file_obj = io.BytesIO()
if raw_download:
blob.download_to_file(file_obj, raw_download=True)
else:
blob.download_to_file(file_obj)
headers = {"accept-encoding": "gzip"}
blob._do_download.assert_called_once_with(
client._http, file_obj, media_link, headers, None, None, raw_download
)
def test_download_to_file_wo_chunks_wo_raw(self):
self._download_to_file_helper(use_chunks=False, raw_download=False)
def test_download_to_file_w_chunks_wo_raw(self):