refactor(downloader): shrink download_book to 4 domain params
Replace 9-parameter signature (book, client, output_base, history, format_strategy, config, transport, progress, cancel_event) with 4 domain-aligned parameters (book, session, plan, reporter) that return a frozen DownloadResult dataclass. Key changes: - Add DownloadResult(status, path, format, error) frozen dataclass - Add format_strategy field to OutputPlan - Move history writing from download_book() to caller (cli closure) - Remove config param from download_accompanying_files() - Wire cancel_event through reporter.cancel_event attribute - Extract transport from session._client._transport Closes #29 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
1 parent
0ee8186361
commit
9ac581e5b7
11 files changed
+492
-174
No files matched your search
+36
-34
@@ -5,6 +5,7 @@ from unittest.mock import patch
|
||||
import pytest
|
||||
|
||||
from librofm_downloader.cli import run
|
||||
from librofm_downloader.downloader import DownloadResult
|
||||
|
||||
|
||||
class TestCLIHappyPath:
|
||||
@@ -154,12 +155,12 @@ class TestCLIDownloadOrchestration:
|
||||
mock_history_instance = mock_history_cls.return_value
|
||||
mock_history_instance.is_downloaded.return_value = False
|
||||
|
||||
# download_book returns Path for success, None for skip
|
||||
# download_book returns DownloadResult for each book
|
||||
from pathlib import Path
|
||||
mock_download.side_effect = [
|
||||
Path("/audiobooks/A1/M4B Book.m4b"), # success
|
||||
None, # no M4B available (skipped)
|
||||
Path("/audiobooks/A3/Another M4B.m4b"), # success
|
||||
DownloadResult(status="downloaded", path=Path("/audiobooks/A1/M4B Book.m4b"), format="m4b"),
|
||||
DownloadResult(status="skipped"),
|
||||
DownloadResult(status="downloaded", path=Path("/audiobooks/A3/Another M4B.m4b"), format="m4b"),
|
||||
]
|
||||
|
||||
exit_code = run(
|
||||
@@ -203,7 +204,7 @@ class TestCLIVerbose:
|
||||
]
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = None # skipped (no M4B)
|
||||
mock_download.return_value = DownloadResult(status="skipped") # skipped (no M4B)
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
@@ -293,7 +294,7 @@ class TestCLILimitFlag:
|
||||
]
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = None
|
||||
mock_download.return_value = DownloadResult(status="skipped")
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
@@ -309,12 +310,13 @@ class TestCLIFormatWiring:
|
||||
"""Format strategy from config is passed to download_book."""
|
||||
|
||||
def test_format_passed_to_download_book(self):
|
||||
"""config.format is forwarded to download_book(format_strategy=...)."""
|
||||
"""config.format is forwarded to OutputPlan (via resolve_output_plan)."""
|
||||
with (
|
||||
patch("librofm_downloader.cli.load_config") as mock_config,
|
||||
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
|
||||
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
|
||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
||||
patch("librofm_downloader.cli.resolve_output_plan") as mock_plan,
|
||||
patch("librofm_downloader.cli.Book") as mock_book_cls,
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
@@ -340,8 +342,8 @@ class TestCLIFormatWiring:
|
||||
history_path="/fake/history.json",
|
||||
)
|
||||
|
||||
# download_book was called with format_strategy="mp3_only"
|
||||
_, kwargs = mock_download.call_args
|
||||
# resolve_output_plan was called with format_strategy="mp3_only"
|
||||
_, kwargs = mock_plan.call_args
|
||||
assert kwargs.get("format_strategy") == "mp3_only"
|
||||
|
||||
def test_mp3_download_reported_as_downloaded_not_skipped(self, capsys):
|
||||
@@ -371,8 +373,8 @@ class TestCLIFormatWiring:
|
||||
]
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
# download_book returns a Path (MP3 dir) — not None
|
||||
mock_download.return_value = Path("/audiobooks/A/MP3 Book")
|
||||
# download_book returns DownloadResult with MP3 path
|
||||
mock_download.return_value = DownloadResult(status="downloaded", path=Path("/audiobooks/A/MP3 Book"), format="mp3")
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
@@ -422,7 +424,7 @@ class TestGracefulShutdown:
|
||||
|
||||
from pathlib import Path
|
||||
mock_download.side_effect = [
|
||||
Path("/audiobooks/A/Book A.m4b"),
|
||||
DownloadResult(status="downloaded", path=Path("/audiobooks/A/Book A.m4b"), format="m4b"),
|
||||
KeyboardInterrupt,
|
||||
]
|
||||
|
||||
@@ -494,7 +496,7 @@ class TestIntegrationHappyPath:
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
|
||||
from pathlib import Path
|
||||
mock_download.return_value = Path("/audiobooks/Author/Book.m4b")
|
||||
mock_download.return_value = DownloadResult(status="downloaded", path=Path("/audiobooks/Author/Book.m4b"), format="m4b")
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
@@ -540,9 +542,9 @@ class TestIntegrationMixedResult:
|
||||
import httpx
|
||||
|
||||
# Deterministic mock based on ISBN — thread-safe for concurrent workers
|
||||
def _download_side_effect(book, **kwargs):
|
||||
def _download_side_effect(book, *args, **kwargs):
|
||||
if book.isbn == "978333":
|
||||
return None # skipped (no format available)
|
||||
return DownloadResult(status="skipped") # skipped (no format available)
|
||||
if book.isbn == "978444":
|
||||
raise httpx.HTTPStatusError(
|
||||
message="Not Found",
|
||||
@@ -550,7 +552,7 @@ class TestIntegrationMixedResult:
|
||||
response=httpx.Response(404, request=httpx.Request("GET", "https://example.com/fail")),
|
||||
)
|
||||
# 978111 and 978222 succeed
|
||||
return Path(f"/audiobooks/{book.authors[0]}/{book.title}.m4b")
|
||||
return DownloadResult(status="downloaded", path=Path(f"/audiobooks/{book.authors[0]}/{book.title}.m4b"), format="m4b")
|
||||
|
||||
mock_download.side_effect = _download_side_effect
|
||||
|
||||
@@ -903,7 +905,7 @@ class TestCLIWorkersFlag:
|
||||
{"isbn": "978111", "title": "B1", "authors": ["A"], "narrators": ["N"]},
|
||||
]
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = None
|
||||
mock_download.return_value = DownloadResult(status="skipped")
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
@@ -934,7 +936,7 @@ class TestCLIWorkersFlag:
|
||||
{"isbn": "978111", "title": "B1", "authors": ["A"], "narrators": ["N"]},
|
||||
]
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = None
|
||||
mock_download.return_value = DownloadResult(status="skipped")
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
@@ -963,7 +965,7 @@ class TestCLIWorkersFlag:
|
||||
{"isbn": "978111", "title": "B1", "authors": ["A"], "narrators": ["N"]},
|
||||
]
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = None
|
||||
mock_download.return_value = DownloadResult(status="skipped")
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
@@ -1011,7 +1013,7 @@ class TestParallelWorkers1Parity:
|
||||
]
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = Path("/audiobooks/Author/Book.m4b")
|
||||
mock_download.return_value = DownloadResult(status="downloaded", path=Path("/audiobooks/Author/Book.m4b"), format="m4b")
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
@@ -1045,7 +1047,7 @@ class TestParallelWorkers1Parity:
|
||||
]
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = Path("/audiobooks/A/Only.m4b")
|
||||
mock_download.return_value = DownloadResult(status="downloaded", path=Path("/audiobooks/A/Only.m4b"), format="m4b")
|
||||
|
||||
exit_code = run(workers=1)
|
||||
|
||||
@@ -1152,12 +1154,12 @@ class TestParallelSummaryOrdering:
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
|
||||
def _download_side_effect(book, **kwargs):
|
||||
def _download_side_effect(book, *args, **kwargs):
|
||||
if book.isbn == "978222":
|
||||
raise Exception("Download failed")
|
||||
if book.isbn == "978444":
|
||||
return None # skip (no format available)
|
||||
return Path(f"/audiobooks/{book.isbn}.m4b")
|
||||
return DownloadResult(status="skipped") # skip (no format available)
|
||||
return DownloadResult(status="downloaded", path=Path(f"/audiobooks/{book.isbn}.m4b"), format="m4b")
|
||||
|
||||
mock_download.side_effect = _download_side_effect
|
||||
|
||||
@@ -1194,12 +1196,12 @@ class TestParallelSummaryOrdering:
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
|
||||
def _download_side_effect(book, **kwargs):
|
||||
def _download_side_effect(book, *args, **kwargs):
|
||||
if book.isbn == "978222":
|
||||
raise Exception("boom")
|
||||
if book.isbn == "978333":
|
||||
return None # skip
|
||||
return Path(f"/audiobooks/{book.isbn}.m4b")
|
||||
return DownloadResult(status="skipped") # skip
|
||||
return DownloadResult(status="downloaded", path=Path(f"/audiobooks/{book.isbn}.m4b"), format="m4b")
|
||||
|
||||
mock_download.side_effect = _download_side_effect
|
||||
|
||||
@@ -1246,9 +1248,9 @@ class TestParallelConcurrency:
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
|
||||
def _slow_download(book, **kwargs):
|
||||
def _slow_download(book, *args, **kwargs):
|
||||
time.sleep(0.1)
|
||||
return Path(f"/audiobooks/{book.isbn}.m4b")
|
||||
return DownloadResult(status="downloaded", path=Path(f"/audiobooks/{book.isbn}.m4b"), format="m4b")
|
||||
|
||||
mock_download.side_effect = _slow_download
|
||||
|
||||
@@ -1288,11 +1290,11 @@ class TestParallelConcurrency:
|
||||
|
||||
call_results: list[str] = []
|
||||
|
||||
def _download_side_effect(book, **kwargs):
|
||||
def _download_side_effect(book, *args, **kwargs):
|
||||
call_results.append(book.isbn)
|
||||
if book.isbn == "978222":
|
||||
raise Exception("network error")
|
||||
return Path(f"/audiobooks/{book.isbn}.m4b")
|
||||
return DownloadResult(status="downloaded", path=Path(f"/audiobooks/{book.isbn}.m4b"), format="m4b")
|
||||
|
||||
mock_download.side_effect = _download_side_effect
|
||||
|
||||
@@ -1335,7 +1337,7 @@ class TestParallelVerboseMode:
|
||||
]
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = Path(f"/audiobooks/book.m4b")
|
||||
mock_download.return_value = DownloadResult(status="downloaded", path=Path(f"/audiobooks/book.m4b"), format="m4b")
|
||||
|
||||
# Should not raise or produce garbled output
|
||||
exit_code = run(verbose=True, workers=3)
|
||||
@@ -1367,10 +1369,10 @@ class TestParallelVerboseMode:
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
|
||||
def _download_side_effect(book, **kwargs):
|
||||
def _download_side_effect(book, *args, **kwargs):
|
||||
if book.isbn == "978111":
|
||||
raise Exception("connection reset")
|
||||
return Path(f"/audiobooks/{book.isbn}.m4b")
|
||||
return DownloadResult(status="downloaded", path=Path(f"/audiobooks/{book.isbn}.m4b"), format="m4b")
|
||||
|
||||
mock_download.side_effect = _download_side_effect
|
||||
|
||||
|
||||
+192
-60
@@ -16,15 +16,130 @@ from librofm_downloader.path import (
|
||||
resolve_output_plan,
|
||||
)
|
||||
from librofm_downloader.downloader import (
|
||||
DownloadResult,
|
||||
_write_history,
|
||||
download_m4b,
|
||||
download_zip_part,
|
||||
download_book,
|
||||
download_accompanying_files,
|
||||
)
|
||||
from librofm_downloader.progress import DownloadReporter
|
||||
from librofm_downloader.session import LibroFmSession
|
||||
from librofm_downloader.history import DownloadHistory
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Issue #29: DownloadResult dataclass
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestDownloadResult:
|
||||
"""DownloadResult frozen dataclass — shape and immutability."""
|
||||
|
||||
def test_instantiates_with_each_status_value(self):
|
||||
"""All three status values produce valid instances."""
|
||||
downloaded = DownloadResult(status="downloaded", path=Path("/tmp/a.m4b"), format="m4b")
|
||||
skipped = DownloadResult(status="skipped")
|
||||
failed = DownloadResult(status="failed", error="network error")
|
||||
|
||||
assert downloaded.status == "downloaded"
|
||||
assert skipped.status == "skipped"
|
||||
assert failed.status == "failed"
|
||||
|
||||
def test_optional_fields_default_to_none(self):
|
||||
"""path, format, error all default to None when omitted."""
|
||||
result = DownloadResult(status="skipped")
|
||||
|
||||
assert result.path is None
|
||||
assert result.format is None
|
||||
assert result.error is None
|
||||
|
||||
def test_is_frozen(self):
|
||||
"""Assigning to an attribute raises FrozenInstanceError."""
|
||||
from dataclasses import FrozenInstanceError
|
||||
|
||||
result = DownloadResult(status="downloaded")
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
result.status = "failed" # type: ignore[misc]
|
||||
|
||||
def test_all_four_fields_present_on_downloaded_result(self):
|
||||
"""A fully-populated 'downloaded' result has all fields set."""
|
||||
result = DownloadResult(
|
||||
status="downloaded",
|
||||
path=Path("/out/book.m4b"),
|
||||
format="m4b",
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
assert result.path == Path("/out/book.m4b")
|
||||
assert result.format == "m4b"
|
||||
assert result.error is None
|
||||
|
||||
def test_failed_result_carries_error_message(self):
|
||||
"""A 'failed' result includes the error string."""
|
||||
result = DownloadResult(
|
||||
status="failed",
|
||||
error="HTTP 500 Internal Server Error",
|
||||
)
|
||||
|
||||
assert result.status == "failed"
|
||||
assert result.path is None
|
||||
assert result.format is None
|
||||
assert result.error == "HTTP 500 Internal Server Error"
|
||||
|
||||
|
||||
class TestDownloadBookNewInterface:
|
||||
"""download_book() with 4 domain-aligned params returning DownloadResult."""
|
||||
|
||||
def test_returns_download_result_on_successful_m4b(self):
|
||||
"""New 4-param signature returns DownloadResult(status='downloaded') for M4B."""
|
||||
import io
|
||||
|
||||
m4b_payload = b"new-interface-test-data"
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
if request.url.path == "/api/v10/audiobooks/9781111111111/packaged_m4b":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"m4b_url": "https://cdn.example.com/book.m4b"},
|
||||
)
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=m4b_payload)
|
||||
return httpx.Response(404)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
|
||||
client.authenticate()
|
||||
|
||||
book = Book(
|
||||
title="Interface Test Book",
|
||||
authors=["Test Author"],
|
||||
narrators=["Test Narr"],
|
||||
isbn="9781111111111",
|
||||
)
|
||||
|
||||
from librofm_downloader.progress import DownloadReporter
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_mp3_fallback")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
result = download_book(book, client, plan, reporter)
|
||||
|
||||
# Returns DownloadResult, not Path | None
|
||||
assert isinstance(result, DownloadResult)
|
||||
assert result.status == "downloaded"
|
||||
assert result.path is not None
|
||||
assert result.path.exists()
|
||||
assert result.format == "m4b"
|
||||
|
||||
|
||||
class TestSanitizeIllegalChars:
|
||||
"""Sanitization strips characters that are unsafe in filesystem paths."""
|
||||
|
||||
@@ -866,7 +981,7 @@ class TestDownloadBook:
|
||||
"""End-to-end orchestration with mocked HTTP."""
|
||||
|
||||
def test_writes_history_entry_after_successful_download(self):
|
||||
"""After successful M4B download, history entry is persisted."""
|
||||
"""After successful M4B download, caller writes history entry."""
|
||||
m4b_payload = b"complete-m4b-audio-data"
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
@@ -901,23 +1016,27 @@ class TestDownloadBook:
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
plan = resolve_output_plan(book, base_dir)
|
||||
reporter = DownloadReporter()
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
transport=transport,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
)
|
||||
|
||||
# History is caller's responsibility now
|
||||
assert result.status == "downloaded"
|
||||
_write_history(history, book, result.format or "m4b", str(result.path))
|
||||
|
||||
# History was written
|
||||
assert history.is_downloaded("9781111111111")
|
||||
entry = history.find("9781111111111")
|
||||
assert entry is not None
|
||||
assert entry.format == "m4b"
|
||||
assert entry.title == "History Test Book"
|
||||
|
||||
def test_skips_book_without_m4b(self):
|
||||
"""Book with no M4B available → returns None, no history entry, no error."""
|
||||
"""Book with no M4B available → DownloadResult(skipped), no history entry."""
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
@@ -944,16 +1063,17 @@ class TestDownloadBook:
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
plan = resolve_output_plan(book, base_dir)
|
||||
reporter = DownloadReporter()
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
transport=transport,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
)
|
||||
|
||||
# Returns None (skipped)
|
||||
assert result is None
|
||||
# Returns skipped (no M4B in m4b_mp3_fallback → tries MP3 manifest → also 404)
|
||||
assert result.status == "skipped"
|
||||
# No history entry written
|
||||
assert history.is_downloaded("9780000000000") is False
|
||||
|
||||
@@ -991,13 +1111,14 @@ class TestDownloadBook:
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
plan = resolve_output_plan(book, base_dir)
|
||||
reporter = DownloadReporter()
|
||||
with pytest.raises(httpx.HTTPStatusError):
|
||||
download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
transport=transport,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
)
|
||||
|
||||
# No history entry written for failed download
|
||||
@@ -1034,21 +1155,23 @@ class TestDownloadBook:
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
plan = resolve_output_plan(book, base_dir)
|
||||
reporter = DownloadReporter()
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
transport=transport,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
)
|
||||
|
||||
# File is at leaf (flat), not inside a subdirectory
|
||||
assert result is not None
|
||||
assert result.status == "downloaded"
|
||||
assert result.path is not None
|
||||
# Path should be base/Author/Title.m4b (flat) — title is filename stem
|
||||
assert result.stem == "Standalone Book"
|
||||
assert result.path.stem == "Standalone Book"
|
||||
# No extra subdirectory between author and file
|
||||
assert result.parent.name == "Solo Author"
|
||||
assert result.exists()
|
||||
assert result.path.parent.name == "Solo Author"
|
||||
assert result.path.exists()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1104,21 +1227,24 @@ class TestFormatStrategy:
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_mp3_fallback")
|
||||
reporter = DownloadReporter()
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
format_strategy="m4b_mp3_fallback",
|
||||
transport=transport,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
)
|
||||
|
||||
# M4B was downloaded (not MP3)
|
||||
assert result is not None
|
||||
assert result.suffix == ".m4b"
|
||||
assert result.status == "downloaded"
|
||||
assert result.path is not None
|
||||
assert result.path.suffix == ".m4b"
|
||||
assert result.format == "m4b"
|
||||
# Manifest was never queried
|
||||
assert len(mp3_calls) == 0
|
||||
# History records M4B format
|
||||
# History is caller's responsibility now
|
||||
_write_history(history, book, result.format, str(result.path))
|
||||
entry = history.find("9781111111111")
|
||||
assert entry is not None
|
||||
assert entry.format == "m4b"
|
||||
@@ -1163,21 +1289,24 @@ class TestFormatStrategy:
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_mp3_fallback")
|
||||
reporter = DownloadReporter()
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
format_strategy="m4b_mp3_fallback",
|
||||
transport=transport,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
)
|
||||
|
||||
# MP3 files were extracted
|
||||
assert result is not None
|
||||
assert result.status == "downloaded"
|
||||
assert result.path is not None
|
||||
assert result.format == "mp3"
|
||||
# At least one .mp3 file exists in output tree
|
||||
mp3_files = list(base_dir.rglob("*.mp3"))
|
||||
assert len(mp3_files) >= 1
|
||||
# History records mp3 format
|
||||
# History is caller's responsibility now
|
||||
_write_history(history, book, result.format, str(result.path))
|
||||
entry = history.find("9782222222222")
|
||||
assert entry is not None
|
||||
assert entry.format == "mp3"
|
||||
@@ -1224,22 +1353,25 @@ class TestFormatStrategy:
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="mp3_only")
|
||||
reporter = DownloadReporter()
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
format_strategy="mp3_only",
|
||||
transport=transport,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
)
|
||||
|
||||
# MP3 files extracted
|
||||
assert result is not None
|
||||
assert result.status == "downloaded"
|
||||
assert result.path is not None
|
||||
assert result.format == "mp3"
|
||||
mp3_files = list(base_dir.rglob("*.mp3"))
|
||||
assert len(mp3_files) >= 1
|
||||
# M4B was never queried
|
||||
assert len(m4b_calls) == 0
|
||||
# History records mp3 format
|
||||
# History is caller's responsibility now
|
||||
_write_history(history, book, result.format, str(result.path))
|
||||
entry = history.find("9783333333333")
|
||||
assert entry is not None
|
||||
assert entry.format == "mp3"
|
||||
@@ -1273,17 +1405,17 @@ class TestFormatStrategy:
|
||||
history_path = Path(tmpdir) / "history.json"
|
||||
history = DownloadHistory(history_path)
|
||||
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="m4b_only")
|
||||
reporter = DownloadReporter()
|
||||
result = download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
format_strategy="m4b_only",
|
||||
transport=transport,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
)
|
||||
|
||||
# Skipped (no M4B)
|
||||
assert result is None
|
||||
assert result.status == "skipped"
|
||||
# Manifest was never queried
|
||||
assert len(manifest_calls) == 0
|
||||
# No history entry
|
||||
@@ -1328,7 +1460,7 @@ class TestDownloadAccompanyingFiles:
|
||||
)
|
||||
|
||||
plan = resolve_output_plan(book, output_dir, config=config)
|
||||
download_accompanying_files(book, plan, config, transport=transport)
|
||||
download_accompanying_files(book, plan, transport=transport)
|
||||
|
||||
# Cover file exists at plan.resolved location
|
||||
cover_path = plan.cover_path
|
||||
@@ -1370,7 +1502,7 @@ class TestDownloadAccompanyingFiles:
|
||||
mock_client.fetch_pdf_extra_url.return_value = "https://cdn.example.com/map.pdf"
|
||||
|
||||
plan = resolve_output_plan(book, output_dir, config=config)
|
||||
downloaded = download_accompanying_files(book, plan, config, client=mock_client, transport=transport)
|
||||
downloaded = download_accompanying_files(book, plan, client=mock_client, transport=transport)
|
||||
|
||||
# PDF file exists at plan.resolved location
|
||||
pdf_path = plan.pdf_path
|
||||
@@ -1408,7 +1540,7 @@ class TestDownloadAccompanyingFiles:
|
||||
)
|
||||
|
||||
plan = resolve_output_plan(book, output_dir, config=config)
|
||||
download_accompanying_files(book, plan, config, transport=transport)
|
||||
download_accompanying_files(book, plan, transport=transport)
|
||||
|
||||
# Final file exists at plan.resolved location
|
||||
final_path = plan.cover_path
|
||||
@@ -1443,7 +1575,7 @@ class TestDownloadAccompanyingFiles:
|
||||
)
|
||||
|
||||
plan = resolve_output_plan(book, output_dir, config=config)
|
||||
downloaded = download_accompanying_files(book, plan, config, client=mock_client)
|
||||
downloaded = download_accompanying_files(book, plan, client=mock_client)
|
||||
|
||||
# No files downloaded (no cover URL either)
|
||||
assert len(downloaded) == 0
|
||||
@@ -1472,7 +1604,7 @@ class TestDownloadAccompanyingFiles:
|
||||
)
|
||||
|
||||
plan = resolve_output_plan(book, output_dir, config=config)
|
||||
downloaded = download_accompanying_files(book, plan, config)
|
||||
downloaded = download_accompanying_files(book, plan)
|
||||
|
||||
# No files downloaded (no PDF extras either)
|
||||
assert len(downloaded) == 0
|
||||
@@ -1508,7 +1640,7 @@ class TestDownloadAccompanyingFiles:
|
||||
|
||||
# Should NOT raise — failure is non-critical
|
||||
plan = resolve_output_plan(book, output_dir, config=config)
|
||||
result = download_accompanying_files(book, plan, config, transport=transport)
|
||||
result = download_accompanying_files(book, plan, transport=transport)
|
||||
|
||||
# Returns empty list (nothing downloaded)
|
||||
assert result == []
|
||||
@@ -1694,7 +1826,7 @@ class TestOutputStructure:
|
||||
|
||||
# Should NOT raise — failure is non-critical
|
||||
plan = resolve_output_plan(book, output_dir, config=config)
|
||||
result = download_accompanying_files(book, plan, config, client=mock_client)
|
||||
result = download_accompanying_files(book, plan, client=mock_client)
|
||||
|
||||
# Returns empty list (nothing downloaded)
|
||||
assert result == []
|
||||
@@ -814,3 +814,40 @@ class TestResolveOutputPlan:
|
||||
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
plan.audio_path = Path("/other") # type: ignore[misc]
|
||||
|
||||
|
||||
|
||||
class TestOutputPlanFormatStrategy:
|
||||
"""OutputPlan carries format_strategy from resolve_output_plan()."""
|
||||
|
||||
def test_default_format_strategy(self):
|
||||
"""When no format_strategy passed, defaults to m4b_mp3_fallback."""
|
||||
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000010")
|
||||
plan = resolve_output_plan(book, "/base")
|
||||
|
||||
assert hasattr(plan, "format_strategy")
|
||||
assert plan.format_strategy == "m4b_mp3_fallback"
|
||||
|
||||
def test_explicit_format_strategy(self):
|
||||
"""Passing format_strategy='mp3_only' is reflected on the plan."""
|
||||
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000011")
|
||||
plan = resolve_output_plan(book, "/base", format_strategy="mp3_only")
|
||||
|
||||
assert plan.format_strategy == "mp3_only"
|
||||
|
||||
def test_m4b_only_format_strategy(self):
|
||||
"""Passing format_strategy='m4b_only' is reflected on the plan."""
|
||||
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000012")
|
||||
plan = resolve_output_plan(book, "/base", format_strategy="m4b_only")
|
||||
|
||||
assert plan.format_strategy == "m4b_only"
|
||||
|
||||
def test_format_strategy_on_frozen_plan(self):
|
||||
"""format_strategy field is part of the frozen OutputPlan."""
|
||||
from dataclasses import FrozenInstanceError
|
||||
|
||||
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000013")
|
||||
plan = resolve_output_plan(book, "/base")
|
||||
|
||||
with pytest.raises(FrozenInstanceError):
|
||||
plan.format_strategy = "mp3_only" # type: ignore[misc]
|
||||
+20
-14
@@ -178,11 +178,13 @@ class TestFailureIsolationCLI:
|
||||
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
|
||||
from librofm_downloader.downloader import DownloadResult
|
||||
|
||||
# Book A succeeds, Book B fails, Book C succeeds
|
||||
mock_download.side_effect = [
|
||||
Path("/audiobooks/A1/Book A.m4b"), # success
|
||||
DownloadResult(status="downloaded", path=Path("/audiobooks/A1/Book A.m4b"), format="m4b"), # success
|
||||
Exception("Network timeout"), # failure
|
||||
Path("/audiobooks/A3/Book C.m4b"), # success
|
||||
DownloadResult(status="downloaded", path=Path("/audiobooks/A3/Book C.m4b"), format="m4b"), # success
|
||||
]
|
||||
|
||||
exit_code = run = __import__("librofm_downloader.cli").cli.run
|
||||
@@ -658,13 +660,15 @@ class TestProgressCallbackWiring:
|
||||
"""download_book() threads the progress callback through to low-level downloads."""
|
||||
|
||||
def test_download_book_forwards_progress_to_m4b(self):
|
||||
"""progress callable passed to download_book reaches download_m4b."""
|
||||
"""progress callback from reporter reaches download_m4b chunk loop."""
|
||||
import httpx
|
||||
from pathlib import Path
|
||||
from unittest.mock import MagicMock
|
||||
from librofm_downloader.book import Book
|
||||
from librofm_downloader.downloader import download_book
|
||||
from librofm_downloader.session import LibroFmSession
|
||||
from librofm_downloader.history import DownloadHistory
|
||||
from librofm_downloader.path import resolve_output_plan
|
||||
from librofm_downloader.progress import DownloadReporter
|
||||
|
||||
m4b_payload = b"callback-test-data" * 10 # 160 bytes
|
||||
|
||||
@@ -685,25 +689,27 @@ class TestProgressCallbackWiring:
|
||||
client.authenticate()
|
||||
|
||||
book = Book(title="CB Test", authors=["A"], narrators=["N"], isbn="9781111111111")
|
||||
progress_calls: list[int] = []
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
history = DownloadHistory(Path(tmpdir) / "history.json")
|
||||
|
||||
plan = resolve_output_plan(book, base_dir)
|
||||
reporter = DownloadReporter()
|
||||
# Spy on the reporter's update method (used as progress callback)
|
||||
reporter.update = MagicMock(wraps=reporter.update)
|
||||
|
||||
download_book(
|
||||
book=book,
|
||||
client=client,
|
||||
output_base=base_dir,
|
||||
history=history,
|
||||
transport=transport,
|
||||
progress=lambda n, **kw: progress_calls.append(n),
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
)
|
||||
|
||||
# Progress callback was invoked during the M4B download
|
||||
assert len(progress_calls) >= 1
|
||||
# Final value reflects the full download size
|
||||
assert progress_calls[-1] == len(m4b_payload)
|
||||
assert reporter.update.call_count >= 1
|
||||
# Final call reflects the full download size
|
||||
last_call_args = reporter.update.call_args_list[-1]
|
||||
assert last_call_args[0][0] == len(m4b_payload)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in new issue
Block a user