refactor(progress): return bound callable from start_download (#30)

start_download(book) now returns a per-book bound callable
instead of raw task_id. Task identity is fully internal to
progress.py — no caller ever sees or passes task_id.

- Orchestrator: removed closure pattern, now threads
  progress_cb = start_download(book) directly
- downloader: download_book() accepts optional progress= kwarg,
  uses it when provided (falls back to reporter.update)
- cli.py: forwards progress kwarg through _download_fn
- Public update() drops task_id param; bound callable calls
  _progress.update(task_id_internal) directly

382 tests pass (+11 new), 6/6 AC met.
This commit is contained in:
AlexKucera committed 2026-06-05 11:58:04 +02:00
1 parent 9ac581e5b7
commit 1f46467f2c
10 files changed
+398 -95

No files matched your search

+1
View File
@@ -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-issue30-download-reporting-bound-callable-per-book_log.md](docs/devlog/20260605-issue30-download-reporting-bound-callable-per-book_log.md) | **Issue #30 Complete:** Bound callable per book from `start_download()`. Task identity internal to `progress.py`. Orchestrator closure eliminated. **11 new tests, 382 total** · **All pass** · **6/6 AC** |
| 2026-06-04 | issue | [20260604-issue29-download-attempt-interface-shrink-to-4-params_log.md](docs/devlog/20260604-issue29-download-attempt-interface-shrink-to-4-params_log.md) | **Issue #29 Complete:** `download_book()` 9→4 domain-aligned params. `DownloadResult` frozen dataclass. History moved to caller. `OutputPlan.format_strategy` added. Cancel via reporter. **15 new TDD tests, 368 total** · **All pass** · **6/6 AC** |
| 2026-06-04 | issue | [20260604-issue28-output-plan-dataclass_log.md](docs/devlog/20260604-issue28-output-plan-dataclass_log.md) | **Issue #28 Complete:** `OutputPlan` frozen dataclass + `resolve_output_plan()`. Centralized all path computation; download functions consume plan fields. Eliminated duplicated audio-path code. **10 new TDD tests, 237 total** · **All pass** · **5/5 AC** |
| 2026-06-04 | issue | [20260604-issue27-librofm-session-constructor-injection-and-rename_log.md](docs/devlog/20260604-issue27-librofm-session-constructor-injection-and-rename_log.md) | **Issue #27 Complete:** `LibroFmClient` → `LibroFmSession`, relocated to `session.py`. Constructor transport injection, shared `httpx.Client`, auth headers assembled once. **17 new TDD tests, 244 total** · **227 pass (3 pre-existing hang)** · **6/6 AC** |
+6
View File
@@ -28,6 +28,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
extract transport from session. Remove config from accompanying_files.
368 tests pass (+15 new). Closes #29.
- **progress:** Return bound callable from start_download() instead of raw
task_id. Task identity is fully internal to progress.py. Orchestrator
no longer creates per-book closures — passes the bound callback
directly. download_book() accepts optional progress= kwarg. Public
update() drops task_id param. 382 tests pass (+11 new). Closes #30.
10:9bb|### Fixed
- **progress:** Wire task_id through parallel progress callback.
All concurrent download updates went to the same (most recently started) bar
@@ -0,0 +1,55 @@
# Issue #30 — Download Reporting: Bound Callable Per Book
> **Date:** 2026-06-05
> **Type:** issue
> **Reference:** #30
## Goal
Refactor `start_download(book)` to return a bound callable that already targets the correct progress bar, making task identity fully internal to `progress.py`. Eliminate the per-book closure pattern from the orchestrator.
## What Was Done
- **`librofm_downloader/progress.py`** — `start_download()` now returns `Callable[[int], None]` (bound closure) instead of `int task_id`. Public `update()` no longer accepts `task_id` param. The bound callable captures `task_id` internally and calls `_progress.update(task_id, ...)` directly.
- **`librofm_downloader/orchestrator.py`** — Removed closure pattern from `_download_one`. Now calls `progress_cb = reporter.start_download(book)` and passes `progress_cb` as `progress=` kwarg to `download_fn`.
- **`librofm_downloader/downloader.py`** — `download_book()` accepts optional `progress=` kwarg; uses it when provided, falls back to `reporter.update` for backward compatibility.
- **`librofm_downloader/cli.py`** — `_download_fn` now passes `progress=progress` through to `download_book()`.
- **`tests/test_progress.py`** — 9 existing tests refactored for new return type (int → callable) + 5 new tests in `TestBoundCallableFromStartDownload`.
- **`tests/test_orchestrator.py`** — 1 new test: `TestOrchestratorUsesBoundCallback`.
- **`tests/test_downloader.py`** — 1 new test: `test_uses_provided_progress_callback_over_reporter_update`.
## Decisions & Rationale
| Decision | Rationale |
|----------|-----------|
| Bound closure over callback-with-book-arg | Simpler API; prevents cross-bar contamination by construction — caller can't possibly target wrong task |
| Kept public `update()` without `task_id` param | Fallback for direct callers not going through orchestrator; targets most-recent task |
| Bound callable calls `_progress.update()` directly (not public `update()`) | Keeps fast path clean; avoids any guard logic in the hot loop |
## Gotchas & Fixes
| Problem | Root Cause | Fix |
|---------|------------|-----|
| Downloader progress-wiring test showed "skipped" status | Mock URLs didn't match `/packaged_m4b` path or CDN host patterns used by real download path selection | Used proper mock URLs matching real route conditions |
| `MagicMock(spec=DownloadReporter)` raised error | `DownloadReporter` is a factory function, not a class — `spec=` expects a class | Switched to bare `MagicMock()` |
| 9 existing tests broke after return-type change | `start_download()` changed from returning `int` → `Callable`; tests asserted on `isinstance(result, int)` or passed result to `update(task_id=)` | Refactored all 9 to call returned callable directly |
## Files Changed
| File | Change Summary |
|------|---------------|
| `librofm_downloader/progress.py` | `start_download()` returns bound `Callable[[int], None]`; public `update()` drops `task_id` param |
| `librofm_downloader/orchestrator.py` | Removed per-book closure; uses bound callable from `start_download()` |
| `librofm_downloader/downloader.py` | `download_book()` accepts optional `progress=` kwarg with fallback to reporter |
| `librofm_downloader/cli.py` | Wires `progress=` kwarg through `_download_fn` → `download_book()` |
| `tests/test_progress.py` | 9 refactored + 5 new tests for bound callable behavior |
| `tests/test_orchestrator.py` | 1 new test: orchestrator uses bound callback correctly |
| `tests/test_downloader.py` | 1 new test: provided progress callback takes priority over reporter |
## Open Items & Next Steps
- None — issue fully complete, 6/6 AC met
---
*Log written by write-log skill*
+1 -1
View File
@@ -157,7 +157,7 @@ def run(
book, config.output_dir, config=config, format_strategy=config.format,
)
result = download_book(book, client, plan, reporter)
result = download_book(book, client, plan, reporter, progress=progress)
# Write history as caller (no longer inside download_book)
if result.status == "downloaded":
+5 -1
View File
@@ -236,6 +236,8 @@ def download_book(
session: "LibroFmSession",
plan: "OutputPlan",
reporter: "DownloadReporter",
*,
progress: "Callable[[int], None] | None" = None,
) -> DownloadResult:
"""Orchestrate a single book download with format strategy.
@@ -253,7 +255,9 @@ def download_book(
output_dir.mkdir(parents=True, exist_ok=True)
format_strategy = plan.format_strategy
progress = reporter.update
# Use provided bound callback (from start_download) or fall back to reporter.update
if progress is None:
progress = reporter.update
cancel_event = reporter.cancel_event
transport = session._client._transport
+5 -9
View File
@@ -69,17 +69,13 @@ def _download_one(
- error: exception string if download_fn raised, else None
- was_skipped: True if download_fn returned None (skipped)
"""
task_id = reporter.start_download(book)
# Create a per-book progress callback bound to this book's task_id.
# Without this, reporter.update() falls back to the most-recently-started
# bar (see ProgressReporter.update), so all parallel downloads would
# update the same progress bar.
def _progress(completed: int, *, total: int | None = None) -> None:
reporter.update(completed, total=total, task_id=task_id)
# Issue #30: start_download() returns a bound callable that already carries
# task identity internally. For TTY reporters this is a per-book update fn;
# for plain-text reporters it is None. No closure needed here.
progress_cb = reporter.start_download(book)
try:
result = download_fn(book, progress=_progress)
result = download_fn(book, progress=progress_cb)
if result is None:
# Skipped (no format available)
reporter.complete(book) # still "complete" the progress tracking
+24 -15
View File
@@ -94,11 +94,12 @@ class ProgressReporter:
self._book_ids: dict[int, int] = {} # id(book) -> task_id
self.cancel_event: threading.Event | None = None
def start_download(self, book, total_bytes: int = 0) -> int:
def start_download(self, book, total_bytes: int = 0) -> callable:
"""Start a progress bar for this book's download.
Returns:
The Rich task ID for this book's progress bar.
A bound callable ``(completed, *, total=None) -> None`` that updates
only this book's progress bar. Returns ``None`` for PlainTextReporter.
"""
from rich.progress import (
BarColumn,
@@ -128,26 +129,34 @@ class ProgressReporter:
self._tasks[task_id] = book
self._book_ids[id(book)] = task_id
return task_id
# Return a bound callable that carries task_id internally.
# Calls _progress.update() directly — bypasses the public update().
task_id_internal = task_id
_progress_obj = self._progress
def update(self, completed: int, *, total: int | None = None, task_id: int | None = None) -> None:
"""Update progress bar with bytes completed.
def _update(completed: int, *, total: int | None = None) -> None:
kwargs: dict = {"completed": completed}
if total is not None:
kwargs["total"] = total
_progress_obj.update(task_id_internal, **kwargs)
If *total* is provided (e.g. from a Content-Length header), also
updates the task's total so that percentage and ETA can be computed.
return _update
def update(self, completed: int, *, total: int | None = None) -> None:
"""Update progress for the most recently started download.
This is a convenience fallback for callers that don't have a bound
callable from start_download(). It always targets the most-recently-started
task. For per-book targeting, use the bound callable returned by
start_download() instead.
Args:
completed: Bytes downloaded so far.
total: Optional total bytes (from Content-Length).
task_id: Specific task to update. Falls back to most recent if omitted.
total: Optional new total (e.g. from Content-Length header).
"""
if not self._progress:
return
if task_id is None:
# Backward compat: use the most recently started task
task_id = next(reversed(self._tasks), None)
if task_id is None or task_id not in self._tasks:
if not self._progress or not self._tasks:
return
task_id = next(reversed(self._tasks))
kwargs: dict = {"completed": completed}
if total is not None:
kwargs["total"] = total
+48
View File
@@ -139,6 +139,54 @@ class TestDownloadBookNewInterface:
assert result.path.exists()
assert result.format == "m4b"
def test_uses_provided_progress_callback_over_reporter_update(self):
"""When progress= is passed, download_book uses it instead of reporter.update.
Issue #30: The orchestrator passes a bound callable from start_download().
download_book must thread it through to the chunk loop, not ignore it.
"""
import httpx
from unittest.mock import MagicMock
from librofm_downloader.downloader import download_book
m4b_payload = b"progress-callback-test-data" * 10 # 240 bytes
received: list[int] = []
def my_callback(completed: int, *, total: int | None = None) -> None:
received.append(completed)
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 "/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_payload, headers={"Content-Length": str(len(m4b_payload))})
return httpx.Response(404)
transport = httpx.MockTransport(handler)
session = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
session.authenticate()
book = Book(title="Callback Test", authors=["Author"], narrators=["N"], isbn="9789900000000")
reporter = MagicMock()
reporter.cancel_event = None
with tempfile.TemporaryDirectory() as tmpdir:
plan = resolve_output_plan(book, Path(tmpdir), format_strategy="m4b_only")
result = download_book(book, session, plan, reporter, progress=my_callback)
assert result.status == "downloaded"
# Our callback should have been called (not reporter.update)
assert len(received) >= 1, "Bound callback should receive progress updates"
# reporter.update should NOT have been called
reporter.update.assert_not_called()
class TestSanitizeIllegalChars:
"""Sanitization strips characters that are unsafe in filesystem paths."""
+77 -1
View File
@@ -875,4 +875,80 @@ class TestCtrlCDrain:
# Should NOT have waited for all 3 books
assert len(completed_isbns) < 3, (
f"Cooperative cancel should stop early; got {len(completed_isbns)} completions"
)
)
# ---------------------------------------------------------------------------
# Issue #30: Bound Callable — Orchestrator uses callback directly
# ---------------------------------------------------------------------------
class TestOrchestratorUsesBoundCallback:
"""Orchestrator passes start_download()'s bound callable to download_fn.
Issue #30: No closure-wiring code in _download_one. The reporter owns
task identity; the orchestrator just threads the callable through.
"""
def test_download_fn_receives_bound_callback_from_reporter(self):
"""download_fn(progress=...) gets the callable returned by start_download()."""
received_callbacks: list = []
class TrackingReporter:
"""Returns a per-book callable from start_download()."""
def __init__(self):
self.started: list[Book] = []
self.completed: list[Book] = []
self._callables: list[callable] = []
def start_download(self, book: Book, total_bytes: int = 0) -> callable:
self.started.append(book)
cb = lambda completed, **kw: None # no-op but unique per book
self._callables.append(cb)
return cb
def complete(self, book: Book) -> None:
self.completed.append(book)
def fail(self, book: Book, reason: str = "") -> None:
pass
def stop(self) -> None:
pass
def summary(self, **kwargs) -> None:
pass
def download_fn(book: Book, *, progress=None) -> Path | None:
# Capture whatever the orchestrator passes as progress=
received_callbacks.append((book.isbn, progress))
return Path(f"/fake/{book.isbn}.m4b")
raw_books = [
_make_raw_book(isbn="978111", title="Book A"),
_make_raw_book(isbn="978222", title="Book B"),
]
reporter = TrackingReporter()
result = download_all_books(
raw_books,
workers=2,
download_fn=download_fn,
reporter=reporter,
)
assert result.downloaded_count == 2
assert len(received_callbacks) == 2
# Each book should have received its OWN bound callable (not None, not shared)
isbn_a, cb_a = received_callbacks[0]
isbn_b, cb_b = received_callbacks[1]
assert callable(cb_a), f"Book A's progress should be callable, got {type(cb_a)}"
assert callable(cb_b), f"Book B's progress should be callable, got {type(cb_b)}"
assert cb_a is not cb_b, "Each book must get its own bound callable"
# The callables must be exactly the ones the reporter created
assert cb_a in reporter._callables
assert cb_b in reporter._callables
+176 -68
View File
@@ -729,12 +729,13 @@ class TestProgressTotalFromContentLength:
reporter = DownloadReporter(stdout=mock_tty)
book = Book(title="Big", authors=["A"], narrators=["N"], isbn="9780000000010")
task_id = reporter.start_download(book, total_bytes=0) # unknown at start
reporter.start_download(book, total_bytes=0) # unknown at start
# Simulate what download_m4b does after reading Content-Length header
reporter.update(0, total=100_000_000)
# Task now has a total — percentage can be computed
task_id = reporter._book_ids[id(book)]
task = reporter._progress.tasks[task_id]
assert task.total == 100_000_000
@@ -748,13 +749,14 @@ class TestProgressTotalFromContentLength:
reporter = DownloadReporter(stdout=mock_tty)
book = Book(title="Pct", authors=["A"], narrators=["N"], isbn="9780000000011")
task_id = reporter.start_download(book, total_bytes=0)
reporter.start_download(book, total_bytes=0)
# First callback sets total (from Content-Length)
reporter.update(0, total=50_000_000)
# Now at 50% when half done
reporter.update(25_000_000)
task_id = reporter._book_ids[id(book)]
task = reporter._progress.tasks[task_id]
assert task.percentage == 50.0
@@ -883,10 +885,11 @@ class TestMultiBarProgress:
reporter = ProgressReporter(stdout=mock_tty)
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
callback_a = reporter.start_download(book_a, total_bytes=100_000_000)
# start_download should return a task_id (int)
assert isinstance(task_id_a, int)
# start_download should return a callable (bound to this book's task)
assert callable(callback_a)
assert not isinstance(callback_a, int)
# Progress should have exactly 1 task
assert len(reporter._progress.tasks) == 1
@@ -902,11 +905,11 @@ class TestMultiBarProgress:
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
callback_a = reporter.start_download(book_a, total_bytes=100_000_000)
callback_b = reporter.start_download(book_b, total_bytes=50_000_000)
# Two distinct task IDs
assert task_id_a != task_id_b
# Two distinct callables
assert callback_a is not callback_b
# Progress should have exactly 2 active tasks
assert len(reporter._progress.tasks) == 2
@@ -922,12 +925,14 @@ class TestMultiBarProgress:
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
callback_a = reporter.start_download(book_a, total_bytes=100_000_000)
callback_b = reporter.start_download(book_b, total_bytes=50_000_000)
# Update only book A's bar to 50%
reporter.update(50_000_000, task_id=task_id_a)
# Update only book A's bar to 50% using its bound callable
callback_a(50_000_000)
task_id_a = reporter._book_ids[id(book_a)]
task_id_b = reporter._book_ids[id(book_b)]
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
@@ -946,17 +951,17 @@ class TestMultiBarProgress:
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
reporter.start_download(book_a, total_bytes=100_000_000)
reporter.start_download(book_b, total_bytes=50_000_000)
assert len(reporter._progress.tasks) == 2
# Complete only book A
reporter.complete(book_a)
# Book A's task is gone, Book B's remains
assert task_id_a not in reporter._tasks
assert task_id_b in reporter._tasks
# Book A's task is gone from internal mapping, Book B's remains
assert id(book_a) not in reporter._book_ids
assert id(book_b) in reporter._book_ids
assert len(reporter._progress.tasks) == 2 # Rich keeps it (completed), but our mapping is clean
def test_fail_removes_only_its_bar(self):
@@ -971,15 +976,15 @@ class TestMultiBarProgress:
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
reporter.start_download(book_a, total_bytes=100_000_000)
reporter.start_download(book_b, total_bytes=50_000_000)
# Fail only book B
reporter.fail(book_b, reason="connection reset")
# Book B's task is gone, Book A's remains
assert task_id_b not in reporter._tasks
assert task_id_a in reporter._tasks
# Book B's task is gone from internal mapping, Book A's remains
assert id(book_b) not in reporter._book_ids
assert id(book_a) in reporter._book_ids
def test_summary_stops_progress_after_all_tasks_done(self):
"""summary() stops progress after all books completed/failed."""
@@ -1018,12 +1023,14 @@ class TestMultiBarProgress:
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=50_000_000)
reporter.start_download(book_a, total_bytes=100_000_000)
reporter.start_download(book_b, total_bytes=50_000_000)
# Update WITHOUT task_id — should fall back to most recent (book_b)
reporter.update(25_000_000)
task_id_b = reporter._book_ids[id(book_b)]
task_id_a = reporter._book_ids[id(book_a)]
task_b = reporter._progress.tasks[task_id_b]
task_a = reporter._progress.tasks[task_id_a]
@@ -1101,9 +1108,9 @@ class TestParallelProgressCallbackWiring:
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=100_000_000)
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
reporter.start_download(book_a, total_bytes=100_000_000)
reporter.start_download(book_b, total_bytes=100_000_000)
reporter.start_download(book_c, total_bytes=100_000_000)
# Simulate what happens in production: each download thread calls
# reporter.update(completed) WITHOUT passing task_id — because
@@ -1117,6 +1124,9 @@ class TestParallelProgressCallbackWiring:
# BUG: all updates went to the most recently started bar (book_c)
# because task_id was None every time, triggering the fallback.
task_id_a = reporter._book_ids[id(book_a)]
task_id_b = reporter._book_ids[id(book_b)]
task_id_c = reporter._book_ids[id(book_c)]
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
task_c = reporter._progress.tasks[task_id_c]
@@ -1126,17 +1136,8 @@ class TestParallelProgressCallbackWiring:
assert task_a.completed == 0 # book A never got an update ← THE BUG
assert task_b.completed == 0 # book B never got an update ← THE BUG
def make_progress_callback(self, reporter, task_id):
"""Factory: returns a progress closure bound to a specific task_id.
This is what cli.py SHOULD do instead of passing ``reporter.update`` directly.
"""
def _progress(completed, *, total=None):
reporter.update(completed, total=total, task_id=task_id)
return _progress
def test_bound_callback_updates_correct_bar(self):
"""When each thread gets a task_id-bound callback, bars update independently."""
"""When each thread gets a bound callback from start_download(), bars update independently."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
@@ -1148,20 +1149,19 @@ class TestParallelProgressCallbackWiring:
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=100_000_1000)
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
# Each download thread gets its OWN callback, pre-bound to its task_id
progress_a = self.make_progress_callback(reporter, task_id_a)
progress_b = self.make_progress_callback(reporter, task_id_b)
progress_c = self.make_progress_callback(reporter, task_id_c)
# Each download thread gets its OWN bound callable from start_download()
progress_a = reporter.start_download(book_a, total_bytes=100_000_000)
progress_b = reporter.start_download(book_b, total_bytes=100_000_1000)
progress_c = reporter.start_download(book_c, total_bytes=100_000_000)
# Each thread reports its own progress
progress_a(50_000_000)
progress_b(30_000_000)
progress_c(80_000_000)
task_id_a = reporter._book_ids[id(book_a)]
task_id_b = reporter._book_ids[id(book_b)]
task_id_c = reporter._book_ids[id(book_c)]
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
task_c = reporter._progress.tasks[task_id_c]
@@ -1192,9 +1192,9 @@ class TestParallelProgressCallbackWiring:
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=100_000_000)
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
reporter.start_download(book_a, total_bytes=100_000_000)
reporter.start_download(book_b, total_bytes=100_000_000)
reporter.start_download(book_c, total_bytes=100_000_000)
# Simulate what happens in production: each download thread calls
# reporter.update(completed) WITHOUT passing task_id — because
@@ -1208,6 +1208,9 @@ class TestParallelProgressCallbackWiring:
# BUG: all updates went to the most recently started bar (book_c)
# because task_id was None every time, triggering the fallback.
task_id_a = reporter._book_ids[id(book_a)]
task_id_b = reporter._book_ids[id(book_b)]
task_id_c = reporter._book_ids[id(book_c)]
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
task_c = reporter._progress.tasks[task_id_c]
@@ -1217,17 +1220,8 @@ class TestParallelProgressCallbackWiring:
assert task_a.completed == 0 # book A never got an update ← THE BUG
assert task_b.completed == 0 # book B never got an update ← THE BUG
def make_progress_callback(self, reporter, task_id):
"""Factory: returns a progress closure bound to a specific task_id.
This is what cli.py SHOULD do instead of passing ``reporter.update`` directly.
"""
def _progress(completed, *, total=None):
reporter.update(completed, total=total, task_id=task_id)
return _progress
def test_bound_callback_updates_correct_bar(self):
"""When each thread gets a task_id-bound callback, bars update independently."""
"""When each thread gets a bound callback from start_download(), bars update independently."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
@@ -1239,20 +1233,19 @@ class TestParallelProgressCallbackWiring:
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
book_c = Book(title="Book C", authors=["Author C"], narrators=["N"], isbn="9783333333333")
task_id_a = reporter.start_download(book_a, total_bytes=100_000_000)
task_id_b = reporter.start_download(book_b, total_bytes=100_000_000)
task_id_c = reporter.start_download(book_c, total_bytes=100_000_000)
# Each download thread gets its OWN callback, pre-bound to its task_id
progress_a = self.make_progress_callback(reporter, task_id_a)
progress_b = self.make_progress_callback(reporter, task_id_b)
progress_c = self.make_progress_callback(reporter, task_id_c)
# Each download thread gets its OWN bound callable from start_download()
progress_a = reporter.start_download(book_a, total_bytes=100_000_000)
progress_b = reporter.start_download(book_b, total_bytes=100_000_1000)
progress_c = reporter.start_download(book_c, total_bytes=100_000_000)
# Each thread reports its own progress
progress_a(50_000_000)
progress_b(30_000_000)
progress_c(80_000_000)
task_id_a = reporter._book_ids[id(book_a)]
task_id_b = reporter._book_ids[id(book_b)]
task_id_c = reporter._book_ids[id(book_c)]
task_a = reporter._progress.tasks[task_id_a]
task_b = reporter._progress.tasks[task_id_b]
task_c = reporter._progress.tasks[task_id_c]
@@ -1295,4 +1288,119 @@ class TestParallelProgressCallbackWiring:
# Completions and failures present
assert "Completed: Author A - Alpha" in output
assert "Completed: Author C - Gamma" in output
assert "Failed: Author B - Beta [9782222222222] (network error)" in output
assert "Failed: Author B - Beta [9782222222222] (network error)" in output
# ---------------------------------------------------------------------------
# Issue #30: Bound Callable Per Book
# ---------------------------------------------------------------------------
class TestBoundCallableFromStartDownload:
"""start_download() returns a bound callable that targets the correct bar.
Issue #30: task_id never leaves progress.py. The callable returned by
start_download() already carries the task identity internally.
"""
def test_start_download_returns_callable_for_tty_reporter(self):
"""ProgressReporter.start_download() returns a callable, not an int."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
book = Book(title="Test Book", authors=["Author"], narrators=["N"], isbn="9780000000000")
callback = reporter.start_download(book, total_bytes=100_000_000)
# Must return a callable (bound to this book's task)
assert callable(callback)
# It must NOT be a raw int (the old API)
assert not isinstance(callback, int)
def test_bound_callable_updates_correct_bar(self):
"""Calling each book's bound callable updates only that book's bar."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
book_a = Book(title="Book A", authors=["Author A"], narrators=["N"], isbn="9781111111111")
book_b = Book(title="Book B", authors=["Author B"], narrators=["N"], isbn="9782222222222")
callback_a = reporter.start_download(book_a, total_bytes=100_000_000)
callback_b = reporter.start_download(book_b, total_bytes=50_000_000)
# Update only book A's progress
callback_a(25_000_000) # 25%
# Book A's task should show 25%, Book B should still be at 0%
task_a = reporter._book_ids[id(book_a)]
task_b = reporter._book_ids[id(book_b)]
# Rich stores completed per-task; check via internal state
tasks = reporter._progress.tasks
assert tasks[task_a].completed == 25_000_000
assert tasks[task_b].completed == 0
# Now update only book B
callback_b(25_000_000) # 50% of its total
assert tasks[task_a].completed == 25_000_000 # unchanged
assert tasks[task_b].completed == 25_000_000
def test_plain_text_reporter_returns_none(self):
"""PlainTextReporter.start_download() returns None (no progress bar)."""
reporter = PlainTextReporter()
book = Book(title="Test Book", authors=["Author"], narrators=["N"], isbn="9780000000000")
result = reporter.start_download(book)
assert result is None
def test_bound_callable_forwards_total_kwarg(self):
"""Bound callable accepts and forwards the total kwarg to update()."""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
book = Book(title="Test Book", authors=["Author"], narrators=["N"], isbn="9780000000000")
callback = reporter.start_download(book, total_bytes=50_000_000)
# Update with a new total (e.g. Content-Length arriving mid-download)
callback(10_000_000, total=100_000_000)
task_id = reporter._book_ids[id(book)]
tasks = reporter._progress.tasks
# Total should be updated to 100M, completed should be 10M
assert tasks[task_id].completed == 10_000_000
assert tasks[task_id].total == 100_000_000
def test_update_does_not_accept_task_id(self):
"""Public update() no longer exposes task_id — use bound callable instead.
Issue #30: task_id is fully internal. The public update() only accepts
completed and total kwargs.
"""
from unittest.mock import MagicMock
mock_tty = MagicMock()
mock_tty.isatty.return_value = True
reporter = ProgressReporter(stdout=mock_tty)
book = Book(title="Test", authors=["A"], narrators=["N"], isbn="9780000000000")
reporter.start_download(book, total_bytes=100_000_000)
# Calling update with task_id should raise TypeError (parameter removed)
import inspect
sig = inspect.signature(reporter.update)
assert "task_id" not in sig.parameters, (
"update() should not expose task_id; use bound callable from start_download()"
)