forked from kenzuya/unshackle
fix(subprocess): name the tool, exit and reason in external-tool errors
This commit is contained in:
@@ -120,7 +120,7 @@ def test_a_missing_decrypter_is_a_drm_error(monkeypatch: pytest.MonkeyPatch) ->
|
||||
monkeypatch.setattr(binaries, "Mp4decrypt", None)
|
||||
monkeypatch.setattr(binaries, "ShakaPackager", None)
|
||||
assert code_of(lambda: decrypters.mp4decrypt(Path("x.mp4"), lambda kids: [])) == APIErrorCode.DRM_ERROR
|
||||
assert code_of(lambda: decrypters.shaka_decrypt(Path("x.mp4"), "", "Widevine")) == APIErrorCode.DRM_ERROR
|
||||
assert code_of(lambda: decrypters.shaka_decrypt(Path("x.mp4"), "")) == APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
def http_failure(status: Any) -> requests.ConnectionError:
|
||||
|
||||
@@ -14,6 +14,7 @@ from tests.core.test_kid_windows import A, B, box, clear_audio, encv, moof, movi
|
||||
from tests.core.test_zero_kid_fallback import _playready, _widevine
|
||||
from tests.test_segment_decrypt import read_argv
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core.api.errors import categorize_exception
|
||||
from unshackle.core.config import config
|
||||
from unshackle.core.drm import ClearKeyCENC
|
||||
from unshackle.core.drm import decrypters as decrypters_module
|
||||
@@ -21,6 +22,7 @@ from unshackle.core.drm.decrypters import mp4decrypt_or_shaka
|
||||
from unshackle.core.drm.key_args import shaka_noise, track_key_args
|
||||
from unshackle.core.drm.segment_decrypt import SegmentDecrypter, can_use
|
||||
from unshackle.core.drm.verify import kidless_track_kids
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
|
||||
KEY = "b5df2ae3f63b8dda9049d6e41422e075"
|
||||
OTHER_KEY = "11" * 16
|
||||
@@ -251,59 +253,55 @@ class FakePackager:
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_packager(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> list[str]:
|
||||
"""Route shaka-packager to ``FakePackager`` and collect what the console prints."""
|
||||
printed: list[str] = []
|
||||
def fake_packager(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Route shaka-packager to ``FakePackager``."""
|
||||
FakePackager.code, FakePackager.log = 0, ""
|
||||
monkeypatch.setattr(decrypters_module.subprocess, "Popen", FakePackager)
|
||||
monkeypatch.setattr(binaries, "ShakaPackager", Path("packager"))
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
monkeypatch.setattr(decrypters_module.console, "log", lambda text: printed.append(str(text)))
|
||||
return printed
|
||||
|
||||
|
||||
def shaka_run(tmp_path: Path, make: Callable[[], Any], raises: type[BaseException]) -> None:
|
||||
"""Decrypt a one-key track of ``make()`` through ``FakePackager`` and expect ``raises``."""
|
||||
def shaka_run(tmp_path: Path, make: Callable[[], Any], raises: type[BaseException]) -> BaseException:
|
||||
"""Decrypt a one-key track of ``make()`` through ``FakePackager`` and return the ``raises`` it raised."""
|
||||
path = tmp_path / "track.mp4"
|
||||
path.write_bytes(b"encrypted")
|
||||
drm = make()
|
||||
drm.content_keys[A] = KEY
|
||||
with pytest.raises(raises):
|
||||
with pytest.raises(raises) as caught:
|
||||
drm.decrypt_with_shaka_packager(path)
|
||||
assert path.read_bytes() == b"encrypted"
|
||||
return caught.value
|
||||
|
||||
|
||||
@pytest.mark.parametrize("make", DRMS)
|
||||
def test_every_drm_passes_the_fake_clock(tmp_path: Path, fake_packager: list[str], make: Callable[[], Any]) -> None:
|
||||
@pytest.mark.usefixtures("fake_packager")
|
||||
def test_every_drm_passes_the_fake_clock(tmp_path: Path, make: Callable[[], Any]) -> None:
|
||||
shaka_run(tmp_path, make, FileNotFoundError)
|
||||
assert "--use_fake_clock_for_muxer" in FakePackager.argv
|
||||
|
||||
|
||||
def test_clearkey_gives_no_zero_kid_fallback(tmp_path: Path, fake_packager: list[str]) -> None:
|
||||
@pytest.mark.usefixtures("fake_packager")
|
||||
def test_clearkey_gives_no_zero_kid_fallback(tmp_path: Path) -> None:
|
||||
shaka_run(tmp_path, lambda: ClearKeyCENC(kids=[A]), FileNotFoundError)
|
||||
assert FakePackager.argv[FakePackager.argv.index("--keys") + 1] == f"label=0:key_id={A.hex}:key={KEY}"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("make", "label"),
|
||||
[
|
||||
pytest.param(lambda: _widevine(A), "Widevine", id="widevine"),
|
||||
pytest.param(lambda: _playready(A), "PlayReady", id="playready"),
|
||||
pytest.param(lambda: ClearKeyCENC(kids=[A]), "ClearKey", id="clearkey"),
|
||||
],
|
||||
)
|
||||
def test_a_shaka_failure_logs_under_the_drm_label(
|
||||
tmp_path: Path, fake_packager: list[str], make: Callable[[], Any], label: str
|
||||
) -> None:
|
||||
FakePackager.code, FakePackager.log = 1, "[1103/153702:ERROR:main.cc(1)] Bad key\n"
|
||||
shaka_run(tmp_path, make, subprocess.CalledProcessError)
|
||||
assert len(fake_packager) == 1 and f"[{label}]: " in fake_packager[0] and "Bad key" in fake_packager[0]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("fake_packager")
|
||||
@pytest.mark.parametrize("make", DRMS)
|
||||
def test_a_skipped_shaka_stream_keeps_the_input(
|
||||
tmp_path: Path, fake_packager: list[str], make: Callable[[], Any]
|
||||
) -> None:
|
||||
def test_a_shaka_failure_names_the_reason_and_keeps_the_key(tmp_path: Path, make: Callable[[], Any]) -> None:
|
||||
FakePackager.code = 2
|
||||
FakePackager.log = (
|
||||
"I1103 15:37:02 demuxer.cc(89)] Demuxer::Run()\n[1103/153702:ERROR:main.cc(1)] Packaging Error: 5\n"
|
||||
)
|
||||
error = shaka_run(tmp_path, make, subprocess.CalledProcessError)
|
||||
assert str(error).startswith("shaka-packager failed (exit 2): Packaging Error: 5; command: ")
|
||||
assert KEY in str(error) and "Demuxer" not in str(error)
|
||||
assert categorize_exception(error).error_code == APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("fake_packager")
|
||||
@pytest.mark.parametrize("make", DRMS)
|
||||
def test_a_skipped_shaka_stream_keeps_the_input(tmp_path: Path, make: Callable[[], Any]) -> None:
|
||||
FakePackager.log = (
|
||||
"[1128/120000:INFO:mp4_muxer.cc(1)] Skip stream 'track_decrypted.mp4' which does not contain any sample.\n"
|
||||
)
|
||||
@@ -320,7 +318,8 @@ def test_a_skipped_shaka_stream_keeps_the_input(
|
||||
assert not stray.exists()
|
||||
|
||||
|
||||
def test_a_shaka_ctrl_c_exit_is_a_keyboard_interrupt(tmp_path: Path, fake_packager: list[str]) -> None:
|
||||
@pytest.mark.usefixtures("fake_packager")
|
||||
def test_a_shaka_ctrl_c_exit_is_a_keyboard_interrupt(tmp_path: Path) -> None:
|
||||
FakePackager.code = 0xC000013A
|
||||
shaka_run(tmp_path, lambda: _widevine(A), KeyboardInterrupt)
|
||||
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import subprocess
|
||||
import sys
|
||||
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.drm import decrypters
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.tracks import Audio, Subtitle
|
||||
from unshackle.core.tracks.subtitle_convert import SubtitleEditBackend
|
||||
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"
|
||||
|
||||
|
||||
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_malformed_aac_repackage_retries_with_the_adts_filter(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
script = (
|
||||
'case "$*" in *aac_adtstoasc*) for last; do :; done; echo ok > "$last"; exit 0;; esac\n'
|
||||
"echo 'Malformed AAC bitstream detected' >&2; exit 1"
|
||||
)
|
||||
monkeypatch.setattr(binaries, "FFMPEG", stub(tmp_path, "ffmpeg", script))
|
||||
track = Audio("http://example.test/a.mp4", "en", codec=Audio.Codec.AAC)
|
||||
track.path = tmp_path / "a.mp4"
|
||||
track.path.write_bytes(b"audio")
|
||||
|
||||
track.repackage()
|
||||
|
||||
assert track.path == tmp_path / "a_repack.mp4" and track.path.read_text() == "ok\n"
|
||||
|
||||
|
||||
@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
|
||||
Reference in New Issue
Block a user