refactor(reporters): remove cancel_event from progress reporters

Thread cancel_event explicitly through the parameter chain
(sync_run closure → download_book() → streaming calls) instead of
stashing it on reporter objects as shared state. Remove the
cancel_event attribute from both PlainTextReporter and
ProgressReporter — cancellation is not a reporting concern.

Closes #39

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
AlexKuceraandClaude Opus 4.6 committed 2026-06-05 18:45:27 +02:00
1 parent caca930c7c
commit 2930d163b2
9 files changed
+154 -9

No files matched your search

+59 -1
View File
@@ -177,7 +177,6 @@ class TestDownloadBookNewInterface:
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")
@@ -894,6 +893,65 @@ class TestCooperativeCancellation:
a threading.Event between 8 MB chunks and raises InterruptedDownload.
"""
def test_download_book_forwards_cancel_event(self):
"""download_book() accepts cancel_event explicitly and forwards it.
Regression test for Issue #39: cancel_event must flow through the
explicit parameter chain (sync_run → download_book → streaming calls),
NOT through reporter.cancel_event.
"""
import threading
import time
cancel_event = threading.Event()
from librofm_downloader.downloader import CHUNK_SIZE
# Payload > CHUNK_SIZE so iter_bytes produces multiple chunks,
# giving the cancel check a chance to fire mid-stream.
payload = b"\x00" * (CHUNK_SIZE + 1024)
def handler(request):
if "/oauth/token" in request.url.path:
return httpx.Response(200, json={"access_token": "tok", "token_type": "bearer"})
if "/audiobooks/" in request.url.path and "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=payload, headers={"Content-Length": str(len(payload))})
return httpx.Response(404)
transport = httpx.MockTransport(handler)
session = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
session.authenticate()
from unittest.mock import MagicMock
from librofm_downloader.downloader import InterruptedDownload
book = Book(title="Cancel Test", authors=["Author"], narrators=["N"], isbn="9789900000001")
reporter = MagicMock()
with tempfile.TemporaryDirectory() as tmpdir:
plan = resolve_output_plan(book, Path(tmpdir), format_strategy="m4b_only")
# Set cancel_event shortly after download starts so the chunk loop
# sees it between iterations.
def set_cancel_soon():
time.sleep(0) # yield to ensure thread runs before download starts
cancel_event.set()
t = threading.Thread(target=set_cancel_soon, daemon=True)
t.start()
try:
download_book(
book, session, plan, reporter,
cancel_event=cancel_event,
)
assert False, "Expected InterruptedDownload"
except InterruptedDownload:
pass
t.join(timeout=2)
def test_m4b_raises_interrupted_when_cancelled_mid_download(self):
"""download_m4b raises InterruptedDownload when cancel_event is set mid-stream.
+25
View File
@@ -1401,4 +1401,29 @@ class TestBoundCallableFromStartDownload:
sig = inspect.signature(reporter.update)
assert "task_id" not in sig.parameters, (
"update() should not expose task_id; use bound callable from start_download()"
)
class TestReporterNoCancelEvent:
"""Issue #39: Reporters must not carry cancellation state.
cancel_event flows through explicit parameters (sync_run → download_book →
streaming calls), NOT through reporter attributes.
"""
@pytest.mark.parametrize("reporter_cls", [PlainTextReporter, ProgressReporter])
def test_reporter_has_no_cancel_event_attribute(self, reporter_cls):
"""Neither reporter class exposes cancel_event on its public interface."""
reporter = reporter_cls()
assert not hasattr(reporter, "cancel_event"), (
f"{reporter_cls.__name__} must not have cancel_event attribute (Issue #39)"
)
@pytest.mark.parametrize("reporter_cls", [PlainTextReporter, ProgressReporter])
def test_reporter_init_signature_has_no_cancel_event(self, reporter_cls):
"""cancel_event is not a constructor parameter."""
import inspect
sig = inspect.signature(reporter_cls.__init__)
assert "cancel_event" not in sig.parameters, (
f"{reporter_cls.__name__}.__init__ must not accept cancel_event (Issue #39)"
)
-3
View File
@@ -132,7 +132,6 @@ class TestSyncRunInterrupted:
)
mock_reporter = MagicMock()
mock_reporter.cancel_event = None
mock_reporter_cls.return_value = mock_reporter
result = sync_run(verbose=False, limit=0, workers=0)
@@ -270,7 +269,6 @@ class TestSyncRunFilteringAndLimit:
mock_hist.is_downloaded.side_effect = lambda isbn: isbn in ("9781111111111", "9782222222222")
mock_reporter = MagicMock()
mock_reporter.cancel_event = None
mock_reporter_cls.return_value = mock_reporter
sync_run(verbose=False, limit=0, workers=0)
@@ -308,7 +306,6 @@ class TestSyncRunFilteringAndLimit:
mock_history_cls.return_value.is_downloaded.return_value = False
mock_reporter = MagicMock()
mock_reporter.cancel_event = None
mock_reporter_cls.return_value = mock_reporter
sync_run(verbose=False, limit=2, workers=0)