@@ -43,6 +43,14 @@ def tearDown(self):
4343
4444
4545class TestGzip (BaseTest ):
46+ def write_and_read_back (self , data , mode = 'b' ):
47+ b_data = bytes (data )
48+ with gzip .GzipFile (self .filename , 'w' + mode ) as f :
49+ l = f .write (data )
50+ self .assertEqual (l , len (b_data ))
51+ with gzip .GzipFile (self .filename , 'r' + mode ) as f :
52+ self .assertEqual (f .read (), b_data )
53+
4654 def test_write (self ):
4755 with gzip .GzipFile (self .filename , 'wb' ) as f :
4856 f .write (data1 * 50 )
@@ -57,6 +65,31 @@ def test_write(self):
5765 # Test multiple close() calls.
5866 f .close ()
5967
68+ # The following test_write_xy methods test that write accepts
69+ # the corresponding bytes-like object type as input
70+ # and that the data written equals bytes(xy) in all cases.
71+ def test_write_memoryview (self ):
72+ self .write_and_read_back (memoryview (data1 * 50 ))
73+ m = memoryview (bytes (range (256 )))
74+ data = m .cast ('B' , shape = [8 ,8 ,4 ])
75+ self .write_and_read_back (data )
76+
77+ def test_write_bytearray (self ):
78+ self .write_and_read_back (bytearray (data1 * 50 ))
79+
80+ def test_write_incompatible_type (self ):
81+ # Test that non-bytes-like types raise TypeError.
82+ # Issue #21560: attempts to write incompatible types
83+ # should not affect the state of the fileobject
84+ with gzip .GzipFile (self .filename , 'wb' ) as f :
85+ with self .assertRaises (TypeError ):
86+ f .write ('a' )
87+ with self .assertRaises (TypeError ):
88+ f .write ([1 ])
89+ f .write (data1 )
90+ with gzip .GzipFile (self .filename , 'rb' ) as f :
91+ self .assertEqual (f .read (), data1 )
92+
6093 def test_read (self ):
6194 self .test_write ()
6295 # Try reading.
0 commit comments