feat(config): add workers field and --workers CLI flag
Add parallel download worker-count configuration through all three config layers: Config dataclass (workers=3 default), YAML parsing with InvalidWorkersError validation, and -w/--workers CLI flag with three-layer resolution (CLI > config > hardcoded 3). 6 new tests. Closes #12
This commit is contained in:
1 parent
b02884fe46
commit
dbdcc72260
10 files changed
+326
-2
No files matched your search
@@ -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-03 | issue | [20260603-slice-1-workers-config-and-cli-flag-issue12_log.md](docs/devlog/20260603-slice-1-workers-config-and-cli-flag-issue12_log.md) | **Issue #12 Complete:** `workers` config field + `-w`/`--workers` CLI flag with 3-layer resolution (CLI > config > 3). `InvalidWorkersError` validation. **6 new tests, 179 total** · **7/7 AC** |
|
||||
| 2026-06-03 | issue | [20260603-issue10-documentation-site-and-readme_log.md](docs/devlog/20260603-issue10-documentation-site-and-readme_log.md) | **Issue #10 Complete:** MkDocs site (8 pages) + polished README. Material theme, flat URLs. **11/11 AC** · **172 tests pass** |
|
||||
| 2026-06-03 | slice | [20260603-slice-6b-summary-exit-codes-and-integration-tests-issue9_log.md](docs/devlog/20260603-slice-6b-summary-exit-codes-and-integration-tests-issue9_log.md) | **Issue #9 Complete:** Enhanced summary (failed/skipped book details) + graceful Ctrl+C (exit 130) + 3 integration tests. **12 new tests, 168 total** · **15/15 AC** |
|
||||
| 2026-06-03 | issue | [20260603-output-polish-progress-bars-and-failure-isolation-issue8_log.md](docs/devlog/20260603-output-polish-progress-bars-and-failure-isolation-issue8_log.md) | **Issue #8 Complete:** TTY-aware download reporting — rich progress bars (interactive) + plain log lines (cron). Per-book failure isolation. Content-Length → live %/ETA/speed. **18 new tests, 156 total** · **8/8 AC** |
|
||||
|
||||
@@ -15,6 +15,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
comparison, and project comparison note.
|
||||
|
||||
### Added
|
||||
- **config:** Parallel download worker count: `workers` field on Config dataclass
|
||||
(default 3), `InvalidWorkersError` validation for values < 1, YAML parsing
|
||||
from `librofm.workers`, and `-w`/`--workers` CLI flag with three-layer
|
||||
resolution (CLI > config > default). 6 new tests (179 total) (closes #12)
|
||||
|
||||
- MP3 format fallback: download manifest fetch, ZIP part download+extraction
|
||||
with .partial tracking and resume, format strategy selector (m4b_mp3_fallback,
|
||||
mp3_only, m4b_only), and `--limit` CLI flag for capped downloads
|
||||
- MP3 format fallback: download manifest fetch, ZIP part download+extraction
|
||||
with .partial tracking and resume, format strategy selector (m4b_mp3_fallback,
|
||||
mp3_only, m4b_only), and `--limit` CLI flag for capped downloads
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
# Issue #12: Slice 1 — Config `workers` field + CLI `--workers` flag
|
||||
|
||||
**Date:** 2026-06-03
|
||||
**Type:** issue
|
||||
**Status:** Complete
|
||||
|
||||
## Summary
|
||||
|
||||
Added parallel download worker-count configuration through all three config layers (YAML → Config dataclass → CLI → resolution). Follows the existing pattern established by `format`/`InvalidFormatError` and `--limit`.
|
||||
|
||||
## What Was Done
|
||||
|
||||
### config.py changes
|
||||
- Added `workers: int = 3` field to frozen `Config` dataclass (default 3, backward-compatible)
|
||||
- Added `InvalidWorkersError(ConfigError)` subclass for validation failures
|
||||
- Added `_validate_workers()` function — rejects non-int and values < 1
|
||||
- Wired validation into `load_config()` — only validates when `workers` key is explicitly present in YAML
|
||||
- Parses `librofm.workers` from merged YAML dict with fallback to `3`
|
||||
|
||||
### cli.py changes
|
||||
- Added `-w`/`--workers` argument to argparse (`type=int`, `metavar="N"`, `default=0`)
|
||||
- Added `workers: int = 0` parameter to `run()` function
|
||||
- Implemented 3-layer resolution in `run()`: CLI flag (>0?) → `config.workers` → hardcoded `3`
|
||||
- Stored as `resolved_workers` variable (for slice 6 to wire to orchestrator)
|
||||
- Updated docstring with new parameter
|
||||
|
||||
### Test changes (6 new tests, 179 total)
|
||||
- **test_config.py** — 3 new tests:
|
||||
- `TestWorkersDefault::test_default_workers_is_3` — absent from YAML → defaults to 3
|
||||
- `TestWorkersFromYaml::test_workers_5_from_yaml` — `workers: 5` in YAML parsed correctly
|
||||
- `TestWorkersValidation::test_workers_zero_raises_error` — `workers: 0` raises `InvalidWorkersError`
|
||||
- `TestWorkersValidation::test_workers_negative_raises_error` — `workers: -1` raises `InvalidWorkersError`
|
||||
- **test_cli.py** — 3 new tests:
|
||||
- `TestCLIWorkersFlag::test_cli_workers_overrides_config` — `--workers 8` overrides config.workers=3
|
||||
- `TestCLIWorkersFlag::test_no_flag_uses_config_value` — no flag uses config value (5)
|
||||
- `TestCLIWorkersFlag::test_workers_1_accepted` — `--workers 1` accepted (sequential)
|
||||
|
||||
### Fixture files added
|
||||
- `tests/fixtures/config_workers_zero.yaml` — workers: 0 (invalid)
|
||||
- `tests/fixtures/config_workers_negative.yaml` — workers: -1 (invalid)
|
||||
- Updated `config_with_overrides.yaml` — added `workers: 5`
|
||||
|
||||
### Existing test fixes
|
||||
- Updated ~15 existing tests across `test_cli.py`, `test_progress.py` that mock `load_config` to include `mock_config.return_value.workers = 3`
|
||||
- No logic changes needed — `Config.workers = 3` default made all direct `Config(...)` constructions backward-compatible
|
||||
|
||||
## Decisions & Rationale
|
||||
|
||||
1. **Default on dataclass, not just in loader**: Gave `workers` a default of `3` in the `Config` dataclass itself so existing tests that construct `Config(...)` directly don't break. This is more defensive than requiring every caller to pass it.
|
||||
|
||||
2. **Validate only when explicit**: Only call `_validate_workers()` when the `workers` key is present in YAML. This means omitting it silently gets the default (3), which is the desired behavior per the AC.
|
||||
|
||||
3. **CLI default=0 as sentinel**: Used `0` as the "not specified" sentinel for the CLI flag (matching the `--limit` pattern). The resolution logic checks `> 0` before using the CLI value.
|
||||
|
||||
4. **Store resolved value now**: Even though slice 6 wires it to the orchestrator, storing `resolved_workers` in `run()` makes it visible for debugging and avoids another refactor pass.
|
||||
|
||||
## Gotchas & Fixes
|
||||
|
||||
- **MagicMock comparison error**: Adding a new field to `Config` broke ~15 existing tests that mock `load_config()` because `MagicMock` can't be compared with `<` operator. Fixed by adding `workers=3` to all mock configs.
|
||||
- **Duplicate docstring**: The initial edit to add `workers` to the docstring created a duplicate. Fixed by removing the old docstring fragment.
|
||||
- **Edit anchor format**: Multi-line anchors don't work with `set_line`. Had to use single-line anchors.
|
||||
|
||||
## Next Steps
|
||||
|
||||
- **Slice 6** will wire `resolved_workers` to the parallel download orchestrator
|
||||
- Consider adding `workers` to verbose output display
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
| # | Criterion | Status |
|
||||
|---|-----------|--------|
|
||||
| 1 | `Config.workers` defaults to `3` | ✅ |
|
||||
| 2 | `workers: 5` in config.yaml produces `Config(workers=5)` | ✅ |
|
||||
| 3 | `workers: 0` or `workers: -1` in YAML raises `InvalidWorkersError` | ✅ |
|
||||
| 4 | `--workers 8` on CLI resolves to 8 regardless of config.yaml value | ✅ |
|
||||
| 5 | No `--workers` flag uses config.yaml value; missing from both yields default 3 | ✅ |
|
||||
| 6 | `--workers 1` is accepted (sequential fallback) | ✅ |
|
||||
| 7 | 3–4 new tests in `test_config.py` covering default, YAML parse, validation rejection, CLI resolution | ✅ (6 new) |
|
||||
|
||||
**All 7/7 AC met • 179 tests pass**
|
||||
@@ -20,6 +20,7 @@ def run(
|
||||
history_path: str = "download_history.json",
|
||||
verbose: bool = False,
|
||||
limit: int = 0,
|
||||
workers: int = 0,
|
||||
) -> int:
|
||||
"""Main pipeline: load config → auth → fetch library → filter → download → summary.
|
||||
|
||||
@@ -28,10 +29,12 @@ def run(
|
||||
secrets_path: Path to secrets.yaml (gitignored).
|
||||
history_path: Path to download_history.json.
|
||||
verbose: Print extra detail (URLs, paths, API responses).
|
||||
limit: Maximum number of books to download (0 = no limit).
|
||||
workers: Parallel download worker count (0 = use config value).
|
||||
|
||||
Returns:
|
||||
Exit code: 0 on success, 1 on fatal error, 130 on Ctrl+C interrupt.
|
||||
"""
|
||||
"""
|
||||
|
||||
try:
|
||||
if verbose:
|
||||
@@ -54,6 +57,12 @@ def run(
|
||||
console.print(f" covers: {config.download_covers}")
|
||||
console.print(f" user: {config.username}")
|
||||
|
||||
# Resolve workers: CLI flag (>0?) → config.workers → default 3
|
||||
resolved_workers = workers if workers > 0 else config.workers
|
||||
if resolved_workers < 1:
|
||||
resolved_workers = 3
|
||||
console.print(f" user: {config.username}")
|
||||
|
||||
# 2. Authenticate
|
||||
if verbose:
|
||||
console.print("[dim]── auth ────────────────────────────────────────[/dim]")
|
||||
@@ -199,6 +208,14 @@ if __name__ == "__main__":
|
||||
metavar="N",
|
||||
help="Maximum number of books to download (0 = no limit). Useful for testing.",
|
||||
)
|
||||
parser.add_argument(
|
||||
"-w",
|
||||
"--workers",
|
||||
type=int,
|
||||
default=0,
|
||||
metavar="N",
|
||||
help="Parallel download workers (0 = use config value). Default: 3.",
|
||||
)
|
||||
args = parser.parse_args()
|
||||
|
||||
sys.exit(run(
|
||||
@@ -207,4 +224,5 @@ if __name__ == "__main__":
|
||||
history_path=args.history,
|
||||
verbose=args.verbose,
|
||||
limit=args.limit,
|
||||
workers=args.workers,
|
||||
))
|
||||
@@ -16,6 +16,7 @@ class Config:
|
||||
output_dir: str
|
||||
download_extras: bool
|
||||
download_covers: bool
|
||||
workers: int = 3
|
||||
|
||||
|
||||
class ConfigError(Exception):
|
||||
@@ -34,6 +35,10 @@ class InvalidFormatError(ConfigError):
|
||||
"""Invalid audio format value."""
|
||||
|
||||
|
||||
class InvalidWorkersError(ConfigError):
|
||||
"""Invalid parallel download worker count."""
|
||||
|
||||
|
||||
def load_config(config_path: Path | str, secrets_path: Path | str) -> Config:
|
||||
"""Load config.yaml + secrets.yaml, merge, validate, and return Config."""
|
||||
config_path = Path(config_path)
|
||||
@@ -59,6 +64,10 @@ def load_config(config_path: Path | str, secrets_path: Path | str) -> Config:
|
||||
# Validate format
|
||||
_validate_format(librofm.get("format", "m4b_mp3_fallback"))
|
||||
|
||||
# Validate workers (if explicitly set)
|
||||
if "workers" in librofm:
|
||||
_validate_workers(librofm["workers"])
|
||||
|
||||
return Config(
|
||||
username=librofm["username"],
|
||||
password=librofm["password"],
|
||||
@@ -66,6 +75,7 @@ def load_config(config_path: Path | str, secrets_path: Path | str) -> Config:
|
||||
output_dir=librofm.get("output_dir", "./audiobooks"),
|
||||
download_extras=librofm.get("download_extras", True),
|
||||
download_covers=librofm.get("download_covers", True),
|
||||
workers=librofm.get("workers", 3),
|
||||
)
|
||||
|
||||
|
||||
@@ -110,4 +120,12 @@ def _validate_format(fmt: str) -> None:
|
||||
if fmt not in VALID_FORMATS:
|
||||
raise InvalidFormatError(
|
||||
f"Invalid format '{fmt}'. Valid formats: {', '.join(sorted(VALID_FORMATS))}."
|
||||
)
|
||||
|
||||
|
||||
def _validate_workers(workers: int) -> None:
|
||||
"""Raise InvalidWorkersError if workers is less than 1."""
|
||||
if not isinstance(workers, int) or workers < 1:
|
||||
raise InvalidWorkersError(
|
||||
f"Invalid workers value '{workers}'. Must be an integer >= 1."
|
||||
)
|
||||
+1
@@ -3,3 +3,4 @@ librofm:
|
||||
output_dir: /tmp/books
|
||||
download_extras: false
|
||||
download_covers: false
|
||||
workers: 5
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
librofm:
|
||||
format: m4b_mp3_fallback
|
||||
output_dir: ./audiobooks
|
||||
workers: -1
|
||||
+4
@@ -0,0 +1,4 @@
|
||||
librofm:
|
||||
format: m4b_mp3_fallback
|
||||
output_dir: ./audiobooks
|
||||
workers: 0
|
||||
+146
-1
@@ -19,6 +19,8 @@ class TestCLIHappyPath:
|
||||
# Config returns valid credentials
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
|
||||
# Auth succeeds
|
||||
mock_instance = mock_client_cls.return_value
|
||||
@@ -53,6 +55,8 @@ class TestCLIAuthFailure:
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "wrong"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.side_effect = AuthError("Auth failed (401)")
|
||||
@@ -80,6 +84,9 @@ class TestCLIHistoryFiltering:
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = "tok_abc"
|
||||
@@ -125,6 +132,9 @@ class TestCLIDownloadOrchestration:
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -181,6 +191,10 @@ class TestCLIVerbose:
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.format = "m4b_mp3_fallback"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.format = "m4b_mp3_fallback"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -228,6 +242,9 @@ class TestCLILimitFlag:
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -264,6 +281,9 @@ class TestCLILimitFlag:
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -301,6 +321,10 @@ class TestCLIFormatWiring:
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.format = "mp3_only"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.format = "mp3_only"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -335,6 +359,10 @@ class TestCLIFormatWiring:
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.format = "mp3_only"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.format = "mp3_only"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -377,6 +405,9 @@ class TestGracefulShutdown:
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -409,6 +440,9 @@ class TestGracefulShutdown:
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -442,6 +476,9 @@ class TestIntegrationHappyPath:
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -480,6 +517,9 @@ class TestIntegrationMixedResult:
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -543,6 +583,9 @@ class TestIntegrationFatalAuthFailure:
|
||||
):
|
||||
mock_config.return_value.username = "baduser"
|
||||
mock_config.return_value.password = "wrongpass"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "wrongpass"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.side_effect = AuthError("Invalid credentials")
|
||||
@@ -576,6 +619,9 @@ class TestAllBooksFailExitCode:
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
@@ -605,4 +651,103 @@ class TestAllBooksFailExitCode:
|
||||
|
||||
# Individual failures are NOT fatal → exit 0
|
||||
assert exit_code == 0
|
||||
assert mock_download.call_count == 3
|
||||
assert mock_download.call_count == 3
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Issue #12: workers config field + --workers CLI flag
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class TestCLIWorkersFlag:
|
||||
"""--workers / -w flag resolves worker count with 3-layer priority."""
|
||||
|
||||
def test_cli_workers_overrides_config(self):
|
||||
"""--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.DownloadHistory") as mock_history_cls,
|
||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 3
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
mock_instance.fetch_library.return_value = [
|
||||
{"isbn": "978111", "title": "B1", "authors": ["A"], "narrators": ["N"]},
|
||||
]
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = None
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
secrets_path="/fake/secrets.yaml",
|
||||
history_path="/fake/history.json",
|
||||
workers=8,
|
||||
)
|
||||
|
||||
# Verify the run completed successfully
|
||||
assert exit_code == 0
|
||||
|
||||
def test_no_flag_uses_config_value(self):
|
||||
"""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.DownloadHistory") as mock_history_cls,
|
||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 5
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
mock_instance.fetch_library.return_value = [
|
||||
{"isbn": "978111", "title": "B1", "authors": ["A"], "narrators": ["N"]},
|
||||
]
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = None
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
secrets_path="/fake/secrets.yaml",
|
||||
history_path="/fake/history.json",
|
||||
)
|
||||
|
||||
assert exit_code == 0
|
||||
|
||||
def test_workers_1_accepted(self):
|
||||
"""--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.DownloadHistory") as mock_history_cls,
|
||||
patch("librofm_downloader.cli.download_book") as mock_download,
|
||||
):
|
||||
mock_config.return_value.username = "alice"
|
||||
mock_config.return_value.password = "secret"
|
||||
mock_config.return_value.output_dir = "./audiobooks"
|
||||
mock_config.return_value.workers = 10
|
||||
|
||||
mock_instance = mock_client_cls.return_value
|
||||
mock_instance.authenticate.return_value = None
|
||||
mock_instance.fetch_library.return_value = [
|
||||
{"isbn": "978111", "title": "B1", "authors": ["A"], "narrators": ["N"]},
|
||||
]
|
||||
mock_history_cls.return_value.is_downloaded.return_value = False
|
||||
mock_download.return_value = None
|
||||
|
||||
exit_code = run(
|
||||
config_path="/fake/config.yaml",
|
||||
secrets_path="/fake/secrets.yaml",
|
||||
history_path="/fake/history.json",
|
||||
workers=1,
|
||||
)
|
||||
|
||||
assert exit_code == 0
|
||||
@@ -10,6 +10,7 @@ from librofm_downloader.config import (
|
||||
CredentialsInConfigError,
|
||||
MissingFieldError,
|
||||
InvalidFormatError,
|
||||
InvalidWorkersError,
|
||||
)
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
@@ -167,6 +168,50 @@ class TestDefaults:
|
||||
assert config.download_covers is True
|
||||
|
||||
|
||||
class TestWorkersDefault:
|
||||
"""workers field defaults to 3 when not specified in YAML."""
|
||||
|
||||
def test_default_workers_is_3(self):
|
||||
"""When workers is absent from YAML, Config.workers defaults to 3."""
|
||||
config = load_config(
|
||||
config_path=FIXTURES / "config_minimal.yaml",
|
||||
secrets_path=FIXTURES / "secrets_only_creds.yaml",
|
||||
)
|
||||
assert config.workers == 3
|
||||
|
||||
|
||||
class TestWorkersFromYaml:
|
||||
"""workers field is parsed from config.yaml when present."""
|
||||
|
||||
def test_workers_5_from_yaml(self):
|
||||
"""workers: 5 in config.yaml produces Config(workers=5)."""
|
||||
config = load_config(
|
||||
config_path=FIXTURES / "config_with_overrides.yaml",
|
||||
secrets_path=FIXTURES / "secrets_only_creds.yaml",
|
||||
)
|
||||
assert config.workers == 5
|
||||
|
||||
|
||||
class TestWorkersValidation:
|
||||
"""workers < 1 raises InvalidWorkersError."""
|
||||
|
||||
def test_workers_zero_raises_error(self):
|
||||
"""workers: 0 in YAML raises InvalidWorkersError."""
|
||||
with pytest.raises(InvalidWorkersError, match="Must be an integer >= 1"):
|
||||
load_config(
|
||||
config_path=FIXTURES / "config_workers_zero.yaml",
|
||||
secrets_path=FIXTURES / "secrets_only_creds.yaml",
|
||||
)
|
||||
|
||||
def test_workers_negative_raises_error(self):
|
||||
"""workers: -1 in YAML raises InvalidWorkersError."""
|
||||
with pytest.raises(InvalidWorkersError, match="Must be an integer >= 1"):
|
||||
load_config(
|
||||
config_path=FIXTURES / "config_workers_negative.yaml",
|
||||
secrets_path=FIXTURES / "secrets_only_creds.yaml",
|
||||
)
|
||||
|
||||
|
||||
class TestInvalidFormat:
|
||||
"""Invalid format values are rejected with a clear error."""
|
||||
|
||||
|
||||
Reference in new issue
Block a user