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
39 changes: 22 additions & 17 deletions src/zimscraperlib/download.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
32 changes: 31 additions & 1 deletion tests/download/test_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()