feat(downloader): add path resolution and sanitization (closes #4)

Add pure-logic downloader module with Book dataclass, filesystem-safe
path component sanitization, default conditional path patterns, custom
{TOKEN} pattern substitution, and subdirectory decision logic.

- sanitize(): 5-rule pipeline — colon→dash, strip illegal/control chars,
  trim whitespace, remove trailing dots, cap at 255 characters
- resolve_path(book, pattern?): default mode selects pattern by series
  presence; custom mode substitutes 11 tokens with sanitization
- needs_subdirectory(book): True when PDF extras or cover art present
- @dataclass(frozen=True) Book: immutable record for all book metadata

56 new tests across 11 classes. 97 total tests passing. 16/16 AC met.
This commit is contained in:
AlexKucera committed 2026-06-03 12:03:00 +02:00
1 parent 515f5c01f6
commit 25ee66b95d
5 files changed
+682

No files matched your search

+1
View File
@@ -8,4 +8,5 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
<!-- write-log: session-log-index -->
| Date | Type | File | Summary |
|------|------|------|---------|
| 2026-06-03 | slice | [20260603-slice-3a-path-resolution-and-sanitization-issue4_log.md](docs/devlog/20260603-slice-3a-path-resolution-and-sanitization-issue4_log.md) | **Issue #4 Complete:** Path resolution + sanitization + Book model + custom patterns. 56 new tests, **97 total** · **16/16 AC** |
| 2026-06-03 | issue | [20260603-project-scaffolding-and-config-module-issue2_log.md](docs/devlog/20260603-project-scaffolding-and-config-module-issue2_log.md) | **Issue #2 Complete:** pyproject.toml + venv + config module (load/merge/validate) + 25 tests. 11/11 AC met |
+4
View File
@@ -13,3 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- OAuth2 client with password grant auth and paginated library fetch
- Download history tracking with corrupt JSON recovery
- CLI skeleton wiring config → auth → library → filter → print
- Path resolution with default conditional patterns and custom token substitution
- Filesystem-safe component sanitization (illegal chars, control chars, colons)
- Immutable Book dataclass for typed book metadata
- Subdirectory decision logic based on PDF extras or cover art presence
@@ -0,0 +1,114 @@
# Slice 3a: Path Resolution + Sanitization
> **Date:** 2026-06-03
> **Type:** slice
> **Reference:** [Issue #4](https://github.com/AlexKucera/librofm-downloader/issues/4)
## Goal
Build a pure logic module for resolving output file paths from book metadata and sanitizing components for filesystem safety. No I/O, no network — all deterministic string manipulation.
## What Was Done
### 1. `Book` dataclass (`librofm_downloader/downloader.py`)
- **`@dataclass(frozen=True) Book`** — immutable record with fields: `title`, `authors`, `narrators`, `isbn`, `series`, `series_num`, `cover_url`, `pdf_extras`, `publication_year/month/day`
- All metadata needed for path resolution and subdirectory decisions in one typed, immutable container
### 2. `sanitize(component)` function
Pure string sanitization with 5 rules applied in order:
1. Replace `:` → ` -`
2. Strip `< > / \ | ? *` via `str.translate()` + control chars U+0000–U+001F
3. Trim whitespace (before dot removal so exposed dots are caught)
4. Remove trailing dots (`rstrip(".")`)
5. Cap at 255 characters
Preserves: dashes, commas, apostrophes, parentheses, internal periods.
### 3. `resolve_path(book, pattern=None)` function
- **Default mode** (no pattern): conditional logic based on series presence:
- series + series_num → `{Author}/{Series}/Book N {Title}`
- series only → `{Author}/{Series}/{Title}`
- no series → `{Author}/{Title}`
- **Custom mode** (pattern set): token substitution via regex `\{([A-Z_]+)\}` with 11 supported tokens: `FIRST_AUTHOR`, `ALL_AUTHORS`, `SERIES_NAME`, `SERIES_NUM`, `BOOK_TITLE`, `ISBN`, `FIRST_NARRATOR`, `ALL_NARRATORS`, `PUBLICATION_YEAR/MONTH/DAY`
- Every component sanitized after substitution
- Token registry pattern: `_TOKEN_REGISTRY` dict maps token names to `(attribute, formatter)` tuples; `_token_value()` resolves each token
### 4. `needs_subdirectory(book)` function
- Returns `True` when `book.pdf_extras` is truthy OR `book.cover_url` is non-empty
- Returns `False` otherwise (standalone audiobook file as leaf node)
### Test Suite (56 new tests across 10 test classes)
| Class | Tests | What's Verified |
|-------|-------|-----------------|
| `TestSanitizeIllegalChars` | 6 | `< > / \ | ? *` stripped |
| `TestSanitizeColonReplacement` | 3 | `:` → ` -`, including combined with illegal chars |
| `TestSanitizeControlChars` | 5 | Null, tab, newline, CR, range U+01–U+1E stripped |
| `TestSanitizeTrailingDots` | 4 | Single/multiple dots removed, internal preserved, trim-then-strip order |
| `TestSanitizeTrimWhitespace` | 4 | Leading/trailing/internal space handling |
| `TestSanitizeLengthCap` | 3 | Short unchanged, >255 capped, exact 255 unchanged |
| `TestSanitizePreservedChars` | 6 | Dashes, commas, apostrophes, parentheses, periods, combined safe+unsafe |
| `TestSanitizeEdgeCases` | 5 | Empty string, all-illegal, whitespace-only, unicode, unicode+illegal |
| `TestDefaultPath*` (3 classes) | 5 | Series+num, series-only, no-series paths with sanitization |
| `TestCustomPathPattern` | 10 | All 11 tokens, override behavior, missing tokens, sanitization |
| `TestNeedsSubdirectory` | 5 | PDF extras, cover art, both, neither, defaults |
**Total: 97 tests** (41 existing + 56 new) — all passing
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| `@dataclass(frozen=True)` for Book | Immutable records prevent accidental mutation; same pattern as Config and HistoryEntry |
| `resolve_path(book, pattern=None)` as single function | Simple, testable, follows existing patterns in codebase. Optional `pattern` param avoids needing a class |
| Token registry dict pattern | Declarative mapping of tokens to (attr, formatter) pairs makes adding new tokens trivial — just add one line to `_TOKEN_REGISTRY` |
| Regex-based token substitution (`\{([A-Z_]+)\`) | Simple, handles any ordering of tokens, unknown tokens produce empty string (not error) |
| Trim before trailing-dot removal | `" filename. "` must become `"filename"`, not `"filename."`. Discovered via failing test |
| `str.translate()` for illegal char stripping | O(n) single-pass character deletion; faster than repeated `str.replace()` calls |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Test expectation error: `"O'Brien, Brandon - Author"` vs actual `"O'Brien, Brandon Author"` | Test author assumed colon was in author name `"O'Brien, Brandon <Author>"` but there's no colon there — only angle brackets and comma | Fixed test expectation to match actual behavior |
| Trailing dot not removed after whitespace trim | Original implementation ordered: strip dots → trim whitespace. Input `" filename. "` → strip dots → `" filename "` → trim → `"filename."` (dot exposed by trim but already processed) | Swapped order: trim → strip dots. Added `test_trailing_dot_after_whitespace_trim` to catch this |
| `import re` inside function body | Initial implementation placed import inside `_resolve_custom_pattern` for laziness | Moved to module-level import per Python best practices |
## Files Changed
| File | Change Summary |
|------|---------------|
| `librofm_downloader/downloader.py` | **New** — Book dataclass, sanitize(), resolve_path(), needs_subdirectory(), token registry (~130 lines) |
| `tests/test_downloader.py` | **New** — 56 tests across 11 classes covering all sanitization rules, default paths, custom tokens, subdirectory logic |
## Acceptance Criteria
| # | Criterion | Status |
|---|-----------|--------|
| 1 | Default path resolves correctly for book with series + series_num | ✅ `test_basic_series_with_number` |
| 2 | Default path resolves correctly for book with series but no series_num | ✅ `test_basic_series_no_number` |
| 3 | Default path resolves correctly for book without series | ✅ `test_standalone_book` |
| 4 | Custom path_pattern with token substitution works for all documented tokens | ✅ 11 tokens tested across 7 tests |
| 5 | Custom path_pattern overrides default when set | ✅ `test_custom_pattern_overrides_default` |
| 6 | Colons replaced with `-` in all components | ✅ 3 tests in `TestSanitizeColonReplacement` |
| 7 | Illegal chars stripped: `< > / \ | ? *` | ✅ 6 tests in `TestSanitizeIllegalChars` |
| 8 | Control characters stripped | ✅ 5 tests in `TestSanitizeControlChars` |
| 9 | Trailing dots removed | ✅ 4 tests in `TestSanitizeTrailingDots` |
| 10 | Whitespace trimmed | ✅ 4 tests in `TestSanitizeTrimWhitespace` |
| 11 | Components capped at 255 chars | ✅ 3 tests in `TestSanitizeLengthCap` |
| 12 | Dashes, commas, apostrophes, parentheses preserved | ✅ 6 tests in `TestSanitizePreservedChars` |
| 13 | Subdirectory-needed returns True when PDF extras or cover art present | ✅ 3 tests in `TestNeedsSubdirectory` |
| 14 | Subdirectory-needed returns False when neither present | ✅ 2 tests in `TestNeedsSubdirectory` |
| 15 | ~20 tests covering all path patterns, every sanitization rule, edge cases | ✅ **56 tests** (nearly 3× target) |
| 16 | All tests pass | ✅ **97/97 passed** |
**16/16 AC met** ✅
## Open Items & Next Steps
- This slice builds pure logic only — no file system operations
- Next slices would wire this into the download pipeline: resolve paths before downloading, create subdirectories when `needs_subdirectory()` returns True
- The `Config` dataclass doesn't have a `path_pattern` field yet — that would be added when wiring custom patterns from config into `resolve_path()`
---
*Log written by write-log skill*
+149
View File
@@ -0,0 +1,149 @@
"""Path resolution and sanitization for librofm-downloader.
Pure logic module — no I/O, no network. All deterministic string manipulation.
"""
import re
from dataclasses import dataclass
# Characters that are unsafe in filesystem path components
_ILLEGAL_CHARS = str.maketrans("", "", "<>/\\|?*")
# Control characters U+0000–U+001F
_CONTROL_CHARS = {chr(i) for i in range(0x00, 0x20)}
@dataclass(frozen=True)
class Book:
"""Immutable book metadata record from Libro.fm."""
title: str
authors: list[str]
narrators: list[str]
isbn: str
series: str = ""
series_num: int | None = None
cover_url: str = ""
pdf_extras: bool = False
publication_year: int | None = None
publication_month: int | None = None
publication_day: int | None = None
def sanitize(component: str) -> str:
"""Sanitize a single path component for filesystem safety.
Rules applied in order:
1. Replace ``:`` with `` -``
2. Strip ``< > / \\ | ? *`` and control characters (U+0000–U+001F)
3. Remove trailing dots
4. Trim whitespace
5. Cap at 255 characters
Preserves: dashes, commas, apostrophes, parentheses, periods (non-trailing).
"""
# 1. Replace colons
result = component.replace(":", " -")
# 2. Strip illegal chars and control characters
result = result.translate(_ILLEGAL_CHARS)
result = "".join(ch for ch in result if ch not in _CONTROL_CHARS)
# 3. Trim whitespace (before dot removal so exposed dots are caught)
result = result.strip()
# 4. Remove trailing dots
result = result.rstrip(".")
# 5. Cap at 255 characters
return result[:255]
# Token name → (attribute_path, formatter)
# attribute_path is a space-separated chain of attr lookups;
# formatter converts the raw value to string.
_TOKEN_REGISTRY: dict[str, tuple[str, str]] = {
"FIRST_AUTHOR": ("authors", "first"),
"ALL_AUTHORS": ("authors", "join"),
"SERIES_NAME": ("series", "raw"),
"SERIES_NUM": ("series_num", "raw"),
"BOOK_TITLE": ("title", "raw"),
"ISBN": ("isbn", "raw"),
"FIRST_NARRATOR":("narrators", "first"),
"ALL_NARRATORS": ("narrators", "join"),
"PUBLICATION_YEAR": ("publication_year", "raw"),
"PUBLICATION_MONTH": ("publication_month", "raw"),
"PUBLICATION_DAY": ("publication_day", "raw"),
}
def _token_value(book: Book, token: str) -> str:
"""Resolve a single token to its string value from the book."""
if token not in _TOKEN_REGISTRY:
return ""
attr, fmt = _TOKEN_REGISTRY[token]
# Get the attribute value
val = getattr(book, attr)
# Format based on formatter type
if fmt == "first":
if isinstance(val, list) and val:
return str(val[0])
return ""
if fmt == "join":
if isinstance(val, list):
return ", ".join(str(v) for v in val)
return str(val) if val is not None else ""
# fmt == "raw"
return str(val) if val is not None else ""
def resolve_path(book: Book, pattern: str | None = None) -> str:
"""Resolve the relative output path for a book.
Args:
book: The book metadata.
pattern: Optional custom path pattern with token placeholders.
When set, overrides default conditional logic.
Tokens: FIRST_AUTHOR, ALL_AUTHORS, SERIES_NAME, SERIES_NUM,
BOOK_TITLE, ISBN, FIRST_NARRATOR, ALL_NARRATORS,
PUBLICATION_YEAR, PUBLICATION_MONTH, PUBLICATION_DAY.
Returns:
Sanitized relative path string.
"""
if pattern:
return _resolve_custom_pattern(book, pattern)
return _resolve_default_path(book)
def _resolve_default_path(book: Book) -> str:
"""Default conditional path logic."""
first_author = sanitize(book.authors[0] if book.authors else "Unknown")
title = sanitize(book.title)
if book.series and book.series_num is not None:
series_name = sanitize(book.series)
return f"{first_author}/{series_name}/Book {book.series_num} {title}"
if book.series:
series_name = sanitize(book.series)
return f"{first_author}/{series_name}/{title}"
return f"{first_author}/{title}"
def _resolve_custom_pattern(book: Book, pattern: str) -> str:
"""Resolve path using custom pattern with token substitution."""
def replacer(match: re.Match) -> str:
token = match.group(1)
raw = _token_value(book, token)
return sanitize(raw)
# Replace {TOKEN} patterns
result = re.sub(r"\{([A-Z_]+)\}", replacer, pattern)
return result
def needs_subdirectory(book: Book) -> bool:
"""Check whether a book needs a subdirectory for accompanying files.
Returns True when PDF extras or cover art are present.
"""
return bool(book.pdf_extras) or bool(book.cover_url)
+414
View File
@@ -0,0 +1,414 @@
"""Tests for librofm_downloader.downloader — TDD vertical slices."""
import pytest
from librofm_downloader.downloader import Book, needs_subdirectory, resolve_path, sanitize
class TestSanitizeIllegalChars:
"""Sanitization strips characters that are unsafe in filesystem paths."""
def test_strips_angle_brackets(self):
assert sanitize("Foo<Bar>") == "FooBar"
def test_strips_forward_slash(self):
assert sanitize("Foo/Bar") == "FooBar"
def test_strips_backslash(self):
assert sanitize("Foo\\Bar") == "FooBar"
def test_strips_pipe(self):
assert sanitize("Foo|Bar") == "FooBar"
def test_strips_question_mark(self):
assert sanitize("Foo?Bar") == "FooBar"
def test_strips_asterisk(self):
assert sanitize("Foo*Bar") == "FooBar"
class TestSanitizeColonReplacement:
"""Colons are replaced with ' -' (space-dash), not stripped."""
def test_single_colon_replaced(self):
assert sanitize("Part A: Part B") == "Part A - Part B"
def test_multiple_colons_replaced(self):
assert sanitize("A:B:C") == "A -B -C"
def test_colon_with_illegal_chars(self):
# Colon replaced first, then illegal chars stripped
assert sanitize("Foo:<>Bar") == "Foo -Bar"
class TestSanitizeControlChars:
"""Control characters U+0000–U+001F are stripped."""
def test_strips_null_byte(self):
assert sanitize("Foo\x00Bar") == "FooBar"
def test_strips_tab(self):
assert sanitize("Foo\tBar") == "FooBar"
def test_strips_newline(self):
assert sanitize("Foo\nBar") == "FooBar"
def test_strips_carriage_return(self):
assert sanitize("Foo\rBar") == "FooBar"
def test_strips_multiple_control_chars(self):
assert sanitize("\x01\x02Hello\x1F\x1E") == "Hello"
class TestSanitizeTrailingDots:
"""Trailing dots are removed (problematic on Windows)."""
def test_removes_single_trailing_dot(self):
assert sanitize("filename.") == "filename"
def test_removes_multiple_trailing_dots(self):
assert sanitize("filename...") == "filename"
def test_preserves_internal_dots(self):
assert sanitize("file.name.txt") == "file.name.txt"
def test_trailing_dot_after_whitespace_trim(self):
assert sanitize(" filename. ") == "filename"
class TestSanitizeTrimWhitespace:
"""Leading and trailing whitespace is trimmed."""
def test_trims_leading_space(self):
assert sanitize(" filename") == "filename"
def test_trims_trailing_space(self):
assert sanitize("filename ") == "filename"
def test_trims_both_ends(self):
assert sanitize(" filename ") == "filename"
def test_preserves_internal_spaces(self):
assert sanitize("my filename") == "my filename"
class TestSanitizeLengthCap:
"""Components are capped at 255 characters."""
def test_short_string_unchanged(self):
short = "a" * 100
assert sanitize(short) == short
def test_capped_at_255_chars(self):
long = "a" * 300
assert len(sanitize(long)) == 255
def test_exact_255_unchanged(self):
exact = "a" * 255
assert len(sanitize(exact)) == 255
class TestSanitizePreservedChars:
"""Safe characters that must be preserved through sanitization."""
def test_preserves_dashes(self):
assert sanitize("some-name") == "some-name"
def test_preserves_commas(self):
assert sanitize("Last, First") == "Last, First"
def test_preserves_apostrophes(self):
assert sanitize("O'Brien") == "O'Brien"
def test_preserves_parentheses(self):
assert sanitize("Book (subtitle)") == "Book (subtitle)"
def test_preserves_internal_periods(self):
assert sanitize("Dr. Jekyll") == "Dr. Jekyll"
def test_combined_safe_and_unsafe(self):
assert sanitize("O'Brien, Pat (Author): A Life*") == "O'Brien, Pat (Author) - A Life"
class TestSanitizeEdgeCases:
"""Edge cases: empty strings, unicode, all-illegal input."""
def test_empty_string_returns_empty(self):
assert sanitize("") == ""
def test_only_illegal_chars_returns_empty(self):
assert sanitize("<>/\\|?*") == ""
def test_only_whitespace_returns_empty(self):
assert sanitize(" ") == ""
def test_unicode_preserved(self):
assert sanitize("日本語タイトル") == "日本語タイトル"
def test_unicode_with_illegal_ascii(self):
assert sanitize("日本語<title>") == "日本語title"
# ---------------------------------------------------------------------------
# Default path resolution
# ---------------------------------------------------------------------------
class TestDefaultPathSeriesWithNumber:
"""Book with series AND series_num: Author/Series/Book N Title."""
def test_basic_series_with_number(self):
book = Book(
title="The Final Empire",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765374991",
series="Mistborn",
series_num=1,
)
path = resolve_path(book)
assert path == "Brandon Sanderson/Mistborn/Book 1 The Final Empire"
def test_sanitizes_author_name(self):
book = Book(
title="The Final Empire",
authors=["O'Brien, Brandon <Author>"],
narrators=["Michael Kramer"],
isbn="9780765374991",
series="Mistborn: Era 1",
series_num=1,
)
path = resolve_path(book)
# Angle brackets stripped from author, colon replaced in series
assert path == "O'Brien, Brandon Author/Mistborn - Era 1/Book 1 The Final Empire"
def test_sanitizes_series_and_title(self):
book = Book(
title="The Way of Kings (Book 1)",
authors=["Brandon Sanderson"],
narrators=["Kate Reading", "Michael Kramer"],
isbn="9780765398270",
series="Stormlight Archive*",
series_num=1,
)
path = resolve_path(book)
assert path == "Brandon Sanderson/Stormlight Archive/Book 1 The Way of Kings (Book 1)"
class TestDefaultPathSeriesWithoutNumber:
"""Book with series but no series_num: Author/Series/Title."""
def test_basic_series_no_number(self):
book = Book(
title="Warbreaker",
authors=["Brandon Sanderson"],
narrators=["Alyssa Bresnahan"],
isbn="9781433232829",
series="Cosmere: Standalones",
series_num=None,
)
path = resolve_path(book)
assert path == "Brandon Sanderson/Cosmere - Standalones/Warbreaker"
class TestDefaultPathNoSeries:
"""Book without series: Author/Title."""
def test_standalone_book(self):
book = Book(
title="Skyward",
authors=["Brandon Sanderson"],
narrators=["Sophie Aldred"],
isbn="9781509697815",
series="",
series_num=None,
)
path = resolve_path(book)
assert path == "Brandon Sanderson/Skyward"
class TestCustomPathPattern:
"""Custom path_pattern with token substitution overrides default logic."""
def test_basic_custom_pattern(self):
book = Book(
title="The Final Empire",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765374991",
series="Mistborn",
series_num=1,
)
pattern = "{FIRST_AUTHOR}/{SERIES_NAME}/{BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "Brandon Sanderson/Mistborn/The Final Empire"
def test_custom_pattern_overrides_default(self):
"""When pattern is set, default conditional logic is NOT used."""
book = Book(
title="The Final Empire",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765374991",
series="Mistborn",
series_num=1,
)
# Custom pattern without series_num — should NOT get "Book 1" prefix
pattern = "{FIRST_AUTHOR}/{BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "Brandon Sanderson/The Final Empire"
def test_all_authors_token(self):
book = Book(
title="Good Omens",
authors=["Neil Gaiman", "Terry Pratchett"],
narrators=["Martin Jarvis", "Stephen Briggs"],
isbn="9780062982360",
)
pattern = "{ALL_AUTHORS}/{BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "Neil Gaiman, Terry Pratchett/Good Omens"
def test_series_num_token(self):
book = Book(
title="The Final Empire",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765374991",
series="Mistborn",
series_num=1,
)
pattern = "{SERIES_NAME} {SERIES_NUM} - {BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "Mistborn 1 - The Final Empire"
def test_isbn_token(self):
book = Book(
title="The Final Empire",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765374991",
)
pattern = "{ISBN}/{BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "9780765374991/The Final Empire"
def test_narrator_tokens(self):
book = Book(
title="Good Omens",
authors=["Neil Gaiman"],
narrators=["Martin Jarvis", "Stephen Briggs"],
isbn="9780062982360",
)
pattern = "{FIRST_AUTHOR} - {FIRST_NARRATOR}/{BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "Neil Gaiman - Martin Jarvis/Good Omens"
def test_all_narrators_token(self):
book = Book(
title="Good Omens",
authors=["Neil Gaiman"],
narrators=["Martin Jarvis", "Stephen Briggs"],
isbn="9780062982360",
)
pattern = "{ALL_NARRATORS}/{BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "Martin Jarvis, Stephen Briggs/Good Omens"
def test_publication_date_tokens(self):
book = Book(
title="The Final Empire",
authors=["Brandon Sanderson"],
narrators=["Michael Kramer"],
isbn="9780765374991",
publication_year=2006,
publication_month=7,
publication_day=17,
)
pattern = "{PUBLICATION_YEAR}/{PUBLICATION_MONTH}/{PUBLICATION_DAY}/{BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "2006/7/17/The Final Empire"
def test_missing_optional_tokens_omitted(self):
"""Tokens with no value produce empty string (not error)."""
book = Book(
title="Standalone",
authors=["Some Author"],
narrators=[],
isbn="9780000000001",
)
pattern = "{SERIES_NAME}/{BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "/Standalone"
def test_sanitizes_custom_pattern_output(self):
book = Book(
title="Book: A Subtitle<Extra>",
authors=["O'Brien, Author"],
narrators=["Narrator"],
isbn="9780000000001",
)
pattern = "{FIRST_AUTHOR}/{BOOK_TITLE}"
path = resolve_path(book, pattern=pattern)
assert path == "O'Brien, Author/Book - A SubtitleExtra"
# ---------------------------------------------------------------------------
# Subdirectory decision
# ---------------------------------------------------------------------------
class TestNeedsSubdirectory:
"""Subdirectory is needed when PDF extras or cover art are present."""
def test_true_when_pdf_extras_present(self):
book = Book(
title="Some Book",
authors=["Author"],
narrators=["Narrator"],
isbn="9780000000001",
pdf_extras=True,
cover_url="",
)
assert needs_subdirectory(book) is True
def test_true_when_cover_url_present(self):
book = Book(
title="Some Book",
authors=["Author"],
narrators=["Narrator"],
isbn="9780000000001",
pdf_extras=False,
cover_url="https://example.com/cover.jpg",
)
assert needs_subdirectory(book) is True
def test_true_when_both_present(self):
book = Book(
title="Some Book",
authors=["Author"],
narrators=["Narrator"],
isbn="9780000000001",
pdf_extras=True,
cover_url="https://example.com/cover.jpg",
)
assert needs_subdirectory(book) is True
def test_false_when_neither_present(self):
book = Book(
title="Some Book",
authors=["Author"],
narrators=["Narrator"],
isbn="9780000000001",
pdf_extras=False,
cover_url="",
)
assert needs_subdirectory(book) is False
def test_false_with_defaults(self):
"""Book created with default fields (no extras, no cover)."""
book = Book(
title="Some Book",
authors=["Author"],
narrators=["Narrator"],
isbn="9780000000001",
)
assert needs_subdirectory(book) is False