refactor(session): rename LibroFmClient → LibroFmSession

Relocate API client from client.py to session.py with constructor
injection. Transport is now passed once at construction time
instead of per-method, eliminating 5 redundant httpx.Client
creations per session lifecycle.

- New session.py: LibroFmSession with shared _client, transport
  injected at construction, auth headers set once after
  authenticate()
- Old client.py: deprecated re-export shim (LibroFmClient alias)
- All endpoint signatures slimmed to ≤3 params (removed
  transport= from authenticate/fetch_library/fetch_m4b_url/
  fetch_download_manifest/fetch_pdf_extra_url)
- Updated all source imports (cli.py, downloader.py) and test
  files (test_client, test_downloader, test_cli, test_progress)
- 17 new TDD tests in test_session.py

Closes #27
This commit is contained in:
AlexKucera committed 2026-06-04 15:27:11 +02:00
1 parent fb219be248
commit 006a7561ce
11 files changed
+986 -413

No files matched your search

+37 -37
View File
@@ -14,7 +14,7 @@ class TestCLIHappyPath:
"""Happy path: valid config, auth succeeds, books are printed."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
):
# Config returns valid credentials
mock_config.return_value.username = "alice"
@@ -47,11 +47,11 @@ class TestCLIAuthFailure:
def test_exits_one_on_auth_failure(self, capsys):
"""Auth fails → exit code 1 + error message printed."""
from librofm_downloader.client import AuthError
from librofm_downloader.session import AuthError
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "wrong"
@@ -79,7 +79,7 @@ class TestCLIHistoryFiltering:
"""Books in history file don't appear in output."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
):
mock_config.return_value.username = "alice"
@@ -124,7 +124,7 @@ class TestCLIDownloadOrchestration:
Books without M4B are skipped (not errors)."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
patch("librofm_downloader.cli.Book") as mock_book_cls,
@@ -182,7 +182,7 @@ class TestCLIVerbose:
"""--verbose shows config values and auth status."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
patch("librofm_downloader.cli.Book") as mock_book_cls,
@@ -234,7 +234,7 @@ class TestCLILimitFlag:
"""--limit 2 → only first 2 books are attempted."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
patch("librofm_downloader.cli.Book") as mock_book_cls,
@@ -273,7 +273,7 @@ class TestCLILimitFlag:
"""--limit 0 (default) → all books are processed."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
patch("librofm_downloader.cli.Book") as mock_book_cls,
@@ -312,7 +312,7 @@ class TestCLIFormatWiring:
"""config.format is forwarded to download_book(format_strategy=...)."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
patch("librofm_downloader.cli.Book") as mock_book_cls,
@@ -350,7 +350,7 @@ class TestCLIFormatWiring:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
patch("librofm_downloader.cli.Book") as mock_book_cls,
@@ -402,7 +402,7 @@ class TestGracefulShutdown:
"""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -439,7 +439,7 @@ class TestGracefulShutdown:
"""KeyboardInterrupt during library fetch → clean exit."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "secret"
@@ -472,7 +472,7 @@ class TestIntegrationHappyPath:
"""Full pipeline: auth + library fetch + 3 downloads → exit 0 + summary."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -513,7 +513,7 @@ class TestIntegrationMixedResult:
"""2 download (1 M4B, 1 MP3), 1 skipped, 1 fails → summary lists all + exit 0."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -570,11 +570,11 @@ class TestIntegrationFatalAuthFailure:
def test_auth_failure_returns_exit_code_1_no_downloads(self, capsys):
"""Authentication failure → exit code 1, download_book never called."""
from librofm_downloader.client import AuthError
from librofm_downloader.session import AuthError
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
mock_config.return_value.username = "baduser"
@@ -608,7 +608,7 @@ class TestAllBooksFailExitCode:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -672,7 +672,7 @@ class TestCLIHistoryResolution:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
):
mock_config.return_value.username = "alice"
@@ -708,7 +708,7 @@ class TestCLIHistoryResolution:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
):
mock_config.return_value.username = "alice"
@@ -735,7 +735,7 @@ class TestCLIHistoryResolution:
"""Explicit --history flag uses the exact path provided."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
):
mock_config.return_value.username = "alice"
@@ -775,7 +775,7 @@ class TestCLIConfigResolutionMessages:
monkeypatch.chdir(cwd)
with (
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.download_book"),
):
mock_instance = mock_client_cls.return_value
@@ -806,7 +806,7 @@ class TestCLIConfigResolutionMessages:
monkeypatch.chdir(cwd)
with (
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.download_book"),
):
mock_instance = mock_client_cls.return_value
@@ -862,7 +862,7 @@ class TestCLIMissingFilesErrors:
monkeypatch.chdir(cwd)
with (
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.download_book"),
):
mock_instance = mock_client_cls.return_value
@@ -888,7 +888,7 @@ class TestCLIWorkersFlag:
"""--workers 8 overrides config.workers=3 → resolved workers = 8."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -919,7 +919,7 @@ class TestCLIWorkersFlag:
"""No --workers flag uses config.workers (5) instead of default 3."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -948,7 +948,7 @@ class TestCLIWorkersFlag:
"""--workers 1 is accepted (sequential fallback)."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -993,7 +993,7 @@ class TestParallelWorkers1Parity:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -1029,7 +1029,7 @@ class TestParallelWorkers1Parity:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -1066,7 +1066,7 @@ class TestParallelCtrlCDrain:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -1093,7 +1093,7 @@ class TestParallelCtrlCDrain:
"""KeyboardInterrupt prints 'Aborting...' or similar message."""
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -1131,7 +1131,7 @@ class TestParallelSummaryOrdering:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -1173,7 +1173,7 @@ class TestParallelSummaryOrdering:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
patch("librofm_downloader.cli.DownloadReporter") as mock_reporter_cls,
@@ -1227,7 +1227,7 @@ class TestParallelConcurrency:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -1267,7 +1267,7 @@ class TestParallelConcurrency:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -1317,7 +1317,7 @@ class TestParallelVerboseMode:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -1349,7 +1349,7 @@ class TestParallelVerboseMode:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -1396,7 +1396,7 @@ class TestParallelPartialFileSafety:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
+140 -119
View File
@@ -1,4 +1,4 @@
"""Tests for librofm_downloader.client — TDD vertical slices."""
"""Tests for librofm_downloader.session — TDD vertical slices."""
import json
import logging
@@ -6,7 +6,7 @@ import logging
import httpx
import pytest
from librofm_downloader.client import LibroFmClient, AuthError, M4BUnavailableError
from librofm_downloader.session import LibroFmSession, AuthError, M4BUnavailableError
class TestAuthenticate:
@@ -14,11 +14,6 @@ class TestAuthenticate:
def test_returns_access_token_on_valid_credentials(self):
"""Valid username/password → access_token returned."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def token_handler(request: httpx.Request) -> httpx.Response:
assert request.method == "POST"
@@ -29,36 +24,37 @@ class TestAuthenticate:
)
transport = httpx.MockTransport(token_handler)
token = client.authenticate(transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
token = session.authenticate()
assert token == "tok_abc123"
def test_raises_auth_error_on_invalid_credentials(self):
"""Wrong password → AuthError with descriptive message."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="wrongpass",
)
def token_handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(401, json={"error": "invalid_grant"})
transport = httpx.MockTransport(token_handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="wrongpass",
transport=transport,
)
with pytest.raises(AuthError, match="Auth failed") as exc_info:
client.authenticate(transport=transport)
session.authenticate()
assert "401" in str(exc_info.value)
def test_sends_required_headers_with_auth_request(self):
"""X-LibroFm-AppVer and User-Agent headers must be present."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
headers_captured: dict[str, str] = {}
def token_handler(request: httpx.Request) -> httpx.Response:
@@ -69,7 +65,13 @@ class TestAuthenticate:
)
transport = httpx.MockTransport(token_handler)
client.authenticate(transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
assert headers_captured["x-librofm-appver"] == "7.34.8"
assert headers_captured["user-agent"] == "okhttp/5.3.2"
@@ -80,12 +82,6 @@ class TestFetchLibrary:
def test_returns_books_on_single_page(self):
"""Single-page library returns all books, no pagination loop."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
books = [{"isbn": "9781234567890", "title": "Test Book"}]
def handler(request: httpx.Request) -> httpx.Response:
@@ -99,20 +95,20 @@ class TestFetchLibrary:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
result = client.fetch_library(transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
result = session.fetch_library()
assert len(result) == 1
assert result[0]["isbn"] == "9781234567890"
def test_paginates_through_all_pages(self):
"""Multi-page library: follows next_page until exhausted."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
page1_books = [{"isbn": "978111", "title": "Book A"}]
page2_books = [{"isbn": "978222", "title": "Book B"}, {"isbn": "978333", "title": "Book C"}]
@@ -132,8 +128,14 @@ class TestFetchLibrary:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
result = client.fetch_library(transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
result = session.fetch_library()
assert len(result) == 3
assert result[0]["isbn"] == "978111"
@@ -142,14 +144,14 @@ class TestFetchLibrary:
def test_raises_auth_error_if_not_authenticated(self):
"""Calling fetch_library before authenticate → clear error."""
client = LibroFmClient(
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
with pytest.raises(AuthError, match="Not authenticated"):
client.fetch_library()
session.fetch_library()
@@ -158,11 +160,6 @@ class TestFetchM4BUrl:
def test_returns_download_url_when_m4b_available(self):
"""Book with M4B format available → returns CDN URL string."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
@@ -178,18 +175,19 @@ class TestFetchM4BUrl:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
url = client.fetch_m4b_url("9781234567890", transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
url = session.fetch_m4b_url("9781234567890")
assert url == "https://cdn.libro.fm/audiobooks/9781234567890.m4b"
def test_raises_m4b_unavailable_on_404(self):
"""Book without M4B format → raises M4BUnavailableError."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
@@ -202,10 +200,16 @@ class TestFetchM4BUrl:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
with pytest.raises(M4BUnavailableError, match="M4B not available for ISBN 9780000000001"):
client.fetch_m4b_url("9780000000001", transport=transport)
session.fetch_m4b_url("9780000000001")
# ---------------------------------------------------------------------------
@@ -218,11 +222,6 @@ class TestFetchDownloadManifest:
def test_returns_parts_and_tracks_when_available(self):
"""Book with MP3 format → returns parts list and track metadata."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
@@ -247,8 +246,14 @@ class TestFetchDownloadManifest:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
manifest = client.fetch_download_manifest("9781234567890", transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
manifest = session.fetch_download_manifest("9781234567890")
assert len(manifest["parts"]) == 2
assert manifest["parts"][0]["url"] == "https://cdn.libro.fm/part1.zip"
@@ -258,11 +263,6 @@ class TestFetchDownloadManifest:
def test_returns_empty_parts_when_no_mp3_available(self):
"""Book without MP3 format → returns empty manifest (404 or empty)."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
@@ -275,10 +275,16 @@ class TestFetchDownloadManifest:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
with pytest.raises(M4BUnavailableError):
client.fetch_download_manifest("9780000000001", transport=transport)
session.fetch_download_manifest("9780000000001")
# ---------------------------------------------------------------------------
@@ -291,11 +297,6 @@ class TestFetchPdfExtraUrl:
def test_returns_pdf_url_when_available(self):
"""Book with PDF extra available → returns CDN URL string."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
@@ -312,29 +313,33 @@ class TestFetchPdfExtraUrl:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
url = client.fetch_pdf_extra_url("9781234567890", "map.pdf", transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
url = session.fetch_pdf_extra_url("9781234567890", "map.pdf")
assert url == "https://cdn.libro.fm/pdf/9781234567890/map.pdf"
def test_raises_auth_error_if_not_authenticated(self):
"""Calling fetch_pdf_extra_url before authenticate → clear error."""
client = LibroFmClient(
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
with pytest.raises(AuthError, match="Not authenticated"):
client.fetch_pdf_extra_url("9781234567890", "map.pdf")
session.fetch_pdf_extra_url("9781234567890", "map.pdf")
# ---------------------------------------------------------------------------
# API Rate Limiter — Issue #15
# ---------------------------------------------------------------------------
import threading
import time
@@ -348,11 +353,6 @@ class TestApiRateLimiter:
def test_semaphore_blocks_at_capacity(self):
"""4 concurrent callers: 3 proceed immediately, 4th blocks until one finishes."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
call_can_finish: threading.Event = threading.Event()
state_lock = threading.Lock()
@@ -377,13 +377,19 @@ class TestApiRateLimiter:
)
transport = httpx.MockTransport(slow_handler)
client.authenticate(transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
errors: list[BaseException] = []
def fetch_thread(isbn: str):
try:
client.fetch_m4b_url(isbn, transport=transport)
session.fetch_m4b_url(isbn)
except BaseException as exc:
errors.append(exc)
@@ -406,12 +412,6 @@ class TestApiRateLimiter:
def test_semaphore_releases_on_exception(self):
"""Semaphore is released even when the API call raises an exception."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
call_number = [1] # Use list for mutability in closure
def handler(request: httpx.Request) -> httpx.Response:
@@ -430,18 +430,24 @@ class TestApiRateLimiter:
)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
# First call should succeed (releases semaphore normally)
result = client.fetch_m4b_url("978111", transport=transport)
result = session.fetch_m4b_url("978111")
assert result == "https://cdn.libro.fm/test.m4b"
# Second call should raise (semaphore must still be released after this)
with pytest.raises(M4BUnavailableError):
client.fetch_m4b_url("978222", transport=transport)
session.fetch_m4b_url("978222")
# Third call should succeed — proves semaphore was released by the failed call
result3 = client.fetch_m4b_url("978333", transport=transport)
result3 = session.fetch_m4b_url("978333")
assert result3 == "https://cdn.libro.fm/test.m4b"
def test_cdn_downloads_bypass_semaphore(self):
@@ -450,12 +456,6 @@ class TestApiRateLimiter:
from librofm_downloader.downloader import download_m4b
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
# Fill all 3 API semaphore slots with slow calls that block
api_calls_blocked: threading.Event = threading.Event()
@@ -473,11 +473,17 @@ class TestApiRateLimiter:
)
api_transport = httpx.MockTransport(slow_api_handler)
client.authenticate(transport=api_transport)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=api_transport,
)
session.authenticate()
# Occupy all 3 semaphore slots with blocked API calls
api_threads = [
threading.Thread(target=client.fetch_m4b_url, args=(f"978block{i}",), kwargs={"transport": api_transport})
threading.Thread(target=session.fetch_m4b_url, args=(f"978block{i}",))
for i in range(3)
]
for t in api_threads:
@@ -509,12 +515,6 @@ class TestApiRateLimiter:
def test_authenticate_and_fetch_library_not_limited(self):
"""authenticate() and fetch_library() do NOT acquire the API semaphore."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
# Fill all 3 API semaphore slots with blocked calls
api_calls_blocked: threading.Event = threading.Event()
@@ -530,12 +530,21 @@ class TestApiRateLimiter:
json={"m4b_url": "https://cdn.libro.fm/test.m4b"},
)
# NOTE: This test uses a separate session for the blocking API calls.
# The session under test gets a different transport so authenticate/fetch_library
# can use a different handler while the blocking calls hold the semaphore.
api_transport = httpx.MockTransport(slow_api_handler)
client.authenticate(transport=api_transport)
blocking_session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=api_transport,
)
blocking_session.authenticate()
# Occupy all 3 slots
api_threads = [
threading.Thread(target=client.fetch_m4b_url, args=(f"978block{i}",), kwargs={"transport": api_transport})
threading.Thread(target=blocking_session.fetch_m4b_url, args=(f"978block{i}",))
for i in range(3)
]
for t in api_threads:
@@ -543,25 +552,37 @@ class TestApiRateLimiter:
time.sleep(0.2)
# authenticate() should work fine — it doesn't use the semaphore
# We need a fresh session+transport for this since the old one's auth handler
# would conflict with the slow_api_handler
def auth_handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={"access_token": "tok_new", "token_type": "bearer", "expires_in": 7200},
)
auth_transport = httpx.MockTransport(auth_handler)
token = client.authenticate(transport=auth_transport)
assert token == "tok_new"
# fetch_library() should also work — it doesn't use the semaphore
def library_handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"audiobooks": []})
library_transport = httpx.MockTransport(library_handler)
books = client.fetch_library(transport=library_transport)
def combined_handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
return auth_handler(request)
return library_handler(request)
test_transport = httpx.MockTransport(combined_handler)
test_session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=test_transport,
)
token = test_session.authenticate()
assert token == "tok_new"
# fetch_library() should also work — it doesn't use the semaphore
books = test_session.fetch_library()
assert books == []
# Clean up
api_calls_blocked.set()
for t in api_threads:
t.join(timeout=5)
t.join(timeout=5)
+17 -17
View File
@@ -19,7 +19,7 @@ from librofm_downloader.downloader import (
download_book,
download_accompanying_files,
)
from librofm_downloader.client import LibroFmClient
from librofm_downloader.session import LibroFmSession
from librofm_downloader.history import DownloadHistory
@@ -884,8 +884,8 @@ class TestDownloadBook:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
client.authenticate(transport=transport)
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
client.authenticate()
book = Book(
title="History Test Book",
@@ -927,8 +927,8 @@ class TestDownloadBook:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
client.authenticate(transport=transport)
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
client.authenticate()
book = Book(
title="No M4B Book",
@@ -974,8 +974,8 @@ class TestDownloadBook:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
client.authenticate(transport=transport)
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
client.authenticate()
book = Book(
title="Fail Book",
@@ -1016,8 +1016,8 @@ class TestDownloadBook:
return httpx.Response(200, content=payload)
transport = httpx.MockTransport(handler)
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
client.authenticate(transport=transport)
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
client.authenticate()
book = Book(
title="Standalone Book",
@@ -1092,8 +1092,8 @@ class TestFormatStrategy:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
client.authenticate(transport=transport)
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
client.authenticate()
book = Book(title="M4B Available", authors=["A"], narrators=["N"], isbn="9781111111111")
@@ -1151,8 +1151,8 @@ class TestFormatStrategy:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
client.authenticate(transport=transport)
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
client.authenticate()
book = Book(title="MP3 Fallback Book", authors=["A"], narrators=["N"], isbn="9782222222222")
@@ -1212,8 +1212,8 @@ class TestFormatStrategy:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
client.authenticate(transport=transport)
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
client.authenticate()
book = Book(title="MP3 Only Book", authors=["A"], narrators=["N"], isbn="9783333333333")
@@ -1261,8 +1261,8 @@ class TestFormatStrategy:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
client.authenticate(transport=transport)
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
client.authenticate()
book = Book(title="No M4B Skip", authors=["A"], narrators=["N"], isbn="9780000000000")
+6 -6
View File
@@ -157,7 +157,7 @@ class TestFailureIsolationCLI:
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.DownloadHistory") as mock_history_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
@@ -218,11 +218,11 @@ class TestFatalVsBookLevel:
def test_auth_failure_exits_one_before_downloads(self, capsys):
"""Auth failure → exit 1, download_book never called."""
from unittest.mock import patch
from librofm_downloader.client import AuthError
from librofm_downloader.session import AuthError
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
patch("librofm_downloader.cli.LibroFmSession") as mock_client_cls,
patch("librofm_downloader.cli.download_book") as mock_download,
):
mock_config.return_value.username = "alice"
@@ -663,7 +663,7 @@ class TestProgressCallbackWiring:
from pathlib import Path
from librofm_downloader.book import Book
from librofm_downloader.downloader import download_book
from librofm_downloader.client import LibroFmClient
from librofm_downloader.session import LibroFmSession
from librofm_downloader.history import DownloadHistory
m4b_payload = b"callback-test-data" * 10 # 160 bytes
@@ -681,8 +681,8 @@ class TestProgressCallbackWiring:
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client = LibroFmClient(base_url="https://libro.fm", username="u", password="p")
client.authenticate(transport=transport)
client = LibroFmSession(base_url="https://libro.fm", username="u", password="p", transport=transport)
client.authenticate()
book = Book(title="CB Test", authors=["A"], narrators=["N"], isbn="9781111111111")
progress_calls: list[int] = []
+449
View File
@@ -0,0 +1,449 @@
"""Tests for librofm_downloader.session — TDD vertical slices."""
from __future__ import annotations
import httpx
import pytest
from librofm_downloader.session import LibroFmSession, AuthError, M4BUnavailableError
class TestConstructor:
"""LibroFmSession constructor builds a shared internal httpx.Client."""
def test_importable_from_session_module(self):
"""LibroFmSession can be imported from librofm_downloader.session."""
assert LibroFmSession is not None
def test_creates_internal_httpx_client(self):
"""Constructor creates self._client as an httpx.Client instance."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
assert isinstance(session._client, httpx.Client)
def test_injects_transport_into_internal_client(self):
"""When transport= is passed, the internal client uses it for requests."""
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"ok": True})
transport = httpx.MockTransport(handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
assert isinstance(session._client, httpx.Client)
# Verify the injected transport works by making a request through the internal client
resp = session._client.get("/test")
assert resp.status_code == 200
assert resp.json() == {"ok": True}
def test_default_transport_is_none(self):
"""When no transport is passed, the client has no custom transport (real HTTP)."""
session = LibroFmSession(
base_url="https://libro.fm",
username="u",
password="p",
)
# With transport=None, httpx.Client uses its default transport (real network)
# We just verify the client was created and has the expected base_url
assert session._client.base_url == "https://libro.fm"
class TestAuthenticate:
"""OAuth2 password grant authentication — uses shared _client, no transport param."""
def test_returns_access_token_on_valid_credentials(self):
"""Valid username/password → access_token returned."""
def token_handler(request: httpx.Request) -> httpx.Response:
assert request.method == "POST"
assert request.url.path == "/oauth/token"
return httpx.Response(
200,
json={"access_token": "tok_abc123", "token_type": "bearer", "expires_in": 7200},
)
transport = httpx.MockTransport(token_handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
token = session.authenticate() # NO transport arg!
assert token == "tok_abc123"
def test_raises_auth_error_on_invalid_credentials(self):
"""Wrong password → AuthError with descriptive message."""
def token_handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(401, json={"error": "invalid_grant"})
transport = httpx.MockTransport(token_handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="wrongpass",
transport=transport,
)
with pytest.raises(AuthError, match="Auth failed") as exc_info:
session.authenticate()
assert "401" in str(exc_info.value)
def test_sends_required_headers_with_auth_request(self):
"""X-LibroFm-AppVer and User-Agent headers must be present."""
headers_captured: dict[str, str] = {}
def token_handler(request: httpx.Request) -> httpx.Response:
headers_captured.update(dict(request.headers))
return httpx.Response(
200,
json={"access_token": "tok_abc123", "token_type": "bearer", "expires_in": 7200},
)
transport = httpx.MockTransport(token_handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
assert headers_captured["x-librofm-appver"] == "7.34.8"
assert headers_captured["user-agent"] == "okhttp/5.3.2"
def test_stores_token_on_instance_and_client_headers(self):
"""After authenticate(), token is on self._access_token AND in client headers."""
def token_handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(
200,
json={"access_token": "tok_stored", "token_type": "bearer", "expires_in": 7200},
)
transport = httpx.MockTransport(token_handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
token = session.authenticate()
assert token == "tok_stored"
assert session._access_token == "tok_stored"
class TestFetchLibrary:
"""Paginated library fetch — GET /api/v10/library, uses shared _client."""
def test_returns_books_on_single_page(self):
"""Single-page library returns all books, no pagination loop."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
books = [{"isbn": "9781234567890", "title": "Test Book"}]
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
return httpx.Response(
200,
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
)
if request.url.path == "/api/v10/library":
return httpx.Response(200, json={"audiobooks": books})
return httpx.Response(404)
transport = httpx.MockTransport(handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
result = session.fetch_library() # NO transport arg!
assert len(result) == 1
assert result[0]["isbn"] == "9781234567890"
def test_paginates_through_all_pages(self):
"""Multi-page library: follows next_page until exhausted."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
page1_books = [{"isbn": "978111", "title": "Book A"}]
page2_books = [{"isbn": "978222", "title": "Book B"}, {"isbn": "978333", "title": "Book C"}]
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
return httpx.Response(
200,
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
)
if request.url.path == "/api/v10/library" and "page" not in request.url.params:
return httpx.Response(
200,
json={"audiobooks": page1_books, "next_page": "/api/v10/library?page=2"},
)
if "page=2" in str(request.url):
return httpx.Response(200, json={"audiobooks": page2_books}) # no next_page → stop
return httpx.Response(404)
transport = httpx.MockTransport(handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
result = session.fetch_library() # NO transport arg!
assert len(result) == 3
assert result[0]["isbn"] == "978111"
assert result[1]["isbn"] == "978222"
assert result[2]["isbn"] == "978333"
def test_raises_auth_error_if_not_authenticated(self):
"""Calling fetch_library before authenticate → clear error."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
with pytest.raises(AuthError, match="Not authenticated"):
session.fetch_library()
class TestFetchM4BUrl:
"""M4B download URL lookup — GET /api/v10/audiobooks/{isbn}/packaged_m4b."""
def test_returns_download_url_when_m4b_available(self):
"""Book with M4B format available → returns CDN URL string."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
return httpx.Response(
200,
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
)
if request.url.path == "/api/v10/audiobooks/9781234567890/packaged_m4b":
return httpx.Response(
200,
json={"m4b_url": "https://cdn.libro.fm/audiobooks/9781234567890.m4b"},
)
return httpx.Response(404)
transport = httpx.MockTransport(handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
url = session.fetch_m4b_url("9781234567890") # NO transport arg!
assert url == "https://cdn.libro.fm/audiobooks/9781234567890.m4b"
def test_raises_m4b_unavailable_on_404(self):
"""Book without M4B format → raises M4BUnavailableError."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
return httpx.Response(
200,
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
)
if request.url.path == "/api/v10/audiobooks/9780000000001/packaged_m4b":
return httpx.Response(404)
return httpx.Response(404)
transport = httpx.MockTransport(handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
with pytest.raises(M4BUnavailableError, match="M4B not available for ISBN 9780000000001"):
session.fetch_m4b_url("9780000000001")
# ---------------------------------------------------------------------------
# MP3 download manifest — Issue #6
# ---------------------------------------------------------------------------
class TestFetchDownloadManifest:
"""MP3 download manifest — GET /api/v10/download-manifest?isbn=."""
def test_returns_parts_and_tracks_when_available(self):
"""Book with MP3 format → returns parts list and track metadata."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
return httpx.Response(
200,
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
)
if request.url.path == "/api/v10/download-manifest" and request.url.params.get("isbn") == "9781234567890":
return httpx.Response(
200,
json={
"parts": [
{"url": "https://cdn.libro.fm/part1.zip", "name": "part01"},
{"url": "https://cdn.libro.fm/part2.zip", "name": "part02"},
],
"tracks": [
{"number": 1, "chapter_title": "Chapter 1"},
{"number": 2, "chapter_title": "Chapter 2"},
],
},
)
return httpx.Response(404)
transport = httpx.MockTransport(handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
manifest = session.fetch_download_manifest("9781234567890") # NO transport arg!
assert len(manifest["parts"]) == 2
assert manifest["parts"][0]["url"] == "https://cdn.libro.fm/part1.zip"
assert manifest["parts"][1]["url"] == "https://cdn.libro.fm/part2.zip"
assert len(manifest["tracks"]) == 2
assert manifest["tracks"][0]["chapter_title"] == "Chapter 1"
def test_raises_m4b_unavailable_on_404(self):
"""Book without MP3 format → raises M4BUnavailableError."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
return httpx.Response(
200,
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
)
if request.url.path == "/api/v10/download-manifest":
return httpx.Response(404, json={"error": "not found"})
return httpx.Response(404)
transport = httpx.MockTransport(handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
with pytest.raises(M4BUnavailableError):
session.fetch_download_manifest("9780000000001")
# ---------------------------------------------------------------------------
# PDF extra download URL — Issue #7 / Cycle 6
# ---------------------------------------------------------------------------
class TestFetchPdfExtraUrl:
"""PDF extra download URL — GET /api/v10/library/{isbn}/pdf_extra_url?filename=."""
def test_returns_pdf_url_when_available(self):
"""Book with PDF extra available → returns CDN URL string."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
def handler(request: httpx.Request) -> httpx.Response:
if request.url.path == "/oauth/token":
return httpx.Response(
200,
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
)
if request.url.path == "/api/v10/library/9781234567890/pdf_extra_url":
assert request.url.params.get("filename") == "map.pdf"
return httpx.Response(
200,
json={"pdf_url": "https://cdn.libro.fm/pdf/9781234567890/map.pdf"},
)
return httpx.Response(404)
transport = httpx.MockTransport(handler)
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
transport=transport,
)
session.authenticate()
url = session.fetch_pdf_extra_url("9781234567890", "map.pdf") # NO transport arg!
assert url == "https://cdn.libro.fm/pdf/9781234567890/map.pdf"
def test_raises_auth_error_if_not_authenticated(self):
"""Calling fetch_pdf_extra_url before authenticate → clear error."""
session = LibroFmSession(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
with pytest.raises(AuthError, match="Not authenticated"):
session.fetch_pdf_extra_url("9781234567890", "map.pdf")