Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 12 additions & 12 deletions src/requests/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,18 +278,18 @@ def extract_zipped_paths(path):
if not zipfile.is_zipfile(archive):
return path

zip_file = zipfile.ZipFile(archive)
if member not in zip_file.namelist():
return path

# we have a valid zip archive and a valid member of that archive
tmp = tempfile.gettempdir()
extracted_path = os.path.join(tmp, member.split("/")[-1])
if not os.path.exists(extracted_path):
# use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition
with atomic_open(extracted_path) as file_handler:
file_handler.write(zip_file.read(member))
return extracted_path
with zipfile.ZipFile(archive) as zip_file:
if member not in zip_file.namelist():
return path

# we have a valid zip archive and a valid member of that archive
tmp = tempfile.gettempdir()
extracted_path = os.path.join(tmp, member.split("/")[-1])
if not os.path.exists(extracted_path):
# use read + write to avoid the creating nested folders, we only want the file, avoids mkdir racing condition
with atomic_open(extracted_path) as file_handler:
file_handler.write(zip_file.read(member))
return extracted_path


@contextlib.contextmanager
Expand Down
20 changes: 20 additions & 0 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -359,6 +359,26 @@ def test_invalid_unc_path(self):
path = r"\\localhost\invalid\location"
assert extract_zipped_paths(path) == path

def test_zipfile_closed_on_member_not_found(self, tmpdir):
"""Ensure ZipFile is properly closed when member is not found."""
zipped_py = tmpdir.join("test.zip")
with zipfile.ZipFile(zipped_py.strpath, "w") as f:
f.writestr("existing_file.txt", "content")

nonexistent_path = os.path.join(zipped_py.strpath, "nonexistent_member.txt")

close_called = []
original_close = zipfile.ZipFile.close

def tracking_close(self):
close_called.append(True)
return original_close(self)

with mock.patch.object(zipfile.ZipFile, "close", tracking_close):
result = extract_zipped_paths(nonexistent_path)
assert result == nonexistent_path
assert close_called, "ZipFile.close() was not called"


class TestContentEncodingDetection:
def test_none(self):
Expand Down