fix(subprocess): log handled tool failures at debug and drop an empty ccextractor output

This commit is contained in:
imSp4rky
2026-12-02 15:57:11 -07:00
parent eeab646272
commit ce0babb4f2
7 changed files with 192 additions and 39 deletions
+110 -2
View File
@@ -1,5 +1,7 @@
import json
import subprocess
import sys
from collections.abc import Callable, Iterator
from pathlib import Path
from types import SimpleNamespace
@@ -7,12 +9,15 @@ 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, Subtitle
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_tool, tool_reason
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")
@@ -138,3 +143,106 @@ def test_an_mp4decrypt_failure_names_the_reason_and_keeps_the_key(
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())
+19 -5
View File
@@ -13,7 +13,22 @@ from unshackle.core.tracks import Video
from unshackle.core.tracks import video as video_module
def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
def no_captions_exit(args: list[Any]) -> subprocess.CompletedProcess:
"""ccextractor exits 2 when the input file is missing and 10 when it finds no captions."""
if not Path(args[-1]).exists():
raise subprocess.CalledProcessError(2, args)
raise subprocess.CalledProcessError(10, args)
def empty_output(args: list[Any]) -> subprocess.CompletedProcess:
Path(args[-2]).write_bytes(b"")
return subprocess.CompletedProcess(args, 0, b"", b"")
@pytest.mark.parametrize("ccextractor", [no_captions_exit, empty_output])
def test_no_captions_retries_on_the_repackaged_file(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch, ccextractor: Any
) -> None:
original = tmp_path / "v.mp4"
original.write_bytes(b"x")
repacked = tmp_path / "v_repack.mp4"
@@ -27,11 +42,9 @@ def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.M
inputs: list[Path] = []
def fake_run(args: list[Any], **_: Any) -> None:
def fake_run(args: list[Any], **_: Any) -> subprocess.CompletedProcess:
inputs.append(Path(args[-1]))
if not Path(args[-1]).exists():
raise subprocess.CalledProcessError(2, args) # ccextractor: no input file
raise subprocess.CalledProcessError(10, args) # ccextractor: no captions found
return ccextractor(args)
monkeypatch.setattr(video_module.binaries, "CCExtractor", Path("/usr/bin/ccextractor"))
monkeypatch.setattr(video_module.subprocess, "run", fake_run)
@@ -39,3 +52,4 @@ def test_retry_runs_on_the_repackaged_file(tmp_path: Path, monkeypatch: pytest.M
assert track.ccextractor("cc", tmp_path / "cc.srt", Language.get("en")) is None
assert inputs == [original, repacked]
assert not (tmp_path / "cc.srt").exists()