test(downloader): add rename_chapters pipeline integration tests (Issue #35)
Add 4 end-to-end integration tests proving rename_chapters() fires correctly through the full download pipeline for each format strategy, and is properly suppressed when disabled. Closes #35
This commit is contained in:
1 parent
a415fc37f5
commit
a8ff0b2134
3 files changed
+340
-1
No files matched your search
@@ -8,6 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste
|
||||
<!-- write-log: session-log-index -->
|
||||
| Date | Type | File | Summary |
|
||||
|------|------|------|---------|
|
||||
| 2026-06-05 | issue | [20260605-issue35-integration-tests-rename-chapters-pipeline-wiring_log.md](docs/devlog/20260605-issue35-integration-tests-rename-chapters-pipeline-wiring_log.md) | **Issue #35 Complete (Slice 4):** Integration tests for rename_chapters pipeline wiring. AC#3 missing test + 4 edge cases (special chars, single-track, 105-chapter 3-digit padding). **4 new tests, ~233 total** · **All pass** · **6/6 AC** |
|
||||
| 2026-06-05 | issue | [20260605-issue34-wire-rename-chapters-into-download-pipeline_log.md](docs/devlog/20260605-issue34-wire-rename-chapters-into-download-pipeline_log.md) | **Issue #34 Complete (Slice 3):** Wired `rename_chapters()` into download pipeline. `_download_mp3()` returns tuple with tracks, `download_book()` accepts `rename_chapters` kwarg, `_rename_and_log()` helper + user-visible reporter feedback. **6 new tests, ~229 total** · **All pass** · **8/8 AC** |
|
||||
| 2026-06-05 | issue | [20260605-issue33-rename-chapters-config-field-and-cli-flag_log.md](docs/devlog/20260605-issue33-rename-chapters-config-field-and-cli-flag_log.md) | **Issue #33 Complete (Slice 2):** `rename_chapters` config field + `--rename-chapters` CLI flag. 2-layer resolution (CLI > config), defaults True. **5 new tests, 223 total** · **All pass** · **6/7 AC** (env var skipped per user choice) |
|
||||
| 2026-06-05 | issue | [20260605-issue32-rename-chapters-function-and-unit-tests_log.md](docs/devlog/20260605-issue32-rename-chapters-function-and-unit-tests_log.md) | **Issue #32 Complete:** `rename_chapters()` function in `downloader.py`. Natural sort, zero-padding, null-title fallback, sanitization via existing `sanitize()`. **11 new tests, 106 in downloader** · **All pass** · **12/12 AC** |
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
# Issue #35 — Integration Tests for rename_chapters Pipeline Wiring (Slice 4)
|
||||
|
||||
> **Date:** 2026-06-05
|
||||
> **Type:** issue
|
||||
> **Reference:** [Issue #35](https://github.com/AlexKucera/librofm-downloader/issues/35)
|
||||
> **Parent:** [#19](https://github.com/AlexKucera/librofm-downloader/issues/19)
|
||||
|
||||
## Goal
|
||||
|
||||
Write end-to-end integration tests proving that `rename_chapters()` fires correctly through the full download pipeline for each format strategy, and is properly suppressed when disabled. This is Slice 4 of the rename-chapters feature (parent #19), blocked by issue #34's pipeline wiring work.
|
||||
|
||||
## What Was Done
|
||||
|
||||
### Gap Analysis
|
||||
|
||||
Before writing any code, compared existing `TestRenameChaptersWiring` tests (from issue #34) against issue #35's 6 acceptance criteria. Found that **5 of 6 AC were already covered** by the 6 tests written during issue #34:
|
||||
|
||||
| AC | Criteria | Already Covered? | Existing Test |
|
||||
|----|----------|------------------|---------------|
|
||||
| 1 | mp3_only + rename=True → renamed | ✅ | `test_mp3_only_rename_chapters_true_renames_files` |
|
||||
| 2 | m4b_mp3_fallback (fallback) + rename=True → renamed | ✅ | `test_m4b_mp3_fallback_renames_on_fallback` |
|
||||
| 3 | m4b_mp3_fallback (M4B success) + rename=True → no side effects | ❌ **MISSING** | — |
|
||||
| 4 | m4b_only + rename=True → no rename | ✅ | `test_m4b_only_rename_chapters_not_called` |
|
||||
| 5 | mp3_only + rename=False → originals kept | ✅ | `test_rename_chapters_false_skips_rename` |
|
||||
| 6 | Verbose mode logs rename ops | ✅ | `test_rename_logs_each_operation` |
|
||||
|
||||
### Tests Written (TDD vertical slices)
|
||||
|
||||
**Tracer bullet — AC#3 missing test:**
|
||||
- `test_m4b_mp3_fallback_m4b_success_no_rename_side_effects` — Uses `format_strategy="m4b_mp3_fallback"` with mock transport where M4B endpoint returns 200. Asserts M4B downloaded, no MP3 files exist, no rename side effects.
|
||||
|
||||
**Edge case 1 — Special character sanitization through full pipeline:**
|
||||
- `test_special_chars_in_chapter_titles_sanitized` — Chapter titles with `/ : < > \ | ? *` and book title with `:`, `( )`. Asserts no illegal characters survive in output filenames. Noted that `sanitize()` does NOT strip `"` — test expectation aligned accordingly.
|
||||
|
||||
**Edge case 2 — Single-track zero-padding width=1:**
|
||||
- `test_single_track_zero_padding` — One track → no leading zero (`1 - Title - Chapter.mp3`, not `01 - ...`). Verifies original `1.mp3` removed and exactly 1 MP3 in output.
|
||||
|
||||
**Edge case 3 — 100+ chapter zero-padding (user-requested):**
|
||||
- `test_hundred_plus_chapters_three_digit_padding` — **105 tracks** in ZIP + manifest. Spot-checks 3-digit padding at critical boundaries: `001`, `005`, `099`, **`100`**, `101`, `105`. The 99→100 transition is the key boundary where padding width increases from 2→3 digits. User has audiobooks with 100+ chapters in practice.
|
||||
|
||||
### Results
|
||||
|
||||
| Metric | Value |
|
||||
|--------|-------|
|
||||
| New tests added | 4 (class grew 6 → 10) |
|
||||
| Downloader test count | 116 (was 113) |
|
||||
| Full suite pass | ~233 (3 pre-existing Ctrl+C hang excluded) |
|
||||
| Acceptance criteria | **6/6 met** ✅ |
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
| Decision | Rationale |
|
||||
|----------|-----------|
|
||||
| Only write the missing AC#3 test + edge cases, not rewrite all 6 AC tests | Issue #34 already wrote 6 correct integration tests covering 5/6 AC. Rewriting would be duplication without coverage benefit. |
|
||||
| Use 105 tracks instead of 12 for multi-track test | User explicitly requested 100+ chapter coverage — they have real audiobooks with 100+ chapters. The 99→100 digit-width transition is a meaningful boundary. |
|
||||
| Align sanitization assertions with actual `sanitize()` behavior | `sanitize()` doesn't strip double quotes; test checks only characters that are actually stripped rather than asserting on unsupported chars. |
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
| Problem | Root Cause | Fix |
|
||||
|---------|------------|-----|
|
||||
| Parallel worker reported `test_special_chars_in_chapter_titles_sanitized` failing due to `"` not being sanitized | `sanitize()` function doesn't strip double-quote characters; sibling worker's initial assertion included `"` in forbidden set | Adjusted assertion to check only characters `sanitize()` actually strips: `/ : < > \\ \| ? *`. Test passes cleanly. |
|
||||
| Full suite run interrupted by Ctrl+C hang tests | 3 pre-existing tests in `TestFormatStrategy` hang on KeyboardInterrupt (known since issue #26) | Ran downloader tests separately (116/116 pass) and other modules separately (117/117 pass). Not a regression — documented pre-existing issue. |
|
||||
|
||||
## Files Changed
|
||||
|
||||
| File | Change Summary |
|
||||
|------|---------------|
|
||||
| `tests/test_downloader.py` | Added 4 new tests to `TestRenameChaptersWiring`: AC#3 missing test, special chars sanitization, single-track padding, 105-chapter 3-digit padding (~+260 lines net) |
|
||||
|
||||
## Open Items & Next Steps
|
||||
|
||||
- [ ] None for this slice — all 6/6 AC met, rename-chapters feature slices complete (#32–#35)
|
||||
- [ ] Pre-existing: 3 Ctrl+C hang tests remain unfixed (documented since issue #26)
|
||||
- [ ] Consider: End-to-end HITL test with a real audiobook that has 100+ chapters to validate 3-digit padding against actual Libro.fm CDN content
|
||||
|
||||
---
|
||||
|
||||
*Log written by write-log skill*
|
||||
+260
-1
@@ -2223,6 +2223,61 @@ class TestRenameChaptersWiring:
|
||||
mp3_files = list(result.path.glob("*.mp3"))
|
||||
assert len(mp3_files) == 0
|
||||
|
||||
def test_m4b_mp3_fallback_m4b_success_no_rename_side_effects(self):
|
||||
"""m4b_mp3_fallback + M4B success + rename_chapters=True → no rename side effects."""
|
||||
m4b_content = b"fake-m4b-data"
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"parts": [],
|
||||
"tracks": [{"number": 1, "chapter_title": "Ch1"}],
|
||||
},
|
||||
)
|
||||
# M4B endpoint succeeds → no MP3 fallback
|
||||
if "/packaged_m4b" in request.url.path:
|
||||
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_content)
|
||||
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="M4B Success Fallback Book", authors=["Author"], narrators=["N"], isbn="9789900000007")
|
||||
|
||||
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=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=True, # even with True, M4B success should not trigger rename
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
assert result.format == "m4b"
|
||||
# No MP3 files should exist at all (M4B path taken, no fallback)
|
||||
mp3_files = list(result.path.glob("*.mp3"))
|
||||
assert len(mp3_files) == 0
|
||||
# The .m4b file should exist (proving M4B download succeeded)
|
||||
m4b_files = list(result.path.glob("*.m4b")) if result.path.is_dir() else []
|
||||
if not m4b_files:
|
||||
# result.path may be the .m4b file itself for m4b downloads
|
||||
assert result.path.exists() and result.path.suffix == ".m4b"
|
||||
|
||||
def test_rename_chapters_false_skips_rename(self):
|
||||
"""mp3_only + rename_chapters=False (default) → files NOT renamed."""
|
||||
import io
|
||||
@@ -2467,4 +2522,208 @@ class TestRenameChaptersWiring:
|
||||
assert any("renamed" in m.lower() for m in info_messages), \
|
||||
f"Expected 'renamed' info message, got: {info_messages}"
|
||||
assert any("log test book" in m.lower() for m in info_messages), \
|
||||
f"Expected book title in log, got: {info_messages}"
|
||||
f"Expected book title in log, got: {info_messages}"
|
||||
|
||||
def test_special_chars_in_chapter_titles_sanitized(self):
|
||||
"""Special characters in chapter titles are sanitized through full pipeline."""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
mp3_zip_payload = io.BytesIO()
|
||||
with zipfile.ZipFile(mp3_zip_payload, "w") as zf:
|
||||
zf.writestr("1.mp3", b"audio-1")
|
||||
zf.writestr("2.mp3", b"audio-2")
|
||||
mp3_zip_data = mp3_zip_payload.getvalue()
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"parts": [{"url": "https://cdn.example.com/p1.zip", "name": "p1"}],
|
||||
"tracks": [
|
||||
{"number": 1, "chapter_title": "Introduction: The <Beginning>"},
|
||||
{"number": 2, "chapter_title": 'Chapter 1: "Hello / World"?'},
|
||||
],
|
||||
},
|
||||
)
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_data)
|
||||
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='Test: A Book (2024)', authors=["Author"], narrators=["N"], isbn="9789900000007")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="mp3_only")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=True,
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
assert result.format == "mp3"
|
||||
|
||||
output_dir = result.path
|
||||
# Original numeric names should be gone
|
||||
assert not (output_dir / "1.mp3").exists()
|
||||
assert not (output_dir / "2.mp3").exists()
|
||||
|
||||
# Renamed files should exist with sanitized names (no special chars)
|
||||
mp3_files = sorted(output_dir.glob("*.mp3"))
|
||||
assert len(mp3_files) >= 2
|
||||
for f in mp3_files:
|
||||
name = f.name
|
||||
for char in '/:<>\\|?*':
|
||||
assert char not in name, (
|
||||
f"Special character '{char}' found in filename: {name}"
|
||||
)
|
||||
|
||||
def test_hundred_plus_chapters_three_digit_padding(self):
|
||||
"""100+ chapters → zero-padded to 3 digits (001, 002, … 099, 100, 101)."""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
num_tracks = 105
|
||||
mp3_zip_payload = io.BytesIO()
|
||||
with zipfile.ZipFile(mp3_zip_payload, "w") as zf:
|
||||
for i in range(1, num_tracks + 1):
|
||||
zf.writestr(f"{i}.mp3", f"audio-{i}".encode())
|
||||
mp3_zip_data = mp3_zip_payload.getvalue()
|
||||
|
||||
track_titles = [f"Chapter {i}" for i in range(1, num_tracks + 1)]
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"parts": [{"url": "https://cdn.example.com/p1.zip", "name": "p1"}],
|
||||
"tracks": [
|
||||
{"number": i, "chapter_title": title}
|
||||
for i, title in enumerate(track_titles, start=1)
|
||||
],
|
||||
},
|
||||
)
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_data)
|
||||
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="Big Book", authors=["Author"], narrators=["N"], isbn="9789900000007")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="mp3_only")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=True,
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
assert result.format == "mp3"
|
||||
|
||||
output_dir = result.path
|
||||
# Original numeric names should all be gone
|
||||
for i in range(1, num_tracks + 1):
|
||||
assert not (output_dir / f"{i}.mp3").exists(), \
|
||||
f"Original name {i}.mp3 should be renamed"
|
||||
|
||||
# Three-digit zero-padded renamed files — spot-check boundaries
|
||||
assert (output_dir / "001 - Big Book - Chapter 1.mp3").exists()
|
||||
assert (output_dir / "005 - Big Book - Chapter 5.mp3").exists()
|
||||
assert (output_dir / "099 - Big Book - Chapter 99.mp3").exists()
|
||||
# The 99→100 transition is the critical boundary
|
||||
assert (output_dir / "100 - Big Book - Chapter 100.mp3").exists()
|
||||
assert (output_dir / "101 - Big Book - Chapter 101.mp3").exists()
|
||||
assert (output_dir / "105 - Big Book - Chapter 105.mp3").exists()
|
||||
|
||||
# Exactly 105 MP3 files
|
||||
mp3_files = list(output_dir.glob("*.mp3"))
|
||||
assert len(mp3_files) == num_tracks
|
||||
def test_single_track_zero_padding(self):
|
||||
"""Single-track book: zero-padding width=1, no leading zero."""
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
mp3_zip_payload = io.BytesIO()
|
||||
with zipfile.ZipFile(mp3_zip_payload, "w") as zf:
|
||||
zf.writestr("1.mp3", b"audio-only")
|
||||
mp3_zip_data = mp3_zip_payload.getvalue()
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
if request.url.path == "/api/v10/download-manifest":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"parts": [{"url": "https://cdn.example.com/p1.zip", "name": "p1"}],
|
||||
"tracks": [
|
||||
{"number": 1, "chapter_title": "Only Chapter"},
|
||||
],
|
||||
},
|
||||
)
|
||||
if "cdn.example.com" in request.url.host:
|
||||
return httpx.Response(200, content=mp3_zip_data)
|
||||
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="Single Track Book", authors=["Author"], narrators=["N"], isbn="9789900000008")
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
base_dir = Path(tmpdir) / "audiobooks"
|
||||
plan = resolve_output_plan(book, base_dir, format_strategy="mp3_only")
|
||||
reporter = DownloadReporter()
|
||||
|
||||
result = download_book(
|
||||
book=book,
|
||||
session=client,
|
||||
plan=plan,
|
||||
reporter=reporter,
|
||||
rename_chapters=True,
|
||||
)
|
||||
|
||||
assert result.status == "downloaded"
|
||||
assert result.format == "mp3"
|
||||
|
||||
output_dir = result.path
|
||||
# Original numeric name gone
|
||||
assert not (output_dir / "1.mp3").exists()
|
||||
# Renamed with single-digit (width=1 for 1 track)
|
||||
assert (output_dir / "1 - Single Track Book - Only Chapter.mp3").exists()
|
||||
# Exactly 1 MP3 file
|
||||
assert len(list(output_dir.glob("*.mp3"))) == 1
|
||||
Reference in new issue
Block a user