feat(path): add OutputPlan dataclass for centralized path resolution

Introduce frozen OutputPlan dataclass carrying all resolved file paths
(audio, partial, cover, PDF) for a single Book. Add resolve_output_plan()
function that centralizes every path computation so download functions
receive pre-resolved Paths instead of computing them inline.

Refactor download_book() to consume plan.audio_path (eliminating
duplicated sanitize(title).m4b logic), download_accompanying_files() to
accept an OutputPlan instead of raw output_dir, and _download_cover/_download_pdf
to accept optional expected_path parameter.

Closes #28
This commit is contained in:
AlexKucera committed 2026-06-04 15:47:33 +02:00
1 parent fe7642be7c
commit 0ee8186361
7 files changed
+467 -35

No files matched your search

+26 -14
View File
@@ -12,6 +12,8 @@ from librofm_downloader.path import (
resolve_path,
needs_subdirectory,
_resolve_output_dir,
OutputPlan,
resolve_output_plan,
)
from librofm_downloader.downloader import (
download_m4b,
@@ -1325,10 +1327,12 @@ class TestDownloadAccompanyingFiles:
output_dir=str(tmpdir), download_extras=True, download_covers=True,
)
download_accompanying_files(book, output_dir, config, transport=transport)
plan = resolve_output_plan(book, output_dir, config=config)
download_accompanying_files(book, plan, config, transport=transport)
# Cover file exists in output directory
cover_path = output_dir / "cover.jpg"
# Cover file exists at plan.resolved location
cover_path = plan.cover_path
assert cover_path is not None
assert cover_path.exists()
assert cover_path.read_bytes() == cover_payload
@@ -1365,10 +1369,12 @@ class TestDownloadAccompanyingFiles:
mock_client = unittest.mock.MagicMock()
mock_client.fetch_pdf_extra_url.return_value = "https://cdn.example.com/map.pdf"
downloaded = download_accompanying_files(book, output_dir, config, client=mock_client, transport=transport)
plan = resolve_output_plan(book, output_dir, config=config)
downloaded = download_accompanying_files(book, plan, config, client=mock_client, transport=transport)
# PDF file exists in output directory
pdf_path = output_dir / "map.pdf"
# PDF file exists at plan.resolved location
pdf_path = plan.pdf_path
assert pdf_path is not None
assert pdf_path.exists()
assert pdf_path.read_bytes() == pdf_payload
@@ -1401,14 +1407,16 @@ class TestDownloadAccompanyingFiles:
output_dir=str(tmpdir), download_extras=True, download_covers=True,
)
download_accompanying_files(book, output_dir, config, transport=transport)
plan = resolve_output_plan(book, output_dir, config=config)
download_accompanying_files(book, plan, config, transport=transport)
# Final file exists
final_path = output_dir / "cover.jpg"
# Final file exists at plan.resolved location
final_path = plan.cover_path
assert final_path is not None
assert final_path.exists()
# No .partial file left behind
partial_path = output_dir / "cover.jpg.partial"
partial_path = final_path.with_suffix(final_path.suffix + ".partial")
assert not partial_path.exists()
def test_download_extras_false_skips_pdf(self):
@@ -1434,7 +1442,8 @@ class TestDownloadAccompanyingFiles:
output_dir=str(tmpdir), download_extras=False, download_covers=True,
)
downloaded = download_accompanying_files(book, output_dir, config, client=mock_client)
plan = resolve_output_plan(book, output_dir, config=config)
downloaded = download_accompanying_files(book, plan, config, client=mock_client)
# No files downloaded (no cover URL either)
assert len(downloaded) == 0
@@ -1462,7 +1471,8 @@ class TestDownloadAccompanyingFiles:
output_dir=str(tmpdir), download_extras=True, download_covers=False,
)
downloaded = download_accompanying_files(book, output_dir, config)
plan = resolve_output_plan(book, output_dir, config=config)
downloaded = download_accompanying_files(book, plan, config)
# No files downloaded (no PDF extras either)
assert len(downloaded) == 0
@@ -1497,7 +1507,8 @@ class TestDownloadAccompanyingFiles:
)
# Should NOT raise — failure is non-critical
result = download_accompanying_files(book, output_dir, config, transport=transport)
plan = resolve_output_plan(book, output_dir, config=config)
result = download_accompanying_files(book, plan, config, transport=transport)
# Returns empty list (nothing downloaded)
assert result == []
@@ -1682,7 +1693,8 @@ class TestOutputStructure:
)
# Should NOT raise — failure is non-critical
result = download_accompanying_files(book, output_dir, config, client=mock_client)
plan = resolve_output_plan(book, output_dir, config=config)
result = download_accompanying_files(book, plan, config, client=mock_client)
# Returns empty list (nothing downloaded)
assert result == []
+245
View File
@@ -8,8 +8,10 @@ import pytest
from librofm_downloader.book import Book
from librofm_downloader.path import (
OutputPlan,
needs_subdirectory,
_resolve_output_dir,
resolve_output_plan,
resolve_path,
sanitize,
)
@@ -569,3 +571,246 @@ class TestResolveOutputDir:
with tempfile.TemporaryDirectory() as tmpdir:
output_dir = _resolve_output_dir(book, tmpdir)
assert output_dir == Path(tmpdir) / "Author Name"
# ---------------------------------------------------------------------------
# OutputPlan resolution
# ---------------------------------------------------------------------------
class TestResolveOutputPlan:
"""OutputPlan frozen dataclass and resolve_output_plan() function."""
def test_happy_path_all_enabled(self):
"""Default pattern with all flags enabled produces all 4 paths."""
from librofm_downloader.config import Config
from librofm_downloader.path import OutputPlan, resolve_output_plan
book = Book(
title="The Final Empire",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765374991",
series="Mistborn",
series_num=1,
cover_url="https://covers.libro.fm/cover.jpg",
pdf_extras=True,
)
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=True, download_extras=True,
)
plan = resolve_output_plan(book, "/audiobooks", config)
# OutputPlan is a frozen dataclass with expected fields
assert isinstance(plan, OutputPlan)
# Audio path: sanitized title + .m4b extension
assert plan.audio_path.name == "The Final Empire.m4b"
assert plan.audio_path.suffix == ".m4b"
# Partial path is audio_path + ".partial"
assert str(plan.partial_path) == f"{str(plan.audio_path)}.partial"
# Cover path populated (covers enabled + cover_url present)
assert plan.cover_path is not None
assert plan.cover_path.name == "cover.jpg"
# PDF path populated (extras enabled + pdf_extras True)
assert plan.pdf_path is not None
assert plan.pdf_path.name == "map.pdf"
# All file paths share the same parent directory (resolved output dir)
assert plan.audio_path.parent == plan.cover_path.parent
assert plan.audio_path.parent == plan.pdf_path.parent
# Subdirectory layout because pdf_extras=True
assert plan.audio_path.is_relative_to(Path("/audiobooks"))
def test_custom_output_pattern(self):
"""Custom pattern overrides default path structure."""
from librofm_downloader.config import Config
book = Book(
title="The Final Empire",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765374991",
series="Mistborn",
series_num=1,
)
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=False, download_extras=False,
)
plan = resolve_output_plan(book, "/audiobooks", config)
# Audio path should exist even without extras
assert plan.audio_path.name == "The Final Empire.m4b"
# Flat layout (no extras) → under author directory
assert "Brandon" in str(plan.audio_path)
def test_cover_disabled_returns_none(self):
"""download_covers=False → cover_path is None regardless of cover_url."""
from librofm_downloader.config import Config
book = Book(
title="No Cover Book",
authors=["Author"],
narrators=["Nar"],
isbn="9780000000001",
cover_url="https://covers.libro.fm/cover.jpg",
)
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=False, download_extras=False,
)
plan = resolve_output_plan(book, "/audiobooks", config)
assert plan.cover_path is None
def test_pdf_disabled_returns_none(self):
"""download_extras=False → pdf_path is None regardless of pdf_extras."""
from librofm_downloader.config import Config
book = Book(
title="No PDF Book",
authors=["Author"],
narrators=["Nar"],
isbn="9780000000002",
pdf_extras=True,
)
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=False, download_extras=False,
)
plan = resolve_output_plan(book, "/audiobooks", config)
assert plan.pdf_path is None
def test_no_cover_url_returns_none(self):
"""Empty cover_url → cover_path is None even with download_covers=True."""
from librofm_downloader.config import Config
book = Book(
title="No URL Book",
authors=["Author"],
narrators=["Nar"],
isbn="9780000000003",
cover_url="", # empty string = no cover available
)
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=True, download_extras=False,
)
plan = resolve_output_plan(book, "/audiobooks", config)
assert plan.cover_path is None
def test_no_pdf_extras_returns_none(self):
"""pdf_extras=False → pdf_path is None even with download_extras=True."""
from librofm_downloader.config import Config
book = Book(
title="No Extras Book",
authors=["Author"],
narrators=["Nar"],
isbn="9780000000004",
pdf_extras=False,
)
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=False, download_extras=True,
)
plan = resolve_output_plan(book, "/audiobooks", config)
assert plan.pdf_path is None
def test_string_output_base_accepted(self):
"""String output_base works (converted to Path internally)."""
from librofm_downloader.config import Config
book = Book(
title="String Base Book",
authors=["Author"],
narrators=["Nar"],
isbn="9780000000005",
)
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=False, download_extras=False,
)
# Should not raise; should return a plan with absolute paths
plan = resolve_output_plan(book, "/some/string/base", config)
assert isinstance(plan.audio_path, Path)
assert plan.audio_path.is_absolute()
def test_subdirectory_layout_when_pdf_extras_true(self):
"""pdf_extras=True creates subdirectory layout (Author/Title/)."""
from librofm_downloader.config import Config
book = Book(
title="Subdir Layout",
authors=["Author Name"],
narrators=["Nar"],
isbn="9780000000006",
pdf_extras=True,
)
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=True, download_extras=True,
)
plan = resolve_output_plan(book, "/audiobooks", config)
# Should be /audiobooks/Author Name/Subdir Layout/The Final Empire.m4b
expected_parent = Path("/audiobooks") / "Author Name" / "Subdir Layout"
assert plan.audio_path.parent == expected_parent
def test_flat_layout_when_no_extras(self):
"""No extras + no cover → flat layout (audio file under author dir)."""
from librofm_downloader.config import Config
book = Book(
title="Flat Layout",
authors=["Author Name"],
narrators=["Nar"],
isbn="9780000000007",
)
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=False, download_extras=False,
)
plan = resolve_output_plan(book, "/audiobooks", config)
# Flat: audio is leaf under author dir
expected_parent = Path("/audiobooks") / "Author Name"
assert plan.audio_path.parent == expected_parent
def test_output_plan_is_frozen(self):
"""OutputPlan is immutable (frozen dataclass)."""
from dataclasses import FrozenInstanceError
from librofm_downloader.config import Config
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000008")
config = Config(
username="u", password="p", format="m4b_mp3_fallback",
output_dir="/tmp", download_covers=False, download_extras=False,
)
plan = resolve_output_plan(book, "/base", config)
with pytest.raises(FrozenInstanceError):
plan.audio_path = Path("/other") # type: ignore[misc]