fix(dl): exit 1 when a title's track download fails

This commit is contained in:
imSp4rky
2026-12-02 11:40:45 -07:00
parent 9842a61d3f
commit b1497c77a2
4 changed files with 88 additions and 6 deletions
+3
View File
@@ -238,6 +238,9 @@ order the service used, then renumbers the episodes into the order you asked for
!!! warning "Some flags cannot be combined" !!! warning "Some flags cannot be combined"
`--select-titles` and `--wanted` are mutually exclusive. `--vbitrate` and `--vbitrate-range` (and the audio equivalents) are mutually exclusive. `--select-titles` and `--wanted` are mutually exclusive. `--vbitrate` and `--vbitrate-range` (and the audio equivalents) are mutually exclusive.
!!! info "Exit codes"
`dl` exits with code 1 when a track download or a mux fails, or when a missing track or language stops the run. A signal gives code 128 plus the signal number: 143 for SIGTERM. A run that ends without a failure, a `--list` run included, exits with code 0.
--- ---
## `search` ## `search`
+72
View File
@@ -0,0 +1,72 @@
"""The exit code of the dl command when a title's track download fails."""
import signal
from pathlib import Path
from typing import Any
import pytest
from click.testing import CliRunner, Result
from unshackle.commands import dl as dl_module
from unshackle.core import process_exit
from unshackle.core.titles import Movie, Movies
from unshackle.core.tracks import Chapters, Tracks, Video
pytestmark = pytest.mark.usefixtures("example_service")
def run_dl(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, download: Any, *args: str, standalone_mode: bool = True
) -> Result:
"""Run ``dl EXAMPLE`` on one movie with one video track, with ``download`` as the track download step."""
from unshackle.core import services
service = services.ensure_loaded("EXAMPLE")
assert service is not None
movie = Movie(id_="movie-1", service=service, name="Title", year=2020, language="en")
monkeypatch.setattr(service, "authenticate", lambda self, *a, **k: None)
monkeypatch.setattr(service, "get_titles", lambda self: Movies([movie]))
monkeypatch.setattr(
service,
"get_tracks",
lambda self, title: Tracks(Video(url="https://example.invalid/v.mp4", language="en", codec=Video.Codec.AVC)),
)
monkeypatch.setattr(service, "get_chapters", lambda self, title: Chapters())
monkeypatch.setattr(dl_module.TitleMetadata, "search", lambda self, *a, **k: None)
monkeypatch.setattr(dl_module.config, "key_vaults", [])
monkeypatch.setattr(dl_module.config, "output_template", {"movies": "{title}"})
monkeypatch.setattr(dl_module.config.directories, "temp", tmp_path / "temp")
monkeypatch.setattr(dl_module.dl, "get_cdm", lambda self, *a, **k: None)
monkeypatch.setattr(dl_module, "download_tracks_in_passes", download)
monkeypatch.setattr(dl_module.dl.cli, "_result_callback", dl_module.dl.cli._result_callback)
args = ("-o", str(tmp_path / "out"), "-l", "en", *args, "EXAMPLE", "--movie", "movie-1")
return CliRunner().invoke(dl_module.dl.cli, args, standalone_mode=standalone_mode)
def fail(*_: Any, **__: Any) -> None:
raise ConnectionError("segment refused")
@pytest.mark.parametrize("standalone_mode", [True, False], ids=["cli", "embedded"])
def test_a_failed_track_download_exits_1(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, standalone_mode: bool
) -> None:
result = run_dl(monkeypatch, tmp_path, fail, standalone_mode=standalone_mode)
assert "segment refused" in result.output
assert result.exit_code == 1
def test_a_download_that_a_signal_stopped_keeps_the_signal_exit(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
def stopped(*_: Any, **__: Any) -> None:
monkeypatch.setattr(process_exit.Stop, "signum", signal.SIGTERM)
fail()
assert run_dl(monkeypatch, tmp_path, stopped).exit_code == 128 + signal.SIGTERM
@pytest.mark.parametrize("flag", ["--no-mux", "--skip-dl", "--list"])
def test_a_run_without_a_failed_download_exits_0(monkeypatch: pytest.MonkeyPatch, tmp_path: Path, flag: str) -> None:
assert run_dl(monkeypatch, tmp_path, lambda *a, **k: None, flag).exit_code == 0
+12 -5
View File
@@ -1239,8 +1239,8 @@ class dl:
self.archive_scope = "cli" self.archive_scope = "cli"
self.archive_cache: Path | None = None self.archive_cache: Path | None = None
# result() catches a download-worker failure, reports it, and returns rather than # result() catches a download-worker failure, reports it, and returns rather than
# re-raising (so the CLI still exits cleanly). Keep it so an embedding caller (the API # re-raising, so later code can tell the title did not complete: cli_result exits 1
# worker) can tell the title did not complete instead of reading it as a success. # on it, and the API worker reads it from the outcome.
self.download_error: BaseException | None = None self.download_error: BaseException | None = None
if not config.output_template: if not config.output_template:
@@ -1500,7 +1500,14 @@ class dl:
# needs to be added this way instead of @cli.result_callback to be # needs to be added this way instead of @cli.result_callback to be
# able to keep `self` as the first positional # able to keep `self` as the first positional
self.cli._result_callback = self.result self.cli._result_callback = self.cli_result
def cli_result(self, *args: Any, **kwargs: Any) -> RunOutcome:
"""Run :meth:`result` for the CLI and exit 1 when a download failed, unless a signal already stops the run."""
outcome = self.result(*args, **kwargs)
if outcome.error is not None and not process_exit.stopping():
sys.exit(1)
return outcome
def outcome(self) -> RunOutcome: def outcome(self) -> RunOutcome:
"""What the run gave back so far, for an embedding caller such as the API job.""" """What the run gave back so far, for an embedding caller such as the API job."""
@@ -2400,8 +2407,8 @@ class dl:
self.export.log_summary() self.export.log_summary()
return self.outcome() return self.outcome()
except Exception as e: # noqa except Exception as e: # noqa
# Reported and swallowed (no re-raise) so the CLI exits cleanly; keep it so the # Reported and swallowed (no re-raise): cli_result exits 1 on it, and the API
# API worker sees the title failed rather than completing with no output. # worker reads it from the outcome rather than completing with no output.
self.download_error = e self.download_error = e
console.print(Padding(Group(*self.failure_lines(e)), (1, 5))) console.print(Padding(Group(*self.failure_lines(e)), (1, 5)))
if not isinstance(e, click.ClickException) and not retries_exhausted(e): if not isinstance(e, click.ClickException) and not retries_exhausted(e):
+1 -1
View File
@@ -459,7 +459,7 @@ def perform_download(
log.debug("Stderr: %s", stderr_capture.getvalue()) log.debug("Stderr: %s", stderr_capture.getvalue())
raise raise
# dl.result() reports a download-worker exception and returns normally, so the CLI exits cleanly. # dl.result() reports a download-worker exception and returns it in the outcome, not raised.
if outcome.error is not None: if outcome.error is not None:
# segment URLs carry signed CDN tokens (hmac, session IDs) that redact_text does not match # segment URLs carry signed CDN tokens (hmac, session IDs) that redact_text does not match
detail = redact_all(dl_instance.failure_lines(outcome.error)[1].strip()) detail = redact_all(dl_instance.failure_lines(outcome.error)[1].strip())