mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-26 19:05:13 +00:00
fix(api): let a core failure name its own API error code
This commit is contained in:
@@ -0,0 +1,158 @@
|
||||
"""Each core raiser names its own API error code, so a reworded message keeps the code."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from typing import Any, Callable, Optional
|
||||
|
||||
import click
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from unshackle.core import binaries
|
||||
from unshackle.core import service as service_mod
|
||||
from unshackle.core.api.errors import categorize_exception
|
||||
from unshackle.core.api.input_bridge import InputBridge, NoUserBridge
|
||||
from unshackle.core.drm import ClearKeyCENC, MonaLisa, PlayReady, Widevine, decrypters
|
||||
from unshackle.core.import_service import ImportService, manifest_fetch_error
|
||||
from unshackle.core.proxies.gluetun import Gluetun
|
||||
from unshackle.core.proxies.nordvpn import NordVPN
|
||||
from unshackle.core.proxies.resolve import Unavailable, find_provider, pick_proxy
|
||||
from unshackle.core.proxies.surfsharkvpn import SurfsharkVPN
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.service import Service
|
||||
from unshackle.core.utils import ip_info, run_proxy
|
||||
|
||||
|
||||
def code_of(call: Callable[[], Any]) -> Optional[APIErrorCode]:
|
||||
"""The code the raised exception names itself, not the one its message would give."""
|
||||
with pytest.raises(BaseException) as caught:
|
||||
call()
|
||||
return getattr(caught.value, "error_code", None)
|
||||
|
||||
|
||||
def test_a_login_email_for_a_vpn_provider_is_a_proxy_error() -> None:
|
||||
assert code_of(lambda: NordVPN("user@example.com", "secret")) == APIErrorCode.INVALID_PROXY
|
||||
assert code_of(lambda: SurfsharkVPN("user@example.com", "secret")) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
def test_gluetun_without_docker_is_a_proxy_error(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(binaries, "Docker", None)
|
||||
assert code_of(Gluetun) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
def test_a_provider_that_failed_to_load_or_is_unknown_is_a_proxy_error() -> None:
|
||||
providers = [Unavailable("NordVPN", ValueError("bad credentials"))]
|
||||
assert code_of(lambda: find_provider(providers, "nordvpn")) == APIErrorCode.INVALID_PROXY
|
||||
assert code_of(lambda: find_provider(providers, "other")) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
def test_a_query_no_provider_answers_is_a_proxy_error() -> None:
|
||||
assert code_of(lambda: pick_proxy([], "gb")) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxied, failures", [(None, 99), ({"ip": "1.1.1.1", "country": "gb"}, 0)])
|
||||
def test_a_failed_proxy_check_is_a_proxy_error(monkeypatch: pytest.MonkeyPatch, proxied: Any, failures: int) -> None:
|
||||
def lookup(session: Any = None, cached: bool = False, errors: Any = None) -> Any:
|
||||
if errors is not None:
|
||||
errors.extend(OSError("refused") for _ in range(failures))
|
||||
return proxied if session is not None and not cached else {"ip": "1.1.1.1"}
|
||||
|
||||
monkeypatch.setattr(ip_info, "get_ip_info", lookup)
|
||||
assert code_of(lambda: ip_info.verify_proxy_exit(SimpleNamespace())) == APIErrorCode.INVALID_PROXY
|
||||
|
||||
|
||||
class Blocked(Service):
|
||||
GEOBLOCK = ("gb",)
|
||||
|
||||
def get_titles(self): # type: ignore[no-untyped-def]
|
||||
raise NotImplementedError
|
||||
|
||||
def get_tracks(self, title): # type: ignore[no-untyped-def]
|
||||
raise NotImplementedError
|
||||
|
||||
def get_chapters(self, title): # type: ignore[no-untyped-def]
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
@pytest.mark.parametrize("proxy", [None, "https://u:p@chosen.example:89"], ids=["own-region", "proxy-region"])
|
||||
def test_a_blocked_region_is_a_geofence_error(monkeypatch: pytest.MonkeyPatch, proxy: Optional[str]) -> None:
|
||||
monkeypatch.setattr(service_mod, "get_ip_info", lambda *args, **kwargs: {"country": "gb"})
|
||||
monkeypatch.setattr(service_mod, "verify_proxy_exit", lambda session: {"country": "gb"})
|
||||
monkeypatch.setattr(run_proxy, "watched", {})
|
||||
monkeypatch.setattr(run_proxy, "proxy_hosts", set())
|
||||
ctx = SimpleNamespace(
|
||||
obj=SimpleNamespace(config={}, proxy_providers=[]), parent=SimpleNamespace(params={"proxy": proxy})
|
||||
)
|
||||
assert code_of(lambda: Blocked(ctx)) == APIErrorCode.GEOFENCE # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_a_login_that_needs_an_absent_user_is_an_auth_error() -> None:
|
||||
assert code_of(lambda: NoUserBridge().request_input("Enter OTP")) == APIErrorCode.AUTH_FAILED
|
||||
assert code_of(NoUserBridge().ensure_active) == APIErrorCode.AUTH_FAILED
|
||||
assert code_of(lambda: InputBridge().request_input("Enter OTP", timeout=0.05)) == APIErrorCode.AUTH_FAILED
|
||||
|
||||
|
||||
def test_an_import_key_the_export_lacks_is_a_drm_error() -> None:
|
||||
assert ImportService.missing_key(SimpleNamespace(drm=None)).error_code == APIErrorCode.DRM_ERROR # type: ignore[arg-type,attr-defined]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"error",
|
||||
[
|
||||
Widevine.Exceptions.PSSHNotFound,
|
||||
Widevine.Exceptions.KIDNotFound,
|
||||
PlayReady.Exceptions.PSSHNotFound,
|
||||
PlayReady.Exceptions.KIDNotFound,
|
||||
PlayReady.Exceptions.DeviceRevoked,
|
||||
ClearKeyCENC.Exceptions.KIDNotFound,
|
||||
MonaLisa.Exceptions.TicketNotFound,
|
||||
MonaLisa.Exceptions.KeyExtractionFailed,
|
||||
],
|
||||
)
|
||||
def test_a_drm_exception_class_is_a_drm_error(error: type[Exception]) -> None:
|
||||
assert categorize_exception(error("PSSH was not found in track data.")).error_code == APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
def test_a_missing_decrypter_is_a_drm_error(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
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
|
||||
|
||||
|
||||
def http_failure(status: Any) -> requests.ConnectionError:
|
||||
return requests.ConnectionError("Failed to request the MPD document.", response=SimpleNamespace(status_code=status))
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"failure, code",
|
||||
[
|
||||
(http_failure(404), APIErrorCode.NOT_FOUND),
|
||||
(http_failure(410), APIErrorCode.NOT_FOUND),
|
||||
(http_failure(429), APIErrorCode.RATE_LIMITED),
|
||||
(http_failure(503), APIErrorCode.SERVICE_UNAVAILABLE),
|
||||
(http_failure(403), None),
|
||||
(http_failure(SimpleNamespace()), None),
|
||||
(requests.ConnectionError("dns"), None),
|
||||
],
|
||||
ids=["404", "410", "429", "503", "403", "not-a-status", "no-answer"],
|
||||
)
|
||||
def test_a_manifest_fetch_failure_is_coded_from_an_unambiguous_status(
|
||||
failure: Exception, code: Optional[APIErrorCode]
|
||||
) -> None:
|
||||
error = manifest_fetch_error("DASH", "Example Movie", failure)
|
||||
assert isinstance(error, click.ClickException) and "may have expired" in error.message
|
||||
assert getattr(error, "error_code", None) == code
|
||||
|
||||
|
||||
def test_a_manifest_fetch_failure_names_the_http_status() -> None:
|
||||
assert "(HTTP 403)" in manifest_fetch_error("DASH", "Example Movie", http_failure(403)).message
|
||||
|
||||
|
||||
def test_a_manifest_status_behind_exhausted_retries_is_read_from_the_cause() -> None:
|
||||
exhausted = RuntimeError("Max retries exceeded")
|
||||
exhausted.__cause__ = http_failure(503)
|
||||
error = manifest_fetch_error("DASH", "Example Movie", exhausted)
|
||||
assert "(HTTP 503)" in error.message and getattr(error, "error_code", None) == APIErrorCode.SERVICE_UNAVAILABLE
|
||||
@@ -6,6 +6,7 @@ import pytest
|
||||
|
||||
from unshackle.core import console
|
||||
from unshackle.core.api.input_bridge import NO_USER_MESSAGE, InputBridge, NoUserBridge
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.service import Service
|
||||
|
||||
|
||||
@@ -19,8 +20,9 @@ def test_returns_the_first_value_check_gives():
|
||||
|
||||
|
||||
def test_times_out_when_check_never_gives_a_value():
|
||||
with pytest.raises(TimeoutError):
|
||||
with pytest.raises(TimeoutError) as caught:
|
||||
Service.wait_for_approval(_service(), "enter code", lambda: None, timeout=0.05, interval=0.01)
|
||||
assert caught.value.error_code is APIErrorCode.AUTH_FAILED
|
||||
|
||||
|
||||
def test_stops_when_the_remote_session_is_cancelled():
|
||||
@@ -58,7 +60,6 @@ def test_a_request_with_no_user_fails_at_once():
|
||||
|
||||
def test_no_user_message_is_an_authentication_error():
|
||||
from unshackle.core.api.errors import categorize_exception
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
|
||||
assert categorize_exception(RuntimeError(NO_USER_MESSAGE)).error_code == APIErrorCode.AUTH_FAILED
|
||||
|
||||
|
||||
@@ -404,6 +404,7 @@ def test_a_prompt_discards_an_answer_sent_before_it(tmp_path: Path, monkeypatch:
|
||||
finally:
|
||||
set_prompt_handler(None)
|
||||
assert categorize_exception(exc_info.value).error_code is APIErrorCode.AUTH_FAILED
|
||||
assert exc_info.value.error_code is APIErrorCode.AUTH_FAILED # type: ignore[attr-defined]
|
||||
|
||||
|
||||
def test_concurrent_prompts_go_out_one_at_a_time(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
|
||||
@@ -7,7 +7,7 @@ import json
|
||||
import pytest
|
||||
|
||||
from unshackle.core.api.errors import APIError, build_error_response, categorize_exception, handle_api_exception
|
||||
from unshackle.core.remote_protocol import APIErrorCode
|
||||
from unshackle.core.remote_protocol import APIErrorCode, coded
|
||||
|
||||
pytestmark = pytest.mark.unit
|
||||
|
||||
@@ -225,3 +225,71 @@ def test_categorize_system_exit_is_a_service_error() -> None:
|
||||
err = categorize_exception(SystemExit(1), {"service": "EXAMPLE"})
|
||||
assert err.error_code == APIErrorCode.SERVICE_ERROR
|
||||
assert err.message == "Service EXAMPLE exited"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"code, message",
|
||||
[
|
||||
(APIErrorCode.GEOFENCE, "login token expired"),
|
||||
(APIErrorCode.INVALID_PROXY, "region not available in GB"),
|
||||
(APIErrorCode.AUTH_FAILED, "read timeout"),
|
||||
(APIErrorCode.NETWORK_ERROR, "license refused"),
|
||||
(APIErrorCode.NOT_FOUND, "the proxy failed"),
|
||||
(APIErrorCode.RATE_LIMITED, "not found"),
|
||||
(APIErrorCode.DRM_ERROR, "proxy check failed"),
|
||||
(APIErrorCode.SERVICE_UNAVAILABLE, "invalid input"),
|
||||
(APIErrorCode.SERVICE_ERROR, "Docker not found"),
|
||||
(APIErrorCode.INTERNAL_ERROR, "connection refused"),
|
||||
],
|
||||
)
|
||||
def test_a_coded_exception_keeps_its_code_whatever_its_message_says(code: APIErrorCode, message: str) -> None:
|
||||
err = categorize_exception(coded(RuntimeError(message), code), {"service": "EXAMPLE"})
|
||||
assert err.error_code == code
|
||||
assert err.retryable is (
|
||||
code in {APIErrorCode.NETWORK_ERROR, APIErrorCode.RATE_LIMITED, APIErrorCode.SERVICE_UNAVAILABLE}
|
||||
)
|
||||
assert err.message.endswith(message) and err.details["service"] == "EXAMPLE"
|
||||
|
||||
|
||||
def test_a_coded_exception_gets_the_message_prefix_of_its_keyword_twin() -> None:
|
||||
coded_err = categorize_exception(coded(ValueError("Service is not available in GB"), APIErrorCode.GEOFENCE))
|
||||
guessed = categorize_exception(ValueError("Service is not available in GB"))
|
||||
assert (coded_err.message, coded_err.details) == (guessed.message, guessed.details)
|
||||
|
||||
|
||||
def test_a_coded_cause_names_the_code_of_its_wrapper() -> None:
|
||||
try:
|
||||
try:
|
||||
raise coded(ValueError("bad"), APIErrorCode.INVALID_PROXY)
|
||||
except ValueError as e:
|
||||
raise RuntimeError("license step failed") from e
|
||||
except RuntimeError as wrapper:
|
||||
err = categorize_exception(wrapper)
|
||||
assert err.error_code == APIErrorCode.INVALID_PROXY
|
||||
assert err.message.endswith("bad")
|
||||
|
||||
|
||||
def test_the_wrapper_code_wins_over_the_cause_code() -> None:
|
||||
try:
|
||||
try:
|
||||
raise coded(ValueError("bad"), APIErrorCode.INVALID_PROXY)
|
||||
except ValueError as e:
|
||||
raise coded(RuntimeError("outer"), APIErrorCode.DRM_ERROR) from e
|
||||
except RuntimeError as wrapper:
|
||||
assert categorize_exception(wrapper).error_code == APIErrorCode.DRM_ERROR
|
||||
|
||||
|
||||
def test_an_error_code_that_is_no_api_code_falls_back_to_the_keywords() -> None:
|
||||
exc = RuntimeError("Connection refused")
|
||||
exc.error_code = 104 # type: ignore[attr-defined]
|
||||
assert categorize_exception(exc).error_code == APIErrorCode.NETWORK_ERROR
|
||||
|
||||
|
||||
def test_a_system_exit_stays_a_service_error_whatever_its_cause_names() -> None:
|
||||
try:
|
||||
try:
|
||||
raise coded(ValueError("bad"), APIErrorCode.INVALID_PROXY)
|
||||
except ValueError as e:
|
||||
raise SystemExit(1) from e
|
||||
except SystemExit as exit_:
|
||||
assert categorize_exception(exit_).error_code == APIErrorCode.SERVICE_ERROR
|
||||
|
||||
Reference in New Issue
Block a user