491 lines
26 KiB
Python
491 lines
26 KiB
Python
"""Offline regression checks for CLI boundaries; no production stream is invoked."""
|
|
|
|
from contextlib import redirect_stderr, redirect_stdout
|
|
import hashlib
|
|
import importlib.util
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import types
|
|
import unittest
|
|
from unittest.mock import Mock, patch
|
|
|
|
|
|
sys.dont_write_bytecode = True
|
|
ROOT = Path(__file__).resolve().parents[2]
|
|
SCRIPTS = ROOT / "scripts"
|
|
sys.path.insert(0, str(SCRIPTS))
|
|
|
|
|
|
def load_script(name, path):
|
|
spec = importlib.util.spec_from_file_location(name, path)
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
video = load_script("phase1_video", SCRIPTS / "proxer-dl-video.py")
|
|
series = load_script("phase1_series", SCRIPTS / "proxer-dl-series.py")
|
|
import request_validation as validation
|
|
|
|
|
|
def protected_snapshot():
|
|
return {str(path.relative_to(ROOT)): hashlib.sha256(path.read_bytes()).hexdigest()
|
|
for path in (SCRIPTS / "lib").rglob("*") if path.is_file()}
|
|
|
|
|
|
class ValidationTests(unittest.TestCase):
|
|
def test_cookie_preserves_equals_in_value(self):
|
|
self.assertEqual(validation.parse_token("FixtureCookie=base64=="), ("FixtureCookie", "base64=="))
|
|
|
|
def test_stdin_cookie_preserves_equals_and_accepts_one_line(self):
|
|
args = types.SimpleNamespace(token_stdin=True, token=None)
|
|
for ending in ("", "\n", "\r\n"):
|
|
with self.subTest(ending=ending):
|
|
self.assertEqual(validation.token_from_args(args, io.StringIO("FixtureCookie=base64==" + ending)),
|
|
("FixtureCookie", "base64=="))
|
|
|
|
def test_stdin_cookie_rejects_extra_lines_controls_and_overflow(self):
|
|
args = types.SimpleNamespace(token_stdin=True, token=None)
|
|
for value in ("FixtureCookie=abc\nsecond\n", "FixtureCookie=abc\n\n", "FixtureCookie=a\x00b\n",
|
|
"FixtureCookie=a\x80b\n", "a=" + "b" * 8191 + "\n"):
|
|
with self.subTest(length=len(value)), self.assertRaises(validation.ValidationError):
|
|
validation.token_from_args(args, io.StringIO(value))
|
|
|
|
def test_token_length_boundary_and_invalid_utf8(self):
|
|
args = types.SimpleNamespace(token_stdin=True, token=None)
|
|
value = "a=" + "b" * 8190
|
|
self.assertEqual(validation.token_from_args(args, io.StringIO(value + "\n")), ("a", "b" * 8190))
|
|
with self.assertRaises(validation.ValidationError):
|
|
validation.token_from_args(args, io.BytesIO(b"a=\xff\n"))
|
|
with self.assertRaises(validation.ValidationError):
|
|
validation.parse_token(value + "b")
|
|
|
|
def test_invalid_cookies_are_rejected(self):
|
|
for token in ("", "name", "=value", "name=", "bad name=value", "name=a\nb", "name=a;b", "name=a b"):
|
|
with self.subTest(token=token), self.assertRaises(validation.ValidationError):
|
|
validation.parse_token(token)
|
|
|
|
def test_canonical_watch_url(self):
|
|
self.assertEqual(validation.validate_watch_url("https://www.proxer.me:443/watch/123/9/engsub/#details"),
|
|
"https://proxer.me/watch/123/9/engsub")
|
|
|
|
def test_watch_url_length_is_bounded(self):
|
|
base = "https://proxer.me/watch/123/1/engsub#"
|
|
self.assertEqual(validation.validate_watch_url(base + "x" * (2048 - len(base))),
|
|
"https://proxer.me/watch/123/1/engsub")
|
|
with self.assertRaises(validation.ValidationError):
|
|
validation.validate_watch_url(base + "x" * (2049 - len(base)))
|
|
|
|
def test_unsupported_or_ambiguous_urls_are_rejected(self):
|
|
for url in ("http://proxer.me/watch/123/1/engsub", "https://proxer.me.evil.invalid/watch/123/1/engsub",
|
|
"https://user:password@proxer.me/watch/123/1/engsub", "https://proxer.me:8443/watch/123/1/engsub",
|
|
"https://proxer.me/watch/123/1/engsub?cookie=secret", "https://proxer.me/watch/0/1/engsub",
|
|
"https://proxer.me/watch/123/0/engsub", "https://proxer.me/watch/123/1/de",
|
|
"https://proxer.me/watch/123/1/engsub\n", "https://proxer.me/watch/9007199254740992/1/engsub"):
|
|
with self.subTest(url=url), self.assertRaises(validation.ValidationError):
|
|
validation.validate_watch_url(url)
|
|
|
|
def test_unsafe_filenames_are_rejected(self):
|
|
for filename in ("", ".", "..", "../outside", "nested/name", "nested\\name", "nul\x00name", "line\nname", " leading", "trailing "):
|
|
with self.subTest(filename=filename), self.assertRaises(validation.ValidationError):
|
|
validation.validate_filename(filename)
|
|
self.assertEqual(validation.validate_filename("A safe 日本語 name S01E02"), "A safe 日本語 name S01E02")
|
|
|
|
def test_filename_limit_counts_utf8_bytes_and_extension(self):
|
|
self.assertEqual(validation.validate_filename("a" * 251), "a" * 251)
|
|
for filename in ("a" * 252, "日" * 84):
|
|
with self.subTest(filename=filename), self.assertRaises(validation.ValidationError):
|
|
validation.validate_filename(filename)
|
|
|
|
def test_ranges_are_inclusive_bounded_and_strict(self):
|
|
with patch.dict(os.environ, {"MAX_SERIES_EPISODES": "2"}):
|
|
self.assertEqual(validation.episode_range("9-10"), (9, 10))
|
|
for value in ("1-3", "3-2", "0-2", "1.0-2", "1-2-3", "1-", "1e1-12", "1-9007199254740992"):
|
|
with self.subTest(value=value), self.assertRaises(validation.ValidationError):
|
|
validation.episode_range(value)
|
|
|
|
def test_default_range_limit_is_500(self):
|
|
with patch.dict(os.environ, {}, clear=True):
|
|
self.assertEqual(validation.episode_range("1-500"), (1, 500))
|
|
with self.assertRaises(validation.ValidationError):
|
|
validation.episode_range("1-501")
|
|
|
|
def test_bad_range_configuration_is_a_validation_error(self):
|
|
with patch.dict(os.environ, {"MAX_SERIES_EPISODES": "unlimited"}), self.assertRaises(validation.ValidationError):
|
|
validation.episode_range("1-2")
|
|
|
|
def test_series_configuration_matches_shared_limit(self):
|
|
for value in ("0", "10001", "9" * 5000):
|
|
with self.subTest(length=len(value)), patch.dict(os.environ, {"MAX_SERIES_EPISODES": value}), self.assertRaises(validation.ValidationError):
|
|
validation.episode_range("1-2")
|
|
for value in ("10000", "00002", ""):
|
|
with self.subTest(value=value), patch.dict(os.environ, {"MAX_SERIES_EPISODES": value}):
|
|
self.assertEqual(validation.episode_range("1-2"), (1, 2))
|
|
|
|
def test_oversized_integer_is_rejected_without_conversion_failure(self):
|
|
with self.assertRaises(validation.ValidationError):
|
|
validation.positive_integer("9" * 5000, "Series ID")
|
|
|
|
def test_authentication_requires_status_evidence_not_message_keywords(self):
|
|
error = RuntimeError("filename token-captcha-403-blocked.mp4")
|
|
self.assertEqual(validation.error_result(error)["errorCategory"], "unknown")
|
|
error.response = types.SimpleNamespace(status_code=403)
|
|
self.assertEqual(validation.error_result(error)["errorCategory"], "authentication")
|
|
|
|
def test_chained_authentication_error_is_recognized_without_secret_output(self):
|
|
cause = RuntimeError("https://signed.invalid/file?token=DO_NOT_LOG")
|
|
cause.response = types.SimpleNamespace(status_code=401)
|
|
outer = RuntimeError("wrapped DO_NOT_LOG")
|
|
outer.__context__ = cause
|
|
result = validation.error_result(outer)
|
|
self.assertEqual(result["errorCategory"], "authentication")
|
|
self.assertNotIn("DO_NOT_LOG", json.dumps(result))
|
|
|
|
def test_resolution_requires_exact_library_exception_metadata(self):
|
|
unrelated_not_found = type("NotFoundError", (Exception,), {"__module__": "unrelated_library"})
|
|
for error in (unrelated_not_found("DO_NOT_LOG"), RuntimeError("Embed code not found captcha DO_NOT_LOG")):
|
|
with self.subTest(error_type=type(error)):
|
|
result = validation.error_result(error)
|
|
self.assertEqual(result["errorCategory"], "unknown")
|
|
self.assertNotIn("DO_NOT_LOG", json.dumps(result))
|
|
|
|
|
|
class DownloadTests(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.original_protected = protected_snapshot()
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
if protected_snapshot() != cls.original_protected:
|
|
raise AssertionError("The protected library tree changed during Python tests.")
|
|
|
|
def setUp(self):
|
|
self.temporary = tempfile.TemporaryDirectory(prefix="proxer-phase1-")
|
|
self.addCleanup(self.temporary.cleanup)
|
|
self.output = Path(self.temporary.name)
|
|
package = types.ModuleType("lib")
|
|
package.__path__ = []
|
|
self.library = types.ModuleType("lib.proxer_utils")
|
|
self.library.NetworkError = type("NetworkError", (Exception,), {"__module__": "lib.proxer_utils"})
|
|
self.library.NotFoundError = type("NotFoundError", (Exception,), {"__module__": "lib.proxer_utils"})
|
|
self.library.get_embed_url = Mock(return_value="https://signed.invalid/embed?token=DO_NOT_LOG")
|
|
self.library.get_mp4_url = Mock(return_value="https://signed.invalid/video?token=DO_NOT_LOG")
|
|
self.library.download_mp4 = Mock(side_effect=lambda url, target, label: Path(target).write_bytes(b"synthetic media fixture"))
|
|
self.module_patch = patch.dict(sys.modules, {"lib": package, "lib.proxer_utils": self.library})
|
|
self.module_patch.start()
|
|
self.addCleanup(self.module_patch.stop)
|
|
self.sleep_patch = patch.object(series, "sleep")
|
|
self.sleep_patch.start()
|
|
self.addCleanup(self.sleep_patch.stop)
|
|
self.env_patch = patch.dict(os.environ, {"MAX_SERIES_EPISODES": "500"})
|
|
self.env_patch.start()
|
|
self.addCleanup(self.env_patch.stop)
|
|
|
|
def video_args(self, **overrides):
|
|
values = {"url": "https://proxer.me/watch/999999999/2/engsub", "filename": "Fixture Video S01E02",
|
|
"token": "FixtureCookie=NOT_REAL==", "output": str(self.output)}
|
|
values.update(overrides)
|
|
return [part for key, value in values.items() for part in ("--" + key, value)]
|
|
|
|
def series_args(self, **overrides):
|
|
values = {"id": "999999999", "name": "Fixture Series", "episodes": "1-2", "language": "engsub",
|
|
"token": "FixtureCookie=NOT_REAL==", "output": str(self.output)}
|
|
values.update(overrides)
|
|
return [part for key, value in values.items() for part in ("--" + key, value)]
|
|
|
|
def invoke(self, entrypoint, args):
|
|
stdout, stderr = io.StringIO(), io.StringIO()
|
|
with redirect_stdout(stdout), redirect_stderr(stderr):
|
|
code = entrypoint.main(args)
|
|
records = [line[len(validation.RESULT_PREFIX):] for line in stdout.getvalue().splitlines()
|
|
if line.startswith(validation.RESULT_PREFIX)]
|
|
self.assertEqual(len(records), 1, stdout.getvalue())
|
|
self.assertNotIn("DO_NOT_LOG", stdout.getvalue() + stderr.getvalue())
|
|
self.assertNotIn("NOT_REAL", stdout.getvalue() + stderr.getvalue())
|
|
return code, json.loads(records[0]), stdout.getvalue()
|
|
|
|
def test_video_success_has_one_result_and_preserves_stream_order(self):
|
|
calls = Mock()
|
|
calls.attach_mock(self.library.get_embed_url, "embed")
|
|
calls.attach_mock(self.library.get_mp4_url, "media")
|
|
calls.attach_mock(self.library.download_mp4, "download")
|
|
code, result, _ = self.invoke(video, self.video_args())
|
|
self.assertEqual(code, 0)
|
|
self.assertEqual(result, {"version": 1, "status": "completed"})
|
|
self.assertEqual([item[0] for item in calls.mock_calls], ["embed", "media", "download"])
|
|
self.assertEqual(self.library.get_embed_url.call_args.args[1], ("FixtureCookie", "NOT_REAL=="))
|
|
self.assertTrue((self.output / "Fixture Video S01E02.mp4").is_file())
|
|
|
|
def test_resolver_failure_is_nonzero_and_requires_verification(self):
|
|
for resolver in (self.library.get_embed_url, self.library.get_mp4_url):
|
|
for wrapped in (False, True):
|
|
with self.subTest(resolver=resolver, wrapped=wrapped):
|
|
error = self.library.NotFoundError("https://signed.invalid/page?token=DO_NOT_LOG")
|
|
if wrapped:
|
|
outer = RuntimeError("wrapped DO_NOT_LOG")
|
|
outer.__cause__ = error
|
|
error = outer
|
|
resolver.side_effect = error
|
|
code, result, _ = self.invoke(video, self.video_args())
|
|
self.assertEqual(code, 1)
|
|
self.assertEqual(result["status"], "failed")
|
|
self.assertEqual(result["errorCategory"], "resolution")
|
|
self.assertIn("verification", result["message"])
|
|
self.assertNotIn("captcha", result["message"].lower())
|
|
self.library.download_mp4.assert_not_called()
|
|
resolver.side_effect = None
|
|
|
|
def test_wrapped_http_status_distinguishes_authentication_from_missing_source(self):
|
|
http_error = type("HTTPError", (Exception,), {"__module__": "requests.exceptions"})
|
|
for status, category in ((401, "authentication"), (403, "authentication"), (404, "source")):
|
|
with self.subTest(status=status):
|
|
cause = http_error("https://signed.invalid/page?token=DO_NOT_LOG")
|
|
cause.response = types.SimpleNamespace(status_code=status)
|
|
error = self.library.NetworkError("Failed to fetch episode page: DO_NOT_LOG")
|
|
error.__context__ = cause
|
|
self.library.get_embed_url.side_effect = error
|
|
code, result, _ = self.invoke(video, self.video_args())
|
|
self.assertEqual(code, 1)
|
|
self.assertEqual(result["errorCategory"], category)
|
|
self.library.download_mp4.assert_not_called()
|
|
|
|
def test_network_failure_is_not_automatically_authentication(self):
|
|
self.library.get_mp4_url.side_effect = self.library.NetworkError("captcha token 403 DO_NOT_LOG")
|
|
code, result, _ = self.invoke(video, self.video_args())
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual(result["errorCategory"], "network")
|
|
|
|
def test_transfer_failure_is_nonzero_even_when_an_old_file_exists(self):
|
|
(self.output / "Fixture Video S01E02.mp4").write_bytes(b"old output")
|
|
self.library.download_mp4.side_effect = RuntimeError("DO_NOT_LOG")
|
|
code, result, _ = self.invoke(video, self.video_args())
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual(result["status"], "failed")
|
|
|
|
def test_storage_failure_is_nonzero(self):
|
|
self.library.download_mp4.side_effect = PermissionError("DO_NOT_LOG")
|
|
code, result, _ = self.invoke(video, self.video_args())
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual(result["errorCategory"], "storage")
|
|
|
|
def test_missing_stream_dependency_is_configuration_failure(self):
|
|
for entrypoint, args in ((video, self.video_args()), (series, self.series_args())):
|
|
with self.subTest(entrypoint=entrypoint.__name__), patch.dict(sys.modules, {"lib.proxer_utils": None}):
|
|
code, result, _ = self.invoke(entrypoint, args)
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual(result["errorCategory"], "configuration")
|
|
self.library.get_embed_url.assert_not_called()
|
|
|
|
def test_dependency_import_error_never_exposes_exception_text(self):
|
|
self.library.get_embed_url.side_effect = ImportError("DO_NOT_LOG")
|
|
code, result, _ = self.invoke(video, self.video_args())
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual(result["errorCategory"], "configuration")
|
|
|
|
def test_missing_or_empty_output_is_not_success(self):
|
|
for make_empty in (False, True):
|
|
with self.subTest(make_empty=make_empty):
|
|
self.library.download_mp4.side_effect = lambda url, target, label: Path(target).touch() if make_empty else None
|
|
code, result, _ = self.invoke(video, self.video_args())
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual(result["errorCategory"], "storage")
|
|
|
|
def test_invalid_url_never_calls_protected_library(self):
|
|
code, result, _ = self.invoke(video, self.video_args(url="https://unrelated.invalid/watch/1/1/engsub"))
|
|
self.assertEqual(code, 2)
|
|
self.assertEqual(result["errorCategory"], "validation")
|
|
self.library.get_embed_url.assert_not_called()
|
|
|
|
def test_path_traversal_never_calls_protected_library(self):
|
|
code, result, _ = self.invoke(video, self.video_args(filename="../outside"))
|
|
self.assertEqual(code, 2)
|
|
self.assertEqual(result["errorCategory"], "validation")
|
|
self.library.get_embed_url.assert_not_called()
|
|
|
|
def test_missing_output_directory_is_not_created(self):
|
|
missing = self.output / "missing"
|
|
code, result, _ = self.invoke(video, self.video_args(output=str(missing)))
|
|
self.assertEqual(code, 1)
|
|
self.assertEqual(result["errorCategory"], "storage")
|
|
self.assertFalse(missing.exists())
|
|
|
|
def test_symlink_output_is_rejected_and_target_untouched(self):
|
|
outside = self.output / "other-file"
|
|
outside.write_bytes(b"must not change")
|
|
(self.output / "Fixture Video S01E02.mp4").symlink_to(outside)
|
|
code, result, _ = self.invoke(video, self.video_args())
|
|
self.assertEqual(code, 2)
|
|
self.assertEqual(result["errorCategory"], "validation")
|
|
self.assertEqual(outside.read_bytes(), b"must not change")
|
|
self.library.download_mp4.assert_not_called()
|
|
|
|
def test_nonregular_output_is_rejected(self):
|
|
(self.output / "Fixture Video S01E02.mp4").mkdir()
|
|
code, _, _ = self.invoke(video, self.video_args())
|
|
self.assertEqual(code, 2)
|
|
self.library.download_mp4.assert_not_called()
|
|
|
|
def test_invalid_cli_arguments_emit_safe_failure(self):
|
|
code, result, output = self.invoke(video, ["--unrecognized", "DO_NOT_LOG"])
|
|
self.assertEqual(code, 2)
|
|
self.assertEqual(result["errorCategory"], "validation")
|
|
self.assertNotIn("DO_NOT_LOG", output)
|
|
|
|
def test_video_stdin_token_uses_same_pipeline(self):
|
|
args = self.video_args()
|
|
position = args.index("--token")
|
|
args[position:position + 2] = ["--token-stdin"]
|
|
with patch.object(sys, "stdin", io.StringIO("FixtureCookie=NOT_REAL==\n")):
|
|
code, result, _ = self.invoke(video, args)
|
|
self.assertEqual(code, 0)
|
|
self.assertEqual(result["status"], "completed")
|
|
self.assertEqual(self.library.get_embed_url.call_args.args[1], ("FixtureCookie", "NOT_REAL=="))
|
|
|
|
def test_series_stdin_token_and_mutual_exclusion(self):
|
|
args = self.series_args()
|
|
position = args.index("--token")
|
|
args[position:position + 2] = ["--token-stdin"]
|
|
with patch.object(sys, "stdin", io.StringIO("FixtureCookie=NOT_REAL==\n")):
|
|
code, _, _ = self.invoke(series, args)
|
|
self.assertEqual(code, 0)
|
|
code, result, _ = self.invoke(video, self.video_args() + ["--token-stdin"])
|
|
self.assertEqual(code, 2)
|
|
self.assertEqual(result["errorCategory"], "validation")
|
|
|
|
def test_series_preserves_legacy_filenames_and_cli_flags(self):
|
|
fixtures = json.loads((ROOT / "tests/fixtures/legacy-contracts.json").read_text())
|
|
sample = next(item for item in fixtures["namingCases"] if item["entrypoint"] == "cli-series")
|
|
args = self.series_args(**sample["input"])
|
|
code, result, _ = self.invoke(series, args)
|
|
self.assertEqual(code, 0)
|
|
self.assertEqual(result["completed"], 2)
|
|
self.assertEqual(sorted(path.name for path in self.output.iterdir()), sorted(sample["expectedFilenames"]))
|
|
for mode, entrypoint, normal_args in (("video", video, self.video_args()), ("series", series, args)):
|
|
replacements = {long: short for short, long in fixtures["cli"][mode]["requiredFlags"]}
|
|
self.assertEqual(vars(entrypoint.parse_args(normal_args)),
|
|
vars(entrypoint.parse_args([replacements.get(arg, arg) for arg in normal_args])))
|
|
|
|
def test_series_partial_failure_is_nonzero_with_counts(self):
|
|
calls = 0
|
|
|
|
def transfer(url, target, label):
|
|
nonlocal calls
|
|
calls += 1
|
|
if calls == 1:
|
|
raise self.library.NetworkError("DO_NOT_LOG")
|
|
Path(target).write_bytes(b"synthetic media fixture")
|
|
|
|
self.library.download_mp4.side_effect = transfer
|
|
code, result, _ = self.invoke(series, self.series_args())
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (1, 1, 0))
|
|
self.assertEqual(result["failures"], [{"episode": 1, "errorCategory": "network"}])
|
|
|
|
def test_series_access_failure_stops_remaining_requests(self):
|
|
error = self.library.NetworkError("DO_NOT_LOG")
|
|
error.response = types.SimpleNamespace(status_code=403)
|
|
self.library.get_embed_url.side_effect = error
|
|
code, result, _ = self.invoke(series, self.series_args(episodes="1-3"))
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (0, 1, 2))
|
|
self.assertEqual(self.library.get_embed_url.call_count, 1)
|
|
|
|
def test_series_resolution_failure_stops_remaining_requests(self):
|
|
self.library.get_embed_url.side_effect = ["synthetic-embed", self.library.NotFoundError("DO_NOT_LOG")]
|
|
code, result, _ = self.invoke(series, self.series_args(episodes="1-4"))
|
|
self.assertEqual(code, 1)
|
|
self.assertEqual(result["errorCategory"], "resolution")
|
|
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (1, 1, 2))
|
|
self.assertEqual(result["failures"], [{"episode": 2, "errorCategory": "resolution"}])
|
|
self.assertEqual(self.library.get_embed_url.call_count, 2)
|
|
self.assertEqual(self.library.download_mp4.call_count, 1)
|
|
|
|
def test_series_confirmed_missing_source_does_not_pause_remaining_requests(self):
|
|
cause = RuntimeError("DO_NOT_LOG")
|
|
cause.response = types.SimpleNamespace(status_code=404)
|
|
error = self.library.NetworkError("DO_NOT_LOG")
|
|
error.__context__ = cause
|
|
self.library.get_embed_url.side_effect = [error, "synthetic-embed"]
|
|
code, result, _ = self.invoke(series, self.series_args())
|
|
self.assertEqual(code, 1)
|
|
self.assertEqual(result["errorCategory"], "source")
|
|
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (1, 1, 0))
|
|
self.assertEqual(self.library.get_embed_url.call_count, 2)
|
|
self.assertEqual(self.library.download_mp4.call_count, 1)
|
|
|
|
def test_series_host_failures_stop_remaining_requests(self):
|
|
for error, expected_category in ((PermissionError("DO_NOT_LOG"), "storage"),
|
|
(ImportError("DO_NOT_LOG"), "configuration")):
|
|
with self.subTest(category=expected_category):
|
|
self.library.get_embed_url.reset_mock()
|
|
self.library.get_embed_url.side_effect = error
|
|
code, result, _ = self.invoke(series, self.series_args(episodes="1-3"))
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (0, 1, 2))
|
|
self.assertEqual(result["errorCategory"], expected_category)
|
|
self.assertEqual(self.library.get_embed_url.call_count, 1)
|
|
|
|
def test_series_summary_reports_failure_that_stopped_the_batch(self):
|
|
for error, category in ((PermissionError("DO_NOT_LOG"), "storage"),
|
|
(self.library.NotFoundError("DO_NOT_LOG"), "resolution")):
|
|
with self.subTest(category=category):
|
|
self.library.get_embed_url.reset_mock()
|
|
self.library.get_embed_url.side_effect = [self.library.NetworkError("DO_NOT_LOG"), error]
|
|
code, result, _ = self.invoke(series, self.series_args(episodes="1-3"))
|
|
self.assertNotEqual(code, 0)
|
|
self.assertEqual(result["errorCategory"], category)
|
|
self.assertEqual((result["completed"], result["failed"], result["notAttempted"]), (0, 2, 1))
|
|
self.assertEqual(self.library.get_embed_url.call_count, 2)
|
|
|
|
def test_series_validates_every_destination_before_requests(self):
|
|
(self.output / "Fixture Series_Episode_2_engsub.mp4").symlink_to(self.output / "missing")
|
|
code, result, _ = self.invoke(series, self.series_args())
|
|
self.assertEqual(code, 2)
|
|
self.assertEqual(result["errorCategory"], "validation")
|
|
self.library.get_embed_url.assert_not_called()
|
|
|
|
|
|
class ProcessExitTests(unittest.TestCase):
|
|
def test_real_cli_entrypoint_reports_process_exit(self):
|
|
# Run __main__ in a separate process with an entirely synthetic imported library.
|
|
driver = '''
|
|
import pathlib, runpy, sys, types
|
|
root, destination, mode = sys.argv[1:]
|
|
sys.path.insert(0, str(pathlib.Path(root) / "scripts"))
|
|
package = types.ModuleType("lib")
|
|
package.__path__ = []
|
|
library = types.ModuleType("lib.proxer_utils")
|
|
library.get_embed_url = lambda *args: "synthetic-embed"
|
|
library.get_mp4_url = lambda *args: "synthetic-media"
|
|
def download(url, path, label):
|
|
if mode == "fail":
|
|
raise RuntimeError("PRIVATE_SIGNED_URL_DO_NOT_LOG")
|
|
pathlib.Path(path).write_bytes(b"synthetic payload")
|
|
library.download_mp4 = download
|
|
sys.modules["lib"] = package
|
|
sys.modules["lib.proxer_utils"] = library
|
|
script = str(pathlib.Path(root) / "scripts/proxer-dl-video.py")
|
|
sys.argv = [script, "-u", "https://proxer.me/watch/999999999/1/engsub", "-f", "Fixture", "-t", "FixtureCookie=synthetic==", "-o", destination]
|
|
runpy.run_path(script, run_name="__main__")
|
|
'''
|
|
before = protected_snapshot()
|
|
for mode, expected_code in (("ok", 0), ("fail", 1)):
|
|
with self.subTest(mode=mode), tempfile.TemporaryDirectory(prefix="proxer-cli-") as destination:
|
|
result = subprocess.run([sys.executable, "-B", "-c", driver, str(ROOT), destination, mode],
|
|
capture_output=True, text=True, timeout=10)
|
|
self.assertEqual(result.returncode, expected_code, result.stderr)
|
|
records = [line for line in result.stdout.splitlines() if line.startswith(validation.RESULT_PREFIX)]
|
|
self.assertEqual(len(records), 1)
|
|
self.assertNotIn("PRIVATE_SIGNED_URL", result.stdout + result.stderr)
|
|
self.assertEqual(protected_snapshot(), before)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|