From c65a5a3a15379f56a81541b5dbdf1ee76685b864 Mon Sep 17 00:00:00 2001 From: rajanpanth Date: Sat, 5 Dec 2026 09:48:46 +0545 Subject: [PATCH] fix(download): close the output file when a streamed download fails stream_file closed the file only after a successful read, so an error from the response body left the handle open. Co-authored-by: Cursor --- src/zimscraperlib/download.py | 39 +++++++++++++++++++-------------- tests/download/test_download.py | 32 ++++++++++++++++++++++++++- 2 files changed, 53 insertions(+), 18 deletions(-) diff --git a/src/zimscraperlib/download.py b/src/zimscraperlib/download.py index 4fb55f08..b1b8bfb9 100644 --- a/src/zimscraperlib/download.py +++ b/src/zimscraperlib/download.py @@ -375,26 +375,31 @@ def stream_file( # noqa: PLR0917 resp.raise_for_status() total_downloaded = 0 - if fpath is not None: - fpath_handler = open(fpath, "wb") - else: - fpath_handler = None - - for data in resp.iter_content(block_size): - total_downloaded += len(data) + fpath_handler = open(fpath, "wb") if fpath is not None else None + + try: + for data in resp.iter_content(block_size): + total_downloaded += len(data) + if fpath_handler: + fpath_handler.write(data) + if byte_stream: + byte_stream.write(data) + + # stop downloading/reading if we're just testing first block + if only_first_block: + break + finally: + # A mid-download error used to skip this and leave the file open. if fpath_handler: - fpath_handler.write(data) - if byte_stream: - byte_stream.write(data) - - # stop downloading/reading if we're just testing first block - if only_first_block: - break + fpath_handler.close() + resp.close() logger.debug(f"Downloaded {total_downloaded} bytes from {url}") - if fpath_handler: - fpath_handler.close() - elif isinstance(byte_stream, SupportsSeekableWrite) and byte_stream.seekable(): + if ( + fpath_handler is None + and isinstance(byte_stream, SupportsSeekableWrite) + and byte_stream.seekable() + ): byte_stream.seek(0) return total_downloaded, resp.headers diff --git a/tests/download/test_download.py b/tests/download/test_download.py index 96d3d606..49b63291 100644 --- a/tests/download/test_download.py +++ b/tests/download/test_download.py @@ -4,7 +4,7 @@ import re from collections.abc import Iterator from typing import ClassVar -from unittest.mock import MagicMock, Mock +from unittest.mock import MagicMock, Mock, patch import pytest import requests @@ -774,3 +774,33 @@ def test_get_options_override_outtmpl_other_vars( assert overriden[key] == value else: assert overriden[key] == custom_outtmpl + + +def test_stream_file_closes_the_file_when_the_body_fails(tmp_path: pathlib.Path): + dest = tmp_path / "partial.bin" + session = requests.Session() + response = MagicMock() + response.headers = requests.structures.CaseInsensitiveDict() + response.raise_for_status.return_value = None + + def chunks(_block_size: int): + yield b"abc" + raise OSError("connection reset") + + response.iter_content.side_effect = chunks + session.get = Mock(return_value=response) + opened: list[io.BufferedWriter] = [] + + def spy_open(path: pathlib.Path, mode: str): + handle = open(path, mode) + opened.append(handle) + return handle + + with pytest.raises(OSError, match="connection reset"), patch( + "zimscraperlib.download.open", spy_open + ): + stream_file("https://example.test/file", fpath=dest, session=session) + + assert len(opened) == 1 + assert opened[0].closed + response.close.assert_called_once()