66import os
77import io
88import struct
9+ import array
910gzip = support .import_module ('gzip' )
1011
1112data1 = b""" int length=DEFAULTALLOC, err = Z_OK;
@@ -43,6 +44,14 @@ def tearDown(self):
4344
4445
4546class TestGzip (BaseTest ):
47+ def write_and_read_back (self , data , mode = 'b' ):
48+ b_data = bytes (data )
49+ with gzip .GzipFile (self .filename , 'w' + mode ) as f :
50+ l = f .write (data )
51+ self .assertEqual (l , len (b_data ))
52+ with gzip .GzipFile (self .filename , 'r' + mode ) as f :
53+ self .assertEqual (f .read (), b_data )
54+
4655 def test_write (self ):
4756 with gzip .GzipFile (self .filename , 'wb' ) as f :
4857 f .write (data1 * 50 )
@@ -57,6 +66,34 @@ def test_write(self):
5766 # Test multiple close() calls.
5867 f .close ()
5968
69+ # The following test_write_xy methods test that write accepts
70+ # the corresponding bytes-like object type as input
71+ # and that the data written equals bytes(xy) in all cases.
72+ def test_write_memoryview (self ):
73+ self .write_and_read_back (memoryview (data1 * 50 ))
74+ m = memoryview (bytes (range (256 )))
75+ data = m .cast ('B' , shape = [8 ,8 ,4 ])
76+ self .write_and_read_back (data )
77+
78+ def test_write_bytearray (self ):
79+ self .write_and_read_back (bytearray (data1 * 50 ))
80+
81+ def test_write_array (self ):
82+ self .write_and_read_back (array .array ('I' , data1 * 40 ))
83+
84+ def test_write_incompatible_type (self ):
85+ # Test that non-bytes-like types raise TypeError.
86+ # Issue #21560: attempts to write incompatible types
87+ # should not affect the state of the fileobject
88+ with gzip .GzipFile (self .filename , 'wb' ) as f :
89+ with self .assertRaises (TypeError ):
90+ f .write ('' )
91+ with self .assertRaises (TypeError ):
92+ f .write ([])
93+ f .write (data1 )
94+ with gzip .GzipFile (self .filename , 'rb' ) as f :
95+ self .assertEqual (f .read (), data1 )
96+
6097 def test_read (self ):
6198 self .test_write ()
6299 # Try reading.
0 commit comments