Skip to content

Commit e0ef08f

Browse files
authored
gh-122356: restore the position of a file-like object after zipfile.is_zipfile (#122397)
1 parent 3d8ac48 commit e0ef08f

File tree

3 files changed

+13
-2
lines changed

3 files changed

+13
-2
lines changed

Lib/test/test_zipfile/test_core.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1969,10 +1969,16 @@ def test_is_zip_valid_file(self):
19691969
zip_contents = fp.read()
19701970
# - passing a file-like object
19711971
fp = io.BytesIO()
1972-
fp.write(zip_contents)
1972+
end = fp.write(zip_contents)
1973+
self.assertEqual(fp.tell(), end)
1974+
mid = end // 2
1975+
fp.seek(mid, 0)
19731976
self.assertTrue(zipfile.is_zipfile(fp))
1974-
fp.seek(0, 0)
1977+
# check that the position is left unchanged after the call
1978+
# see: https://github.com/python/cpython/issues/122356
1979+
self.assertEqual(fp.tell(), mid)
19751980
self.assertTrue(zipfile.is_zipfile(fp))
1981+
self.assertEqual(fp.tell(), mid)
19761982

19771983
def test_non_existent_file_raises_OSError(self):
19781984
# make sure we don't raise an AttributeError when a partially-constructed

Lib/zipfile/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,7 +241,9 @@ def is_zipfile(filename):
241241
result = False
242242
try:
243243
if hasattr(filename, "read"):
244+
pos = filename.tell()
244245
result = _check_zipfile(fp=filename)
246+
filename.seek(pos)
245247
else:
246248
with open(filename, "rb") as fp:
247249
result = _check_zipfile(fp)
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Guarantee that the position of a file-like object passed to
2+
:func:`zipfile.is_zipfile` is left untouched after the call.
3+
Patch by Bénédikt Tran.

0 commit comments

Comments
 (0)