81 lines
2.8 KiB
Python
81 lines
2.8 KiB
Python
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
from yt_shorts_downloader import api
|
|
from yt_shorts_downloader.exceptions import InvalidSessionError, InvalidUrlError
|
|
from yt_shorts_downloader.models import DownloadedVideo, SessionValidation
|
|
|
|
|
|
def _build_valid_session_validation(path: Path) -> SessionValidation:
|
|
return SessionValidation(True, True, True, True, str(path))
|
|
|
|
|
|
def test_download_returns_binary_mp4(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None:
|
|
expected_content = b"mp4-binary-content"
|
|
|
|
def fake_validate_session_file(path: Path) -> SessionValidation:
|
|
return _build_valid_session_validation(path)
|
|
|
|
def fake_download_video(*, url: str, output_dir: Path, session_path: Path) -> Path:
|
|
del url, session_path
|
|
downloaded_file = output_dir / "video.mp4"
|
|
downloaded_file.write_bytes(expected_content)
|
|
return downloaded_file
|
|
|
|
monkeypatch.setattr(api, "validate_session_file", fake_validate_session_file)
|
|
monkeypatch.setattr(api, "download_video", fake_download_video)
|
|
|
|
downloaded_video = api.download(
|
|
"https://youtube.com/shorts/example",
|
|
session_path="cookies.txt",
|
|
)
|
|
|
|
assert downloaded_video == DownloadedVideo(
|
|
filename="video.mp4",
|
|
content=expected_content,
|
|
)
|
|
|
|
|
|
def test_download_to_path_returns_path_from_downloader(
|
|
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
|
|
) -> None:
|
|
expected_path = tmp_path / "video.mp4"
|
|
|
|
def fake_validate_session_file(path: Path) -> SessionValidation:
|
|
return _build_valid_session_validation(path)
|
|
|
|
def fake_download_video(*, url: str, output_dir: Path, session_path: Path) -> Path:
|
|
del url, session_path
|
|
expected_path.write_bytes(b"mp4")
|
|
return output_dir / expected_path.name
|
|
|
|
monkeypatch.setattr(api, "validate_session_file", fake_validate_session_file)
|
|
monkeypatch.setattr(api, "download_video", fake_download_video)
|
|
|
|
downloaded_path = api.download_to_path(
|
|
"https://youtube.com/shorts/example",
|
|
session_path="cookies.txt",
|
|
output_dir=tmp_path,
|
|
)
|
|
|
|
assert downloaded_path == expected_path
|
|
|
|
|
|
def test_download_rejects_invalid_url() -> None:
|
|
with pytest.raises(InvalidUrlError):
|
|
api.download("https://example.com/watch?v=1", session_path="cookies.txt")
|
|
|
|
|
|
def test_download_rejects_invalid_session(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
def fake_validate_session_file(path: Path) -> SessionValidation:
|
|
del path
|
|
return SessionValidation(False, False, False, False, "bad session")
|
|
|
|
monkeypatch.setattr(api, "validate_session_file", fake_validate_session_file)
|
|
|
|
with pytest.raises(InvalidSessionError, match="bad session"):
|
|
api.download("https://youtube.com/shorts/example", session_path="cookies.txt")
|