feat(selector): add interactive book selection module
New selector.py with select_books() and _format_row(). Questionary checkbox prompt, all unchecked by default, confirmation summary + y/N, original order preservation, Ctrl+C propagation via unsafe_ask(). 9 tests. Closes #47
This commit is contained in:
1 parent
48ec81d92d
commit
922e7fe6bb
4 files changed
+187
No files matched your search
@@ -6,6 +6,15 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
### Added
|
||||
|
||||
- **selector:** Add interactive book selection module with
|
||||
`select_books(books) -> list[Book]`. Questionary checkbox prompt
|
||||
(all unchecked by default), confirmation summary with y/N prompt,
|
||||
original-input-order preservation, Ctrl+C propagation via
|
||||
`unsafe_ask()`. Row format: `N. Title — Author [Series #N]`.
|
||||
9 tests. Closes #47.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **downloader:** Fix progress bar exceeding 100% on resumed downloads.
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Interactive book selection via questionary checkbox prompt.
|
||||
|
||||
Public API: select_books(books) -> list[Book]
|
||||
Internal helper: _format_row(book, index) -> str
|
||||
"""
|
||||
|
||||
import questionary
|
||||
|
||||
from librofm_downloader.book import Book
|
||||
|
||||
|
||||
def _format_row(book: Book, index: int) -> str:
|
||||
"""Format a Book into a display string for the checkbox prompt.
|
||||
|
||||
Format: "N. Title — First Author [Series #N]"
|
||||
Series suffix omitted when absent. Author falls back to "Unknown".
|
||||
"""
|
||||
author = book.authors[0] if book.authors else "Unknown"
|
||||
base = f"{index}. {book.title} — {author}"
|
||||
if book.series and book.series_num is not None:
|
||||
base += f" [{book.series} #{book.series_num}]"
|
||||
return base
|
||||
|
||||
|
||||
def select_books(books: list[Book]) -> list[Book]:
|
||||
"""Present an interactive checkbox prompt and return selected Books.
|
||||
|
||||
Returns selected Books in their original input order.
|
||||
Returns empty list on zero selection or confirmation rejection.
|
||||
Propagates KeyboardInterrupt from the checkbox prompt.
|
||||
"""
|
||||
rows = [_format_row(b, i + 1) for i, b in enumerate(books)]
|
||||
chosen = questionary.checkbox(
|
||||
"Select books to download:",
|
||||
choices=rows,
|
||||
).unsafe_ask()
|
||||
|
||||
if not chosen:
|
||||
print("No books selected. Exiting.")
|
||||
return []
|
||||
|
||||
# Map display rows back to Book objects
|
||||
row_to_book = {row: book for row, book in zip(rows, books)}
|
||||
selected = [row_to_book[row] for row in chosen]
|
||||
|
||||
# Confirmation prompt
|
||||
print(f"{len(selected)} book(s) selected for download:")
|
||||
for book in selected:
|
||||
print(f" - {book.title}")
|
||||
|
||||
if not questionary.confirm("Proceed with download?", default=False).ask():
|
||||
return []
|
||||
|
||||
# Return in original input order
|
||||
selected_set = {id(b) for b in selected}
|
||||
return [b for b in books if id(b) in selected_set]
|
||||
@@ -12,6 +12,7 @@ requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"httpx>=0.27",
|
||||
"pyyaml>=6.0",
|
||||
"questionary>=2.1.1",
|
||||
"rich>=13.0",
|
||||
]
|
||||
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
"""Tests for selector.py — interactive book selection."""
|
||||
|
||||
import unittest.mock as mock
|
||||
|
||||
from librofm_downloader.book import Book
|
||||
from librofm_downloader.selector import _format_row, select_books
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _book(title, authors=None, **kw):
|
||||
"""Convenience Book factory for tests."""
|
||||
return Book(
|
||||
title=title,
|
||||
authors=authors or ["Author"],
|
||||
narrators=[],
|
||||
isbn=kw.pop("isbn", "0000"),
|
||||
**kw,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# _format_row
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_format_row_with_series():
|
||||
book = Book(
|
||||
title="The Way of Kings",
|
||||
authors=["Brandon Sanderson"],
|
||||
narrators=["Michael Kramer"],
|
||||
isbn="9780765365279",
|
||||
series="Stormlight Archive",
|
||||
series_num=1,
|
||||
)
|
||||
assert _format_row(book, 3) == "3. The Way of Kings — Brandon Sanderson [Stormlight Archive #1]"
|
||||
|
||||
|
||||
def test_format_row_without_series():
|
||||
book = Book(
|
||||
title="Project Hail Mary",
|
||||
authors=["Andy Weir"],
|
||||
narrators=["Ray Porter"],
|
||||
isbn="9780593135204",
|
||||
)
|
||||
assert _format_row(book, 1) == "1. Project Hail Mary — Andy Weir"
|
||||
|
||||
|
||||
def test_format_row_no_authors_falls_back_to_unknown():
|
||||
book = Book(
|
||||
title="Mystery Book",
|
||||
authors=[],
|
||||
narrators=[],
|
||||
isbn="0000000000",
|
||||
)
|
||||
assert _format_row(book, 5) == "5. Mystery Book — Unknown"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# select_books
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def test_select_books_returns_selected_in_original_order():
|
||||
books = [_book("A"), _book("B"), _book("C"), _book("D")]
|
||||
with mock.patch("librofm_downloader.selector.questionary") as q:
|
||||
q.checkbox.return_value.unsafe_ask.return_value = ["3. C — Author", "1. A — Author"]
|
||||
q.confirm.return_value.ask.return_value = True
|
||||
result = select_books(books)
|
||||
assert [b.title for b in result] == ["A", "C"]
|
||||
|
||||
|
||||
def test_select_books_returns_empty_on_zero_selection(capsys):
|
||||
books = [_book("A"), _book("B")]
|
||||
with mock.patch("librofm_downloader.selector.questionary") as q:
|
||||
q.checkbox.return_value.unsafe_ask.return_value = []
|
||||
result = select_books(books)
|
||||
assert result == []
|
||||
assert "No books selected" in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_select_books_returns_empty_on_confirm_rejection():
|
||||
books = [_book("A"), _book("B")]
|
||||
with mock.patch("librofm_downloader.selector.questionary") as q:
|
||||
q.checkbox.return_value.unsafe_ask.return_value = ["1. A — Author"]
|
||||
q.confirm.return_value.ask.return_value = False # N / bare Enter
|
||||
result = select_books(books)
|
||||
assert result == []
|
||||
|
||||
|
||||
def test_select_books_returns_books_on_confirm_acceptance(capsys):
|
||||
books = [_book("Alpha"), _book("Beta")]
|
||||
with mock.patch("librofm_downloader.selector.questionary") as q:
|
||||
q.checkbox.return_value.unsafe_ask.return_value = ["2. Beta — Author"]
|
||||
q.confirm.return_value.ask.return_value = True # y/Y
|
||||
result = select_books(books)
|
||||
assert [b.title for b in result] == ["Beta"]
|
||||
out = capsys.readouterr().out
|
||||
assert "1 book(s) selected" in out
|
||||
assert "- Beta" in out
|
||||
|
||||
|
||||
def test_select_books_propagates_keyboard_interrupt():
|
||||
books = [_book("A")]
|
||||
with mock.patch("librofm_downloader.selector.questionary") as q:
|
||||
q.checkbox.return_value.unsafe_ask.side_effect = KeyboardInterrupt
|
||||
try:
|
||||
select_books(books)
|
||||
except KeyboardInterrupt:
|
||||
pass # expected
|
||||
else:
|
||||
raise AssertionError("Should have propagated KeyboardInterrupt")
|
||||
|
||||
|
||||
def test_select_books_single_book_library():
|
||||
books = [_book("Solo")]
|
||||
with mock.patch("librofm_downloader.selector.questionary") as q:
|
||||
q.checkbox.return_value.unsafe_ask.return_value = ["1. Solo — Author"]
|
||||
q.confirm.return_value.ask.return_value = True
|
||||
result = select_books(books)
|
||||
assert [b.title for b in result] == ["Solo"]
|
||||
Reference in new issue
Block a user