]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-44439: _ZipWriteFile.write() handle buffer protocol correctly (GH-29468)
authorMa Lin <animalize@users.noreply.github.com>
Tue, 8 Mar 2022 09:33:56 +0000 (17:33 +0800)
committerGitHub <noreply@github.com>
Tue, 8 Mar 2022 09:33:56 +0000 (11:33 +0200)
Co-authored-by: Marco Ribeiro <marcoffee@users.noreply.github.com>
Lib/test/test_zipfile.py
Lib/zipfile.py
Misc/NEWS.d/next/Library/2021-11-08-20-27-41.bpo-44439.I_8qro.rst [new file with mode: 0644]

index de2dd33f4366097076d7c4bde46cc7b620eba04e..759a4abb9d4d4e58d53e13361567e6e83caee9da 100644 (file)
@@ -1,3 +1,4 @@
+import array
 import contextlib
 import importlib.util
 import io
@@ -1121,6 +1122,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
 
index 8e9325b934326064256b2061f26972a3054b6188..41bf49a8fe6850a49258bc4be9ad2bf5e26dd577 100644 (file)
@@ -1147,8 +1147,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)
diff --git a/Misc/NEWS.d/next/Library/2021-11-08-20-27-41.bpo-44439.I_8qro.rst b/Misc/NEWS.d/next/Library/2021-11-08-20-27-41.bpo-44439.I_8qro.rst
new file mode 100644 (file)
index 0000000..f4e562c
--- /dev/null
@@ -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.