@@ -76,3 +76,63 @@ def test_blobwriter_and_blobreader_text_mode(
76
76
assert text_data [:100 ] == reader .read (100 )
77
77
assert 0 == reader .seek (0 )
78
78
assert reader .read () == text_data
79
+
80
+
81
+ def test_blobwriter_exit (
82
+ shared_bucket ,
83
+ blobs_to_delete ,
84
+ service_account ,
85
+ ):
86
+ blob = shared_bucket .blob ("NeverUploaded" )
87
+
88
+ # no-op when nothing was uploaded yet
89
+ with pytest .raises (ValueError , match = "SIGTERM received" ):
90
+ with blob .open ("wb" ) as writer :
91
+ writer .write (b"first chunk" ) # not yet uploaded
92
+ raise ValueError ("SIGTERM received" ) # no upload to cancel in __exit__
93
+ # blob should not exist
94
+ assert not blob .exists ()
95
+
96
+ # unhandled exceptions should cancel the upload
97
+ with pytest .raises (ValueError , match = "SIGTERM received" ):
98
+ with blob .open ("wb" , chunk_size = CHUNK_SIZE_MULTIPLE ) as writer :
99
+ writer .write (b"first chunk" ) # not yet uploaded
100
+ writer .write (bytes (CHUNK_SIZE_MULTIPLE )) # uploaded
101
+ raise ValueError ("SIGTERM received" ) # upload is cancelled in __exit__
102
+ # blob should not exist
103
+ assert not blob .exists ()
104
+
105
+ # handled exceptions should not cancel the upload
106
+ with blob .open ("wb" , chunk_size = CHUNK_SIZE_MULTIPLE ) as writer :
107
+ writer .write (b"first chunk" ) # not yet uploaded
108
+ writer .write (bytes (CHUNK_SIZE_MULTIPLE )) # uploaded
109
+ try :
110
+ raise ValueError ("This is fine" )
111
+ except ValueError :
112
+ pass # no exception context passed to __exit__
113
+ blobs_to_delete .append (blob )
114
+ # blob should have been uploaded
115
+ assert blob .exists ()
116
+
117
+
118
+ def test_blobreader_w_raw_download (
119
+ shared_bucket ,
120
+ blobs_to_delete ,
121
+ file_data ,
122
+ ):
123
+ blob = shared_bucket .blob ("LargeFile" )
124
+ info = file_data ["big" ]
125
+ with open (info ["path" ], "rb" ) as file_obj :
126
+ with blob .open ("wb" , chunk_size = 256 * 1024 , if_generation_match = 0 ) as writer :
127
+ writer .write (file_obj .read ())
128
+ blobs_to_delete .append (blob )
129
+
130
+ # Test BlobReader read and seek handles raw downloads.
131
+ with open (info ["path" ], "rb" ) as file_obj :
132
+ with blob .open ("rb" , chunk_size = 256 * 1024 , raw_download = True ) as reader :
133
+ reader .seek (0 )
134
+ file_obj .seek (0 )
135
+ assert file_obj .read () == reader .read ()
136
+ # End of file reached; further reads should be blank but not
137
+ # raise an error.
138
+ assert reader .read () == b""
0 commit comments