Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 14 additions & 0 deletions astrbot/core/utils/io.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,10 @@ async def download_file(
_safe_url_for_log(url),
resp.status,
)
raise RuntimeError(
"Failed to download file from "
f"{_safe_url_for_log(url)}. HTTP status code: {resp.status}"
)
total_size = int(resp.headers.get("content-length", 0))
downloaded_size = 0
start_time = time.time()
Expand Down Expand Up @@ -291,6 +295,16 @@ async def download_file(
ssl_context.verify_mode = ssl.CERT_NONE
async with aiohttp.ClientSession() as session:
async with session.get(url, ssl=ssl_context, timeout=120) as resp:
if resp.status != 200:
logger.error(
"Failed to download file from %s. HTTP status code: %s",
_safe_url_for_log(url),
resp.status,
)
raise RuntimeError(
"Failed to download file from "
f"{_safe_url_for_log(url)}. HTTP status code: {resp.status}"
)
Comment thread
VectorPeak marked this conversation as resolved.
Outdated
total_size = int(resp.headers.get("content-length", 0))
downloaded_size = 0
start_time = time.time()
Expand Down
76 changes: 76 additions & 0 deletions tests/unit/test_io_download_file.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import pytest

from astrbot.core.utils import io


class _FakeContent:
def __init__(self, chunks: list[bytes]):
self._chunks = chunks

async def read(self, _size: int) -> bytes:
if self._chunks:
return self._chunks.pop(0)
return b""


class _FakeResponse:
def __init__(self, *, status: int, chunks: list[bytes]):
self.status = status
self.headers = {"content-length": str(sum(len(chunk) for chunk in chunks))}
self.content = _FakeContent(chunks)

async def __aenter__(self):
return self

async def __aexit__(self, exc_type, exc, tb):
return False


class _FakeSession:
def __init__(self, response: _FakeResponse):
self._response = response

async def __aenter__(self):
return self

async def __aexit__(self, exc_type, exc, tb):
return False

def get(self, *_args, **_kwargs):
return self._response


def _patch_download_session(monkeypatch, response: _FakeResponse):
monkeypatch.setattr(io.aiohttp, "TCPConnector", lambda **_kwargs: object())
monkeypatch.setattr(
io.aiohttp,
"ClientSession",
lambda **_kwargs: _FakeSession(response),
)


@pytest.mark.asyncio
async def test_download_file_rejects_non_200_response(monkeypatch, tmp_path):
target_path = tmp_path / "missing.bin"
_patch_download_session(
monkeypatch,
_FakeResponse(status=404, chunks=[b"not found"]),
)

with pytest.raises(RuntimeError, match="HTTP status code: 404"):
await io.download_file("https://example.test/missing", str(target_path))

assert not target_path.exists()
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Outdated


@pytest.mark.asyncio
async def test_download_file_writes_successful_response(monkeypatch, tmp_path):
target_path = tmp_path / "ok.bin"
_patch_download_session(
monkeypatch,
_FakeResponse(status=200, chunks=[b"hello", b" world"]),
)

await io.download_file("https://example.test/ok.bin", str(target_path))

assert target_path.read_bytes() == b"hello world"
Loading