/
test_fileio.py
955 lines (761 loc) · 35.3 KB
/
test_fileio.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
# coding=utf-8
# Copyright 2021 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 unittest
import io
import string
import mock
from google.api_core.exceptions import RequestRangeNotSatisfiable
from google.cloud.storage.retry import DEFAULT_RETRY
TEST_TEXT_DATA = string.ascii_lowercase + "\n" + string.ascii_uppercase + "\n"
TEST_BINARY_DATA = TEST_TEXT_DATA.encode("utf-8")
TEST_MULTIBYTE_TEXT_DATA = u"あいうえおかきくけこさしすせそたちつてと"
PLAIN_CONTENT_TYPE = "text/plain"
NUM_RETRIES = 2
class _BlobReaderBase:
@staticmethod
def _make_blob_reader(*args, **kwargs):
from google.cloud.storage.fileio import BlobReader
return BlobReader(*args, **kwargs)
class _BlobWriterBase:
@staticmethod
def _make_blob_writer(*args, **kwargs):
from google.cloud.storage.fileio import BlobWriter
return BlobWriter(*args, **kwargs)
class TestBlobReaderBinary(unittest.TestCase, _BlobReaderBase):
def test_attributes(self):
blob = mock.Mock()
blob.chunk_size = 256
reader = self._make_blob_reader(blob)
self.assertTrue(reader.seekable())
self.assertTrue(reader.readable())
self.assertFalse(reader.writable())
self.assertEqual(reader._chunk_size, 256)
self.assertEqual(reader._retry, DEFAULT_RETRY)
def test_attributes_explict(self):
blob = mock.Mock()
blob.chunk_size = 256
reader = self._make_blob_reader(blob, chunk_size=1024, retry=None)
self.assertEqual(reader._chunk_size, 1024)
self.assertIsNone(reader._retry)
def test_read(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_BINARY_DATA[start:end]
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
download_kwargs = {"if_metageneration_match": 1}
reader = self._make_blob_reader(blob, chunk_size=8, **download_kwargs)
# Read and trigger the first download of chunk_size.
self.assertEqual(reader.read(1), TEST_BINARY_DATA[0:1])
blob.download_as_bytes.assert_called_once_with(
start=0, end=8, checksum=None, retry=DEFAULT_RETRY, **download_kwargs
)
# Read from buffered data only.
self.assertEqual(reader.read(3), TEST_BINARY_DATA[1:4])
blob.download_as_bytes.assert_called_once()
# Read remaining buffer plus an additional chunk read.
self.assertEqual(reader.read(8), TEST_BINARY_DATA[4:12])
self.assertEqual(reader._pos, 12)
self.assertEqual(blob.download_as_bytes.call_count, 2)
blob.download_as_bytes.assert_called_with(
start=8, end=16, checksum=None, retry=DEFAULT_RETRY, **download_kwargs
)
# Read a larger amount, requiring a download larger than chunk_size.
self.assertEqual(reader.read(16), TEST_BINARY_DATA[12:28])
self.assertEqual(reader._pos, 28)
self.assertEqual(blob.download_as_bytes.call_count, 3)
blob.download_as_bytes.assert_called_with(
start=16, end=28, checksum=None, retry=DEFAULT_RETRY, **download_kwargs
)
# Read all remaining data.
self.assertEqual(reader.read(), TEST_BINARY_DATA[28:])
self.assertEqual(blob.download_as_bytes.call_count, 4)
blob.download_as_bytes.assert_called_with(
start=28, end=None, checksum=None, retry=DEFAULT_RETRY, **download_kwargs
)
reader.close()
def test_read_with_raw_download(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_BINARY_DATA[start:end]
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
download_kwargs = {"raw_download": True}
reader = self._make_blob_reader(blob, chunk_size=8, **download_kwargs)
# Read and trigger the first download of chunk_size.
self.assertEqual(reader.read(1), TEST_BINARY_DATA[0:1])
blob.download_as_bytes.assert_called_once_with(
start=0, end=8, checksum=None, retry=DEFAULT_RETRY, raw_download=True
)
reader.close()
def test_retry_passed_through(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_BINARY_DATA[start:end]
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
download_kwargs = {"if_metageneration_match": 1}
reader = self._make_blob_reader(
blob, chunk_size=8, retry=None, **download_kwargs
)
# Read and trigger the first download of chunk_size.
self.assertEqual(reader.read(1), TEST_BINARY_DATA[0:1])
blob.download_as_bytes.assert_called_once_with(
start=0, end=8, checksum=None, retry=None, **download_kwargs
)
reader.close()
def test_416_error_handled(self):
blob = mock.Mock()
blob.download_as_bytes = mock.Mock(
side_effect=RequestRangeNotSatisfiable("message")
)
reader = self._make_blob_reader(blob)
self.assertEqual(reader.read(), b"")
def test_readline(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_BINARY_DATA[start:end]
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
reader = self._make_blob_reader(blob, chunk_size=10)
# Read a line. With chunk_size=10, expect three chunks downloaded.
self.assertEqual(reader.readline(), TEST_BINARY_DATA[:27])
blob.download_as_bytes.assert_called_with(
start=20, end=30, checksum=None, retry=DEFAULT_RETRY
)
self.assertEqual(blob.download_as_bytes.call_count, 3)
# Read another line.
self.assertEqual(reader.readline(), TEST_BINARY_DATA[27:])
blob.download_as_bytes.assert_called_with(
start=50, end=60, checksum=None, retry=DEFAULT_RETRY
)
self.assertEqual(blob.download_as_bytes.call_count, 6)
blob.size = len(TEST_BINARY_DATA)
reader.seek(0)
# Read all lines. The readlines algorithm will attempt to read past the end of the last line once to verify there is no more to read.
self.assertEqual(b"".join(reader.readlines()), TEST_BINARY_DATA)
blob.download_as_bytes.assert_called_with(
start=len(TEST_BINARY_DATA),
end=len(TEST_BINARY_DATA) + 10,
checksum=None,
retry=DEFAULT_RETRY,
)
self.assertEqual(blob.download_as_bytes.call_count, 13)
reader.close()
def test_seek(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_BINARY_DATA[start:end]
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
blob.size = None
download_kwargs = {"if_metageneration_match": 1}
reader = self._make_blob_reader(blob, chunk_size=8, **download_kwargs)
# Seek needs the blob size to work and should call reload() if the size
# is not known. Set a mock to initialize the size if reload() is called.
def initialize_size(**_):
blob.size = len(TEST_BINARY_DATA)
blob.reload = mock.Mock(side_effect=initialize_size)
# Seek, forcing a blob reload in order to validate the seek doesn't
# exceed the end of the blob.
self.assertEqual(reader.seek(4), 4)
blob.reload.assert_called_once_with(**download_kwargs)
self.assertEqual(reader.read(4), TEST_BINARY_DATA[4:8])
self.assertEqual(blob.download_as_bytes.call_count, 1)
# Seek forward 2 bytes with whence=1. Position is still in buffer.
self.assertEqual(reader.seek(2, 1), 10)
self.assertEqual(reader.read(2), TEST_BINARY_DATA[10:12])
self.assertEqual(blob.download_as_bytes.call_count, 1)
# Attempt seek past end of file. Position should be at end of file.
self.assertEqual(
reader.seek(len(TEST_BINARY_DATA) + 100), len(TEST_BINARY_DATA)
)
# Seek to beginning. The next read will need to download data again.
self.assertEqual(reader.seek(0), 0)
self.assertEqual(reader.read(4), TEST_BINARY_DATA[0:4])
self.assertEqual(blob.download_as_bytes.call_count, 2)
# Seek relative to end with whence=2.
self.assertEqual(reader.seek(-1, 2), len(TEST_BINARY_DATA) - 1)
self.assertEqual(reader.read(), TEST_BINARY_DATA[-1:])
self.assertEqual(blob.download_as_bytes.call_count, 3)
with self.assertRaises(ValueError):
reader.seek(1, 4)
# tell() is an inherited method that uses seek().
self.assertEqual(reader.tell(), reader._pos)
reader.close()
def test_advanced_seek(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_BINARY_DATA[start:end] * 1024
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
blob.size = None
download_kwargs = {"if_metageneration_match": 1}
reader = self._make_blob_reader(blob, chunk_size=1024, **download_kwargs)
# Seek needs the blob size to work and should call reload() if the size
# is not known. Set a mock to initialize the size if reload() is called.
def initialize_size(**_):
blob.size = len(TEST_BINARY_DATA) * 1024
blob.reload = mock.Mock(side_effect=initialize_size)
self.assertEqual(reader.tell(), 0)
# Mimic tarfile access pattern. Read tarinfo block.
reader.read(512)
self.assertEqual(reader.tell(), 512)
self.assertEqual(reader.seek(512), 512)
# Mimic read actual tar content.
reader.read(400)
self.assertEqual(reader.tell(), 912)
# Tarfile offsets are rounded up by block size
# A sanity seek/read is used to check for unexpected ends.
reader.seek(1023)
reader.read(1)
self.assertEqual(reader.tell(), 1024)
reader.read(512)
self.assertEqual(reader.tell(), 1536)
reader.close()
def test_close(self):
blob = mock.Mock()
reader = self._make_blob_reader(blob)
reader.close()
with self.assertRaises(ValueError):
reader.read()
with self.assertRaises(ValueError):
reader.seek(0)
def test_context_mgr(self):
# Just very that the context manager form doesn't crash.
blob = mock.Mock()
with self._make_blob_reader(blob) as reader:
reader.close()
def test_rejects_invalid_kwargs(self):
blob = mock.Mock()
with self.assertRaises(ValueError):
self._make_blob_reader(blob, invalid_kwarg=1)
class TestBlobWriterBinary(unittest.TestCase, _BlobWriterBase):
def test_attributes(self):
blob = mock.Mock()
blob.chunk_size = 256 * 1024
writer = self._make_blob_writer(blob)
self.assertFalse(writer.seekable())
self.assertFalse(writer.readable())
self.assertTrue(writer.writable())
self.assertEqual(writer._chunk_size, 256 * 1024)
def test_attributes_explicit(self):
blob = mock.Mock()
blob.chunk_size = 256 * 1024
writer = self._make_blob_writer(
blob, chunk_size=512 * 1024, retry=DEFAULT_RETRY
)
self.assertEqual(writer._chunk_size, 512 * 1024)
self.assertEqual(writer._retry, DEFAULT_RETRY)
def test_deprecated_text_mode_attribute(self):
blob = mock.Mock()
blob.chunk_size = 256 * 1024
writer = self._make_blob_writer(blob, text_mode=True)
self.assertTrue(writer._ignore_flush)
writer.flush() # This should do nothing and not raise an error.
def test_reject_wrong_chunk_size(self):
blob = mock.Mock()
blob.chunk_size = 123
with self.assertRaises(ValueError):
_ = self._make_blob_writer(blob)
@mock.patch("warnings.warn")
def test_write(self, mock_warn):
from google.cloud.storage._helpers import _NUM_RETRIES_MESSAGE
blob = mock.Mock()
upload = mock.Mock()
transport = mock.Mock()
blob._initiate_resumable_upload.return_value = (upload, transport)
with mock.patch("google.cloud.storage.fileio.CHUNK_SIZE_MULTIPLE", 1):
# Create a writer with (arbitrary) arguments so we can validate the
# arguments are used.
# It would be normal to use a context manager here, but not doing so
# gives us more control over close() for test purposes.
upload_kwargs = {"if_metageneration_match": 1}
chunk_size = 8 # Note: Real upload requires a multiple of 256KiB.
writer = self._make_blob_writer(
blob,
chunk_size=chunk_size,
num_retries=NUM_RETRIES,
content_type=PLAIN_CONTENT_TYPE,
**upload_kwargs
)
# The transmit_next_chunk method must actually consume bytes from the
# sliding buffer for the flush() feature to work properly.
upload.transmit_next_chunk.side_effect = lambda _: writer._buffer.read(
chunk_size
)
# Write under chunk_size. This should be buffered and the upload not
# initiated.
writer.write(TEST_BINARY_DATA[0:4])
blob.initiate_resumable_upload.assert_not_called()
# Write over chunk_size. This should result in upload initialization
# and multiple chunks uploaded.
writer.write(TEST_BINARY_DATA[4:32])
blob._initiate_resumable_upload.assert_called_once_with(
blob.bucket.client,
writer._buffer,
PLAIN_CONTENT_TYPE,
None,
NUM_RETRIES,
chunk_size=chunk_size,
retry=None,
**upload_kwargs
)
upload.transmit_next_chunk.assert_called_with(transport)
self.assertEqual(upload.transmit_next_chunk.call_count, 4)
# Write another byte, finalize and close.
writer.write(TEST_BINARY_DATA[32:33])
self.assertEqual(writer.tell(), 33)
writer.close()
self.assertEqual(upload.transmit_next_chunk.call_count, 5)
mock_warn.assert_called_once_with(
_NUM_RETRIES_MESSAGE, DeprecationWarning, stacklevel=2,
)
def test_flush_fails(self):
blob = mock.Mock(chunk_size=None)
writer = self._make_blob_writer(blob)
with self.assertRaises(io.UnsupportedOperation):
writer.flush()
def test_seek_fails(self):
blob = mock.Mock(chunk_size=None)
writer = self._make_blob_writer(blob)
with self.assertRaises(io.UnsupportedOperation):
writer.seek()
def test_conditional_retry_failure(self):
blob = mock.Mock()
upload = mock.Mock()
transport = mock.Mock()
blob._initiate_resumable_upload.return_value = (upload, transport)
with mock.patch("google.cloud.storage.fileio.CHUNK_SIZE_MULTIPLE", 1):
# Create a writer.
# It would be normal to use a context manager here, but not doing so
# gives us more control over close() for test purposes.
chunk_size = 8 # Note: Real upload requires a multiple of 256KiB.
writer = self._make_blob_writer(
blob, chunk_size=chunk_size, content_type=PLAIN_CONTENT_TYPE,
)
# The transmit_next_chunk method must actually consume bytes from the
# sliding buffer for the flush() feature to work properly.
upload.transmit_next_chunk.side_effect = lambda _: writer._buffer.read(
chunk_size
)
# Write under chunk_size. This should be buffered and the upload not
# initiated.
writer.write(TEST_BINARY_DATA[0:4])
blob.initiate_resumable_upload.assert_not_called()
# Write over chunk_size. This should result in upload initialization
# and multiple chunks uploaded.
# Due to the condition not being fulfilled, retry should be None.
writer.write(TEST_BINARY_DATA[4:32])
blob._initiate_resumable_upload.assert_called_once_with(
blob.bucket.client,
writer._buffer,
PLAIN_CONTENT_TYPE,
None, # size
None, # num_retries
chunk_size=chunk_size,
retry=None,
)
upload.transmit_next_chunk.assert_called_with(transport)
self.assertEqual(upload.transmit_next_chunk.call_count, 4)
# Write another byte, finalize and close.
writer.write(TEST_BINARY_DATA[32:33])
writer.close()
self.assertEqual(upload.transmit_next_chunk.call_count, 5)
def test_conditional_retry_pass(self):
blob = mock.Mock()
upload = mock.Mock()
transport = mock.Mock()
blob._initiate_resumable_upload.return_value = (upload, transport)
with mock.patch("google.cloud.storage.fileio.CHUNK_SIZE_MULTIPLE", 1):
# Create a writer.
# It would be normal to use a context manager here, but not doing so
# gives us more control over close() for test purposes.
chunk_size = 8 # Note: Real upload requires a multiple of 256KiB.
writer = self._make_blob_writer(
blob,
chunk_size=chunk_size,
content_type=PLAIN_CONTENT_TYPE,
if_generation_match=123456,
)
# The transmit_next_chunk method must actually consume bytes from the
# sliding buffer for the flush() feature to work properly.
upload.transmit_next_chunk.side_effect = lambda _: writer._buffer.read(
chunk_size
)
# Write under chunk_size. This should be buffered and the upload not
# initiated.
writer.write(TEST_BINARY_DATA[0:4])
blob.initiate_resumable_upload.assert_not_called()
# Write over chunk_size. This should result in upload initialization
# and multiple chunks uploaded.
# Due to the condition being fulfilled, retry should be DEFAULT_RETRY.
writer.write(TEST_BINARY_DATA[4:32])
blob._initiate_resumable_upload.assert_called_once_with(
blob.bucket.client,
writer._buffer,
PLAIN_CONTENT_TYPE,
None, # size
None, # num_retries
chunk_size=chunk_size,
retry=DEFAULT_RETRY,
if_generation_match=123456,
)
upload.transmit_next_chunk.assert_called_with(transport)
self.assertEqual(upload.transmit_next_chunk.call_count, 4)
# Write another byte, finalize and close.
writer.write(TEST_BINARY_DATA[32:33])
writer.close()
self.assertEqual(upload.transmit_next_chunk.call_count, 5)
def test_forced_default_retry(self):
blob = mock.Mock()
upload = mock.Mock()
transport = mock.Mock()
blob._initiate_resumable_upload.return_value = (upload, transport)
with mock.patch("google.cloud.storage.fileio.CHUNK_SIZE_MULTIPLE", 1):
# Create a writer.
# It would be normal to use a context manager here, but not doing so
# gives us more control over close() for test purposes.
chunk_size = 8 # Note: Real upload requires a multiple of 256KiB.
writer = self._make_blob_writer(
blob,
chunk_size=chunk_size,
content_type=PLAIN_CONTENT_TYPE,
retry=DEFAULT_RETRY,
)
# The transmit_next_chunk method must actually consume bytes from the
# sliding buffer for the flush() feature to work properly.
upload.transmit_next_chunk.side_effect = lambda _: writer._buffer.read(
chunk_size
)
# Write under chunk_size. This should be buffered and the upload not
# initiated.
writer.write(TEST_BINARY_DATA[0:4])
blob.initiate_resumable_upload.assert_not_called()
# Write over chunk_size. This should result in upload initialization
# and multiple chunks uploaded.
writer.write(TEST_BINARY_DATA[4:32])
blob._initiate_resumable_upload.assert_called_once_with(
blob.bucket.client,
writer._buffer,
PLAIN_CONTENT_TYPE,
None, # size
None, # num_retries
chunk_size=chunk_size,
retry=DEFAULT_RETRY,
)
upload.transmit_next_chunk.assert_called_with(transport)
self.assertEqual(upload.transmit_next_chunk.call_count, 4)
# Write another byte, finalize and close.
writer.write(TEST_BINARY_DATA[32:33])
writer.close()
self.assertEqual(upload.transmit_next_chunk.call_count, 5)
@mock.patch("warnings.warn")
def test_num_retries_and_retry_conflict(self, mock_warn):
from google.cloud.storage._helpers import _NUM_RETRIES_MESSAGE
blob = mock.Mock()
blob._initiate_resumable_upload.side_effect = ValueError
with mock.patch("google.cloud.storage.fileio.CHUNK_SIZE_MULTIPLE", 1):
# Create a writer.
# It would be normal to use a context manager here, but not doing so
# gives us more control over close() for test purposes.
chunk_size = 8 # Note: Real upload requires a multiple of 256KiB.
writer = self._make_blob_writer(
blob,
chunk_size=chunk_size,
content_type=PLAIN_CONTENT_TYPE,
num_retries=2,
retry=DEFAULT_RETRY,
)
# Write under chunk_size. This should be buffered and the upload not
# initiated.
writer.write(TEST_BINARY_DATA[0:4])
blob.initiate_resumable_upload.assert_not_called()
# Write over chunk_size. The mock will raise a ValueError, simulating
# actual behavior when num_retries and retry are both specified.
with self.assertRaises(ValueError):
writer.write(TEST_BINARY_DATA[4:32])
blob._initiate_resumable_upload.assert_called_once_with(
blob.bucket.client,
writer._buffer,
PLAIN_CONTENT_TYPE,
None, # size
2, # num_retries
chunk_size=chunk_size,
retry=DEFAULT_RETRY,
)
mock_warn.assert_called_once_with(
_NUM_RETRIES_MESSAGE, DeprecationWarning, stacklevel=2,
)
@mock.patch("warnings.warn")
def test_num_retries_only(self, mock_warn):
from google.cloud.storage._helpers import _NUM_RETRIES_MESSAGE
blob = mock.Mock()
upload = mock.Mock()
transport = mock.Mock()
blob._initiate_resumable_upload.return_value = (upload, transport)
with mock.patch("google.cloud.storage.fileio.CHUNK_SIZE_MULTIPLE", 1):
# Create a writer.
# It would be normal to use a context manager here, but not doing so
# gives us more control over close() for test purposes.
chunk_size = 8 # Note: Real upload requires a multiple of 256KiB.
writer = self._make_blob_writer(
blob,
chunk_size=chunk_size,
content_type=PLAIN_CONTENT_TYPE,
num_retries=2,
)
# The transmit_next_chunk method must actually consume bytes from the
# sliding buffer for the flush() feature to work properly.
upload.transmit_next_chunk.side_effect = lambda _: writer._buffer.read(
chunk_size
)
# Write under chunk_size. This should be buffered and the upload not
# initiated.
writer.write(TEST_BINARY_DATA[0:4])
blob.initiate_resumable_upload.assert_not_called()
# Write over chunk_size. This should result in upload initialization
# and multiple chunks uploaded.
writer.write(TEST_BINARY_DATA[4:32])
blob._initiate_resumable_upload.assert_called_once_with(
blob.bucket.client,
writer._buffer,
PLAIN_CONTENT_TYPE,
None, # size
2, # num_retries
chunk_size=chunk_size,
retry=None,
)
upload.transmit_next_chunk.assert_called_with(transport)
self.assertEqual(upload.transmit_next_chunk.call_count, 4)
mock_warn.assert_called_once_with(
_NUM_RETRIES_MESSAGE, DeprecationWarning, stacklevel=2
)
# Write another byte, finalize and close.
writer.write(TEST_BINARY_DATA[32:33])
writer.close()
self.assertEqual(upload.transmit_next_chunk.call_count, 5)
def test_rejects_invalid_kwargs(self):
blob = mock.Mock()
with self.assertRaises(ValueError):
self._make_blob_writer(blob, invalid_kwarg=1)
class Test_SlidingBuffer(unittest.TestCase):
@staticmethod
def _make_sliding_buffer(*args, **kwargs):
from google.cloud.storage.fileio import SlidingBuffer
return SlidingBuffer(*args, **kwargs)
def test_write_and_read(self):
buff = self._make_sliding_buffer()
# Write and verify tell() still reports 0 and len is correct.
buff.write(TEST_BINARY_DATA)
self.assertEqual(buff.tell(), 0)
self.assertEqual(len(buff), len(TEST_BINARY_DATA))
# Read and verify tell() reports end.
self.assertEqual(buff.read(), TEST_BINARY_DATA)
self.assertEqual(buff.tell(), len(TEST_BINARY_DATA))
self.assertEqual(len(buff), len(TEST_BINARY_DATA))
def test_flush(self):
buff = self._make_sliding_buffer()
# Write and verify tell() still reports 0 and len is correct.
buff.write(TEST_BINARY_DATA)
self.assertEqual(buff.tell(), 0)
self.assertEqual(len(buff), len(TEST_BINARY_DATA))
# Read 8 bytes and verify tell reports correctly.
self.assertEqual(buff.read(8), TEST_BINARY_DATA[:8])
self.assertEqual(buff.tell(), 8)
self.assertEqual(len(buff), len(TEST_BINARY_DATA))
# Flush buffer and verify tell doesn't change but len does.
buff.flush()
self.assertEqual(buff.tell(), 8)
self.assertEqual(len(buff), len(TEST_BINARY_DATA) - 8)
# Read remainder.
self.assertEqual(buff.read(), TEST_BINARY_DATA[8:])
self.assertEqual(buff.tell(), len(TEST_BINARY_DATA))
self.assertEqual(len(buff), len(TEST_BINARY_DATA[8:]))
def test_seek(self):
buff = self._make_sliding_buffer()
buff.write(TEST_BINARY_DATA)
# Try to seek forward. Verify the tell() doesn't change.
with self.assertRaises(ValueError):
pos = buff.tell()
buff.seek(len(TEST_BINARY_DATA) + 1)
self.assertEqual(pos, buff.tell())
# Read 8 bytes, test seek backwards, read again, and flush.
self.assertEqual(buff.read(8), TEST_BINARY_DATA[:8])
buff.seek(0)
self.assertEqual(buff.read(8), TEST_BINARY_DATA[:8])
buff.flush()
self.assertEqual(buff.tell(), 8)
# Try to seek to a byte that has already been flushed.
with self.assertRaises(ValueError):
pos = buff.tell()
buff.seek(0)
self.assertEqual(pos, buff.tell())
def test_close(self):
buff = self._make_sliding_buffer()
buff.close()
with self.assertRaises(ValueError):
buff.read()
class TestBlobReaderText(unittest.TestCase, _BlobReaderBase):
def test_attributes(self):
blob = mock.Mock()
reader = io.TextIOWrapper(self._make_blob_reader(blob))
self.assertTrue(reader.seekable())
self.assertTrue(reader.readable())
self.assertFalse(reader.writable())
def test_read(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_TEXT_DATA.encode("utf-8")[start:end]
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
blob.chunk_size = None
blob.size = len(TEST_TEXT_DATA.encode("utf-8"))
download_kwargs = {"if_metageneration_match": 1}
reader = io.TextIOWrapper(self._make_blob_reader(blob, **download_kwargs))
# The TextIOWrapper class has an internally defined chunk size which
# will override ours. The wrapper class is not under test.
# Read and trigger the first download of chunk_size.
self.assertEqual(reader.read(1), TEST_TEXT_DATA[0:1])
blob.download_as_bytes.assert_called_once()
# Read from buffered data only.
self.assertEqual(reader.read(3), TEST_TEXT_DATA[1:4])
blob.download_as_bytes.assert_called_once()
# Read all remaining data.
self.assertEqual(reader.read(), TEST_TEXT_DATA[4:])
# Seek to 0 and read all remaining data again.
reader.seek(0)
self.assertEqual(reader.read(), TEST_TEXT_DATA)
reader.close()
def test_multibyte_read(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_MULTIBYTE_TEXT_DATA.encode("utf-8")[start:end]
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
blob.chunk_size = None
blob.size = len(TEST_MULTIBYTE_TEXT_DATA.encode("utf-8"))
download_kwargs = {"if_metageneration_match": 1}
reader = io.TextIOWrapper(self._make_blob_reader(blob, **download_kwargs))
# The TextIOWrapper class has an internally defined chunk size which
# will override ours. The wrapper class is not under test.
# Read and trigger the first download of chunk_size.
self.assertEqual(reader.read(1), TEST_MULTIBYTE_TEXT_DATA[0:1])
blob.download_as_bytes.assert_called_once()
# Read from buffered data only.
self.assertEqual(reader.read(3), TEST_MULTIBYTE_TEXT_DATA[1:4])
blob.download_as_bytes.assert_called_once()
# Read all remaining data.
self.assertEqual(reader.read(), TEST_MULTIBYTE_TEXT_DATA[4:])
# Seek to 0 and read all remaining data again.
reader.seek(0)
self.assertEqual(reader.read(), TEST_MULTIBYTE_TEXT_DATA)
reader.close()
def test_seek(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_TEXT_DATA.encode("utf-8")[start:end]
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
blob.size = None
blob.chunk_size = None
download_kwargs = {"if_metageneration_match": 1}
reader = io.TextIOWrapper(self._make_blob_reader(blob, **download_kwargs))
# Seek needs the blob size to work and should call reload() if the size
# is not known. Set a mock to initialize the size if reload() is called.
def initialize_size(**_):
blob.size = len(TEST_TEXT_DATA.encode("utf-8"))
blob.reload = mock.Mock(side_effect=initialize_size)
# Seek, forcing a blob reload in order to validate the seek doesn't
# exceed the end of the blob.
self.assertEqual(reader.seek(4), 4)
blob.reload.assert_called_once_with(**download_kwargs)
self.assertEqual(reader.read(4), TEST_TEXT_DATA[4:8])
self.assertEqual(blob.download_as_bytes.call_count, 1)
# Seek to beginning. The next read will need to download data again.
self.assertEqual(reader.seek(0), 0)
self.assertEqual(reader.read(), TEST_TEXT_DATA)
self.assertEqual(blob.download_as_bytes.call_count, 2)
reader.close()
def test_multibyte_seek(self):
blob = mock.Mock()
def read_from_fake_data(start=0, end=None, **_):
return TEST_MULTIBYTE_TEXT_DATA.encode("utf-8")[start:end]
blob.download_as_bytes = mock.Mock(side_effect=read_from_fake_data)
blob.size = None
blob.chunk_size = None
download_kwargs = {"if_metageneration_match": 1}
reader = io.TextIOWrapper(self._make_blob_reader(blob, **download_kwargs))
# Seek needs the blob size to work and should call reload() if the size
# is not known. Set a mock to initialize the size if reload() is called.
def initialize_size(**_):
blob.size = len(TEST_MULTIBYTE_TEXT_DATA.encode("utf-8"))
blob.reload = mock.Mock(side_effect=initialize_size)
# Seek, forcing a blob reload in order to validate the seek doesn't
# exceed the end of the blob.
self.assertEqual(reader.seek(4), 4)
blob.reload.assert_called_once_with(**download_kwargs)
# Seek to beginning.
self.assertEqual(reader.seek(0), 0)
self.assertEqual(reader.read(), TEST_MULTIBYTE_TEXT_DATA)
self.assertEqual(blob.download_as_bytes.call_count, 1)
# tell() is an inherited method that uses seek().
self.assertEqual(reader.tell(), len(TEST_MULTIBYTE_TEXT_DATA.encode("utf-8")))
reader.close()
def test_close(self):
blob = mock.Mock()
reader = self._make_blob_reader(blob)
reader.close()
with self.assertRaises(ValueError):
reader.read()
with self.assertRaises(ValueError):
reader.seek(0)
class TestBlobWriterText(unittest.TestCase, _BlobWriterBase):
@mock.patch("warnings.warn")
def test_write(self, mock_warn):
from google.cloud.storage._helpers import _NUM_RETRIES_MESSAGE
blob = mock.Mock()
upload = mock.Mock()
transport = mock.Mock()
blob._initiate_resumable_upload.return_value = (upload, transport)
with mock.patch("google.cloud.storage.fileio.CHUNK_SIZE_MULTIPLE", 1):
# Create a writer in text mode.
# It would be normal to use a context manager here, but not doing so
# gives us more control over close() for test purposes.
chunk_size = 8 # Note: Real upload requires a multiple of 256KiB.
unwrapped_writer = self._make_blob_writer(
blob,
chunk_size=chunk_size,
ignore_flush=True,
num_retries=NUM_RETRIES,
content_type=PLAIN_CONTENT_TYPE,
)
writer = io.TextIOWrapper(unwrapped_writer)
# The transmit_next_chunk method must actually consume bytes from the
# sliding buffer for the flush() feature to work properly.
upload.transmit_next_chunk.side_effect = lambda _: unwrapped_writer._buffer.read(
chunk_size
)
# Write under chunk_size. This should be buffered and the upload not
# initiated.
writer.write(TEST_MULTIBYTE_TEXT_DATA[0:2])
blob.initiate_resumable_upload.assert_not_called()
# Write all data and close.
writer.write(TEST_MULTIBYTE_TEXT_DATA[2:])
writer.close()
blob._initiate_resumable_upload.assert_called_once_with(
blob.bucket.client,
unwrapped_writer._buffer,
PLAIN_CONTENT_TYPE,
None,
NUM_RETRIES,
chunk_size=chunk_size,
retry=None,
)
upload.transmit_next_chunk.assert_called_with(transport)
mock_warn.assert_called_once_with(
_NUM_RETRIES_MESSAGE, DeprecationWarning, stacklevel=2,
)