Files
shelfmark/tests/download/test_output_ignored_files.py
T
CaliBrain a00f3d28bf fix(slskd): refuse unsafe peer paths, keep queued downloads alive, report search outages (#1512)
Fixes four defects in the Soulseek (slskd)

A peer names its own files, and Shelfmark works out where slskd stored
one from the last folder and the file name. `remote_directory_name`
returned the whole directory when its last segment was empty. So
`../../../etc//passwd.epub` or `/abs/path//book.epub` resolved outside
the downloads folder, and Shelfmark imported whatever was there. For a
multi-file release it moved those files into staging (`STAGE_MOVE`).

- New `safe_remote_segments` refuses a name with an empty, `.` or `..`
segment (which covers absolute and UNC paths), a NUL, or a drive
anywhere but a Windows share root (`C:\Books\…`, which never reaches a
local path).
- Search (`iter_peer_files`, so `build_releases`) drops such files.
- `download` refuses them before anything is queued, in both modes. The
spec arrives with the queued release payload, so search filtering alone
is not enough.
- `local_path_for` also refuses a path that resolves outside the root
(`resolve()` + `is_relative_to`), for example through a symlinked
folder.

`_poll`, used when isolation is off and as the fallback for slskd <
0.26, never asked for an activity grace. A file "Queued, Remotely" sent
the same status and progress on every poll, so the orchestrator
cancelled it after 300s and `SLSKD_QUEUE_TIMEOUT_MINUTES` never applied.
It now requests, renews and releases the grace the same way isolated
mode does.

`search` caught every exception per query, so slskd being down or
rejecting the API key showed as "no releases". When no query gets an
answer it now raises `SourceUnavailableError`, as Prowlarr does, and the
error reaches the user. One failed query among answered ones is still
not an outage.

A retry reuses the task's folder, and slskd renames a new file when one
is already there. Files from a failed attempt therefore meant
`_folder_complete`'s exact count could never match again. Now:
- a failed or cancelled attempt removes its folder;
- a new attempt removes any finished files an earlier one left (for
example after a restart) before it queues the batch.

`tests/slskd/conftest.py` stubbed `flask_socketio` whenever it had not
been imported yet, even though it is installed. Running `pytest
tests/slskd tests/` therefore broke the Flask app tests in the same
worker (285 errors, also on 10710ab). It now stubs only when the module
is missing.

- 25 new regression tests. All of them fail on 10710ab.
- `make python-checks` passes.
- `uv run pytest tests/slskd tests/ -m "not integration and not e2e"`
passes: 4047 tests on e83bab9.
2026-10-21 01:58:13 -04:00

92 lines
3.1 KiB
Python

"""Files the user skipped in the pack review are not emailed or uploaded to BookLore."""
from __future__ import annotations
from pathlib import Path
from threading import Event
from unittest.mock import MagicMock, patch
import pytest
from shelfmark.core.models import DownloadTask
EMAIL = "shelfmark.download.outputs.email"
BOOKLORE = "shelfmark.download.outputs.booklore"
def _pack(tmp_path: Path) -> tuple[Path, Path, Path]:
root = tmp_path / "Series Pack"
kept = root / "Book 1" / "one.epub"
skipped = root / "Book 2" / "two.epub"
for book in (kept, skipped):
book.parent.mkdir(parents=True)
book.write_bytes(b"epub")
return root, kept, skipped
def _task(ignored: list[str]) -> DownloadTask:
return DownloadTask(
task_id="pack",
source="prowlarr",
title="Series Pack",
output_args={"to": "reader@example.com"},
ignored_files=ignored,
)
def _send_by_email(root: Path, task: DownloadTask) -> tuple[list[Path] | None, list[tuple]]:
from shelfmark.download.outputs.email import process_email_output
sent: list[Path] = []
statuses: list[tuple] = []
with (
patch(f"{EMAIL}._get_email_settings", return_value={}),
patch(f"{EMAIL}.build_email_smtp_config", return_value=MagicMock()),
patch(
f"{EMAIL}.compose_email_message",
side_effect=lambda _config, **kw: sent.extend(kw["files"]),
),
patch(f"{EMAIL}.send_email_message") as send,
):
process_email_output(root, task, Event(), lambda *s: statuses.append(s))
return (sent if send.called else None), statuses
def _upload_to_booklore(root: Path, task: DownloadTask) -> tuple[list[Path] | None, list[tuple]]:
from shelfmark.download.outputs.booklore import process_booklore_output
statuses: list[tuple] = []
with (
patch(f"{BOOKLORE}._get_booklore_settings", return_value={}),
patch(
f"{BOOKLORE}.build_booklore_config",
return_value=MagicMock(refresh_after_upload=False),
),
patch(f"{BOOKLORE}.booklore_login", return_value="token"),
patch(f"{BOOKLORE}.booklore_upload_file") as upload,
):
process_booklore_output(root, task, Event(), lambda *s: statuses.append(s))
uploaded = [c.args[2] for c in upload.call_args_list]
return (uploaded or None), statuses
@pytest.mark.parametrize("deliver", [_send_by_email, _upload_to_booklore])
def test_a_skipped_book_is_not_delivered(deliver, tmp_path: Path) -> None:
root, kept, _skipped = _pack(tmp_path)
delivered, _statuses = deliver(root, _task(["Series Pack/Book 2/two.epub"]))
assert delivered == [kept]
@pytest.mark.parametrize("deliver", [_send_by_email, _upload_to_booklore])
def test_nothing_is_delivered_when_every_file_was_skipped(deliver, tmp_path: Path) -> None:
root, _kept, _skipped = _pack(tmp_path)
delivered, statuses = deliver(
root, _task(["Series Pack/Book 1/one.epub", "Series Pack/Book 2/two.epub"])
)
assert delivered is None
assert ("error", "No book files found") in statuses