Files
unshackle/tests/core/test_plugin_devices.py
T

215 lines
8.2 KiB
Python

"""A DRM plugin's own device files and its default device: found from a folder or a zip, after the operator's files."""
from __future__ import annotations
import dataclasses
import zipfile
from pathlib import Path
from types import SimpleNamespace
from typing import Any
import pytest
from tests.drm_plugins import EXAMPLE, OTHER, ExampleDevice
from tests.remote.sessions import launch_session
from unshackle.commands.dl import dl
from unshackle.core import plugins
from unshackle.core.api import handlers, key_policy
from unshackle.core.api.key_policy import KeyPolicy
from unshackle.core.cdm import loader
from unshackle.core.config import config
from unshackle.core.plugins import load_folder
from unshackle.core.remote_protocol import Licensor
pytestmark = pytest.mark.unit
SOURCE = """from importlib import resources
from unshackle.core.plugins import DrmPlugin
PLUGIN = DrmPlugin(
id="example",
label="EXAMPLE",
licensing="local",
media="own",
mode="segment",
decrypt=lambda drm, src, dst: None,
device_suffix=".exd",
load_device=lambda path: path.read_bytes(),
devices=lambda: resources.files(__name__) / "devices",
default_device="EXAMPLE_DEFAULT",
)
"""
def bundled_folder(folder: Path) -> None:
path = folder / "bundled_pkg"
(path / "devices").mkdir(parents=True)
(path / "__init__.py").write_text(SOURCE, encoding="utf-8")
(path / "devices" / "EXAMPLE_DEFAULT.exd").write_bytes(b"bundled")
def bundled_zip(folder: Path) -> None:
with zipfile.ZipFile(folder / "bundled_pkg.zip", "w") as z:
z.writestr("bundled_pkg/__init__.py", SOURCE)
z.writestr("bundled_pkg/devices/EXAMPLE_DEFAULT.exd", b"bundled")
def folders(tmp_path: Path) -> SimpleNamespace:
return SimpleNamespace(remote_cdm=[], directories=SimpleNamespace(wvds=tmp_path / "wvds", prds=tmp_path / "prds"))
@pytest.mark.parametrize("make", [bundled_folder, bundled_zip], ids=["folder", "zip"])
def test_a_plugin_loads_its_bundled_device_from_a_folder_or_a_zip(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path, make: Any
) -> None:
make(tmp_path)
monkeypatch.setattr(plugins, "PLUGINS", load_folder(tmp_path))
device = loader.find_device("EXAMPLE_DEFAULT", folders(tmp_path))
assert device is not None and device.system == "example"
assert loader.load_local_cdm("EXAMPLE_DEFAULT", device.system, device.source) == b"bundled"
assert loader.find_device("EXAMPLE_OTHER", folders(tmp_path)) is None
assert loader.default_device("example") == "EXAMPLE_DEFAULT"
def test_an_operator_device_file_comes_before_the_bundled_one(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
bundled_folder(tmp_path)
monkeypatch.setattr(plugins, "PLUGINS", load_folder(tmp_path))
app_config = folders(tmp_path)
app_config.directories.prds.mkdir()
(app_config.directories.prds / "EXAMPLE_DEFAULT.exd").write_bytes(b"operator")
device = loader.find_device("EXAMPLE_DEFAULT", app_config)
assert device is not None and device.source == app_config.directories.prds / "EXAMPLE_DEFAULT.exd"
def test_devices_need_a_device_suffix() -> None:
with pytest.raises(ValueError, match="has devices but no device_suffix"):
dataclasses.replace(OTHER, default_device="EXAMPLE_DEFAULT")
@pytest.fixture
def bundled(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> Path:
"""EXAMPLE with its own devices EXAMPLE_DEFAULT (its default) and EXAMPLE_V3, and no operator device files."""
devices = tmp_path / "bundled"
devices.mkdir()
for name in ("EXAMPLE_DEFAULT", "EXAMPLE_V3"):
(devices / f"{name}.exd").write_bytes(name.encode())
example = dataclasses.replace(EXAMPLE, devices=lambda: devices, default_device="EXAMPLE_DEFAULT")
monkeypatch.setattr(plugins, "PLUGINS", {"example": example})
monkeypatch.setattr(config, "remote_cdm", [], raising=False)
monkeypatch.setattr(config, "cdm", {}, raising=False)
monkeypatch.setattr(config.directories, "wvds", tmp_path / "wvds")
monkeypatch.setattr(config.directories, "prds", tmp_path / "prds")
return tmp_path
def local_device(cdm: dict) -> str:
"""The name of the device ``dl`` gives the EXAMPLE service for the EXAMPLE plugin system."""
config.cdm = cdm
cmd = dl.__new__(dl)
cmd.vaults, cmd.service, cmd.profile, cmd.log = None, "EXAMPLE", None, SimpleNamespace(debug=lambda msg: None)
device = cmd.cdm_for("example")
assert isinstance(device, ExampleDevice)
return device.path.read_bytes().decode()
def server_device(cdm: dict) -> str:
"""The name of the device the server loads for the EXAMPLE plugin system."""
config.cdm = cdm
device = handlers.load_full_cdm("EXAMPLE", None, "example")
assert isinstance(device, ExampleDevice)
return device.path.read_bytes().decode()
@pytest.mark.parametrize("device", [local_device, server_device], ids=["local", "server"])
@pytest.mark.parametrize(
("cdm", "name"),
[
({}, "EXAMPLE_DEFAULT"),
({"default": "wv_other"}, "EXAMPLE_DEFAULT"),
({"EXAMPLE": {"widevine": "wv_other"}}, "EXAMPLE_DEFAULT"),
({"EXAMPLE": {"example": "EXAMPLE_V3"}}, "EXAMPLE_V3"),
({"EXAMPLE": "EXAMPLE_V3"}, "EXAMPLE_V3"),
],
ids=["no entry", "default entry of another system", "entry of another system", "plugin key", "device name"],
)
def test_a_service_gets_the_plugin_default_unless_its_entry_names_a_plugin_device(
monkeypatch: pytest.MonkeyPatch, bundled: Path, device: Any, cdm: dict, name: str
) -> None:
monkeypatch.setattr(loader, "find_device", wrap_unknown(loader.find_device))
load = loader.load_local_cdm
monkeypatch.setattr(
loader,
"load_local_cdm",
lambda n, s, p: SimpleNamespace(is_playready=False) if n[:3] == "wv_" else load(n, s, p),
)
assert device(cdm) == name
def wrap_unknown(find: Any) -> Any:
"""A ``wv_`` name is a Widevine device that the test never loads."""
return lambda name, app_config=None: (
loader.Device("widevine", Path(name)) if name.startswith("wv_") else find(name, app_config)
)
def test_an_operator_file_named_like_the_default_replaces_it(monkeypatch: pytest.MonkeyPatch, bundled: Path) -> None:
(bundled / "wvds").mkdir()
(bundled / "wvds" / "EXAMPLE_DEFAULT.exd").write_bytes(b"operator")
assert local_device({}) == "operator"
def test_an_api_key_cdm_entry_can_name_a_plugin_device(bundled: Path) -> None:
assert key_policy._identity_error("k", {"cdm": {"EXAMPLE": {"example": "EXAMPLE_V3"}}}, config) is None
assert "no example device named 'wv_other'" in str(
key_policy._identity_error("k", {"cdm": {"EXAMPLE": {"example": "wv_other"}}}, config)
)
@pytest.mark.parametrize(
("licensor", "grant", "served"),
[
(Licensor.SERVER_CDM, False, True),
(Licensor.NO_DEVICE, True, False),
(Licensor.CLIENT_DEVICE, True, False),
(None, True, True),
(None, False, False),
],
ids=["server cdm session", "vault session", "client device session", "list with grant", "list without grant"],
)
def test_a_served_service_gets_a_device_by_system_only_where_the_server_licenses(
monkeypatch: pytest.MonkeyPatch, licensor: Licensor | None, grant: bool, served: bool
) -> None:
seen: dict = {}
loads: list = []
def instantiate(parent_ctx: Any, *a: Any) -> Any:
seen["ctx"] = parent_ctx
return SimpleNamespace(authenticate=lambda cookies, credential: None)
monkeypatch.setattr(key_policy, "load_service_config", lambda tag: {})
monkeypatch.setattr(handlers, "resolve_handler_proxy", lambda *a: (None, []))
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: loads.append(a[:3]))
monkeypatch.setattr(handlers.Services, "load", lambda tag: SimpleNamespace())
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
monkeypatch.setattr(handlers, "request_policy", lambda request: KeyPolicy({"server_cdm": grant}))
if licensor is None:
handlers.launch_served(handlers.LIST, {}, "EXAMPLE", "t", None)
else:
launch_session("EXAMPLE", "t", {}, licensor=licensor)
cdm_for = seen["ctx"].obj.cdm_for
before = list(loads)
gives = cdm_for("example") if cdm_for else None
assert (loads[len(before) :] == [("EXAMPLE", None, "example")]) == served
if not served:
assert gives is None