forked from kenzuya/unshackle
159 lines
6.7 KiB
Python
159 lines
6.7 KiB
Python
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
|