import json import subprocess import sys from collections.abc import Callable, Iterator from pathlib import Path from types import SimpleNamespace import pytest from unshackle.core import binaries from unshackle.core.api.errors import categorize_exception from unshackle.core.config import config from unshackle.core.drm import decrypters from unshackle.core.remote_protocol import APIErrorCode from unshackle.core.tracks import Hybrid from unshackle.core.utilities import close_debug_logger, init_debug_logger from unshackle.core.utils import subprocess as subprocess_module from unshackle.core.utils.subprocess import ToolFailed, run_tool, tool_reason KEY = "b5df2ae3f63b8dda9049d6e41422e075" POSIX_STUBS = pytest.mark.skipif(sys.platform == "win32", reason="the tool stubs are shell scripts") def exits(code: int, stderr: str = "", stdout: str = "") -> list[str]: """A Python command that writes ``stdout`` and ``stderr`` and exits with ``code``.""" script = f"import sys; sys.stdout.write({stdout!r}); sys.stderr.write({stderr!r}); sys.exit({code})" return [sys.executable, "-c", script] def test_the_reason_is_the_last_lines_without_blank_lines_or_glog_prefixes() -> None: stderr = b"first\n\nsecond\n[1128/120001:ERROR:packager_main.cc(612)] Packaging Error: 5\n\rlast\n\n" assert tool_reason(stderr) == "second; Packaging Error: 5; last" @pytest.mark.parametrize("empty", [None, "", b"", "\n \n"]) def test_no_output_gives_no_reason(empty: str | bytes | None) -> None: assert tool_reason(empty) == "" def test_stdout_is_the_reason_when_stderr_is_empty() -> None: error = ToolFailed("SubtitleEdit", 1, ["se"], output="Errors:\nAccess denied\n", stderr="") assert str(error) == "SubtitleEdit failed (exit 1): Errors:; Access denied; command: se" def test_run_tool_raises_a_called_process_error_with_the_reason() -> None: with pytest.raises(subprocess.CalledProcessError) as caught: run_tool("tool", exits(2, stderr="Failed to write file out.mp4"), "tool step") assert isinstance(caught.value, ToolFailed) assert caught.value.returncode == 2 and caught.value.stderr == b"Failed to write file out.mp4" assert str(caught.value).startswith("tool failed (exit 2): Failed to write file out.mp4; command: ") def test_a_failed_run_logs_the_reason_without_the_command(monkeypatch: pytest.MonkeyPatch) -> None: logged: list[dict] = [] monkeypatch.setattr( subprocess_module, "get_debug_logger", lambda: SimpleNamespace(log=lambda **kw: logged.append(kw)) ) with pytest.raises(ToolFailed): run_tool("tool", [*exits(3, stderr="disk full\n"), KEY], "tool step") assert len(logged) == 1 and logged[0]["level"] == "ERROR" assert logged[0]["context"]["returncode"] == 3 and logged[0]["context"]["reason"] == "disk full" assert KEY not in str(logged[0]) def stub(tmp_path: Path, name: str, script: str) -> Path: """A shell script ``name`` in ``tmp_path`` that runs ``script``.""" path = tmp_path / name path.write_text(f"#!/bin/sh\n{script}\n") path.chmod(0o755) return path @POSIX_STUBS def test_an_mp4decrypt_failure_names_the_reason_and_keeps_the_key( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setattr( binaries, "Mp4decrypt", stub(tmp_path, "mp4decrypt", "echo 'ERROR: cannot open output file (out.mp4) -5' >&2; exit 1"), ) path = tmp_path / "track.mp4" path.write_bytes(b"encrypted") with pytest.raises(subprocess.CalledProcessError) as caught: decrypters.mp4decrypt(path, lambda kids: ["--key", f"1:{KEY}"]) message = str(caught.value) assert message.startswith("mp4decrypt failed (exit 1): ERROR: cannot open output file (out.mp4) -5; command: ") assert f"1:{KEY}" in message assert categorize_exception(caught.value).error_code == APIErrorCode.DRM_ERROR @pytest.fixture def debug_entries(tmp_path: Path) -> Iterator[Callable[[], list[dict]]]: """An enabled debug logger; the fixture value reads its entries back.""" path = tmp_path / "debug.jsonl" init_debug_logger(log_path=path, enabled=True) yield lambda: [json.loads(line) for line in path.read_text(encoding="utf-8").splitlines() if line.strip()] close_debug_logger() def levels(entries: list[dict], operation: str | None = "tool_run") -> list[str]: """The levels of the entries of operation, or of every entry when operation is None.""" return [e["level"] for e in entries if operation is None or e.get("operation") == operation] @pytest.mark.parametrize(("code", "level"), [(10, "DEBUG"), (3, "ERROR")]) def test_run_tool_logs_a_handled_exit_code_at_debug( debug_entries: Callable[[], list[dict]], code: int, level: str ) -> None: with pytest.raises(ToolFailed): run_tool("tool", exits(code), "tool step", handled=(10,)) assert levels(debug_entries()) == [level] def dovi_stub(tmp_path: Path, mode_3_error: str) -> Path: """A dovi_tool that fails with mode_3_error under -m and writes the RPU without it.""" return stub( tmp_path, "dovi_tool", f'if [ "$1" = "-m" ]; then echo {mode_3_error!r} >&2; exit 1; fi\nprintf rpu > "$4"', ) @POSIX_STUBS def test_a_max_pq_rpu_retries_untouched_without_an_error( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]] ) -> None: monkeypatch.setattr(config.directories, "temp", tmp_path) monkeypatch.setattr(binaries, "DoviTool", dovi_stub(tmp_path, "Error: invalid MAX_PQ_LUMINANCE in RPU")) Hybrid.__new__(Hybrid).extract_rpu(None, untouched=False) # type: ignore[arg-type] assert (tmp_path / "RPU_UNT.bin").read_bytes() == b"rpu" assert "ERROR" not in levels(debug_entries(), None) @POSIX_STUBS def test_a_real_rpu_failure_still_logs_error( tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]] ) -> None: monkeypatch.setattr(config.directories, "temp", tmp_path) monkeypatch.setattr(binaries, "DoviTool", dovi_stub(tmp_path, "Error: Invalid PPS index")) with pytest.raises(ValueError, match="corrupt"): Hybrid.__new__(Hybrid).extract_rpu(None, untouched=False) # type: ignore[arg-type] entries = debug_entries() assert levels(entries) == ["ERROR"] and levels(entries, "hybrid_extract_rpu") == ["ERROR"]