feat(client,history,cli): add auth, library fetch, and download history (closes #3)

Add the data layer that feeds into downloads: OAuth2 password grant
authentication via httpx, paginated library fetching across all pages,
download history JSON read/write with corrupt-recovery safety, and a
CLI skeleton that wires config → auth → fetch → filter → print.

16 new tests (6 client + 7 history + 3 CLI), 41 total passing.
All 11 acceptance criteria met.
This commit is contained in:
AlexKucera committed 2026-06-03 11:44:16 +02:00
1 parent 6c049d1301
commit 515f5c01f6
8 files changed
+699

No files matched your search

+108
View File
@@ -0,0 +1,108 @@
"""Tests for librofm_downloader.cli — TDD vertical slices."""
from unittest.mock import patch
import pytest
from librofm_downloader.cli import run
class TestCLIHappyPath:
"""CLI smoke test: config → auth → fetch library → filter → print → exit 0."""
def test_exits_zero_and_prints_books(self, capsys):
"""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,
):
# Config returns valid credentials
mock_config.return_value.username = "alice"
mock_config.return_value.password = "secret"
# Auth succeeds
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
# Library returns books (none previously downloaded)
mock_instance.fetch_library.return_value = [
{"isbn": "9781234567890", "title": "My Audiobook"},
]
exit_code = run(
config_path="/fake/config.yaml",
secrets_path="/fake/secrets.yaml",
history_path="/fake/history.json",
)
assert exit_code == 0
captured = capsys.readouterr()
assert "My Audiobook" in captured.out
class TestCLIAuthFailure:
"""Auth failure → exit 1 with descriptive message."""
def test_exits_one_on_auth_failure(self, capsys):
"""Auth fails → exit code 1 + error message printed."""
from librofm_downloader.client import AuthError
with (
patch("librofm_downloader.cli.load_config") as mock_config,
patch("librofm_downloader.cli.LibroFmClient") as mock_client_cls,
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "wrong"
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.side_effect = AuthError("Auth failed (401)")
exit_code = run(
config_path="/fake/config.yaml",
secrets_path="/fake/secrets.yaml",
history_path="/fake/history.json",
)
assert exit_code == 1
captured = capsys.readouterr()
assert "Authentication failed" in captured.out
class TestCLIHistoryFiltering:
"""Already-downloaded books are filtered from output."""
def test_filters_out_downloaded_books(self, capsys):
"""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.DownloadHistory") as mock_history_cls,
):
mock_config.return_value.username = "alice"
mock_config.return_value.password = "secret"
mock_instance = mock_client_cls.return_value
mock_instance.authenticate.return_value = "tok_abc"
# 3 books total, 1 already downloaded
mock_instance.fetch_library.return_value = [
{"isbn": "978111", "title": "Old Book"},
{"isbn": "978222", "title": "New Book A"},
{"isbn": "978333", "title": "New Book B"},
]
# 978111 is already downloaded
mock_history_instance = mock_history_cls.return_value
mock_history_instance.is_downloaded.side_effect = lambda isbn: isbn == "978111"
exit_code = run(
config_path="/fake/config.yaml",
secrets_path="/fake/secrets.yaml",
history_path="/fake/history.json",
)
assert exit_code == 0
captured = capsys.readouterr()
assert "Old Book" not in captured.out
assert "New Book A" in captured.out
assert "New Book B" in captured.out
+152
View File
@@ -0,0 +1,152 @@
"""Tests for librofm_downloader.client — TDD vertical slices."""
import json
import logging
import httpx
import pytest
from librofm_downloader.client import LibroFmClient, AuthError
class TestAuthenticate:
"""OAuth2 password grant authentication."""
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"
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)
token = client.authenticate(transport=transport)
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)
with pytest.raises(AuthError, match="Auth failed") as exc_info:
client.authenticate(transport=transport)
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:
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)
client.authenticate(transport=transport)
assert headers_captured["x-librofm-appver"] == "7.34.8"
assert headers_captured["user-agent"] == "okhttp/5.3.2"
class TestFetchLibrary:
"""Paginated library fetch — GET /api/v10/library."""
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:
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={"books": books})
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
result = client.fetch_library(transport=transport)
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"}]
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={"books": page1_books, "next_page": "/api/v10/library?page=2"},
)
if "page=2" in str(request.url):
return httpx.Response(200, json={"books": page2_books}) # no next_page → stop
return httpx.Response(404)
transport = httpx.MockTransport(handler)
client.authenticate(transport=transport)
result = client.fetch_library(transport=transport)
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."""
client = LibroFmClient(
base_url="https://libro.fm",
username="alice",
password="secret123",
)
with pytest.raises(AuthError, match="Not authenticated"):
client.fetch_library()
+103
View File
@@ -0,0 +1,103 @@
"""Tests for librofm_downloader.history — TDD vertical slices."""
import json
import tempfile
from pathlib import Path
import pytest
from librofm_downloader.history import DownloadHistory, HistoryEntry
class TestWriteAndRead:
"""Tracer bullet: write an entry and read it back by ISBN."""
def test_write_and_read_entry_by_isbn(self):
"""After writing an entry, looking it up by ISBN returns it."""
with tempfile.TemporaryDirectory() as tmpdir:
history_path = Path(tmpdir) / "download_history.json"
history = DownloadHistory(history_path)
entry = HistoryEntry(
isbn="9781234567890",
title="Test Book",
format="m4b",
path="/audiobooks/Author/Test Book/Test Book.m4b",
downloaded_at="2025-01-01T12:00:00Z",
)
history.write(entry)
result = history.find("9781234567890")
assert result is not None
assert result.title == "Test Book"
assert result.format == "m4b"
class TestIsDownloaded:
"""is_downloaded() returns bool for previously downloaded ISBNs."""
def test_returns_true_for_downloaded_isbn(self):
with tempfile.TemporaryDirectory() as tmpdir:
history = DownloadHistory(Path(tmpdir) / "history.json")
entry = HistoryEntry(
isbn="978111", title="Book", format="m4b",
path="/book.m4b", downloaded_at="2025-01-01T00:00:00Z",
)
history.write(entry)
assert history.is_downloaded("978111") is True
def test_returns_false_for_unknown_isbn(self):
with tempfile.TemporaryDirectory() as tmpdir:
history = DownloadHistory(Path(tmpdir) / "history.json")
assert history.is_downloaded("978999") is False
class TestFileCreation:
"""History file is created on disk when it doesn't exist."""
def test_file_created_after_write(self):
with tempfile.TemporaryDirectory() as tmpdir:
history_path = Path(tmpdir) / "subdir" / "download_history.json"
history = DownloadHistory(history_path)
entry = HistoryEntry(
isbn="978111", title="Book", format="m4b",
path="/book.m4b", downloaded_at="2025-01-01T00:00:00Z",
)
history.write(entry)
assert history_path.exists()
data = json.loads(history_path.read_text())
assert "978111" in data
class TestCorruptRecovery:
"""Corrupt or missing JSON → empty history with warning."""
def test_corrupt_json_treated_as_empty(self, caplog):
with tempfile.TemporaryDirectory() as tmpdir:
history_path = Path(tmpdir) / "corrupt.json"
history_path.write_text("{this is not valid json!!!")
history = DownloadHistory(history_path)
assert history.is_downloaded("978111") is False
assert history.find("978111") is None
assert "Corrupt" in caplog.text
def test_missing_file_treated_as_empty(self):
with tempfile.TemporaryDirectory() as tmpdir:
history = DownloadHistory(Path(tmpdir) / "no_such_file.json")
assert history.is_downloaded("978111") is False
def test_empty_file_treated_as_empty(self):
with tempfile.TemporaryDirectory() as tmpdir:
history_path = Path(tmpdir) / "empty.json"
history_path.write_text("")
history = DownloadHistory(history_path)
assert history.is_downloaded("978111") is False