230 lines
7.8 KiB
Python
230 lines
7.8 KiB
Python
"""Tests for ``video_analyse.ingest``.
|
|
|
|
The remote branch is exercised with a fake in-memory ``yt_dlp.YoutubeDL``: these
|
|
tests never open a socket and never download anything.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
from typing import Any, ClassVar
|
|
|
|
import pytest
|
|
from yt_dlp.utils import DownloadError
|
|
|
|
from video_analyse.cache import StageCache
|
|
from video_analyse.ingest import IngestResult, fetch, ingest_key_params
|
|
|
|
URL = "https://example.invalid/watch?v=abc123&list=PL123"
|
|
DOWNLOAD_FILE_NAME = "My Clip [abc123].mp4"
|
|
|
|
|
|
class _FakeYoutubeDL:
|
|
"""Minimal stand-in for ``yt_dlp.YoutubeDL`` writing a fake media file."""
|
|
|
|
calls: ClassVar[list[dict[str, Any]]] = []
|
|
fail_with: ClassVar[str | None] = None
|
|
|
|
def __init__(self, params: dict[str, Any] | None = None) -> None:
|
|
self.options = dict(params or {})
|
|
type(self).calls.append(self.options)
|
|
|
|
def __enter__(self) -> _FakeYoutubeDL:
|
|
return self
|
|
|
|
def __exit__(self, *exc_info: object) -> bool:
|
|
return False
|
|
|
|
def extract_info(self, url: str, download: bool = True) -> dict[str, Any]:
|
|
if type(self).fail_with is not None:
|
|
raise DownloadError(type(self).fail_with)
|
|
assert download is True
|
|
home = Path(self.options["paths"]["home"])
|
|
home.mkdir(parents=True, exist_ok=True)
|
|
target = home / DOWNLOAD_FILE_NAME
|
|
target.write_bytes(b"\x00" * 2048)
|
|
return {
|
|
"id": "abc123",
|
|
"title": "My Clip",
|
|
"ext": "mp4",
|
|
"webpage_url": url,
|
|
"duration": 42.5,
|
|
"filepath": str(target),
|
|
"requested_downloads": [{"filepath": str(target)}],
|
|
}
|
|
|
|
def sanitize_info(self, info: dict[str, Any]) -> dict[str, Any]:
|
|
return dict(info)
|
|
|
|
def prepare_filename(self, info: dict[str, Any]) -> str:
|
|
return str(Path(self.options["paths"]["home"]) / DOWNLOAD_FILE_NAME)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset_fake_ydl() -> None:
|
|
_FakeYoutubeDL.calls = []
|
|
_FakeYoutubeDL.fail_with = None
|
|
|
|
|
|
@pytest.fixture
|
|
def fake_ydl(monkeypatch: pytest.MonkeyPatch) -> type[_FakeYoutubeDL]:
|
|
monkeypatch.setattr("yt_dlp.YoutubeDL", _FakeYoutubeDL)
|
|
return _FakeYoutubeDL
|
|
|
|
|
|
async def test_fetch_local_file_does_not_touch_ytdlp(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
clip = tmp_path / "clip.MP4"
|
|
clip.write_bytes(b"\x00" * 1024)
|
|
|
|
def _no_download(*_args: object, **_kwargs: object) -> None:
|
|
raise AssertionError("local files must not be downloaded")
|
|
|
|
monkeypatch.setattr("yt_dlp.YoutubeDL", _no_download)
|
|
|
|
result = await fetch(str(clip), cache_dir=tmp_path / "cache")
|
|
|
|
assert isinstance(result, IngestResult)
|
|
assert result.downloaded is False
|
|
assert result.path == clip.resolve()
|
|
assert result.info == {}
|
|
assert result.title is None
|
|
assert not (tmp_path / "cache").exists()
|
|
|
|
|
|
async def test_fetch_missing_local_file_raises_value_error(tmp_path: Path) -> None:
|
|
with pytest.raises(ValueError, match="not found"):
|
|
await fetch(str(tmp_path / "nope.mp4"), cache_dir=tmp_path / "cache")
|
|
|
|
|
|
async def test_fetch_rejects_non_media_extension(tmp_path: Path) -> None:
|
|
text_file = tmp_path / "notes.txt"
|
|
text_file.write_text("hello", encoding="utf-8")
|
|
with pytest.raises(ValueError, match="does not look like a media file"):
|
|
await fetch(str(text_file), cache_dir=tmp_path / "cache")
|
|
|
|
|
|
async def test_fetch_rejects_empty_local_file(tmp_path: Path) -> None:
|
|
empty = tmp_path / "empty.mp4"
|
|
empty.touch()
|
|
with pytest.raises(ValueError, match="empty"):
|
|
await fetch(str(empty), cache_dir=tmp_path / "cache")
|
|
|
|
|
|
@pytest.mark.parametrize("source", ["ftp://example.invalid/clip.mp4", "file:///tmp/clip.mp4"])
|
|
async def test_fetch_rejects_other_url_schemes(source: str, tmp_path: Path) -> None:
|
|
with pytest.raises(ValueError, match="Unsupported URL scheme"):
|
|
await fetch(source, cache_dir=tmp_path / "cache")
|
|
|
|
|
|
async def test_fetch_rejects_invalid_quality(
|
|
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
|
|
) -> None:
|
|
clip = tmp_path / "clip.mp4"
|
|
clip.write_bytes(b"\x00" * 16)
|
|
for quality in (0, -720):
|
|
with pytest.raises(ValueError, match="quality"):
|
|
await fetch(str(clip), cache_dir=tmp_path / "cache", quality=quality)
|
|
assert fake_ydl.calls == []
|
|
|
|
|
|
async def test_fetch_downloads_http_url_into_cache(
|
|
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
|
|
) -> None:
|
|
cache_dir = tmp_path / "cache"
|
|
|
|
result = await fetch(URL, cache_dir=cache_dir, quality=720)
|
|
|
|
cache = StageCache(cache_dir)
|
|
key = cache.stage_key("ingest", ingest_key_params(URL, 720))
|
|
expected_dir = cache.source_dir(key).resolve()
|
|
assert result.downloaded is True
|
|
assert result.title == "My Clip"
|
|
assert result.info["id"] == "abc123"
|
|
assert result.info["duration"] == pytest.approx(42.5)
|
|
assert result.path.is_file()
|
|
assert result.path.name == DOWNLOAD_FILE_NAME
|
|
assert result.path.parent == expected_dir
|
|
# The old parallel manifest cache is gone: the StageCache artifact is the cache.
|
|
assert not (result.path.parent / "ingest-info.json").exists()
|
|
|
|
assert len(fake_ydl.calls) == 1
|
|
options = fake_ydl.calls[0]
|
|
assert options["format"] == "bv*[height<=720]+ba/b[height<=720]/b"
|
|
assert options["noplaylist"] is True
|
|
assert options["writeinfojson"] is True
|
|
assert "%(id)s" in options["outtmpl"]
|
|
assert Path(options["paths"]["home"]).resolve() == expected_dir
|
|
|
|
|
|
async def test_fetch_uses_a_stable_directory_per_url(
|
|
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
|
|
) -> None:
|
|
cache_dir = tmp_path / "cache"
|
|
first = await fetch(URL, cache_dir=cache_dir)
|
|
second = await fetch(URL, cache_dir=cache_dir)
|
|
|
|
home_dirs = {Path(options["paths"]["home"]) for options in fake_ydl.calls}
|
|
assert len(home_dirs) == 1
|
|
assert first.downloaded is True
|
|
assert second.downloaded is False # reused from the StageCache ingest artifact
|
|
assert len(fake_ydl.calls) == 1
|
|
assert first.path == second.path
|
|
assert first.info == second.info
|
|
|
|
|
|
async def test_fetch_force_bypasses_the_cached_result_and_redownloads(
|
|
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
|
|
) -> None:
|
|
cache_dir = tmp_path / "cache"
|
|
first = await fetch(URL, cache_dir=cache_dir)
|
|
assert first.downloaded is True
|
|
assert len(fake_ydl.calls) == 1
|
|
|
|
forced = await fetch(URL, cache_dir=cache_dir, force=True)
|
|
|
|
assert forced.downloaded is True
|
|
assert len(fake_ydl.calls) == 2
|
|
assert forced.path.is_file()
|
|
|
|
|
|
async def test_fetch_keys_the_download_directory_by_quality(
|
|
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
|
|
) -> None:
|
|
"""PLAN §3.4: changing --quality must not silently reuse the previous height."""
|
|
cache_dir = tmp_path / "cache"
|
|
await fetch(URL, cache_dir=cache_dir, quality=720)
|
|
await fetch(URL, cache_dir=cache_dir, quality=1080)
|
|
|
|
home_dirs = {Path(options["paths"]["home"]) for options in fake_ydl.calls}
|
|
assert len(home_dirs) == 2
|
|
assert len(fake_ydl.calls) == 2
|
|
|
|
|
|
async def test_fetch_maps_download_errors_to_actionable_runtime_error(
|
|
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
|
|
) -> None:
|
|
fake_ydl.fail_with = "ERROR: Video unavailable"
|
|
with pytest.raises(RuntimeError) as excinfo:
|
|
await fetch(URL, cache_dir=tmp_path / "cache")
|
|
|
|
message = str(excinfo.value)
|
|
assert "https://example.invalid/watch" in message
|
|
assert "abc123" not in message # query strings are redacted from errors
|
|
assert "Video unavailable" in message
|
|
assert "local path" in message
|
|
assert excinfo.value.__cause__ is not None
|
|
|
|
|
|
async def test_fetch_never_puts_url_credentials_in_the_cache_path(
|
|
fake_ydl: type[_FakeYoutubeDL], tmp_path: Path
|
|
) -> None:
|
|
result = await fetch(
|
|
"https://alice:s3cr3t@example.invalid/watch?v=abc",
|
|
cache_dir=tmp_path / "cache",
|
|
)
|
|
|
|
assert "s3cr3t" not in str(result.path)
|
|
assert "alice" not in str(result.path)
|