|
| 1 | +import pytest |
| 2 | +from pathlib import Path |
| 3 | +from unittest.mock import MagicMock, patch |
| 4 | + |
| 5 | +from typer.testing import CliRunner |
| 6 | + |
| 7 | +from transcribe.cli import _extract_video_id, sanitize_filename, unique_path, app |
| 8 | + |
| 9 | +runner = CliRunner() |
| 10 | + |
| 11 | + |
| 12 | +class TestExtractVideoId: |
| 13 | + def test_standard_watch_url(self): |
| 14 | + assert _extract_video_id("https://www.youtube.com/watch?v=dQw4w9WgXcQ") == "dQw4w9WgXcQ" |
| 15 | + |
| 16 | + def test_watch_url_with_extra_params(self): |
| 17 | + assert _extract_video_id("https://www.youtube.com/watch?v=dQw4w9WgXcQ&t=42s&list=PLxxx") == "dQw4w9WgXcQ" |
| 18 | + |
| 19 | + def test_short_url(self): |
| 20 | + assert _extract_video_id("https://youtu.be/dQw4w9WgXcQ") == "dQw4w9WgXcQ" |
| 21 | + |
| 22 | + def test_short_url_with_params(self): |
| 23 | + assert _extract_video_id("https://youtu.be/dQw4w9WgXcQ?si=abc123") == "dQw4w9WgXcQ" |
| 24 | + |
| 25 | + def test_embed_url(self): |
| 26 | + assert _extract_video_id("https://www.youtube.com/embed/dQw4w9WgXcQ") == "dQw4w9WgXcQ" |
| 27 | + |
| 28 | + def test_bare_video_id(self): |
| 29 | + assert _extract_video_id("dQw4w9WgXcQ") == "dQw4w9WgXcQ" |
| 30 | + |
| 31 | + def test_invalid_returns_none(self): |
| 32 | + assert _extract_video_id("https://example.com/watch?v=tooshort") is None |
| 33 | + |
| 34 | + def test_empty_string_returns_none(self): |
| 35 | + assert _extract_video_id("") is None |
| 36 | + |
| 37 | + def test_random_text_returns_none(self): |
| 38 | + assert _extract_video_id("not a url at all") is None |
| 39 | + |
| 40 | + def test_id_with_hyphens_and_underscores(self): |
| 41 | + # YouTube IDs are exactly 11 chars and can contain - and _ |
| 42 | + assert _extract_video_id("abc-def_ghi") == "abc-def_ghi" |
| 43 | + |
| 44 | + |
| 45 | +class TestSanitizeFilename: |
| 46 | + @pytest.mark.parametrize("char", ['<', '>', ':', '"', '/', '\\', '|', '?', '*']) |
| 47 | + def test_illegal_chars_replaced(self, char): |
| 48 | + assert "_" in sanitize_filename(f"name{char}here") |
| 49 | + |
| 50 | + def test_normal_name_unchanged(self): |
| 51 | + assert sanitize_filename("My Video Title") == "My Video Title" |
| 52 | + |
| 53 | + def test_leading_trailing_spaces_stripped(self): |
| 54 | + assert sanitize_filename(" hello ") == "hello" |
| 55 | + |
| 56 | + def test_max_length_truncated(self): |
| 57 | + long_name = "a" * 300 |
| 58 | + assert len(sanitize_filename(long_name)) == 200 |
| 59 | + |
| 60 | + def test_custom_max_length(self): |
| 61 | + assert len(sanitize_filename("a" * 50, max_length=10)) == 10 |
| 62 | + |
| 63 | + def test_empty_string(self): |
| 64 | + assert sanitize_filename("") == "" |
| 65 | + |
| 66 | + |
| 67 | +class TestUniquePath: |
| 68 | + def test_nonexistent_path_returned_unchanged(self, tmp_path): |
| 69 | + p = tmp_path / "file.txt" |
| 70 | + assert unique_path(p) == p |
| 71 | + |
| 72 | + def test_existing_file_gets_counter(self, tmp_path): |
| 73 | + p = tmp_path / "file.txt" |
| 74 | + p.write_text("x") |
| 75 | + result = unique_path(p) |
| 76 | + assert result == tmp_path / "file (1).txt" |
| 77 | + |
| 78 | + def test_counter_increments_until_free(self, tmp_path): |
| 79 | + p = tmp_path / "file.txt" |
| 80 | + p.write_text("x") |
| 81 | + (tmp_path / "file (1).txt").write_text("x") |
| 82 | + (tmp_path / "file (2).txt").write_text("x") |
| 83 | + assert unique_path(p) == tmp_path / "file (3).txt" |
| 84 | + |
| 85 | + def test_preserves_extension(self, tmp_path): |
| 86 | + p = tmp_path / "audio.mp3" |
| 87 | + p.write_text("x") |
| 88 | + assert unique_path(p).suffix == ".mp3" |
| 89 | + |
| 90 | + def test_no_extension(self, tmp_path): |
| 91 | + p = tmp_path / "transcript" |
| 92 | + p.write_text("x") |
| 93 | + result = unique_path(p) |
| 94 | + assert result == tmp_path / "transcript (1)" |
| 95 | + |
| 96 | + |
| 97 | +# --------------------------------------------------------------------------- |
| 98 | +# Integration tests for the `run` command (external I/O fully mocked) |
| 99 | +# --------------------------------------------------------------------------- |
| 100 | + |
| 101 | +YT_URL = "https://www.youtube.com/watch?v=jNQXAC9IVRw" |
| 102 | +YT_ID = "jNQXAC9IVRw" |
| 103 | +CAPTION_TEXT = "Hello from captions" |
| 104 | +WHISPER_TEXT = "Hello from Whisper" |
| 105 | + |
| 106 | + |
| 107 | +@pytest.fixture() |
| 108 | +def captions_found(): |
| 109 | + """Patch fetch_youtube_captions to return a fake transcript.""" |
| 110 | + with patch("transcribe.cli.fetch_youtube_captions", return_value=(CAPTION_TEXT, False)) as m: |
| 111 | + yield m |
| 112 | + |
| 113 | + |
| 114 | +@pytest.fixture() |
| 115 | +def no_captions(): |
| 116 | + """Patch fetch_youtube_captions to signal no captions available.""" |
| 117 | + with patch("transcribe.cli.fetch_youtube_captions", return_value=None) as m: |
| 118 | + yield m |
| 119 | + |
| 120 | + |
| 121 | +@pytest.fixture() |
| 122 | +def whisper_ok(): |
| 123 | + """Patch _run_whisper to return a fake transcript without loading a model.""" |
| 124 | + with patch("transcribe.cli._run_whisper", return_value=(WHISPER_TEXT, 1.5)) as m: |
| 125 | + yield m |
| 126 | + |
| 127 | + |
| 128 | +@pytest.fixture() |
| 129 | +def fake_yt_dlp(tmp_path): |
| 130 | + """Patch yt_dlp and TemporaryDirectory so no audio is downloaded.""" |
| 131 | + audio_file = tmp_path / "audio.webm" |
| 132 | + audio_file.write_bytes(b"fake") |
| 133 | + |
| 134 | + class FakeYDL: |
| 135 | + def __init__(self, opts): |
| 136 | + pass |
| 137 | + |
| 138 | + def __enter__(self): |
| 139 | + return self |
| 140 | + |
| 141 | + def __exit__(self, *_): |
| 142 | + pass |
| 143 | + |
| 144 | + def extract_info(self, url, download): |
| 145 | + return {"title": "Fake Video Title"} |
| 146 | + |
| 147 | + # yt_dlp is imported lazily inside the function, so patch the module directly |
| 148 | + with patch("yt_dlp.YoutubeDL", FakeYDL): |
| 149 | + # Make TemporaryDirectory yield our tmp_path so the glob finds the audio file |
| 150 | + mock_td = MagicMock() |
| 151 | + mock_td.return_value.__enter__ = MagicMock(return_value=str(tmp_path)) |
| 152 | + mock_td.return_value.__exit__ = MagicMock(return_value=False) |
| 153 | + with patch("transcribe.cli.tempfile.TemporaryDirectory", mock_td): |
| 154 | + yield tmp_path |
| 155 | + |
| 156 | + |
| 157 | +class TestRunCommand: |
| 158 | + # --- caption happy path --- |
| 159 | + |
| 160 | + def test_print_with_captions(self, captions_found): |
| 161 | + result = runner.invoke(app, ["run", YT_URL, "--print"]) |
| 162 | + assert result.exit_code == 0 |
| 163 | + assert CAPTION_TEXT in result.stdout |
| 164 | + |
| 165 | + def test_bare_video_id_with_captions(self, captions_found): |
| 166 | + result = runner.invoke(app, ["run", YT_ID, "--print"]) |
| 167 | + assert result.exit_code == 0 |
| 168 | + assert CAPTION_TEXT in result.stdout |
| 169 | + |
| 170 | + def test_captions_saved_to_output(self, captions_found, tmp_path): |
| 171 | + out = tmp_path / "out.txt" |
| 172 | + result = runner.invoke(app, ["run", YT_URL, "--output", str(out)]) |
| 173 | + assert result.exit_code == 0 |
| 174 | + assert out.exists() |
| 175 | + assert out.read_text() == CAPTION_TEXT |
| 176 | + |
| 177 | + def test_captions_saved_auto_named(self, captions_found, tmp_path): |
| 178 | + """Without --output, file is saved under output_dir from config.""" |
| 179 | + with patch("transcribe.cli._fetch_title", return_value="My Video"): |
| 180 | + with patch("transcribe.cli.cfg_module.load") as mock_load: |
| 181 | + mock_load.return_value = { |
| 182 | + "defaults": {"model": "turbo", "language": "", "output_dir": str(tmp_path), "output_extension": "txt"}, |
| 183 | + "whisper": {"device": "cpu", "compute_type": "int8", "beam_size": 5, "vad_filter": True}, |
| 184 | + } |
| 185 | + result = runner.invoke(app, ["run", YT_URL]) |
| 186 | + assert result.exit_code == 0 |
| 187 | + assert (tmp_path / "My Video.txt").exists() |
| 188 | + |
| 189 | + # --- Whisper fallback --- |
| 190 | + |
| 191 | + def test_print_whisper_fallback(self, no_captions, whisper_ok, fake_yt_dlp): |
| 192 | + result = runner.invoke(app, ["run", YT_URL, "--print"]) |
| 193 | + assert result.exit_code == 0 |
| 194 | + assert WHISPER_TEXT in result.stdout |
| 195 | + |
| 196 | + def test_force_whisper_skips_captions(self, captions_found, whisper_ok, fake_yt_dlp): |
| 197 | + result = runner.invoke(app, ["run", YT_URL, "--force-whisper", "--print"]) |
| 198 | + assert result.exit_code == 0 |
| 199 | + captions_found.assert_not_called() |
| 200 | + assert WHISPER_TEXT in result.stdout |
| 201 | + |
| 202 | + # --- local file --- |
| 203 | + |
| 204 | + def test_local_file_whisper(self, whisper_ok, tmp_path): |
| 205 | + audio = tmp_path / "clip.mp3" |
| 206 | + audio.write_bytes(b"fake audio") |
| 207 | + out = tmp_path / "clip.txt" |
| 208 | + result = runner.invoke(app, ["run", str(audio), "--output", str(out)]) |
| 209 | + assert result.exit_code == 0 |
| 210 | + assert out.read_text() == WHISPER_TEXT |
| 211 | + whisper_ok.assert_called_once() |
| 212 | + |
| 213 | + def test_local_file_print(self, whisper_ok, tmp_path): |
| 214 | + audio = tmp_path / "clip.mp3" |
| 215 | + audio.write_bytes(b"fake audio") |
| 216 | + result = runner.invoke(app, ["run", str(audio), "--print"]) |
| 217 | + assert result.exit_code == 0 |
| 218 | + assert WHISPER_TEXT in result.stdout |
| 219 | + |
| 220 | + # --- error cases --- |
| 221 | + |
| 222 | + def test_invalid_source_exits_nonzero(self): |
| 223 | + result = runner.invoke(app, ["run", "not-a-url-or-file"]) |
| 224 | + assert result.exit_code != 0 |
| 225 | + |
| 226 | + def test_output_is_directory_exits_nonzero(self, captions_found, tmp_path): |
| 227 | + result = runner.invoke(app, ["run", YT_URL, "--output", str(tmp_path)]) |
| 228 | + assert result.exit_code != 0 |
| 229 | + |
| 230 | + def test_print_and_output_warns(self, captions_found, tmp_path): |
| 231 | + out = tmp_path / "out.txt" |
| 232 | + result = runner.invoke(app, ["run", YT_URL, "--print", "--output", str(out)]) |
| 233 | + assert result.exit_code == 0 |
| 234 | + assert "Warning" in result.output |
0 commit comments