mirror of
https://github.com/python/cpython.git
synced 2025-07-24 11:44:31 +00:00
bpo-44439: _ZipWriteFile.write() handle buffer protocol correctly (GH-29468)
Co-authored-by: Marco Ribeiro <marcoffee@users.noreply.github.com>
(cherry picked from commit 36dd7396fc
)
Co-authored-by: Ma Lin <animalize@users.noreply.github.com>
This commit is contained in:
parent
b099363fa7
commit
21c5b3f73f
3 changed files with 19 additions and 1 deletions
|
@ -1,3 +1,4 @@
|
|||
import array
|
||||
import contextlib
|
||||
import importlib.util
|
||||
import io
|
||||
|
@ -1119,6 +1120,14 @@ class AbstractWriterTests:
|
|||
self.assertRaises(ValueError, w.write, b'')
|
||||
self.assertEqual(zipf.read('test'), data)
|
||||
|
||||
def test_issue44439(self):
|
||||
q = array.array('Q', [1, 2, 3, 4, 5])
|
||||
LENGTH = len(q) * q.itemsize
|
||||
with zipfile.ZipFile(io.BytesIO(), 'w', self.compression) as zip:
|
||||
with zip.open('data', 'w') as data:
|
||||
self.assertEqual(data.write(q), LENGTH)
|
||||
self.assertEqual(zip.getinfo('data').file_size, LENGTH)
|
||||
|
||||
class StoredWriterTests(AbstractWriterTests, unittest.TestCase):
|
||||
compression = zipfile.ZIP_STORED
|
||||
|
||||
|
|
|
@ -1121,8 +1121,15 @@ class _ZipWriteFile(io.BufferedIOBase):
|
|||
def write(self, data):
|
||||
if self.closed:
|
||||
raise ValueError('I/O operation on closed file.')
|
||||
nbytes = len(data)
|
||||
|
||||
# Accept any data that supports the buffer protocol
|
||||
if isinstance(data, (bytes, bytearray)):
|
||||
nbytes = len(data)
|
||||
else:
|
||||
data = memoryview(data)
|
||||
nbytes = data.nbytes
|
||||
self._file_size += nbytes
|
||||
|
||||
self._crc = crc32(data, self._crc)
|
||||
if self._compressor:
|
||||
data = self._compressor.compress(data)
|
||||
|
|
|
@ -0,0 +1,2 @@
|
|||
Fix ``.write()`` method of a member file in ``ZipFile``, when the input data is
|
||||
an object that supports the buffer protocol, the file length may be wrong.
|
Loading…
Add table
Add a link
Reference in a new issue