Files
unshackle/tests/core/test_tool_failed.py
T

249 lines
11 KiB
Python

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 Audio, Hybrid, Subtitle, Video
from unshackle.core.tracks import hybrid as hybrid_module
from unshackle.core.tracks.subtitle_convert import SubtitleEditBackend
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_step, 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"
def test_the_short_glog_prefix_is_removed() -> None:
assert tool_reason("E1128 12:00:01.123456 1 packager_main.cc:612] Packaging Error: 5\n") == "Packaging Error: 5"
def test_a_long_reason_line_keeps_its_start_and_its_end() -> None:
line = "Cannot close file " + "x" * 300 + ", possibly running out of disk space."
reason = tool_reason(line)
assert reason.startswith("Cannot close file ") and reason.endswith("running out of disk space.")
assert len(reason) == 205
@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_the_message_names_tool_exit_reason_and_command() -> None:
error = ToolFailed("FFmpeg", 1, ["ffmpeg", Path("in.mp4")], stderr=b"No space left on device\n")
assert str(error) == "FFmpeg failed (exit 1): No space left on device; command: ffmpeg in.mp4"
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"
@pytest.mark.parametrize(
("code", "text"),
[(5, "exit 5"), (-9, "signal 9"), (0xC0000005, "exit 0xc0000005")],
)
def test_a_failure_with_no_output_names_only_the_exit(code: int, text: str) -> None:
assert str(ToolFailed("ccextractor", code, ["cc"])) == f"ccextractor failed ({text}); command: cc"
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_run_tool_returns_the_completed_process_on_exit_0() -> None:
p = run_tool("tool", exits(0, stdout="done"), "tool step")
assert p.returncode == 0 and p.stdout == b"done"
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_a_repackage_failure_names_the_ffmpeg_reason(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(binaries, "FFMPEG", stub(tmp_path, "ffmpeg", "echo 'No space left on device' >&2; exit 1"))
track = Audio("http://example.test/a.mp4", "en", codec=Audio.Codec.AAC)
track.path = tmp_path / "a.mp4"
track.path.write_bytes(b"audio")
with pytest.raises(subprocess.CalledProcessError, match=r"^FFmpeg failed \(exit 1\): No space left on device; "):
track.repackage()
@POSIX_STUBS
def test_a_subtitleedit_failure_names_the_reason_it_wrote_to_stdout(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
monkeypatch.setattr(binaries, "SubtitleEdit", stub(tmp_path, "SubtitleEdit", "echo 'Access is denied'; exit 1"))
src = tmp_path / "s.srt"
src.write_text("1\n00:00:01,000 --> 00:00:02,000\nhi\n")
with pytest.raises(subprocess.CalledProcessError, match=r"^SubtitleEdit failed \(exit 1\): Access is denied; "):
SubtitleEditBackend().convert(Subtitle.Codec.SubRip, src, Subtitle.Codec.WebVTT, tmp_path / "s.vtt")
@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]
@pytest.mark.parametrize(("stderr", "level"), [("bad MAX_PQ_LUMINANCE value", "DEBUG"), ("Invalid PPS index", "ERROR")])
def test_run_step_logs_a_handled_stderr_marker_at_debug(
debug_entries: Callable[[], list[dict]], stderr: str, level: str
) -> None:
with pytest.raises(RuntimeError, match=stderr):
run_step(exits(1, stderr=stderr), label="tool step", handled=("MAX_PQ_LUMINANCE",))
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"]
@POSIX_STUBS
def test_a_stream_without_hdr10plus_metadata_logs_no_error(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, debug_entries: Callable[[], list[dict]]
) -> None:
monkeypatch.setattr(config.directories, "temp", tmp_path)
tool = stub(tmp_path, "hdr10plus_tool", 'echo "File doesn\'t contain dynamic metadata, stopping." >&2; exit 1')
monkeypatch.setattr(hybrid_module, "HDR10PlusTool", tool)
hybrid = Hybrid.__new__(Hybrid)
hybrid.hdr10plus_file = "HDR10Plus.json"
with pytest.raises(hybrid_module.NoHDR10PlusMetadata):
hybrid.extract_hdr10plus(None) # type: ignore[arg-type]
assert "ERROR" not in levels(debug_entries(), None)
@pytest.mark.skipif(not (binaries.CCExtractor and binaries.FFMPEG), reason="needs ccextractor and FFmpeg")
@pytest.mark.parametrize("suffix", ["mp4", "ts"])
def test_a_video_without_captions_gives_no_cc_track(
tmp_path: Path, debug_entries: Callable[[], list[dict]], suffix: str
) -> None:
clip = tmp_path / f"v.{suffix}"
subprocess.run(
[binaries.FFMPEG, "-v", "error", "-f", "lavfi", "-i", "testsrc=size=320x240:rate=25", "-t", "2"]
+ ["-c:v", "mpeg4", clip],
check=True,
)
video = Video(url="", codec=Video.Codec.AVC, language="en", id_="v")
video.path = clip
assert video.ccextractor(track_id="cc", out_path=tmp_path / "cc.srt", language="en") is None
assert not (tmp_path / "cc.srt").exists()
assert "ERROR" not in levels(debug_entries())