| 1 | """Tests for YouTube transcript highlights and yt-dlp safety flags.""" |
| 2 | |
| 3 | import json |
| 4 | import os |
| 5 | import tempfile |
| 6 | import unittest |
| 7 | import urllib.error |
| 8 | from datetime import datetime, timedelta, timezone |
| 9 | from pathlib import Path |
| 10 | from unittest import mock |
| 11 | |
| 12 | from lib import youtube_yt |
| 13 | |
| 14 | |
| 15 | def _write_transcript_fixture(directory): |
| 16 | (Path(directory) / "abc123.en.vtt").write_text( |
| 17 | "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nOffline transcript fixture.\n", |
| 18 | encoding="utf-8", |
| 19 | ) |
| 20 | |
| 21 | |
| 22 | class _DummyProc: |
| 23 | def __init__(self): |
| 24 | self.pid = 12345 |
| 25 | self.returncode = 0 |
| 26 | |
| 27 | def communicate(self, timeout=None): |
| 28 | return "", "" |
| 29 | |
| 30 | def wait(self, timeout=None): |
| 31 | return 0 |
| 32 | |
| 33 | |
| 34 | class TestYouTubeEngagementZero(unittest.TestCase): |
| 35 | """Verify that 0 engagement counts are preserved (not coerced to fallback).""" |
| 36 | |
| 37 | def test_zero_view_count_preserved(self): |
| 38 | """video.get('view_count') == 0 must stay 0, not become the fallback.""" |
| 39 | from lib.subproc import SubprocResult |
| 40 | |
| 41 | youtube_yt.reset_search_cache() |
| 42 | self.addCleanup(youtube_yt.reset_search_cache) |
| 43 | video = { |
| 44 | "id": "abc123", |
| 45 | "title": "Test", |
| 46 | "view_count": 0, |
| 47 | "like_count": 0, |
| 48 | "comment_count": 0, |
| 49 | "upload_date": "20260301", |
| 50 | "description": "desc", |
| 51 | } |
| 52 | positive = dict(video, id="positive", view_count=321, like_count=7, comment_count=2) |
| 53 | result = SubprocResult( |
| 54 | returncode=0, |
| 55 | stdout="\n".join(json.dumps(item) for item in (video, positive)), |
| 56 | stderr="", |
| 57 | ) |
| 58 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 59 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=result): |
| 60 | out = youtube_yt.search_youtube("Test", "2026-02-01", "2026-03-01") |
| 61 | |
| 62 | self.assertNotIn("error", out) |
| 63 | self.assertEqual([item["video_id"] for item in out["items"]], ["positive", "abc123"]) |
| 64 | self.assertEqual(out["items"][0]["engagement"], {"views": 321, "likes": 7, "comments": 2}) |
| 65 | self.assertEqual(out["items"][1]["engagement"], {"views": 0, "likes": 0, "comments": 0}) |
| 66 | |
| 67 | |
| 68 | class TestYtDlpFlags(unittest.TestCase): |
| 69 | def setUp(self): |
| 70 | youtube_yt.reset_search_cache() |
| 71 | |
| 72 | def _fake_result(self, stdout: str = "", returncode: int = 0): |
| 73 | from lib.subproc import SubprocResult |
| 74 | return SubprocResult(returncode=returncode, stdout=stdout, stderr="") |
| 75 | |
| 76 | def test_search_ignores_global_config_and_browser_cookies(self): |
| 77 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 78 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()) as run_mock: |
| 79 | youtube_yt.search_youtube("Claude Code", "2026-02-01", "2026-03-01") |
| 80 | |
| 81 | cmd = run_mock.call_args.args[0] |
| 82 | self.assertIn("--ignore-config", cmd) |
| 83 | self.assertIn("--no-cookies-from-browser", cmd) |
| 84 | |
| 85 | def test_transcript_fetch_ignores_global_config_and_browser_cookies(self): |
| 86 | with tempfile.TemporaryDirectory() as temp_dir, \ |
| 87 | mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 88 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()) as run_mock: |
| 89 | _write_transcript_fixture(temp_dir) |
| 90 | transcript = youtube_yt.fetch_transcript("abc123", temp_dir) |
| 91 | |
| 92 | self.assertEqual(transcript, "Offline transcript fixture.") |
| 93 | cmd = run_mock.call_args.args[0] |
| 94 | self.assertIn("--ignore-config", cmd) |
| 95 | self.assertIn("--no-cookies-from-browser", cmd) |
| 96 | |
| 97 | |
| 98 | class TestYtDlpSubLangs(unittest.TestCase): |
| 99 | """Verify LAST30DAYS_YT_SUB_LANGS knob and language-agnostic VTT matching.""" |
| 100 | |
| 101 | def _fake_result(self, stdout: str = "", returncode: int = 0): |
| 102 | from lib.subproc import SubprocResult |
| 103 | return SubprocResult(returncode=returncode, stdout=stdout, stderr="") |
| 104 | |
| 105 | def test_default_sub_langs_when_env_unset(self): |
| 106 | """When LAST30DAYS_YT_SUB_LANGS is not set, the default is en,es,pt.""" |
| 107 | with mock.patch.dict(os.environ, {}, clear=False): |
| 108 | os.environ.pop("LAST30DAYS_YT_SUB_LANGS", None) |
| 109 | self.assertEqual(youtube_yt._ytdlp_sub_langs(), "en,es,pt") |
| 110 | |
| 111 | def test_env_var_overrides_default(self): |
| 112 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "fr,de"}): |
| 113 | self.assertEqual(youtube_yt._ytdlp_sub_langs(), "fr,de") |
| 114 | |
| 115 | def test_env_var_normalizes_whitespace_and_case(self): |
| 116 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": " EN , Es , PT "}): |
| 117 | self.assertEqual(youtube_yt._ytdlp_sub_langs(), "en,es,pt") |
| 118 | |
| 119 | def test_env_var_handles_empty_segments(self): |
| 120 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en,,pt,"}): |
| 121 | self.assertEqual(youtube_yt._ytdlp_sub_langs(), "en,pt") |
| 122 | |
| 123 | def test_env_var_empty_string_falls_back_to_default(self): |
| 124 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": " "}): |
| 125 | self.assertEqual(youtube_yt._ytdlp_sub_langs(), "en,es,pt") |
| 126 | |
| 127 | def test_transcript_cmd_uses_default_sub_langs(self): |
| 128 | """Regression: the --sub-lang arg covers en,es,pt by default (issue #469). |
| 129 | |
| 130 | Each language is requested original-speech first (#1314). |
| 131 | """ |
| 132 | with tempfile.TemporaryDirectory() as temp_dir, \ |
| 133 | mock.patch.dict(os.environ, {}, clear=False), \ |
| 134 | mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 135 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()) as run_mock: |
| 136 | os.environ.pop("LAST30DAYS_YT_SUB_LANGS", None) |
| 137 | _write_transcript_fixture(temp_dir) |
| 138 | transcript = youtube_yt.fetch_transcript("abc123", temp_dir) |
| 139 | |
| 140 | self.assertEqual(transcript, "Offline transcript fixture.") |
| 141 | cmd = run_mock.call_args_list[0].args[0] |
| 142 | idx = cmd.index("--sub-lang") |
| 143 | self.assertEqual(cmd[idx + 1], "en-orig,es-orig,pt-orig,en,es,pt") |
| 144 | |
| 145 | def test_transcript_cmd_respects_env_var_override(self): |
| 146 | with tempfile.TemporaryDirectory() as temp_dir, \ |
| 147 | mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "fr,de,it"}), \ |
| 148 | mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 149 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()) as run_mock: |
| 150 | _write_transcript_fixture(temp_dir) |
| 151 | transcript = youtube_yt.fetch_transcript("abc123", temp_dir) |
| 152 | |
| 153 | self.assertEqual(transcript, "Offline transcript fixture.") |
| 154 | cmd = run_mock.call_args_list[0].args[0] |
| 155 | idx = cmd.index("--sub-lang") |
| 156 | self.assertEqual(cmd[idx + 1], "fr-orig,de-orig,it-orig,fr,de,it") |
| 157 | |
| 158 | def test_transcript_cmd_requests_uploaded_and_auto_subtitles(self): |
| 159 | """#1313: manual-only subtitles must not exit 0 with no file.""" |
| 160 | with tempfile.TemporaryDirectory() as temp_dir, \ |
| 161 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()) as run_mock: |
| 162 | _write_transcript_fixture(temp_dir) |
| 163 | youtube_yt._fetch_transcript_ytdlp("abc123", temp_dir) |
| 164 | |
| 165 | cmd = run_mock.call_args_list[0].args[0] |
| 166 | self.assertIn("--write-subs", cmd) |
| 167 | self.assertIn("--write-auto-subs", cmd) |
| 168 | |
| 169 | def test_ssh_transcript_cmd_requests_uploaded_subs_and_orig_first(self): |
| 170 | from lib.subproc import SubprocResult |
| 171 | result = SubprocResult(returncode=0, stdout="WEBVTT\n", stderr="") |
| 172 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en"}), \ |
| 173 | mock.patch.object(youtube_yt, "_run_ytdlp", return_value=result) as run_mock: |
| 174 | youtube_yt._fetch_transcript_ytdlp_via_ssh("abc123", "macmini") |
| 175 | |
| 176 | remote_script = run_mock.call_args.args[0][-1] |
| 177 | self.assertIn("--write-subs --write-auto-subs --sub-lang en-orig,en ", remote_script) |
| 178 | |
| 179 | def test_request_langs_do_not_double_explicit_orig(self): |
| 180 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "fr,en-orig,en"}): |
| 181 | self.assertEqual(youtube_yt._ytdlp_request_langs(), "fr-orig,en-orig,fr,en") |
| 182 | |
| 183 | def test_vtt_matching_prefers_plain_track_within_a_language(self): |
| 184 | """A plain track that downloaded may be the uploaded subtitle; keep it.""" |
| 185 | with tempfile.TemporaryDirectory() as temp_dir: |
| 186 | for name in ("abc123.en.vtt", "abc123.en-orig.vtt", "abc123.es-orig.vtt"): |
| 187 | (Path(temp_dir) / name).write_text("WEBVTT\n") |
| 188 | picked = youtube_yt._pick_ytdlp_vtt("abc123", temp_dir, ["en", "es", "pt"]) |
| 189 | self.assertEqual(picked.name, "abc123.en.vtt") |
| 190 | |
| 191 | def test_vtt_matching_falls_back_to_orig_track(self): |
| 192 | with tempfile.TemporaryDirectory() as temp_dir: |
| 193 | for name in ("abc123.en-orig.vtt", "abc123.es.vtt"): |
| 194 | (Path(temp_dir) / name).write_text("WEBVTT\n") |
| 195 | picked = youtube_yt._pick_ytdlp_vtt("abc123", temp_dir, ["en", "es", "pt"]) |
| 196 | self.assertEqual(picked.name, "abc123.en-orig.vtt") |
| 197 | |
| 198 | def test_configured_orig_code_keeps_its_language_priority(self): |
| 199 | """`en-orig` in SUB_LANGS ranks English first, not after every listed code.""" |
| 200 | with tempfile.TemporaryDirectory() as temp_dir: |
| 201 | for name in ("abc123.fr.vtt", "abc123.en-orig.vtt"): |
| 202 | (Path(temp_dir) / name).write_text("WEBVTT\n") |
| 203 | picked = youtube_yt._pick_ytdlp_vtt("abc123", temp_dir, ["en-orig", "fr"]) |
| 204 | self.assertEqual(picked.name, "abc123.en-orig.vtt") |
| 205 | |
| 206 | def test_dubbed_video_keeps_orig_track_after_plain_track_429(self): |
| 207 | """#1314: `en` 429s after `en-orig` downloaded; keep it, no retry, no SC.""" |
| 208 | from lib.subproc import SubprocResult |
| 209 | failed = SubprocResult( |
| 210 | returncode=1, stdout="", |
| 211 | stderr="ERROR: Unable to download video subtitles for 'en': HTTP Error 429: Too Many Requests", |
| 212 | ) |
| 213 | with tempfile.TemporaryDirectory() as temp_dir: |
| 214 | def _run(cmd, timeout, **_kwargs): |
| 215 | (Path(temp_dir) / "dub123.en-orig.vtt").write_text( |
| 216 | "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nOriginal speech captions.\n", |
| 217 | ) |
| 218 | return failed |
| 219 | |
| 220 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \ |
| 221 | mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 222 | mock.patch.object(youtube_yt, "_ytdlp_ssh_host", return_value=None), \ |
| 223 | mock.patch.object(youtube_yt, "_run_ytdlp", side_effect=_run) as run_mock, \ |
| 224 | mock.patch.object(youtube_yt, "_sc_fetch_transcript") as sc_mock: |
| 225 | transcript = youtube_yt.fetch_transcript("dub123", temp_dir, token="dummy-key") |
| 226 | |
| 227 | self.assertEqual(transcript, "Original speech captions.") |
| 228 | self.assertEqual(run_mock.call_count, 1) |
| 229 | sc_mock.assert_not_called() |
| 230 | |
| 231 | def test_vtt_matching_picks_non_english_track(self): |
| 232 | """When yt-dlp writes a Spanish track (no English available), we read it.""" |
| 233 | with tempfile.TemporaryDirectory() as temp_dir: |
| 234 | # Simulate yt-dlp output: only a Spanish VTT is available |
| 235 | (Path(temp_dir) / "abc123.es.vtt").write_text( |
| 236 | "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nHola mundo esta es una prueba.\n", |
| 237 | encoding="utf-8", |
| 238 | ) |
| 239 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 240 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()): |
| 241 | vtt = youtube_yt._fetch_transcript_ytdlp("abc123", temp_dir) |
| 242 | |
| 243 | self.assertIsNotNone(vtt) |
| 244 | self.assertIn("Hola mundo", vtt) |
| 245 | |
| 246 | def test_partial_success_returns_vtt_despite_nonzero_exit(self): |
| 247 | """A non-zero yt-dlp exit must not discard a VTT already on disk. |
| 248 | |
| 249 | Regression for the 0/N-transcripts bug: with the default |
| 250 | ``--sub-lang en,es,pt``, an English video fetches ``en`` successfully, |
| 251 | then ``es``/``pt`` hit a 429 and yt-dlp exits non-zero. The ``en`` |
| 252 | track is already written and must be returned, not discarded (and not |
| 253 | retried back into the same rate limit). |
| 254 | """ |
| 255 | with tempfile.TemporaryDirectory() as temp_dir: |
| 256 | (Path(temp_dir) / "abc123.en.vtt").write_text( |
| 257 | "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nThis is the english transcript.\n", |
| 258 | encoding="utf-8", |
| 259 | ) |
| 260 | status: dict = {} |
| 261 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 262 | mock.patch.object( |
| 263 | youtube_yt.subproc, |
| 264 | "run_with_timeout", |
| 265 | return_value=self._fake_result(returncode=1), |
| 266 | ) as run_mock: |
| 267 | vtt = youtube_yt._fetch_transcript_ytdlp("abc123", temp_dir, status) |
| 268 | |
| 269 | self.assertIsNotNone(vtt) |
| 270 | self.assertIn("english transcript", vtt) |
| 271 | self.assertNotIn("ytdlp_error", status) |
| 272 | # Salvage must short-circuit the retry loop: yt-dlp must not be called a |
| 273 | # second time when a partial VTT is already on disk (locks in the |
| 274 | # no-retry guarantee against a future salvage-after-retry regression). |
| 275 | self.assertEqual(run_mock.call_count, 1) |
| 276 | |
| 277 | def test_vtt_matching_respects_non_default_priority(self): |
| 278 | """When multiple tracks exist, the user-requested priority wins |
| 279 | over alphabetical order (regression for the Greptile review on #486).""" |
| 280 | with tempfile.TemporaryDirectory() as temp_dir: |
| 281 | (Path(temp_dir) / "abc123.en.vtt").write_text( |
| 282 | "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nEnglish first track.\n", |
| 283 | encoding="utf-8", |
| 284 | ) |
| 285 | (Path(temp_dir) / "abc123.es.vtt").write_text( |
| 286 | "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nSpanish second track.\n", |
| 287 | encoding="utf-8", |
| 288 | ) |
| 289 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "es,en"}), \ |
| 290 | mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 291 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()): |
| 292 | vtt = youtube_yt._fetch_transcript_ytdlp("abc123", temp_dir) |
| 293 | |
| 294 | self.assertIsNotNone(vtt) |
| 295 | self.assertIn("Spanish", vtt) |
| 296 | |
| 297 | def test_vtt_matching_unknown_suffix_sorts_last(self): |
| 298 | """A non-lang suffix (e.g. a stray .tmp or .live_chat) must not |
| 299 | win over a real track that just happens to be alphabetically later.""" |
| 300 | with tempfile.TemporaryDirectory() as temp_dir: |
| 301 | (Path(temp_dir) / "abc123.zz.vtt").write_text( |
| 302 | "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nZZ track content.\n", |
| 303 | encoding="utf-8", |
| 304 | ) |
| 305 | (Path(temp_dir) / "abc123.es.vtt").write_text( |
| 306 | "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nSpanish content.\n", |
| 307 | encoding="utf-8", |
| 308 | ) |
| 309 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "es,en,pt"}), \ |
| 310 | mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 311 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=self._fake_result()): |
| 312 | vtt = youtube_yt._fetch_transcript_ytdlp("abc123", temp_dir) |
| 313 | |
| 314 | self.assertIsNotNone(vtt) |
| 315 | self.assertIn("Spanish", vtt) |
| 316 | |
| 317 | |
| 318 | class TestExtractTranscriptHighlights(unittest.TestCase): |
| 319 | def test_extracts_specific_sentences(self): |
| 320 | transcript = ( |
| 321 | "Hey guys welcome back to the channel. " |
| 322 | "In today's video we're looking at something special. " |
| 323 | "The Lego Bugatti Chiron took 13,438 hours to build with over 1 million pieces. " |
| 324 | "Don't forget to subscribe and hit the bell. " |
| 325 | "The tolerance on each brick is 0.002 millimeters which is insane for injection molding. " |
| 326 | "So yeah that's pretty cool. " |
| 327 | "Thanks for watching see you next time." |
| 328 | ) |
| 329 | highlights = youtube_yt.extract_transcript_highlights(transcript, "Lego") |
| 330 | self.assertTrue(len(highlights) > 0) |
| 331 | joined = " ".join(highlights) |
| 332 | self.assertIn("13,438", joined) |
| 333 | self.assertNotIn("subscribe", joined) |
| 334 | self.assertNotIn("welcome back", joined) |
| 335 | |
| 336 | def test_empty_transcript(self): |
| 337 | self.assertEqual(youtube_yt.extract_transcript_highlights("", "test"), []) |
| 338 | |
| 339 | def test_respects_limit(self): |
| 340 | sentences = ". ".join( |
| 341 | f"The model {i} has {i * 100} parameters and runs at {i * 10} tokens per second" |
| 342 | for i in range(20) |
| 343 | ) + "." |
| 344 | highlights = youtube_yt.extract_transcript_highlights(sentences, "model", limit=3) |
| 345 | self.assertEqual(len(highlights), 3) |
| 346 | |
| 347 | def test_punctuation_free_transcript_produces_highlights(self): |
| 348 | # Auto-generated YouTube captions often lack sentence-ending punctuation |
| 349 | words = ( |
| 350 | "the new Tesla Model Y has 350 miles of range and costs about 45000 dollars " |
| 351 | "which makes it one of the most affordable electric vehicles on the market today " |
| 352 | "compared to the BMW iX which starts at 87000 the value proposition is pretty clear " |
| 353 | "and with the 7500 dollar tax credit you can get it for under 40000" |
| 354 | ) |
| 355 | highlights = youtube_yt.extract_transcript_highlights(words, "Tesla Model Y") |
| 356 | self.assertTrue(len(highlights) > 0, "Should produce highlights from punctuation-free text") |
| 357 | |
| 358 | |
| 359 | class TestFetchTranscriptDirect(unittest.TestCase): |
| 360 | """Tests for _fetch_transcript_direct() — direct HTTP transcript fetching.""" |
| 361 | |
| 362 | # Minimal ytInitialPlayerResponse JSON with a caption track |
| 363 | _PLAYER_RESPONSE = json.dumps({ |
| 364 | "captions": { |
| 365 | "playerCaptionsTracklistRenderer": { |
| 366 | "captionTracks": [ |
| 367 | { |
| 368 | "baseUrl": "https://www.youtube.com/api/timedtext?v=abc123&lang=en", |
| 369 | "languageCode": "en", |
| 370 | } |
| 371 | ] |
| 372 | } |
| 373 | } |
| 374 | }) |
| 375 | |
| 376 | _WATCH_HTML = ( |
| 377 | '<html><script>var ytInitialPlayerResponse = ' |
| 378 | + _PLAYER_RESPONSE |
| 379 | + ';</script></html>' |
| 380 | ) |
| 381 | |
| 382 | _SAMPLE_VTT = ( |
| 383 | "WEBVTT\n\n" |
| 384 | "00:00:00.000 --> 00:00:02.000\n" |
| 385 | "Hello world this is a test sentence with enough words to pass.\n\n" |
| 386 | "00:00:02.000 --> 00:00:04.000\n" |
| 387 | "Another line of transcript text here for testing purposes.\n" |
| 388 | ) |
| 389 | |
| 390 | def _mock_urlopen(self, url_or_req, *, timeout=None): |
| 391 | """Return watch HTML or VTT depending on URL.""" |
| 392 | url = url_or_req.full_url if hasattr(url_or_req, 'full_url') else url_or_req |
| 393 | |
| 394 | class _Resp: |
| 395 | def __init__(self, data): |
| 396 | self._data = data.encode("utf-8") |
| 397 | def read(self): |
| 398 | return self._data |
| 399 | def __enter__(self): |
| 400 | return self |
| 401 | def __exit__(self, *a): |
| 402 | pass |
| 403 | |
| 404 | if "watch?" in url: |
| 405 | return _Resp(self._WATCH_HTML) |
| 406 | elif "timedtext" in url: |
| 407 | return _Resp(self._SAMPLE_VTT) |
| 408 | raise urllib.error.URLError("unexpected URL") |
| 409 | |
| 410 | def test_extracts_vtt_from_mock_page(self): |
| 411 | """Happy path: extracts VTT text from a page with captions.""" |
| 412 | with mock.patch("lib.youtube_yt.urllib.request.urlopen", side_effect=self._mock_urlopen): |
| 413 | result = youtube_yt._fetch_transcript_direct("abc123") |
| 414 | self.assertIsNotNone(result) |
| 415 | self.assertIn("WEBVTT", result) |
| 416 | self.assertIn("Hello world", result) |
| 417 | |
| 418 | def test_no_captions_returns_none(self): |
| 419 | """Video with no caption tracks returns None.""" |
| 420 | no_captions_response = json.dumps({"captions": {"playerCaptionsTracklistRenderer": {"captionTracks": []}}}) |
| 421 | html = f'<html><script>var ytInitialPlayerResponse = {no_captions_response};</script></html>' |
| 422 | |
| 423 | class _Resp: |
| 424 | def __init__(self, data): |
| 425 | self._data = data.encode("utf-8") |
| 426 | def read(self): |
| 427 | return self._data |
| 428 | def __enter__(self): |
| 429 | return self |
| 430 | def __exit__(self, *a): |
| 431 | pass |
| 432 | |
| 433 | def mock_open(req, *, timeout=None): |
| 434 | return _Resp(html) |
| 435 | |
| 436 | with mock.patch("lib.youtube_yt.urllib.request.urlopen", side_effect=mock_open): |
| 437 | result = youtube_yt._fetch_transcript_direct("nocaps") |
| 438 | self.assertIsNone(result) |
| 439 | |
| 440 | def test_http_timeout_returns_none(self): |
| 441 | """HTTP timeout on watch page returns None.""" |
| 442 | def timeout_open(req, *, timeout=None): |
| 443 | raise TimeoutError("timed out") |
| 444 | |
| 445 | with mock.patch("lib.youtube_yt.urllib.request.urlopen", side_effect=timeout_open): |
| 446 | result = youtube_yt._fetch_transcript_direct("timeout_vid") |
| 447 | self.assertIsNone(result) |
| 448 | |
| 449 | def test_direct_vtt_feeds_into_clean_vtt(self): |
| 450 | """VTT from direct fetch produces clean plaintext via _clean_vtt().""" |
| 451 | cleaned = youtube_yt._clean_vtt(self._SAMPLE_VTT) |
| 452 | self.assertNotIn("WEBVTT", cleaned) |
| 453 | self.assertNotIn("-->", cleaned) |
| 454 | self.assertIn("Hello world", cleaned) |
| 455 | self.assertIn("Another line", cleaned) |
| 456 | |
| 457 | |
| 458 | class TestFetchTranscriptFallback(unittest.TestCase): |
| 459 | """Tests that fetch_transcript picks yt-dlp or direct path correctly.""" |
| 460 | |
| 461 | def test_uses_ytdlp_when_installed(self): |
| 462 | """When yt-dlp is installed, uses _fetch_transcript_ytdlp.""" |
| 463 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 464 | mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp", return_value="WEBVTT\n\nfake") as yt_mock, \ |
| 465 | mock.patch.object(youtube_yt, "_fetch_transcript_direct") as direct_mock: |
| 466 | result = youtube_yt.fetch_transcript("vid1", "/tmp/test") |
| 467 | yt_mock.assert_called_once_with("vid1", "/tmp/test", status=None, fast_fail=False) |
| 468 | direct_mock.assert_not_called() |
| 469 | |
| 470 | def test_uses_direct_when_ytdlp_missing(self): |
| 471 | """When yt-dlp is NOT installed, falls back to _fetch_transcript_direct.""" |
| 472 | sample_vtt = ( |
| 473 | "WEBVTT\n\n" |
| 474 | "00:00:00.000 --> 00:00:02.000\n" |
| 475 | "Direct transcript content with enough words for testing.\n" |
| 476 | ) |
| 477 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=False), \ |
| 478 | mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp") as yt_mock, \ |
| 479 | mock.patch.object(youtube_yt, "_fetch_transcript_direct", return_value=sample_vtt) as direct_mock: |
| 480 | result = youtube_yt.fetch_transcript("vid2", "/tmp/test") |
| 481 | yt_mock.assert_not_called() |
| 482 | direct_mock.assert_called_once_with("vid2", status=None) |
| 483 | self.assertIsNotNone(result) |
| 484 | self.assertIn("Direct transcript content", result) |
| 485 | |
| 486 | def test_returns_none_when_both_fail(self): |
| 487 | """Returns None when the chosen path returns None.""" |
| 488 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=False), \ |
| 489 | mock.patch.object(youtube_yt, "_fetch_transcript_direct", return_value=None): |
| 490 | result = youtube_yt.fetch_transcript("novid", "/tmp/test") |
| 491 | self.assertIsNone(result) |
| 492 | |
| 493 | |
| 494 | class TestExpandYouTubeQueries(unittest.TestCase): |
| 495 | """Tests for expand_youtube_queries() multi-query generation.""" |
| 496 | |
| 497 | def test_default_depth_returns_two_plus_queries(self): |
| 498 | queries = youtube_yt.expand_youtube_queries("Kanye West", "default") |
| 499 | self.assertGreaterEqual(len(queries), 2) |
| 500 | # First query is the core subject |
| 501 | self.assertEqual(queries[0].lower(), "kanye west") |
| 502 | |
| 503 | def test_how_to_intent_includes_tutorial_variant(self): |
| 504 | # Use deep depth so the intent variant isn't capped out by core + original |
| 505 | queries = youtube_yt.expand_youtube_queries("how to use Docker", "deep") |
| 506 | variant_found = any( |
| 507 | "tutorial" in q.lower() or "guide" in q.lower() or "explained" in q.lower() |
| 508 | for q in queries |
| 509 | ) |
| 510 | self.assertTrue( |
| 511 | variant_found, |
| 512 | f"Expected tutorial/guide/explained in queries: {queries}", |
| 513 | ) |
| 514 | |
| 515 | def test_product_intent_includes_review_variant(self): |
| 516 | # Use deep depth so the intent variant isn't capped out |
| 517 | queries = youtube_yt.expand_youtube_queries("best running shoes", "deep") |
| 518 | variant_found = any("review" in q.lower() for q in queries) |
| 519 | self.assertTrue(variant_found, f"Expected 'review' in queries: {queries}") |
| 520 | |
| 521 | def test_comparison_intent_includes_vs_variant(self): |
| 522 | queries = youtube_yt.expand_youtube_queries("Claude vs Gemini", "default") |
| 523 | variant_found = any("vs" in q.lower() or "compared" in q.lower() for q in queries) |
| 524 | self.assertTrue(variant_found, f"Expected 'vs' or 'compared' in queries: {queries}") |
| 525 | |
| 526 | def test_quick_depth_returns_one_query(self): |
| 527 | queries = youtube_yt.expand_youtube_queries("Kanye West", "quick") |
| 528 | self.assertEqual(len(queries), 1) |
| 529 | |
| 530 | def test_deep_depth_returns_three_queries(self): |
| 531 | queries = youtube_yt.expand_youtube_queries("Kanye West", "deep") |
| 532 | self.assertEqual(len(queries), 3) |
| 533 | |
| 534 | def test_single_word_returns_at_least_one(self): |
| 535 | queries = youtube_yt.expand_youtube_queries("React", "default") |
| 536 | self.assertGreaterEqual(len(queries), 1) |
| 537 | |
| 538 | def test_temporal_words_stripped_from_core(self): |
| 539 | queries = youtube_yt.expand_youtube_queries("kanye west last 30 days", "default") |
| 540 | core = queries[0].lower() |
| 541 | self.assertNotIn("last", core) |
| 542 | self.assertNotIn("days", core) |
| 543 | self.assertIn("kanye", core) |
| 544 | self.assertIn("west", core) |
| 545 | |
| 546 | |
| 547 | class TestTranscriptCandidateSortKey(unittest.TestCase): |
| 548 | """Tests for _transcript_candidate_sort_key recency-boosted ordering.""" |
| 549 | |
| 550 | @staticmethod |
| 551 | def _d(days_ago: int) -> str: |
| 552 | return (datetime.now(timezone.utc) - timedelta(days=days_ago)).strftime("%Y-%m-%d") |
| 553 | |
| 554 | def _make_item(self, video_id, views, date_str): |
| 555 | return { |
| 556 | "video_id": video_id, |
| 557 | "title": f"Video {video_id}", |
| 558 | "url": f"https://www.youtube.com/watch?v={video_id}", |
| 559 | "channel_name": "TestChannel", |
| 560 | "date": date_str, |
| 561 | "engagement": {"views": views, "likes": 10, "comments": 5}, |
| 562 | "relevance": 0.8, |
| 563 | "why_relevant": "test", |
| 564 | "description": "test desc", |
| 565 | "duration": 600, |
| 566 | } |
| 567 | |
| 568 | def test_recency_breaks_views_tie(self): |
| 569 | """When views are equal, the more recent video gets a higher sort key.""" |
| 570 | new = self._make_item("new", 100_000, self._d(1)) |
| 571 | old = self._make_item("old", 100_000, self._d(13)) |
| 572 | self.assertGreater( |
| 573 | youtube_yt._transcript_candidate_sort_key(new), |
| 574 | youtube_yt._transcript_candidate_sort_key(old), |
| 575 | ) |
| 576 | |
| 577 | def test_old_high_view_can_still_qualify_for_transcript(self): |
| 578 | """An old video with very high views still gets a transcript slot; |
| 579 | recency is a tiebreaker, not a gate.""" |
| 580 | old_high = self._make_item("old_high", 10_000_000, self._d(45)) |
| 581 | recent_low = self._make_item("recent_low", 100, self._d(1)) |
| 582 | self.assertGreater( |
| 583 | youtube_yt._transcript_candidate_sort_key(old_high), |
| 584 | youtube_yt._transcript_candidate_sort_key(recent_low), |
| 585 | ) |
| 586 | |
| 587 | def test_no_date_falls_to_back(self): |
| 588 | """An item with no date gets recency 0, sorting behind dated items.""" |
| 589 | no_date = self._make_item("no_date", 50_000, "") |
| 590 | dated = self._make_item("dated", 50_000, self._d(5)) |
| 591 | self.assertGreater( |
| 592 | youtube_yt._transcript_candidate_sort_key(dated), |
| 593 | youtube_yt._transcript_candidate_sort_key(no_date), |
| 594 | ) |
| 595 | |
| 596 | def test_transcript_candidates_pick_recent_over_old_same_views(self): |
| 597 | """search_and_transcribe selects candidates by (views, recency), |
| 598 | so a recent video is tried before an equal-view older video.""" |
| 599 | items = [ |
| 600 | self._make_item("old", 100_000, self._d(13)), |
| 601 | self._make_item("recent", 100_000, self._d(1)), |
| 602 | self._make_item("mid", 50_000, self._d(5)), |
| 603 | ] |
| 604 | |
| 605 | def fake_search(*args, **kwargs): |
| 606 | return {"items": items} |
| 607 | |
| 608 | call_args_list = [] |
| 609 | |
| 610 | def fake_fetch(video_ids, max_workers=5, out_captions_disabled=None, token=None, **_kwargs): |
| 611 | call_args_list.extend(video_ids) |
| 612 | return {vid: "transcript" for vid in video_ids} |
| 613 | |
| 614 | with mock.patch.object(youtube_yt, "search_youtube", side_effect=fake_search), \ |
| 615 | mock.patch.object(youtube_yt, "fetch_transcripts_parallel", side_effect=fake_fetch): |
| 616 | youtube_yt.search_and_transcribe("test", self._d(14), self._d(0), depth="default") |
| 617 | |
| 618 | # transcript_limit=2, attempt_count=4 (limited to 3 items) |
| 619 | # Sorted by (views, recency): recent(100k) > old(100k) > mid(50k) |
| 620 | self.assertEqual(call_args_list[:2], ["recent", "old"], |
| 621 | "Recent video should be tried before equal-view older video") |
| 622 | |
| 623 | |
| 624 | class TestSearchAndTranscribe(unittest.TestCase): |
| 625 | """Tests for search_and_transcribe() end-to-end flow.""" |
| 626 | |
| 627 | def _make_item(self, video_id, views): |
| 628 | return { |
| 629 | "video_id": video_id, |
| 630 | "title": f"Video {video_id}", |
| 631 | "url": f"https://www.youtube.com/watch?v={video_id}", |
| 632 | "channel_name": "TestChannel", |
| 633 | "date": "2026-03-15", |
| 634 | "engagement": {"views": views, "likes": 10, "comments": 5}, |
| 635 | "relevance": 0.8, |
| 636 | "why_relevant": "test", |
| 637 | "description": "test desc", |
| 638 | "duration": 600, |
| 639 | } |
| 640 | |
| 641 | def test_transcripts_attached_when_top_videos_lack_captions(self): |
| 642 | """When top-viewed videos have no captions, lower-ranked ones still get transcripts.""" |
| 643 | items = [ |
| 644 | self._make_item("music1", 1_000_000), # no captions (music video) |
| 645 | self._make_item("music2", 500_000), # no captions (music video) |
| 646 | self._make_item("talk1", 50_000), # has captions |
| 647 | self._make_item("talk2", 25_000), # has captions |
| 648 | ] |
| 649 | |
| 650 | # fetch_transcripts_parallel returns None for music videos, text for talks |
| 651 | def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None, token=None, **_kwargs): |
| 652 | result = {} |
| 653 | for vid in video_ids: |
| 654 | if vid.startswith("talk"): |
| 655 | result[vid] = "This is a detailed discussion about the topic with 100 data points." |
| 656 | else: |
| 657 | result[vid] = None |
| 658 | return result |
| 659 | |
| 660 | with mock.patch.object(youtube_yt, "search_youtube", return_value={"items": items}), \ |
| 661 | mock.patch.object(youtube_yt, "fetch_transcripts_parallel", side_effect=fake_parallel) as ft_mock: |
| 662 | result = youtube_yt.search_and_transcribe("test topic", "2026-03-01", "2026-03-31", depth="default") |
| 663 | |
| 664 | # Should have attempted more than just the top 2 (transcript_limit=2) |
| 665 | called_ids = ft_mock.call_args[0][0] |
| 666 | self.assertGreater(len(called_ids), 2, "Should attempt more than transcript_limit candidates") |
| 667 | self.assertIn("talk1", called_ids) |
| 668 | self.assertIn("talk2", called_ids) |
| 669 | |
| 670 | # talk1 and talk2 should have transcripts |
| 671 | items_by_id = {i["video_id"]: i for i in result["items"]} |
| 672 | self.assertTrue(items_by_id["talk1"]["transcript_snippet"]) |
| 673 | self.assertTrue(items_by_id["talk1"]["transcript_highlights"]) |
| 674 | # music videos should have empty transcripts |
| 675 | self.assertFalse(items_by_id["music1"]["transcript_snippet"]) |
| 676 | |
| 677 | def test_transcript_limit_zero_skips_fetch(self): |
| 678 | """When transcript_limit is 0 (quick depth), no transcripts are fetched.""" |
| 679 | items = [self._make_item("vid1", 1000)] |
| 680 | with mock.patch.object(youtube_yt, "search_youtube", return_value={"items": items}), \ |
| 681 | mock.patch.object(youtube_yt, "fetch_transcripts_parallel") as ft_mock: |
| 682 | result = youtube_yt.search_and_transcribe("test", "2026-03-01", "2026-03-31", depth="quick") |
| 683 | |
| 684 | ft_mock.assert_not_called() |
| 685 | self.assertEqual(result["items"][0]["transcript_snippet"], "") |
| 686 | |
| 687 | def test_no_items_returns_early(self): |
| 688 | """When search returns no items, returns without fetching transcripts.""" |
| 689 | with mock.patch.object(youtube_yt, "search_youtube", return_value={"items": []}), \ |
| 690 | mock.patch.object(youtube_yt, "fetch_transcripts_parallel") as ft_mock: |
| 691 | result = youtube_yt.search_and_transcribe("nothing", "2026-03-01", "2026-03-31") |
| 692 | |
| 693 | ft_mock.assert_not_called() |
| 694 | |
| 695 | |
| 696 | class TestTranscriptFetchStats(unittest.TestCase): |
| 697 | """Track yt-dlp fetch outcomes for quality_nudge (#531 false stale-yt-dlp nudge).""" |
| 698 | |
| 699 | FROM_DATE = "2026-03-01" |
| 700 | TO_DATE = "2026-03-31" |
| 701 | |
| 702 | def setUp(self): |
| 703 | youtube_yt.reset_transcript_fetch_stats() |
| 704 | |
| 705 | def _make_item(self, video_id, views, date): |
| 706 | return { |
| 707 | "video_id": video_id, |
| 708 | "title": f"Video {video_id}", |
| 709 | "url": f"https://www.youtube.com/watch?v={video_id}", |
| 710 | "channel_name": "TestChannel", |
| 711 | "date": date, |
| 712 | "engagement": {"views": views, "likes": 10, "comments": 5}, |
| 713 | "relevance": 0.8, |
| 714 | "why_relevant": "test", |
| 715 | "description": "test desc", |
| 716 | "duration": 600, |
| 717 | } |
| 718 | |
| 719 | def _run(self, items, fake_parallel=None): |
| 720 | if fake_parallel is None: |
| 721 | def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None, token=None, **_kwargs): |
| 722 | return {vid: "A detailed transcript about the topic." for vid in video_ids} |
| 723 | with mock.patch.object(youtube_yt, "search_youtube", return_value={"items": items}), \ |
| 724 | mock.patch.object(youtube_yt, "fetch_transcripts_parallel", side_effect=fake_parallel): |
| 725 | return youtube_yt.search_and_transcribe( |
| 726 | "test topic", self.FROM_DATE, self.TO_DATE, depth="default", |
| 727 | ) |
| 728 | |
| 729 | def test_fetch_stats_track_attempts_and_failures(self): |
| 730 | items = [ |
| 731 | self._make_item("ok1", 3_000, "2026-03-20"), |
| 732 | self._make_item("fail1", 2_000, "2026-03-15"), |
| 733 | self._make_item("nocap1", 1_000, "2026-03-10"), |
| 734 | ] |
| 735 | |
| 736 | def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None, token=None, **_kwargs): |
| 737 | result = {} |
| 738 | for vid in video_ids: |
| 739 | if vid.startswith("nocap"): |
| 740 | result[vid] = None |
| 741 | if out_captions_disabled is not None: |
| 742 | out_captions_disabled.add(vid) |
| 743 | elif vid.startswith("fail"): |
| 744 | result[vid] = None |
| 745 | else: |
| 746 | result[vid] = "A detailed transcript about the topic." |
| 747 | return result |
| 748 | |
| 749 | self._run(items, fake_parallel) |
| 750 | |
| 751 | stats = youtube_yt.get_transcript_fetch_stats() |
| 752 | self.assertEqual(stats["attempts"], 3) |
| 753 | # Captions-disabled videos can never succeed; they are not failures. |
| 754 | self.assertEqual(stats["failures"], 1) |
| 755 | |
| 756 | def test_fetch_stats_zero_failures_when_all_succeed(self): |
| 757 | # The #531 scenario: every fetch succeeds (on videos later pruned by |
| 758 | # freshness scoring). failures must be 0 so quality_nudge does not |
| 759 | # blame a stale yt-dlp binary. |
| 760 | items = [self._make_item(f"v{i}", 1_000 * (i + 1), "2024-01-15") for i in range(4)] |
| 761 | |
| 762 | self._run(items) |
| 763 | |
| 764 | stats = youtube_yt.get_transcript_fetch_stats() |
| 765 | self.assertEqual(stats["attempts"], 4) |
| 766 | self.assertEqual(stats["failures"], 0) |
| 767 | |
| 768 | def test_fetch_stats_record_the_transcript_target_and_no_block(self): |
| 769 | items = [self._make_item(f"v{i}", 1_000 * (i + 1), "2026-03-15") for i in range(8)] |
| 770 | |
| 771 | self._run(items) |
| 772 | |
| 773 | stats = youtube_yt.get_transcript_fetch_stats() |
| 774 | self.assertEqual(stats["target"], youtube_yt.TRANSCRIPT_LIMITS["default"]) |
| 775 | self.assertEqual(stats["blocked"], 0) |
| 776 | |
| 777 | def test_fetch_stats_record_a_bot_check(self): |
| 778 | items = [self._make_item(f"v{i}", 1_000 * (i + 1), "2026-03-15") for i in range(4)] |
| 779 | |
| 780 | def fake_parallel(video_ids, max_workers=5, out_captions_disabled=None, token=None, **_kwargs): |
| 781 | youtube_yt._note_youtube_block("ERROR: Sign in to confirm you're not a bot") |
| 782 | return {vid: None for vid in video_ids} |
| 783 | |
| 784 | self._run(items, fake_parallel) |
| 785 | |
| 786 | stats = youtube_yt.get_transcript_fetch_stats() |
| 787 | self.assertEqual(stats["blocked"], 1) |
| 788 | self.assertEqual(stats["failures"], stats["attempts"]) |
| 789 | |
| 790 | def test_fetch_stats_count_scrapecreators_rescues(self): |
| 791 | def fake_fetch(vid, temp_dir, status, token, rescue_budget=None): |
| 792 | if vid == "rescued": |
| 793 | status["sc_rescued"] = True |
| 794 | return "A transcript." |
| 795 | |
| 796 | with mock.patch.object(youtube_yt, "fetch_transcript", side_effect=fake_fetch): |
| 797 | youtube_yt.fetch_transcripts_parallel(["rescued", "plain"], token="sc-dummy") |
| 798 | |
| 799 | self.assertEqual(youtube_yt.get_transcript_fetch_stats()["sc_rescued"], 1) |
| 800 | |
| 801 | def test_quality_results_pass_the_new_stats_through(self): |
| 802 | import last30days |
| 803 | report = mock.Mock() |
| 804 | report.items_by_source = {} |
| 805 | report.source_status = {} |
| 806 | report.errors_by_source = {} |
| 807 | stats = {"attempts": 6, "failures": 4, "target": 2, "blocked": 1, "sc_rescued": 2} |
| 808 | results = last30days._quality_research_results(report, {}, stats) |
| 809 | self.assertEqual(results["youtube_transcript_target"], 2) |
| 810 | self.assertEqual(results["youtube_bot_checked"], 1) |
| 811 | self.assertEqual(results["youtube_sc_rescued"], 2) |
| 812 | |
| 813 | |
| 814 | class TestYtdlpSSHRouting(unittest.TestCase): |
| 815 | """LAST30DAYS_YOUTUBE_SSH_HOST routes yt-dlp invocations through SSH for residential IP.""" |
| 816 | |
| 817 | def setUp(self): |
| 818 | # Ensure clean env for each test |
| 819 | self._saved_env = os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None) |
| 820 | youtube_yt.reset_search_cache() |
| 821 | |
| 822 | def tearDown(self): |
| 823 | os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None) |
| 824 | if self._saved_env is not None: |
| 825 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = self._saved_env |
| 826 | |
| 827 | def test_no_env_var_returns_none(self): |
| 828 | """Without the env var set, _ytdlp_ssh_host returns None.""" |
| 829 | self.assertIsNone(youtube_yt._ytdlp_ssh_host()) |
| 830 | |
| 831 | def test_env_var_returns_host(self): |
| 832 | """With LAST30DAYS_YOUTUBE_SSH_HOST set, _ytdlp_ssh_host returns it.""" |
| 833 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "macmini" |
| 834 | self.assertEqual(youtube_yt._ytdlp_ssh_host(), "macmini") |
| 835 | |
| 836 | def test_env_var_whitespace_stripped(self): |
| 837 | """Whitespace around the host alias is stripped.""" |
| 838 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = " macmini " |
| 839 | self.assertEqual(youtube_yt._ytdlp_ssh_host(), "macmini") |
| 840 | |
| 841 | def test_empty_env_var_falls_back_to_none(self): |
| 842 | """An empty env var is treated as unset.""" |
| 843 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "" |
| 844 | self.assertIsNone(youtube_yt._ytdlp_ssh_host()) |
| 845 | |
| 846 | def test_wrap_cmd_passthrough_when_unset(self): |
| 847 | """_wrap_ytdlp_cmd injects player_client but does not SSH-wrap when unset.""" |
| 848 | cmd = ["yt-dlp", "--ignore-config", "ytsearch5:test"] |
| 849 | wrapped = youtube_yt._wrap_ytdlp_cmd(cmd) |
| 850 | self.assertEqual(wrapped[0], "yt-dlp") |
| 851 | self.assertIn("ytsearch5:test", wrapped) |
| 852 | self.assertIn("--extractor-args", wrapped) |
| 853 | self.assertIn("youtube:player_client=android", wrapped) |
| 854 | |
| 855 | def test_wrap_cmd_prepends_ssh_when_set(self): |
| 856 | """_wrap_ytdlp_cmd prepends ssh <host> when SSH routing is on.""" |
| 857 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "macmini" |
| 858 | cmd = ["yt-dlp", "--ignore-config", "ytsearch5:test"] |
| 859 | wrapped = youtube_yt._wrap_ytdlp_cmd(cmd) |
| 860 | self.assertEqual(wrapped[0], "ssh") |
| 861 | self.assertEqual(wrapped[1], "-o") |
| 862 | self.assertEqual(wrapped[2], "BatchMode=yes") |
| 863 | # `--` terminates SSH option parsing so a host starting with `-` |
| 864 | # (e.g. `-oProxyCommand=...`) cannot be reinterpreted as a flag. |
| 865 | self.assertEqual(wrapped[3], "--") |
| 866 | self.assertEqual(wrapped[4], "macmini") |
| 867 | # Final arg is the shell-quoted command string |
| 868 | self.assertIn("yt-dlp", wrapped[5]) |
| 869 | self.assertIn("ytsearch5:test", wrapped[5]) |
| 870 | |
| 871 | def test_wrap_cmd_quotes_args_with_spaces(self): |
| 872 | """Args containing spaces or special chars are shell-quoted.""" |
| 873 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "macmini" |
| 874 | cmd = ["yt-dlp", "ytsearch5:hello world", "--dump-json"] |
| 875 | wrapped = youtube_yt._wrap_ytdlp_cmd(cmd) |
| 876 | # shlex.quote wraps the whole arg in single quotes when it contains spaces |
| 877 | self.assertIn("'ytsearch5:hello world'", wrapped[5]) |
| 878 | |
| 879 | def test_wrap_cmd_uses_option_terminator(self): |
| 880 | """`--` is inserted before host as defense-in-depth even for valid hosts.""" |
| 881 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "macmini" |
| 882 | cmd = ["yt-dlp", "--version"] |
| 883 | wrapped = youtube_yt._wrap_ytdlp_cmd(cmd) |
| 884 | dash_idx = wrapped.index("--") |
| 885 | self.assertEqual(wrapped[dash_idx + 1], "macmini") |
| 886 | |
| 887 | def test_host_alias_with_dash_prefix_is_rejected(self): |
| 888 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "-p22" |
| 889 | self.assertIsNone(youtube_yt._ytdlp_ssh_host()) |
| 890 | cmd = ["yt-dlp", "--version"] |
| 891 | self.assertEqual(youtube_yt._wrap_ytdlp_cmd(cmd), cmd) |
| 892 | |
| 893 | def test_host_alias_with_option_payload_is_rejected(self): |
| 894 | """Reject an SSH option payload independently of command option termination.""" |
| 895 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "-oProxyCommand=evil" |
| 896 | self.assertIsNone(youtube_yt._ytdlp_ssh_host()) |
| 897 | # And the wrap function falls back to the local-execution path. |
| 898 | cmd = ["yt-dlp", "--version"] |
| 899 | self.assertEqual(youtube_yt._wrap_ytdlp_cmd(cmd), cmd) |
| 900 | |
| 901 | def test_host_alias_with_shell_metacharacters_is_rejected(self): |
| 902 | """Host values containing spaces, semicolons, $, etc. are rejected.""" |
| 903 | for bad in ("host;rm -rf /", "host name", "host$IFS", "host`whoami`", "host&cmd"): |
| 904 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = bad |
| 905 | self.assertIsNone( |
| 906 | youtube_yt._ytdlp_ssh_host(), |
| 907 | msg=f"validator should reject {bad!r}", |
| 908 | ) |
| 909 | |
| 910 | def test_host_alias_validator_accepts_realistic_aliases(self): |
| 911 | """Valid SSH config aliases are accepted: bare names, FQDNs, IPs.""" |
| 912 | for good in ("p22", "macmini", "home-server", "pi5.local", "192.168.1.10", "homelab_box"): |
| 913 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = good |
| 914 | self.assertEqual(youtube_yt._ytdlp_ssh_host(), good) |
| 915 | |
| 916 | def test_is_ytdlp_installed_short_circuits_with_ssh(self): |
| 917 | """is_ytdlp_installed returns True without local check when SSH routing is on.""" |
| 918 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "macmini" |
| 919 | with mock.patch("lib.youtube_yt.shutil.which", return_value=None) as which_mock: |
| 920 | self.assertTrue(youtube_yt.is_ytdlp_installed()) |
| 921 | which_mock.assert_not_called() |
| 922 | |
| 923 | def test_is_ytdlp_installed_falls_through_without_ssh(self): |
| 924 | """is_ytdlp_installed checks PATH normally when SSH routing is off.""" |
| 925 | with mock.patch("lib.youtube_yt.shutil.which", return_value="/usr/bin/yt-dlp"): |
| 926 | self.assertTrue(youtube_yt.is_ytdlp_installed()) |
| 927 | with mock.patch("lib.youtube_yt.shutil.which", return_value=None): |
| 928 | self.assertFalse(youtube_yt.is_ytdlp_installed()) |
| 929 | |
| 930 | def test_search_call_routes_through_ssh(self): |
| 931 | """search_youtube wraps the yt-dlp invocation when SSH routing is on.""" |
| 932 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "macmini" |
| 933 | from lib.subproc import SubprocResult |
| 934 | fake_result = SubprocResult(returncode=0, stdout="", stderr="") |
| 935 | with mock.patch.object(youtube_yt.subproc, "run_with_timeout", |
| 936 | return_value=fake_result) as run_mock: |
| 937 | youtube_yt.search_youtube("test", "2026-02-01", "2026-03-01") |
| 938 | cmd = run_mock.call_args.args[0] |
| 939 | self.assertEqual(cmd[0], "ssh") |
| 940 | self.assertEqual(cmd[3], "--") |
| 941 | self.assertEqual(cmd[4], "macmini") |
| 942 | # The shell-quoted yt-dlp invocation lives at index 5 |
| 943 | self.assertIn("yt-dlp", cmd[5]) |
| 944 | self.assertIn("--ignore-config", cmd[5]) |
| 945 | self.assertIn("--no-cookies-from-browser", cmd[5]) |
| 946 | |
| 947 | def test_search_surfaces_ssh_failure_as_error(self): |
| 948 | """SSH connection failures surface as an error, not silent '0 results'.""" |
| 949 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "macmini" |
| 950 | from lib.subproc import SubprocResult |
| 951 | fake_result = SubprocResult( |
| 952 | returncode=255, |
| 953 | stdout="", |
| 954 | stderr="ssh: connect to host macmini port 22: Connection refused\n", |
| 955 | ) |
| 956 | with mock.patch.object(youtube_yt.subproc, "run_with_timeout", |
| 957 | return_value=fake_result): |
| 958 | out = youtube_yt.search_youtube("test", "2026-02-01", "2026-03-01") |
| 959 | self.assertIn("error", out) |
| 960 | self.assertIn("Connection refused", out["error"]) |
| 961 | |
| 962 | |
| 963 | class TestTranscriptSSHRouting(unittest.TestCase): |
| 964 | """LAST30DAYS_YOUTUBE_SSH_HOST routes yt-dlp transcript fetches through SSH.""" |
| 965 | |
| 966 | def setUp(self): |
| 967 | self._saved_env = os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None) |
| 968 | |
| 969 | def tearDown(self): |
| 970 | os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None) |
| 971 | if self._saved_env is not None: |
| 972 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = self._saved_env |
| 973 | |
| 974 | def test_ssh_helper_invokes_remote_mktemp_pipeline(self): |
| 975 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "macmini" |
| 976 | from lib.subproc import SubprocResult |
| 977 | fake_vtt = "WEBVTT\nKind: captions\nLanguage: en\n\n00:00:00.000 --> 00:00:02.000\nhi\n" |
| 978 | fake_result = SubprocResult(returncode=0, stdout=fake_vtt, stderr="") |
| 979 | with mock.patch.object(youtube_yt.subproc, "run_with_timeout", |
| 980 | return_value=fake_result) as run_mock: |
| 981 | out = youtube_yt._fetch_transcript_ytdlp_via_ssh("vid1", "macmini") |
| 982 | self.assertEqual(out, fake_vtt) |
| 983 | remote_script = run_mock.call_args.args[0][5] |
| 984 | self.assertIn("mktemp -d", remote_script) |
| 985 | self.assertIn("find ", remote_script) |
| 986 | |
| 987 | def test_fetch_transcript_uses_ssh_helper_when_routing_on(self): |
| 988 | os.environ["LAST30DAYS_YOUTUBE_SSH_HOST"] = "macmini" |
| 989 | fake_vtt = "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nhello there friends\n" |
| 990 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 991 | mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp_via_ssh", |
| 992 | return_value=fake_vtt) as ssh_mock, \ |
| 993 | mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp") as local_mock, \ |
| 994 | mock.patch.object(youtube_yt, "_fetch_transcript_direct") as direct_mock: |
| 995 | result = youtube_yt.fetch_transcript("vidX", "/tmp/test") |
| 996 | ssh_mock.assert_called_once_with("vidX", "macmini") |
| 997 | local_mock.assert_not_called() |
| 998 | direct_mock.assert_not_called() |
| 999 | self.assertIn("hello there friends", result) |
| 1000 | |
| 1001 | |
| 1002 | class TestScTranscriptFallback(unittest.TestCase): |
| 1003 | """ScrapeCreators fallback wiring in fetch_transcript (U1/U2).""" |
| 1004 | |
| 1005 | def _ytdlp_hard_fail(self, reason="HTTP Error 429: Too Many Requests"): |
| 1006 | def _fake(video_id, temp_dir, status=None, fast_fail=False): |
| 1007 | if status is not None: |
| 1008 | status["ytdlp_error"] = reason |
| 1009 | return None |
| 1010 | return _fake |
| 1011 | |
| 1012 | def test_sc_fallback_fires_on_ytdlp_hard_failure_with_token(self): |
| 1013 | """A yt-dlp hard failure (429) with a key falls back to ScrapeCreators.""" |
| 1014 | status = {} |
| 1015 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1016 | mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp", |
| 1017 | side_effect=self._ytdlp_hard_fail()), \ |
| 1018 | mock.patch.object(youtube_yt, "_fetch_transcript_direct") as direct_mock, \ |
| 1019 | mock.patch.object(youtube_yt, "_sc_fetch_transcript", |
| 1020 | return_value="scrapecreators transcript text") as sc_mock: |
| 1021 | result = youtube_yt.fetch_transcript("vidA", "/tmp/x", status=status, token="key123") |
| 1022 | sc_mock.assert_called_once_with("vidA", "key123") |
| 1023 | direct_mock.assert_not_called() # hard error skips the (also-blocked) direct path |
| 1024 | self.assertEqual(result, "scrapecreators transcript text") |
| 1025 | |
| 1026 | def test_sc_rescue_logged_and_flagged_in_status(self): |
| 1027 | """A yt-dlp hard failure rescued by ScrapeCreators must be logged and |
| 1028 | flagged via status['sc_rescued'] — not just returned silently — so |
| 1029 | fetch_transcripts_parallel() can report the rescue instead of letting |
| 1030 | the batch summary read as a clean success (#831).""" |
| 1031 | status = {} |
| 1032 | logs = [] |
| 1033 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1034 | mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp", |
| 1035 | side_effect=self._ytdlp_hard_fail()), \ |
| 1036 | mock.patch.object(youtube_yt, "_sc_fetch_transcript", |
| 1037 | return_value="rescued transcript text"), \ |
| 1038 | mock.patch.object(youtube_yt, "_log", side_effect=lambda m: logs.append(m)): |
| 1039 | result = youtube_yt.fetch_transcript("vidR", "/tmp/x", status=status, token="key123") |
| 1040 | self.assertEqual(result, "rescued transcript text") |
| 1041 | self.assertTrue(status.get("sc_rescued")) |
| 1042 | self.assertTrue(any("ScrapeCreators" in m and "vidR" in m for m in logs)) |
| 1043 | |
| 1044 | def test_sc_not_called_when_ytdlp_succeeds(self): |
| 1045 | """No credit is spent when yt-dlp returns a transcript.""" |
| 1046 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1047 | mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp", |
| 1048 | return_value="WEBVTT\n\nreal captions here"), \ |
| 1049 | mock.patch.object(youtube_yt, "_sc_fetch_transcript") as sc_mock: |
| 1050 | result = youtube_yt.fetch_transcript("vidB", "/tmp/x", status={}, token="key123") |
| 1051 | sc_mock.assert_not_called() |
| 1052 | self.assertIn("real captions", result) |
| 1053 | |
| 1054 | def test_sc_not_called_without_token(self): |
| 1055 | """Keyless behavior unchanged: no token means no ScrapeCreators.""" |
| 1056 | status = {} |
| 1057 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1058 | mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp", |
| 1059 | side_effect=self._ytdlp_hard_fail()), \ |
| 1060 | mock.patch.object(youtube_yt, "_sc_fetch_transcript") as sc_mock: |
| 1061 | result = youtube_yt.fetch_transcript("vidC", "/tmp/x", status=status, token=None) |
| 1062 | sc_mock.assert_not_called() |
| 1063 | self.assertIsNone(result) |
| 1064 | |
| 1065 | def test_sc_skipped_when_proven_captionless(self): |
| 1066 | """A video proven to have no caption track must not spend a credit.""" |
| 1067 | def _ytdlp_no_captions(video_id, temp_dir, status=None, fast_fail=False): |
| 1068 | return None # exit-0 no captions: returns None, no ytdlp_error |
| 1069 | |
| 1070 | def _direct_no_tracks(video_id, status=None): |
| 1071 | if status is not None: |
| 1072 | status["no_caption_tracks"] = True |
| 1073 | return None |
| 1074 | |
| 1075 | status = {} |
| 1076 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1077 | mock.patch.object(youtube_yt, "_fetch_transcript_ytdlp", side_effect=_ytdlp_no_captions), \ |
| 1078 | mock.patch.object(youtube_yt, "_fetch_transcript_direct", side_effect=_direct_no_tracks), \ |
| 1079 | mock.patch.object(youtube_yt, "_sc_fetch_transcript") as sc_mock: |
| 1080 | result = youtube_yt.fetch_transcript("vidD", "/tmp/x", status=status, token="key123") |
| 1081 | sc_mock.assert_not_called() |
| 1082 | self.assertIsNone(result) |
| 1083 | |
| 1084 | def test_should_try_sc_transcript_predicate(self): |
| 1085 | self.assertTrue(youtube_yt._should_try_sc_transcript(None)) |
| 1086 | self.assertTrue(youtube_yt._should_try_sc_transcript({})) |
| 1087 | self.assertTrue(youtube_yt._should_try_sc_transcript({"ytdlp_error": "429"})) |
| 1088 | self.assertFalse(youtube_yt._should_try_sc_transcript({"no_caption_tracks": True})) |
| 1089 | |
| 1090 | def test_token_threads_through_parallel(self): |
| 1091 | """fetch_transcripts_parallel passes the token to every fetch_transcript.""" |
| 1092 | captured = {} |
| 1093 | |
| 1094 | def _fake_fetch_transcript(video_id, temp_dir, status=None, token=None, **_kwargs): |
| 1095 | captured[video_id] = token |
| 1096 | return None |
| 1097 | |
| 1098 | with mock.patch.object(youtube_yt, "fetch_transcript", side_effect=_fake_fetch_transcript): |
| 1099 | youtube_yt.fetch_transcripts_parallel(["v1", "v2"], token="tok") |
| 1100 | self.assertEqual(captured, {"v1": "tok", "v2": "tok"}) |
| 1101 | |
| 1102 | def test_summary_reports_sc_rescue_not_bare_success(self): |
| 1103 | """Regression for #831: when every video's yt-dlp fetch fails and the |
| 1104 | ScrapeCreators fallback rescues all of them, the batch summary must |
| 1105 | not read as a bare "0 failed" success — it has to say the videos |
| 1106 | were rescued via the fallback, so a fully rate-limited yt-dlp run |
| 1107 | doesn't look like nothing went wrong.""" |
| 1108 | logs = [] |
| 1109 | |
| 1110 | def _rescued_fetch_transcript(video_id, temp_dir, status=None, token=None, **_kwargs): |
| 1111 | if status is not None: |
| 1112 | status["sc_rescued"] = True |
| 1113 | return "rescued transcript" |
| 1114 | |
| 1115 | with mock.patch.object(youtube_yt, "fetch_transcript", |
| 1116 | side_effect=_rescued_fetch_transcript), \ |
| 1117 | mock.patch.object(youtube_yt, "_log", side_effect=lambda m: logs.append(m)): |
| 1118 | results = youtube_yt.fetch_transcripts_parallel(["v1", "v2"], token="tok") |
| 1119 | |
| 1120 | self.assertEqual(results, {"v1": "rescued transcript", "v2": "rescued transcript"}) |
| 1121 | summary = next(m for m in logs if m.startswith("Got transcripts for")) |
| 1122 | self.assertIn("2/2", summary) |
| 1123 | self.assertIn("0 failed", summary) |
| 1124 | self.assertIn("2 rescued via ScrapeCreators fallback", summary) |
| 1125 | |
| 1126 | def test_summary_omits_rescue_note_when_no_fallback_used(self): |
| 1127 | """The plain 'N/N (M failed)' format must be unchanged when no video |
| 1128 | needed the ScrapeCreators fallback — no rescue tag should appear.""" |
| 1129 | logs = [] |
| 1130 | |
| 1131 | def _plain_fetch_transcript(video_id, temp_dir, status=None, token=None, **_kwargs): |
| 1132 | return "a normal transcript" |
| 1133 | |
| 1134 | with mock.patch.object(youtube_yt, "fetch_transcript", |
| 1135 | side_effect=_plain_fetch_transcript), \ |
| 1136 | mock.patch.object(youtube_yt, "_log", side_effect=lambda m: logs.append(m)): |
| 1137 | youtube_yt.fetch_transcripts_parallel(["v1", "v2", "v3"], token="tok") |
| 1138 | |
| 1139 | summary = next(m for m in logs if m.startswith("Got transcripts for")) |
| 1140 | self.assertEqual(summary, "Got transcripts for 3/3 videos (0 failed)") |
| 1141 | |
| 1142 | |
| 1143 | class TestYtdlpFastFail(unittest.TestCase): |
| 1144 | """Fail-fast behavior when a ScrapeCreators key is present (U3).""" |
| 1145 | |
| 1146 | def _transient_fail(self): |
| 1147 | from lib.subproc import SubprocResult |
| 1148 | return SubprocResult( |
| 1149 | returncode=1, stdout="", |
| 1150 | stderr="ERROR: HTTP Error 429: Too Many Requests", |
| 1151 | ) |
| 1152 | |
| 1153 | def test_fast_fail_single_attempt_short_timeout(self): |
| 1154 | """token present -> one attempt, shortened timeout, no retry sleeps.""" |
| 1155 | with tempfile.TemporaryDirectory() as temp_dir: |
| 1156 | status = {} |
| 1157 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_TRANSCRIPT_FAST_TIMEOUT": ""}), \ |
| 1158 | mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1159 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", |
| 1160 | return_value=self._transient_fail()) as run_mock, \ |
| 1161 | mock.patch.object(youtube_yt.time, "sleep") as sleep_mock: |
| 1162 | vtt = youtube_yt._fetch_transcript_ytdlp("vidF", temp_dir, status, fast_fail=True) |
| 1163 | self.assertIsNone(vtt) |
| 1164 | self.assertEqual(run_mock.call_count, 1) # no retries |
| 1165 | self.assertEqual(run_mock.call_args.kwargs.get("timeout"), 12) |
| 1166 | sleep_mock.assert_not_called() |
| 1167 | self.assertIn("ytdlp_error", status) |
| 1168 | |
| 1169 | def test_no_token_retries_with_full_timeout(self): |
| 1170 | """token absent -> full retry budget and 30s timeout, unchanged.""" |
| 1171 | with tempfile.TemporaryDirectory() as temp_dir: |
| 1172 | status = {} |
| 1173 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1174 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", |
| 1175 | return_value=self._transient_fail()) as run_mock, \ |
| 1176 | mock.patch.object(youtube_yt.time, "sleep"): |
| 1177 | vtt = youtube_yt._fetch_transcript_ytdlp("vidG", temp_dir, status, fast_fail=False) |
| 1178 | self.assertIsNone(vtt) |
| 1179 | self.assertEqual(run_mock.call_count, youtube_yt._TRANSCRIPT_MAX_RETRIES + 1) |
| 1180 | self.assertEqual(run_mock.call_args.kwargs.get("timeout"), 30) |
| 1181 | |
| 1182 | |
| 1183 | class TestScTranscriptParsing(unittest.TestCase): |
| 1184 | """ScrapeCreators transcript parse + credits warning (U4).""" |
| 1185 | |
| 1186 | def test_list_of_dict_segments_parsed_to_text(self): |
| 1187 | payload = { |
| 1188 | "transcript": [ |
| 1189 | {"text": "hello there", "startMs": 0, "endMs": 1000}, |
| 1190 | {"text": "general kenobi", "startMs": 1000, "endMs": 2000}, |
| 1191 | ], |
| 1192 | "credits_remaining": 9999, |
| 1193 | } |
| 1194 | with mock.patch.object(youtube_yt.http, "get", return_value=payload): |
| 1195 | result = youtube_yt._sc_fetch_transcript("vidH", "key") |
| 1196 | self.assertIsNotNone(result) |
| 1197 | self.assertIn("hello there", result) |
| 1198 | self.assertIn("general kenobi", result) |
| 1199 | self.assertNotIn("startMs", result) |
| 1200 | self.assertNotIn("{'text'", result) |
| 1201 | |
| 1202 | def test_null_text_segment_does_not_emit_none(self): |
| 1203 | """A present-but-null text field (silent/music segment) must not become "None".""" |
| 1204 | payload = { |
| 1205 | "transcript": [ |
| 1206 | {"text": "real words here", "startMs": 0}, |
| 1207 | {"text": None, "startMs": 1000}, |
| 1208 | {"text": "more real words", "startMs": 2000}, |
| 1209 | ], |
| 1210 | "credits_remaining": 9999, |
| 1211 | } |
| 1212 | with mock.patch.object(youtube_yt.http, "get", return_value=payload): |
| 1213 | result = youtube_yt._sc_fetch_transcript("vidNull", "key") |
| 1214 | self.assertIsNotNone(result) |
| 1215 | self.assertNotIn("None", result) |
| 1216 | self.assertIn("real words here", result) |
| 1217 | self.assertIn("more real words", result) |
| 1218 | |
| 1219 | def test_plain_string_transcript_preserved(self): |
| 1220 | payload = {"transcript": "just a plain transcript string here", "credits_remaining": 9999} |
| 1221 | with mock.patch.object(youtube_yt.http, "get", return_value=payload): |
| 1222 | result = youtube_yt._sc_fetch_transcript("vidI", "key") |
| 1223 | self.assertIn("just a plain transcript", result) |
| 1224 | |
| 1225 | def test_low_credits_emits_warning(self): |
| 1226 | payload = {"transcript": "some transcript text", "credits_remaining": 5} |
| 1227 | logs = [] |
| 1228 | with mock.patch.object(youtube_yt.http, "get", return_value=payload), \ |
| 1229 | mock.patch.object(youtube_yt, "_log", side_effect=lambda m: logs.append(m)): |
| 1230 | youtube_yt._sc_fetch_transcript("vidJ", "key") |
| 1231 | self.assertTrue(any("credits low" in m.lower() for m in logs)) |
| 1232 | |
| 1233 | def test_requests_preferred_language(self): |
| 1234 | """Without a language the endpoint can return an auto-dubbed track (#1169).""" |
| 1235 | payload = {"transcript": "some transcript text", "credits_remaining": 9999} |
| 1236 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \ |
| 1237 | mock.patch.object(youtube_yt.http, "get", return_value=payload) as get_mock: |
| 1238 | youtube_yt._sc_fetch_transcript("vidL", "key") |
| 1239 | self.assertEqual(get_mock.call_args.kwargs["params"]["language"], "en") |
| 1240 | |
| 1241 | def test_language_follows_sub_langs_setting(self): |
| 1242 | payload = {"transcript": "some transcript text", "credits_remaining": 9999} |
| 1243 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "es,en"}), \ |
| 1244 | mock.patch.object(youtube_yt.http, "get", return_value=payload) as get_mock: |
| 1245 | youtube_yt._sc_fetch_transcript("vidM", "key") |
| 1246 | self.assertEqual(get_mock.call_args.kwargs["params"]["language"], "es") |
| 1247 | |
| 1248 | def test_tries_next_language_when_first_has_no_transcript(self): |
| 1249 | responses = [{"transcript": None}, {"transcript": "texto en español"}] |
| 1250 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \ |
| 1251 | mock.patch.object(youtube_yt.http, "get", side_effect=responses) as get_mock: |
| 1252 | out = youtube_yt._sc_fetch_transcript("vidN", "key") |
| 1253 | self.assertEqual(out, "texto en español") |
| 1254 | self.assertEqual( |
| 1255 | [c.kwargs["params"]["language"] for c in get_mock.call_args_list], ["en", "es"], |
| 1256 | ) |
| 1257 | |
| 1258 | def test_default_fallback_reaches_third_language_with_one_deadline(self): |
| 1259 | responses = [ |
| 1260 | {"transcript": None}, |
| 1261 | {"transcript": None}, |
| 1262 | {"transcript": "legendas em português"}, |
| 1263 | ] |
| 1264 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \ |
| 1265 | mock.patch.object(youtube_yt.http, "get", side_effect=responses) as get_mock: |
| 1266 | out = youtube_yt._sc_fetch_transcript("vidP", "key") |
| 1267 | self.assertEqual(out, "legendas em português") |
| 1268 | self.assertEqual( |
| 1269 | [c.kwargs["params"]["language"] for c in get_mock.call_args_list], |
| 1270 | ["en", "es", "pt"], |
| 1271 | ) |
| 1272 | self.assertEqual( |
| 1273 | len({c.kwargs["deadline_monotonic"] for c in get_mock.call_args_list}), 1, |
| 1274 | ) |
| 1275 | self.assertTrue(all(c.kwargs["max_429_retries"] == 0 for c in get_mock.call_args_list)) |
| 1276 | self.assertTrue(all(c.kwargs["owned_get"] for c in get_mock.call_args_list)) |
| 1277 | |
| 1278 | def test_custom_language_list_deduplicates_and_stops_after_three_requests(self): |
| 1279 | with mock.patch.dict( |
| 1280 | os.environ, {"LAST30DAYS_YT_SUB_LANGS": "fr,fr,de,ja,en,es"}, |
| 1281 | ), mock.patch.object( |
| 1282 | youtube_yt.http, "get", return_value={"transcript": None}, |
| 1283 | ) as get_mock: |
| 1284 | out = youtube_yt._sc_fetch_transcript("vidQ", "key") |
| 1285 | self.assertIsNone(out) |
| 1286 | self.assertEqual( |
| 1287 | [c.kwargs["params"]["language"] for c in get_mock.call_args_list], |
| 1288 | ["fr", "de", "ja"], |
| 1289 | ) |
| 1290 | |
| 1291 | def test_orig_codes_are_sent_to_sc_as_plain_languages(self): |
| 1292 | """#1314: SC never receives a yt-dlp-only `-orig` language code.""" |
| 1293 | with mock.patch.dict( |
| 1294 | os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en-orig,en,es"}, |
| 1295 | ), mock.patch.object( |
| 1296 | youtube_yt.http, "get", return_value={"transcript": None}, |
| 1297 | ) as get_mock: |
| 1298 | youtube_yt._sc_fetch_transcript("vidOrig", "key") |
| 1299 | self.assertEqual( |
| 1300 | [c.kwargs["params"]["language"] for c in get_mock.call_args_list], |
| 1301 | ["en", "es"], |
| 1302 | ) |
| 1303 | |
| 1304 | def test_empty_caption_segments_do_not_stop_language_fallback(self): |
| 1305 | responses = [ |
| 1306 | {"transcript": [{"text": None}, {"text": " "}]}, |
| 1307 | {"transcript": [{"text": "texto en español"}]}, |
| 1308 | ] |
| 1309 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en,es"}), \ |
| 1310 | mock.patch.object(youtube_yt.http, "get", side_effect=responses) as get_mock: |
| 1311 | out = youtube_yt._sc_fetch_transcript("vidR", "key") |
| 1312 | self.assertEqual(out, "texto en español") |
| 1313 | self.assertEqual(get_mock.call_count, 2) |
| 1314 | |
| 1315 | def test_404_tries_next_language(self): |
| 1316 | responses = [ |
| 1317 | youtube_yt.http.HTTPError("HTTP 404", status_code=404), |
| 1318 | {"transcript": "texto en español"}, |
| 1319 | ] |
| 1320 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en,es"}), \ |
| 1321 | mock.patch.object(youtube_yt.http, "get", side_effect=responses) as get_mock: |
| 1322 | out = youtube_yt._sc_fetch_transcript("vidS", "key") |
| 1323 | self.assertEqual(out, "texto en español") |
| 1324 | self.assertEqual(get_mock.call_count, 2) |
| 1325 | |
| 1326 | def test_shared_deadline_stops_before_another_request(self): |
| 1327 | clock = {"now": 100.0} |
| 1328 | |
| 1329 | def first_request(*_args, **_kwargs): |
| 1330 | clock["now"] = 131.0 |
| 1331 | return {"transcript": None} |
| 1332 | |
| 1333 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": "en,es"}), \ |
| 1334 | mock.patch.object(youtube_yt.time, "monotonic", side_effect=lambda: clock["now"]), \ |
| 1335 | mock.patch.object(youtube_yt.http, "get", side_effect=first_request) as get_mock: |
| 1336 | out = youtube_yt._sc_fetch_transcript("vidT", "key") |
| 1337 | self.assertIsNone(out) |
| 1338 | self.assertEqual(get_mock.call_count, 1) |
| 1339 | self.assertEqual(get_mock.call_args.kwargs["deadline_monotonic"], 130.0) |
| 1340 | |
| 1341 | def test_stops_on_non_404_error(self): |
| 1342 | with mock.patch.dict(os.environ, {"LAST30DAYS_YT_SUB_LANGS": ""}), \ |
| 1343 | mock.patch.object( |
| 1344 | youtube_yt.http, "get", |
| 1345 | side_effect=youtube_yt.http.HTTPError("HTTP 429", status_code=429), |
| 1346 | ) as get_mock: |
| 1347 | out = youtube_yt._sc_fetch_transcript("vidO", "key") |
| 1348 | self.assertIsNone(out) |
| 1349 | self.assertEqual(get_mock.call_count, 1) |
| 1350 | |
| 1351 | def test_healthy_credits_no_warning(self): |
| 1352 | payload = {"transcript": "some transcript text", "credits_remaining": 9999} |
| 1353 | logs = [] |
| 1354 | with mock.patch.object(youtube_yt.http, "get", return_value=payload), \ |
| 1355 | mock.patch.object(youtube_yt, "_log", side_effect=lambda m: logs.append(m)): |
| 1356 | youtube_yt._sc_fetch_transcript("vidK", "key") |
| 1357 | self.assertFalse(any("credits low" in m.lower() for m in logs)) |
| 1358 | |
| 1359 | |
| 1360 | class TestYoutubeCommentsGating(unittest.TestCase): |
| 1361 | """The legacy ScrapeCreators comment path, which applies only when yt-dlp |
| 1362 | is absent. With yt-dlp installed, comments are free and need no opt-in — |
| 1363 | see tests/test_youtube_comments_ytdlp.py.""" |
| 1364 | |
| 1365 | def test_off_with_key_and_no_include_sources(self): |
| 1366 | """SC path: key without INCLUDE_SOURCES does NOT fetch comments.""" |
| 1367 | from lib import env |
| 1368 | with mock.patch.object(env, "is_ytdlp_available", return_value=False): |
| 1369 | self.assertFalse(env.is_youtube_comments_available({"SCRAPECREATORS_API_KEY": "k"})) |
| 1370 | |
| 1371 | def test_on_with_include_sources(self): |
| 1372 | from lib import env |
| 1373 | cfg = {"SCRAPECREATORS_API_KEY": "k", "INCLUDE_SOURCES": "youtube_comments"} |
| 1374 | with mock.patch.object(env, "is_ytdlp_available", return_value=False): |
| 1375 | self.assertTrue(env.is_youtube_comments_available(cfg)) |
| 1376 | |
| 1377 | def test_unavailable_without_key(self): |
| 1378 | """SC path: no key and no yt-dlp means no comments at all.""" |
| 1379 | from lib import env |
| 1380 | with mock.patch.object(env, "is_ytdlp_available", return_value=False): |
| 1381 | self.assertFalse(env.is_youtube_comments_available({"INCLUDE_SOURCES": "youtube_comments"})) |
| 1382 | |
| 1383 | def test_tiktok_comments_still_opt_in(self): |
| 1384 | """Regression: TikTok comments must STILL require INCLUDE_SOURCES.""" |
| 1385 | from lib import env |
| 1386 | self.assertFalse( |
| 1387 | env.is_tiktok_comments_available({"SCRAPECREATORS_API_KEY": "k"}) |
| 1388 | ) |
| 1389 | self.assertTrue(env.is_tiktok_comments_available( |
| 1390 | {"SCRAPECREATORS_API_KEY": "k", "INCLUDE_SOURCES": "tiktok_comments"} |
| 1391 | )) |
| 1392 | |
| 1393 | |
| 1394 | class TestYouTubeSearchTimeoutAndCache(unittest.TestCase): |
| 1395 | """Comparison-mode load: timeouts, status honesty, and in-run dedup.""" |
| 1396 | |
| 1397 | def setUp(self): |
| 1398 | youtube_yt.reset_search_cache() |
| 1399 | |
| 1400 | def _fake_result(self, stdout: str = "", returncode: int = 0, stderr: str = ""): |
| 1401 | from lib.subproc import SubprocResult |
| 1402 | return SubprocResult(returncode=returncode, stdout=stdout, stderr=stderr) |
| 1403 | |
| 1404 | def test_search_nonzero_exit_reports_error_not_empty(self): |
| 1405 | stderr = ( |
| 1406 | "ERROR: [youtube] abc123: Sign in to confirm you're not a bot. " |
| 1407 | "Use --cookies-from-browser or --cookies for the authentication.\n" |
| 1408 | ) |
| 1409 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1410 | mock.patch.object( |
| 1411 | youtube_yt.subproc, "run_with_timeout", |
| 1412 | return_value=self._fake_result(returncode=1, stderr=stderr), |
| 1413 | ): |
| 1414 | out = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01") |
| 1415 | self.assertEqual(out.get("items"), []) |
| 1416 | self.assertIn("not a bot", out.get("error") or "") |
| 1417 | self.assertEqual( |
| 1418 | youtube_yt.classify_run_failure(out["error"]), |
| 1419 | youtube_yt.health.RATE_LIMITED, |
| 1420 | ) |
| 1421 | |
| 1422 | def test_sc_fallback_results_clear_ytdlp_search_failure(self): |
| 1423 | from lib import pipeline, schema |
| 1424 | video = {"id": "abc123", "title": "Vuori review", "url": "https://www.youtube.com/watch?v=abc123"} |
| 1425 | with mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), \ |
| 1426 | mock.patch.object( |
| 1427 | youtube_yt, "search_and_transcribe", |
| 1428 | return_value={"items": [], "error": "yt-dlp search failed: ERROR: Sign in to confirm you're not a bot"}, |
| 1429 | ), \ |
| 1430 | mock.patch.object(youtube_yt, "search_youtube_sc", return_value={"items": [video]}), \ |
| 1431 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False): |
| 1432 | items, artifact = pipeline._retrieve_stream_impl( |
| 1433 | topic="Vuori", |
| 1434 | subquery=schema.SubQuery(label="q", search_query="Vuori", ranking_query="Vuori", sources=["youtube"]), |
| 1435 | source="youtube", |
| 1436 | config={"SCRAPECREATORS_API_KEY": "k"}, |
| 1437 | depth="default", |
| 1438 | date_range=("2026-06-01", "2026-07-01"), |
| 1439 | runtime=schema.ProviderRuntime(reasoning_provider="mock", planner_model="mock", rerank_model="mock"), |
| 1440 | mock=False, |
| 1441 | ) |
| 1442 | self.assertEqual(items, [video]) |
| 1443 | self.assertNotIn("_source_outcome", artifact) |
| 1444 | self.assertEqual( |
| 1445 | artifact["_source_outcome_if_empty"]["state"], |
| 1446 | youtube_yt.health.RATE_LIMITED, |
| 1447 | ) |
| 1448 | |
| 1449 | def _run_sc_fallback_report( |
| 1450 | self, video, *, initial_empty=False, depth="quick", retry_video=None, |
| 1451 | search_error="yt-dlp search failed: Sign in to confirm you're not a bot", |
| 1452 | ): |
| 1453 | from lib import pipeline |
| 1454 | |
| 1455 | retrieve = pipeline._retrieve_stream |
| 1456 | calls = 0 |
| 1457 | |
| 1458 | def retrieve_live_youtube(*args, **kwargs): |
| 1459 | nonlocal calls |
| 1460 | calls += 1 |
| 1461 | if initial_empty and calls == 1: |
| 1462 | return [], {} |
| 1463 | return retrieve(*args, **{**kwargs, "mock": False}) |
| 1464 | |
| 1465 | plan = { |
| 1466 | "intent": "general", |
| 1467 | "freshness_mode": "balanced_recent", |
| 1468 | "cluster_mode": "story", |
| 1469 | "subqueries": [{ |
| 1470 | "label": "primary", |
| 1471 | "search_query": "Vuori", |
| 1472 | "ranking_query": "Vuori", |
| 1473 | "sources": ["youtube"], |
| 1474 | }], |
| 1475 | "source_weights": {"youtube": 1.0}, |
| 1476 | } |
| 1477 | sc_results = [{"items": [video]}] |
| 1478 | if retry_video is not None: |
| 1479 | sc_results.append({"items": [retry_video]}) |
| 1480 | with mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), \ |
| 1481 | mock.patch.object(pipeline, "_retrieve_stream", side_effect=retrieve_live_youtube), \ |
| 1482 | mock.patch.object( |
| 1483 | youtube_yt, "search_and_transcribe", |
| 1484 | return_value={"items": [], "error": search_error}, |
| 1485 | ), \ |
| 1486 | mock.patch.object( |
| 1487 | youtube_yt, "search_youtube_sc", |
| 1488 | side_effect=sc_results if retry_video is not None else None, |
| 1489 | return_value=sc_results[0], |
| 1490 | ) as sc_search, \ |
| 1491 | mock.patch.object(pipeline.env, "is_youtube_comments_available", return_value=False): |
| 1492 | report = pipeline.run( |
| 1493 | topic="Vuori", |
| 1494 | config={"SCRAPECREATORS_API_KEY": "k"}, |
| 1495 | depth=depth, |
| 1496 | requested_sources=["youtube"], |
| 1497 | mock=True, |
| 1498 | external_plan=plan, |
| 1499 | as_of_date="2026-07-01", |
| 1500 | ) |
| 1501 | return report, sc_search.call_count |
| 1502 | |
| 1503 | def test_sc_fallback_without_usable_video_preserves_search_failure_in_coverage(self): |
| 1504 | from lib import render, schema |
| 1505 | |
| 1506 | report, _ = self._run_sc_fallback_report({ |
| 1507 | "id": "abc123", |
| 1508 | "title": "Vuori review", |
| 1509 | "url": "https://www.youtube.com/watch?v=abc123", |
| 1510 | "date": "2026-05-01", |
| 1511 | "transcript_snippet": "", |
| 1512 | }) |
| 1513 | |
| 1514 | self.assertEqual(report.items_by_source.get("youtube"), []) |
| 1515 | self.assertEqual(report.source_status["youtube"].state, schema.RATE_LIMITED) |
| 1516 | self.assertIn("not a bot", report.source_status["youtube"].detail) |
| 1517 | self.assertIn("rate-limited", "\n".join(render._render_source_coverage(report))) |
| 1518 | |
| 1519 | def test_sc_fallback_with_usable_video_reports_recovered_coverage(self): |
| 1520 | from lib import health, render |
| 1521 | |
| 1522 | report, _ = self._run_sc_fallback_report({ |
| 1523 | "id": "abc123", |
| 1524 | "title": "Vuori review", |
| 1525 | "url": "https://www.youtube.com/watch?v=abc123", |
| 1526 | "date": "2026-06-15", |
| 1527 | "transcript_snippet": "", |
| 1528 | }) |
| 1529 | |
| 1530 | self.assertEqual(report.source_status["youtube"].state, health.OK) |
| 1531 | self.assertEqual(len(report.items_by_source["youtube"]), 1) |
| 1532 | self.assertEqual("\n".join(render._render_source_coverage(report)), |
| 1533 | "## Source Coverage\n\n- YouTube: 1 item") |
| 1534 | |
| 1535 | def test_sc_fallback_retry_without_usable_video_preserves_search_failure(self): |
| 1536 | from lib import schema |
| 1537 | |
| 1538 | report, _ = self._run_sc_fallback_report({ |
| 1539 | "id": "abc123", |
| 1540 | "title": "Vuori review", |
| 1541 | "url": "https://www.youtube.com/watch?v=abc123", |
| 1542 | "date": "2026-05-01", |
| 1543 | "transcript_snippet": "", |
| 1544 | }, initial_empty=True, depth="default") |
| 1545 | |
| 1546 | self.assertEqual(report.source_status["youtube"].state, schema.RATE_LIMITED) |
| 1547 | self.assertIn("not a bot", report.source_status["youtube"].detail) |
| 1548 | |
| 1549 | def test_sc_fallback_transient_failure_recovers_on_thin_retry(self): |
| 1550 | from lib import health |
| 1551 | |
| 1552 | old = { |
| 1553 | "id": "old", "title": "Vuori archive", "date": "2026-05-01", |
| 1554 | "url": "https://www.youtube.com/watch?v=old", "transcript_snippet": "", |
| 1555 | } |
| 1556 | recent = { |
| 1557 | "id": "recent", "title": "Vuori review", "date": "2026-06-15", |
| 1558 | "url": "https://www.youtube.com/watch?v=recent", "transcript_snippet": "", |
| 1559 | } |
| 1560 | for search_error in ( |
| 1561 | "yt-dlp search failed: connection reset", |
| 1562 | "yt-dlp search failed: HTTP Error 503", |
| 1563 | ): |
| 1564 | with self.subTest(search_error=search_error): |
| 1565 | report, calls = self._run_sc_fallback_report( |
| 1566 | old, depth="default", retry_video=recent, |
| 1567 | search_error=search_error, |
| 1568 | ) |
| 1569 | self.assertEqual(calls, 2) |
| 1570 | self.assertEqual(report.source_status["youtube"].state, health.OK) |
| 1571 | self.assertEqual( |
| 1572 | [item.item_id for item in report.items_by_source["youtube"]], |
| 1573 | ["recent"], |
| 1574 | ) |
| 1575 | |
| 1576 | def test_sc_fallback_transient_failure_survives_unusable_thin_retry(self): |
| 1577 | from lib import health |
| 1578 | |
| 1579 | old = { |
| 1580 | "id": "old", "title": "Vuori archive", "date": "2026-05-01", |
| 1581 | "url": "https://www.youtube.com/watch?v=old", "transcript_snippet": "", |
| 1582 | } |
| 1583 | report, calls = self._run_sc_fallback_report( |
| 1584 | old, depth="default", retry_video=old, |
| 1585 | search_error="yt-dlp search failed: connection reset", |
| 1586 | ) |
| 1587 | |
| 1588 | self.assertEqual(calls, 2) |
| 1589 | self.assertEqual(report.source_status["youtube"].state, health.UNREACHABLE) |
| 1590 | self.assertIn("connection reset", report.source_status["youtube"].detail) |
| 1591 | |
| 1592 | def test_sc_fallback_quick_transient_failure_remains_visible(self): |
| 1593 | from lib import health |
| 1594 | |
| 1595 | old = { |
| 1596 | "id": "old", "title": "Vuori archive", "date": "2026-05-01", |
| 1597 | "url": "https://www.youtube.com/watch?v=old", "transcript_snippet": "", |
| 1598 | } |
| 1599 | report, calls = self._run_sc_fallback_report( |
| 1600 | old, search_error="yt-dlp search failed: connection reset", |
| 1601 | ) |
| 1602 | |
| 1603 | self.assertEqual(calls, 1) |
| 1604 | self.assertEqual(report.source_status["youtube"].state, health.UNREACHABLE) |
| 1605 | self.assertIn("youtube", report.errors_by_source) |
| 1606 | |
| 1607 | def test_unrecovered_stream_remains_partial_when_another_stream_has_videos(self): |
| 1608 | from lib import health, pipeline |
| 1609 | |
| 1610 | fresh = [{ |
| 1611 | "id": f"recent-{index}", "title": title, |
| 1612 | "url": f"https://www.youtube.com/watch?v=recent-{index}", |
| 1613 | "date": "2026-06-15", "relevance": 1.0, |
| 1614 | } for index, title in enumerate(( |
| 1615 | "Vuori earnings report", "Vuori trail running gear review", |
| 1616 | "Vuori store opening Toronto", |
| 1617 | ))] |
| 1618 | stale = [{ |
| 1619 | "id": "old", "title": "Vuori archive", "date": "2026-05-01", |
| 1620 | "url": "https://www.youtube.com/watch?v=old", "transcript_snippet": "", |
| 1621 | }] |
| 1622 | |
| 1623 | def retrieve_stream(*_args, **kwargs): |
| 1624 | if kwargs["subquery"].label == "usable": |
| 1625 | return fresh, {} |
| 1626 | return stale, {"_source_outcome_if_empty": { |
| 1627 | "state": health.UNREACHABLE, |
| 1628 | "detail": "yt-dlp search failed: connection reset", |
| 1629 | "attempted": True, |
| 1630 | }} |
| 1631 | |
| 1632 | plan = { |
| 1633 | "intent": "general", "freshness_mode": "balanced_recent", |
| 1634 | "cluster_mode": "story", |
| 1635 | "subqueries": [ |
| 1636 | {"label": label, "search_query": "Vuori", "ranking_query": "Vuori", "sources": ["youtube"]} |
| 1637 | for label in ("usable", "stale") |
| 1638 | ], |
| 1639 | "source_weights": {"youtube": 1.0}, |
| 1640 | } |
| 1641 | with mock.patch.object(pipeline, "_retrieve_stream", side_effect=retrieve_stream) as search: |
| 1642 | report = pipeline.run( |
| 1643 | topic="Vuori", config={}, depth="default", |
| 1644 | requested_sources=["youtube"], mock=True, |
| 1645 | external_plan=plan, as_of_date="2026-07-01", |
| 1646 | ) |
| 1647 | |
| 1648 | self.assertEqual(search.call_count, 2) |
| 1649 | self.assertEqual(report.source_status["youtube"].state, health.PARTIAL) |
| 1650 | self.assertEqual(report.source_status["youtube"].items_returned, 3) |
| 1651 | self.assertIn("connection reset", report.source_status["youtube"].detail) |
| 1652 | |
| 1653 | def test_sc_fallback_auth_and_rate_limit_failures_skip_thin_retry(self): |
| 1654 | from lib import health |
| 1655 | |
| 1656 | old = { |
| 1657 | "id": "old", "title": "Vuori archive", "date": "2026-05-01", |
| 1658 | "url": "https://www.youtube.com/watch?v=old", "transcript_snippet": "", |
| 1659 | } |
| 1660 | recent = { |
| 1661 | "id": "recent", "title": "Vuori review", "date": "2026-06-15", |
| 1662 | "url": "https://www.youtube.com/watch?v=recent", "transcript_snippet": "", |
| 1663 | } |
| 1664 | for search_error, state in ( |
| 1665 | ("yt-dlp search failed: Sign in to confirm you're not a bot", health.RATE_LIMITED), |
| 1666 | ("yt-dlp search failed: login required", health.AUTH_FAILED), |
| 1667 | ): |
| 1668 | with self.subTest(state=state): |
| 1669 | report, calls = self._run_sc_fallback_report( |
| 1670 | old, depth="default", retry_video=recent, search_error=search_error, |
| 1671 | ) |
| 1672 | self.assertEqual(calls, 1) |
| 1673 | self.assertEqual(report.source_status["youtube"].state, state) |
| 1674 | |
| 1675 | def _run_keyless_search_report(self, responses, *, depth="default"): |
| 1676 | from lib import pipeline |
| 1677 | |
| 1678 | retrieve = pipeline._retrieve_stream |
| 1679 | |
| 1680 | def retrieve_live_youtube(*args, **kwargs): |
| 1681 | return retrieve(*args, **{**kwargs, "mock": False}) |
| 1682 | |
| 1683 | plan = { |
| 1684 | "intent": "general", "freshness_mode": "balanced_recent", |
| 1685 | "cluster_mode": "story", |
| 1686 | "subqueries": [{ |
| 1687 | "label": "primary", "search_query": "Vuori", |
| 1688 | "ranking_query": "Vuori", "sources": ["youtube"], |
| 1689 | }], |
| 1690 | "source_weights": {"youtube": 1.0}, |
| 1691 | } |
| 1692 | with mock.patch.object(pipeline, "which", return_value="/usr/bin/yt-dlp"), \ |
| 1693 | mock.patch.object(pipeline, "_retrieve_stream", side_effect=retrieve_live_youtube), \ |
| 1694 | mock.patch.object(youtube_yt, "search_and_transcribe", side_effect=responses) as search, \ |
| 1695 | mock.patch.object(youtube_yt, "search_youtube_sc") as sc_search: |
| 1696 | report = pipeline.run( |
| 1697 | topic="Vuori", config={}, depth=depth, |
| 1698 | requested_sources=["youtube"], mock=True, |
| 1699 | external_plan=plan, as_of_date="2026-07-01", |
| 1700 | ) |
| 1701 | return report, search.call_count, sc_search.call_count |
| 1702 | |
| 1703 | def test_keyless_transient_search_failure_recovers_on_thin_retry(self): |
| 1704 | from lib import health |
| 1705 | |
| 1706 | recent = { |
| 1707 | "id": "recent", "title": "Vuori review", "date": "2026-06-15", |
| 1708 | "url": "https://www.youtube.com/watch?v=recent", |
| 1709 | } |
| 1710 | report, calls, sc_calls = self._run_keyless_search_report([ |
| 1711 | {"items": [], "error": "yt-dlp search failed: connection reset"}, |
| 1712 | {"items": [recent]}, |
| 1713 | ]) |
| 1714 | |
| 1715 | self.assertEqual((calls, sc_calls), (2, 0)) |
| 1716 | self.assertEqual(report.source_status["youtube"].state, health.OK) |
| 1717 | self.assertEqual([item.item_id for item in report.items_by_source["youtube"]], ["recent"]) |
| 1718 | |
| 1719 | def test_keyless_transient_search_failure_survives_failed_thin_retry(self): |
| 1720 | from lib import health |
| 1721 | |
| 1722 | failure = {"items": [], "error": "yt-dlp search failed: connection reset"} |
| 1723 | report, calls, sc_calls = self._run_keyless_search_report([failure, failure]) |
| 1724 | |
| 1725 | self.assertEqual((calls, sc_calls), (2, 0)) |
| 1726 | self.assertEqual(report.source_status["youtube"].state, health.UNREACHABLE) |
| 1727 | self.assertIn("connection reset", report.source_status["youtube"].detail) |
| 1728 | |
| 1729 | def test_keyless_auth_and_rate_limit_failures_skip_thin_retry(self): |
| 1730 | from lib import health |
| 1731 | |
| 1732 | for error, state in ( |
| 1733 | ("yt-dlp search failed: Sign in to confirm you're not a bot", health.RATE_LIMITED), |
| 1734 | ("yt-dlp search failed: login required", health.AUTH_FAILED), |
| 1735 | ): |
| 1736 | with self.subTest(state=state): |
| 1737 | report, calls, sc_calls = self._run_keyless_search_report([ |
| 1738 | {"items": [], "error": error}, |
| 1739 | {"items": [{"id": "recent", "title": "Vuori review", "date": "2026-06-15"}]}, |
| 1740 | ]) |
| 1741 | self.assertEqual((calls, sc_calls), (1, 0)) |
| 1742 | self.assertEqual(report.source_status["youtube"].state, state) |
| 1743 | |
| 1744 | def test_search_zero_exit_with_no_output_is_clean_empty(self): |
| 1745 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1746 | mock.patch.object( |
| 1747 | youtube_yt.subproc, "run_with_timeout", |
| 1748 | return_value=self._fake_result(), |
| 1749 | ): |
| 1750 | out = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01") |
| 1751 | self.assertEqual(out, {"items": []}) |
| 1752 | |
| 1753 | def test_search_timeout_reports_timeout_error_not_empty(self): |
| 1754 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1755 | mock.patch.dict(os.environ, {"LAST30DAYS_YT_SEARCH_TIMEOUT": "1"}), \ |
| 1756 | mock.patch.object( |
| 1757 | youtube_yt.subproc, "run_with_timeout", |
| 1758 | side_effect=youtube_yt.subproc.SubprocTimeout("boom"), |
| 1759 | ): |
| 1760 | out = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01") |
| 1761 | self.assertEqual(out.get("items"), []) |
| 1762 | self.assertIn("timed out", (out.get("error") or "").lower()) |
| 1763 | self.assertEqual( |
| 1764 | youtube_yt.classify_run_failure(out["error"]), |
| 1765 | youtube_yt.health.TIMEOUT, |
| 1766 | ) |
| 1767 | |
| 1768 | def test_search_timeout_env_is_passed_to_subprocess(self): |
| 1769 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1770 | mock.patch.dict(os.environ, {"LAST30DAYS_YT_SEARCH_TIMEOUT": "7"}), \ |
| 1771 | mock.patch.object( |
| 1772 | youtube_yt.subproc, "run_with_timeout", |
| 1773 | return_value=self._fake_result(), |
| 1774 | ) as run_mock: |
| 1775 | youtube_yt.search_youtube("Alo Yoga", "2026-06-01", "2026-07-01") |
| 1776 | self.assertEqual(run_mock.call_args.kwargs.get("timeout"), 7.0) |
| 1777 | |
| 1778 | def test_identical_searches_are_cached_within_run(self): |
| 1779 | video = { |
| 1780 | "id": "abc123", |
| 1781 | "title": "Vuori review", |
| 1782 | "view_count": 100, |
| 1783 | "like_count": 1, |
| 1784 | "comment_count": 0, |
| 1785 | "upload_date": "20260615", |
| 1786 | "description": "desc", |
| 1787 | "channel": "Tester", |
| 1788 | } |
| 1789 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1790 | mock.patch.object( |
| 1791 | youtube_yt.subproc, "run_with_timeout", |
| 1792 | return_value=self._fake_result(stdout=json.dumps(video) + "\n"), |
| 1793 | ) as run_mock: |
| 1794 | first = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01") |
| 1795 | second = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01") |
| 1796 | self.assertEqual(first, second) |
| 1797 | second["items"][0]["title"] = "mutated" |
| 1798 | second["items"][0]["engagement"]["views"] = -1 |
| 1799 | third = youtube_yt.search_youtube("Vuori", "2026-06-01", "2026-07-01") |
| 1800 | self.assertEqual(run_mock.call_count, 1) |
| 1801 | self.assertEqual(len(first["items"]), 1) |
| 1802 | self.assertEqual(len(second["items"]), 1) |
| 1803 | self.assertEqual(first["items"][0]["video_id"], second["items"][0]["video_id"]) |
| 1804 | self.assertEqual(first["items"][0]["title"], "Vuori review") |
| 1805 | self.assertEqual(third, first) |
| 1806 | self.assertEqual(third["items"][0]["engagement"]["views"], 100) |
| 1807 | |
| 1808 | def test_timeout_errors_are_not_cached(self): |
| 1809 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1810 | mock.patch.object( |
| 1811 | youtube_yt.subproc, "run_with_timeout", |
| 1812 | side_effect=youtube_yt.subproc.SubprocTimeout("boom"), |
| 1813 | ) as run_mock: |
| 1814 | youtube_yt.search_youtube("lululemon", "2026-06-01", "2026-07-01") |
| 1815 | youtube_yt.search_youtube("lululemon", "2026-06-01", "2026-07-01") |
| 1816 | self.assertEqual(run_mock.call_count, 2) |
| 1817 | |
| 1818 | def test_waiter_receives_leader_result_without_synthetic_timeout(self): |
| 1819 | """A coalesced waiter must not invent a timeout while the leader runs.""" |
| 1820 | import threading |
| 1821 | from concurrent.futures import ThreadPoolExecutor |
| 1822 | from lib.subproc import SubprocResult |
| 1823 | |
| 1824 | video = { |
| 1825 | "id": "waiter1", |
| 1826 | "title": "Vuori review", |
| 1827 | "view_count": 10, |
| 1828 | "like_count": 1, |
| 1829 | "comment_count": 0, |
| 1830 | "upload_date": "20260615", |
| 1831 | "description": "desc", |
| 1832 | "channel": "Tester", |
| 1833 | } |
| 1834 | started = threading.Event() |
| 1835 | release = threading.Event() |
| 1836 | contender_reached = threading.Event() |
| 1837 | |
| 1838 | def slow_run(cmd, timeout=None): |
| 1839 | if started.is_set(): |
| 1840 | contender_reached.set() |
| 1841 | started.set() |
| 1842 | self.assertTrue(release.wait(timeout=5), "leader was not released") |
| 1843 | return SubprocResult( |
| 1844 | returncode=0, stdout=json.dumps(video) + "\n", stderr="", |
| 1845 | ) |
| 1846 | |
| 1847 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 1848 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", side_effect=slow_run) as run_mock, \ |
| 1849 | ThreadPoolExecutor(max_workers=2) as pool: |
| 1850 | leader = pool.submit(youtube_yt.search_youtube, "Vuori", "2026-06-01", "2026-07-01") |
| 1851 | try: |
| 1852 | self.assertTrue(started.wait(timeout=5), "leader did not start yt-dlp") |
| 1853 | with youtube_yt._search_cache_lock: |
| 1854 | [(event, _slot)] = youtube_yt._search_inflight.values() |
| 1855 | real_wait = event.wait |
| 1856 | |
| 1857 | def observed_wait(timeout=None): |
| 1858 | contender_reached.set() |
| 1859 | return real_wait(timeout) |
| 1860 | |
| 1861 | with mock.patch.object(event, "wait", side_effect=observed_wait) as wait_mock: |
| 1862 | waiter = pool.submit(youtube_yt.search_youtube, "Vuori", "2026-06-01", "2026-07-01") |
| 1863 | self.assertTrue(contender_reached.wait(timeout=5), "second caller did not reach wait or yt-dlp") |
| 1864 | self.assertEqual(run_mock.call_count, 1) |
| 1865 | wait_mock.assert_called_once_with() |
| 1866 | self.assertFalse(leader.done()) |
| 1867 | self.assertFalse(waiter.done()) |
| 1868 | release.set() |
| 1869 | results = [leader.result(timeout=5), waiter.result(timeout=5)] |
| 1870 | finally: |
| 1871 | release.set() |
| 1872 | |
| 1873 | self.assertEqual(run_mock.call_count, 1) |
| 1874 | self.assertEqual(len(results), 2) |
| 1875 | self.assertEqual(results[0], results[1]) |
| 1876 | for result in results: |
| 1877 | self.assertNotIn("error", result) |
| 1878 | self.assertEqual([item["video_id"] for item in result["items"]], ["waiter1"]) |
| 1879 | self.assertEqual(result["items"][0]["engagement"], {"views": 10, "likes": 1, "comments": 0}) |
| 1880 | |
| 1881 | def test_stale_leader_after_reset_does_not_pop_newer_inflight(self): |
| 1882 | """A leader that outlives reset_search_cache must not drop the new slot.""" |
| 1883 | import threading |
| 1884 | |
| 1885 | key = ("ownership", 8, "2026-06-01", "2026-07-01", None) |
| 1886 | old_event = threading.Event() |
| 1887 | old_slot: list = [None] |
| 1888 | new_event = threading.Event() |
| 1889 | new_slot: list = [None] |
| 1890 | |
| 1891 | with youtube_yt._search_cache_lock: |
| 1892 | youtube_yt._search_inflight[key] = (old_event, old_slot) |
| 1893 | |
| 1894 | youtube_yt.reset_search_cache() |
| 1895 | with youtube_yt._search_cache_lock: |
| 1896 | youtube_yt._search_inflight[key] = (new_event, new_slot) |
| 1897 | |
| 1898 | youtube_yt._finish_search_slot( |
| 1899 | key, |
| 1900 | {"items": [{"video_id": "old"}]}, |
| 1901 | event=old_event, |
| 1902 | slot=old_slot, |
| 1903 | ) |
| 1904 | |
| 1905 | with youtube_yt._search_cache_lock: |
| 1906 | current = youtube_yt._search_inflight.get(key) |
| 1907 | cached = youtube_yt._search_cache.get(key) |
| 1908 | |
| 1909 | self.assertIsNotNone(current) |
| 1910 | self.assertIs(current[1], new_slot) |
| 1911 | self.assertIsNone(cached) |
| 1912 | self.assertTrue(old_event.is_set()) |
| 1913 | self.assertEqual(old_slot[0]["items"][0]["video_id"], "old") |
| 1914 | |
| 1915 | def test_multi_query_preserves_timeout_over_later_empty(self): |
| 1916 | responses = [ |
| 1917 | {"items": [], "error": "Search timed out after 1s"}, |
| 1918 | {"items": []}, |
| 1919 | ] |
| 1920 | |
| 1921 | def fake_search(*_args, **_kwargs): |
| 1922 | return responses.pop(0) |
| 1923 | |
| 1924 | with mock.patch.object(youtube_yt, "expand_youtube_queries", return_value=["a", "b"]), \ |
| 1925 | mock.patch.object(youtube_yt, "search_youtube", side_effect=fake_search): |
| 1926 | out = youtube_yt.search_and_transcribe( |
| 1927 | "topic", "2026-06-01", "2026-07-01", depth="default", |
| 1928 | ) |
| 1929 | self.assertEqual(out.get("items"), []) |
| 1930 | self.assertIn("timed out", (out.get("error") or "").lower()) |
| 1931 | self.assertEqual( |
| 1932 | youtube_yt.classify_run_failure(out["error"]), |
| 1933 | youtube_yt.health.TIMEOUT, |
| 1934 | ) |
| 1935 | |
| 1936 | def test_bundle_records_timeout_not_no_results(self): |
| 1937 | from lib import health, schema |
| 1938 | |
| 1939 | bundle = schema.RetrievalBundle() |
| 1940 | bundle.mark_attempted("youtube") |
| 1941 | state = youtube_yt.classify_run_failure("Search timed out after 1s") |
| 1942 | bundle.record_failure("youtube", state, "Search timed out after 1s") |
| 1943 | bundle.add_items("main", "youtube", []) |
| 1944 | self.assertEqual(bundle.source_status["youtube"].state, health.TIMEOUT) |
| 1945 | self.assertNotEqual(bundle.source_status["youtube"].state, schema.NO_RESULTS) |
| 1946 | |
| 1947 | |
| 1948 | class TestYtdlpPlayerClient(unittest.TestCase): |
| 1949 | """#1052: merge player_client into a single youtube extractor-args.""" |
| 1950 | |
| 1951 | def setUp(self): |
| 1952 | self._saved = os.environ.pop("LAST30DAYS_YT_PLAYER_CLIENT", None) |
| 1953 | |
| 1954 | def tearDown(self): |
| 1955 | os.environ.pop("LAST30DAYS_YT_PLAYER_CLIENT", None) |
| 1956 | if self._saved is not None: |
| 1957 | os.environ["LAST30DAYS_YT_PLAYER_CLIENT"] = self._saved |
| 1958 | |
| 1959 | def test_default_android_on_search(self): |
| 1960 | cmd = ["yt-dlp", "--ignore-config", "ytsearch5:test"] |
| 1961 | out = youtube_yt._inject_youtube_player_client(cmd) |
| 1962 | self.assertIn("--extractor-args", out) |
| 1963 | self.assertIn("youtube:player_client=android", out) |
| 1964 | |
| 1965 | def test_empty_env_disables(self): |
| 1966 | os.environ["LAST30DAYS_YT_PLAYER_CLIENT"] = "" |
| 1967 | cmd = ["yt-dlp", "--ignore-config", "ytsearch5:test"] |
| 1968 | self.assertEqual(youtube_yt._inject_youtube_player_client(cmd), cmd) |
| 1969 | |
| 1970 | def test_merges_into_existing_youtube_extractor_args(self): |
| 1971 | cmd = [ |
| 1972 | "yt-dlp", |
| 1973 | "--extractor-args", |
| 1974 | "youtube:comment_sort=top;max_comments=5,all,5", |
| 1975 | "--write-comments", |
| 1976 | "https://www.youtube.com/watch?v=abc", |
| 1977 | ] |
| 1978 | out = youtube_yt._inject_youtube_player_client(cmd) |
| 1979 | self.assertEqual(out.count("--extractor-args"), 1) |
| 1980 | spec = out[out.index("--extractor-args") + 1] |
| 1981 | self.assertTrue(spec.startswith("youtube:")) |
| 1982 | self.assertIn("comment_sort=top", spec) |
| 1983 | self.assertIn("player_client=android", spec) |
| 1984 | |
| 1985 | def test_version_cmd_untouched(self): |
| 1986 | cmd = ["yt-dlp", "--version"] |
| 1987 | self.assertEqual(youtube_yt._inject_youtube_player_client(cmd), cmd) |
| 1988 | |
| 1989 | |
| 1990 | class TestYoutubeProxy(unittest.TestCase): |
| 1991 | """_ytdlp_proxy reads YOUTUBE_PROXY / YT_PROXY and _wrap_ytdlp_cmd injects it.""" |
| 1992 | |
| 1993 | def test_no_env_returns_none(self): |
| 1994 | with mock.patch.dict(os.environ, {}, clear=False): |
| 1995 | os.environ.pop("YOUTUBE_PROXY", None) |
| 1996 | os.environ.pop("YT_PROXY", None) |
| 1997 | self.assertIsNone(youtube_yt._ytdlp_proxy()) |
| 1998 | |
| 1999 | def test_youtube_proxy_env(self): |
| 2000 | with mock.patch.dict(os.environ, {"YOUTUBE_PROXY": "socks5://127.0.0.1:1080"}, clear=False): |
| 2001 | os.environ.pop("YT_PROXY", None) |
| 2002 | self.assertEqual(youtube_yt._ytdlp_proxy(), "socks5://127.0.0.1:1080") |
| 2003 | |
| 2004 | def test_yt_proxy_alias(self): |
| 2005 | with mock.patch.dict(os.environ, {"YT_PROXY": "http://proxy:3128"}, clear=False): |
| 2006 | os.environ.pop("YOUTUBE_PROXY", None) |
| 2007 | self.assertEqual(youtube_yt._ytdlp_proxy(), "http://proxy:3128") |
| 2008 | |
| 2009 | def test_youtube_proxy_takes_precedence_over_yt_proxy(self): |
| 2010 | with mock.patch.dict(os.environ, {"YOUTUBE_PROXY": "socks5://a:1", "YT_PROXY": "http://b:2"}, clear=False): |
| 2011 | self.assertEqual(youtube_yt._ytdlp_proxy(), "socks5://a:1") |
| 2012 | |
| 2013 | def test_empty_env_returns_none(self): |
| 2014 | with mock.patch.dict(os.environ, {"YOUTUBE_PROXY": " "}, clear=False): |
| 2015 | os.environ.pop("YT_PROXY", None) |
| 2016 | self.assertIsNone(youtube_yt._ytdlp_proxy()) |
| 2017 | |
| 2018 | def test_wrap_cmd_injects_proxy(self): |
| 2019 | env_patch = {"YOUTUBE_PROXY": "socks5://127.0.0.1:1080"} |
| 2020 | with mock.patch.dict(os.environ, env_patch, clear=False): |
| 2021 | os.environ.pop("YT_PROXY", None) |
| 2022 | os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None) |
| 2023 | cmd = ["yt-dlp", "--ignore-config", "ytsearch5:test", "--dump-json"] |
| 2024 | result = youtube_yt._wrap_ytdlp_cmd(cmd) |
| 2025 | self.assertIn("--proxy", result) |
| 2026 | self.assertIn("socks5://127.0.0.1:1080", result) |
| 2027 | |
| 2028 | def test_wrap_cmd_no_proxy_when_unset(self): |
| 2029 | with mock.patch.dict(os.environ, {}, clear=False): |
| 2030 | os.environ.pop("YOUTUBE_PROXY", None) |
| 2031 | os.environ.pop("YT_PROXY", None) |
| 2032 | os.environ.pop("LAST30DAYS_YOUTUBE_SSH_HOST", None) |
| 2033 | cmd = ["yt-dlp", "--ignore-config", "ytsearch5:test", "--dump-json"] |
| 2034 | result = youtube_yt._wrap_ytdlp_cmd(cmd) |
| 2035 | self.assertNotIn("--proxy", result) |
| 2036 | |
| 2037 | |
| 2038 | class TestYouTubeUploadDateFallback(unittest.TestCase): |
| 2039 | """A relevance search full of old catalog videos retries with YouTube's upload-date filter.""" |
| 2040 | |
| 2041 | def setUp(self): |
| 2042 | youtube_yt.reset_search_cache() |
| 2043 | self.addCleanup(youtube_yt.reset_search_cache) |
| 2044 | today = datetime.now(timezone.utc).date() |
| 2045 | self.TO = today.isoformat() |
| 2046 | self.FROM = (today - timedelta(days=30)).isoformat() |
| 2047 | self.recent = [(today - timedelta(days=n)).isoformat() for n in (1, 2)] |
| 2048 | |
| 2049 | @staticmethod |
| 2050 | def _stdout(prefix, dates): |
| 2051 | return "\n".join( |
| 2052 | json.dumps({ |
| 2053 | "id": f"{prefix}{i}", "title": f"Kanye West video {i}", "view_count": 100 + i, |
| 2054 | "like_count": 1, "comment_count": 1, "upload_date": d.replace("-", ""), |
| 2055 | "description": "desc", |
| 2056 | }) |
| 2057 | for i, d in enumerate(dates) |
| 2058 | ) |
| 2059 | |
| 2060 | def _search(self, relevance_dates, filtered_dates, freshness_mode="strict_recent", |
| 2061 | from_date=None, to_date=None, relevance_rc=0, relevance_stderr="", |
| 2062 | filtered_rc=0, filtered_stderr=""): |
| 2063 | from lib.subproc import SubprocResult |
| 2064 | calls = [] |
| 2065 | |
| 2066 | def _run(cmd, timeout, **_kwargs): |
| 2067 | calls.append(cmd) |
| 2068 | if any("youtube.com/results" in arg for arg in cmd): |
| 2069 | return SubprocResult( |
| 2070 | returncode=filtered_rc, stdout=self._stdout("new", filtered_dates), |
| 2071 | stderr=filtered_stderr, |
| 2072 | ) |
| 2073 | return SubprocResult( |
| 2074 | returncode=relevance_rc, stdout=self._stdout("old", relevance_dates), |
| 2075 | stderr=relevance_stderr, |
| 2076 | ) |
| 2077 | |
| 2078 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 2079 | mock.patch.object(youtube_yt, "_ytdlp_ssh_host", return_value=None), \ |
| 2080 | mock.patch.object(youtube_yt, "_run_ytdlp", side_effect=_run): |
| 2081 | out = youtube_yt.search_youtube( |
| 2082 | "Kanye West", from_date or self.FROM, to_date or self.TO, |
| 2083 | freshness_mode=freshness_mode, |
| 2084 | ) |
| 2085 | return out, calls |
| 2086 | |
| 2087 | def test_catalog_topic_returns_recent_uploads_from_filtered_search(self): |
| 2088 | out, calls = self._search(["2010-11-22", "2013-06-18"], self.recent) |
| 2089 | self.assertEqual({i["video_id"] for i in out["items"]}, {"new0", "new1"}) |
| 2090 | self.assertEqual(len(calls), 2) |
| 2091 | url = next(arg for arg in calls[1] if "youtube.com/results" in arg) |
| 2092 | self.assertIn("search_query=kanye+west", url.lower()) |
| 2093 | self.assertIn("sp=EgIIBA%3D%3D", url) # "this month" |
| 2094 | |
| 2095 | def test_week_window_uses_this_week_filter(self): |
| 2096 | from_date = (datetime.now(timezone.utc).date() - timedelta(days=7)).isoformat() |
| 2097 | _, calls = self._search(["2010-11-22"], self.recent, from_date=from_date) |
| 2098 | url = next(arg for arg in calls[1] if "youtube.com/results" in arg) |
| 2099 | self.assertIn("sp=EgIIAw%3D%3D", url) |
| 2100 | |
| 2101 | def test_filtered_results_merge_with_in_window_relevance_hits(self): |
| 2102 | out, _ = self._search([self.recent[0], "2010-11-22"], [self.recent[1]]) |
| 2103 | self.assertEqual({i["video_id"] for i in out["items"]}, {"old0", "new0"}) |
| 2104 | |
| 2105 | def test_no_fallback_when_relevance_search_already_has_three_recent(self): |
| 2106 | out, calls = self._search(self.recent + [self.recent[0]], self.recent) |
| 2107 | self.assertEqual(len(calls), 1) |
| 2108 | self.assertEqual(len(out["items"]), 3) |
| 2109 | |
| 2110 | def test_no_fallback_for_evergreen_topics(self): |
| 2111 | out, calls = self._search(["2010-11-22", "2013-06-18"], self.recent, freshness_mode="evergreen_ok") |
| 2112 | self.assertEqual(len(calls), 1) |
| 2113 | self.assertEqual({i["video_id"] for i in out["items"]}, {"old0", "old1"}) |
| 2114 | |
| 2115 | def test_age_restricted_result_does_not_block_the_fallback(self): |
| 2116 | """One age-gated video in the results is not a bot block.""" |
| 2117 | out, calls = self._search( |
| 2118 | ["2010-11-22"], self.recent, relevance_rc=1, |
| 2119 | relevance_stderr="ERROR: [youtube] abc: Sign in to confirm your age. Use --cookies", |
| 2120 | ) |
| 2121 | self.assertEqual(len(calls), 2) |
| 2122 | self.assertEqual({i["video_id"] for i in out["items"]}, {"new0", "new1"}) |
| 2123 | |
| 2124 | def test_all_age_gated_relevance_hits_still_reach_the_fallback(self): |
| 2125 | """Every hit age-gated leaves stdout empty; the retry must still run.""" |
| 2126 | out, calls = self._search( |
| 2127 | [], self.recent, relevance_rc=1, |
| 2128 | relevance_stderr="ERROR: [youtube] abc: Sign in to confirm your age. Use --cookies", |
| 2129 | ) |
| 2130 | self.assertEqual(len(calls), 2) |
| 2131 | self.assertEqual({i["video_id"] for i in out["items"]}, {"new0", "new1"}) |
| 2132 | self.assertNotIn("error", out) |
| 2133 | |
| 2134 | def test_failed_retry_is_reported_instead_of_a_quiet_zero(self): |
| 2135 | out, calls = self._search( |
| 2136 | ["2010-11-22"], [], filtered_rc=1, |
| 2137 | filtered_stderr="ERROR: HTTP Error 429: Too Many Requests", |
| 2138 | ) |
| 2139 | self.assertEqual(len(calls), 2) |
| 2140 | self.assertEqual(out["items"], []) |
| 2141 | self.assertIn("upload-date search failed", out["error"]) |
| 2142 | |
| 2143 | def test_failed_retry_keeps_relevance_hits_without_an_error(self): |
| 2144 | out, _ = self._search( |
| 2145 | [self.recent[0]], [], filtered_rc=1, |
| 2146 | filtered_stderr="ERROR: HTTP Error 429: Too Many Requests", |
| 2147 | ) |
| 2148 | self.assertEqual([i["video_id"] for i in out["items"]], ["old0"]) |
| 2149 | self.assertNotIn("error", out) |
| 2150 | |
| 2151 | def test_bot_block_skips_the_fallback(self): |
| 2152 | _, calls = self._search( |
| 2153 | ["2010-11-22"], self.recent, relevance_rc=1, |
| 2154 | relevance_stderr="ERROR: [youtube] abc: Sign in to confirm you're not a bot.", |
| 2155 | ) |
| 2156 | self.assertEqual(len(calls), 1) |
| 2157 | |
| 2158 | def test_no_fallback_for_past_as_of_window(self): |
| 2159 | """YouTube's upload filters count back from now, so a past window cannot use them.""" |
| 2160 | out, calls = self._search(["2010-11-22"], ["2024-03-01"], from_date="2024-02-01", to_date="2024-03-02") |
| 2161 | self.assertEqual(len(calls), 1) |
| 2162 | self.assertEqual(out["items"], []) |
| 2163 | |
| 2164 | |
| 2165 | class TestYouTubeDateWindowByFreshnessMode(unittest.TestCase): |
| 2166 | """Out-of-window soft fallback is scoped to evergreen_ok (recent topics stay honest).""" |
| 2167 | |
| 2168 | FROM = "2026-09-11" |
| 2169 | TO = "2026-10-11" |
| 2170 | |
| 2171 | def setUp(self): |
| 2172 | youtube_yt.reset_search_cache() |
| 2173 | self.addCleanup(youtube_yt.reset_search_cache) |
| 2174 | |
| 2175 | def _ytdlp_stdout(self, dates): |
| 2176 | videos = [ |
| 2177 | { |
| 2178 | "id": f"v{i}", "title": f"Ghostty video {i}", "view_count": 100 + i, |
| 2179 | "like_count": 1, "comment_count": 1, "upload_date": d.replace("-", ""), |
| 2180 | "description": "desc", |
| 2181 | } |
| 2182 | for i, d in enumerate(dates) |
| 2183 | ] |
| 2184 | return "\n".join(json.dumps(v) for v in videos) |
| 2185 | |
| 2186 | def _search(self, dates, freshness_mode, to_date=None): |
| 2187 | from lib.subproc import SubprocResult |
| 2188 | result = SubprocResult(returncode=0, stdout=self._ytdlp_stdout(dates), stderr="") |
| 2189 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 2190 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=result): |
| 2191 | return youtube_yt.search_youtube( |
| 2192 | "Ghostty terminal", self.FROM, to_date or self.TO, freshness_mode=freshness_mode, |
| 2193 | ) |
| 2194 | |
| 2195 | def test_ytdlp_balanced_recent_with_no_in_range_videos_keeps_nothing(self): |
| 2196 | out = self._search(["2017-03-01", "2020-05-05"], "balanced_recent") |
| 2197 | self.assertEqual(out["items"], []) |
| 2198 | |
| 2199 | def test_ytdlp_strict_recent_keeps_only_in_range_videos(self): |
| 2200 | out = self._search(["2026-10-01", "2017-03-01", "2020-05-05"], "strict_recent") |
| 2201 | self.assertEqual([i["video_id"] for i in out["items"]], ["v0"]) |
| 2202 | |
| 2203 | def test_ytdlp_evergreen_ok_still_keeps_older_videos(self): |
| 2204 | out = self._search(["2017-03-01", "2020-05-05"], "evergreen_ok") |
| 2205 | self.assertEqual({i["video_id"] for i in out["items"]}, {"v0", "v1"}) |
| 2206 | |
| 2207 | def test_ytdlp_unknown_mode_keeps_todays_soft_fallback(self): |
| 2208 | out = self._search(["2017-03-01", "2020-05-05"], None) |
| 2209 | self.assertEqual({i["video_id"] for i in out["items"]}, {"v0", "v1"}) |
| 2210 | |
| 2211 | def test_ytdlp_in_range_path_unchanged_when_three_or_more_recent(self): |
| 2212 | dates = ["2026-10-01", "2026-10-02", "2026-10-03", "2017-03-01"] |
| 2213 | for mode in ("balanced_recent", "evergreen_ok", None): |
| 2214 | youtube_yt.reset_search_cache() |
| 2215 | out = self._search(dates, mode) |
| 2216 | self.assertEqual({i["video_id"] for i in out["items"]}, {"v0", "v1", "v2"}, mode) |
| 2217 | |
| 2218 | def test_ytdlp_search_cache_does_not_leak_across_freshness_modes(self): |
| 2219 | dates = ["2017-03-01", "2020-05-05"] |
| 2220 | self.assertEqual(len(self._search(dates, "evergreen_ok")["items"]), 2) |
| 2221 | self.assertEqual(self._search(dates, "balanced_recent")["items"], []) |
| 2222 | |
| 2223 | def test_ytdlp_search_cache_separates_end_dates_in_both_orders(self): |
| 2224 | dates = ["2026-10-01", self.TO, "2026-10-20"] |
| 2225 | for end_dates in (("2026-10-01", self.TO), (self.TO, "2026-10-01")): |
| 2226 | with self.subTest(end_dates=end_dates): |
| 2227 | youtube_yt.reset_search_cache() |
| 2228 | results = { |
| 2229 | end: self._search(dates, "evergreen_ok", to_date=end) |
| 2230 | for end in end_dates |
| 2231 | } |
| 2232 | self.assertEqual( |
| 2233 | {i["video_id"] for i in results["2026-10-01"]["items"]}, {"v0"}, |
| 2234 | ) |
| 2235 | self.assertEqual( |
| 2236 | {i["video_id"] for i in results[self.TO]["items"]}, {"v0", "v1"}, |
| 2237 | ) |
| 2238 | |
| 2239 | def test_ytdlp_inflight_searches_separate_end_dates(self): |
| 2240 | import threading |
| 2241 | from concurrent.futures import ThreadPoolExecutor |
| 2242 | from lib.subproc import SubprocResult |
| 2243 | |
| 2244 | started = threading.Event() |
| 2245 | release = threading.Event() |
| 2246 | result = SubprocResult( |
| 2247 | returncode=0, |
| 2248 | stdout=self._ytdlp_stdout(["2026-10-01", self.TO, "2026-10-20"]), |
| 2249 | stderr="", |
| 2250 | ) |
| 2251 | |
| 2252 | def slow_first_search(*_args, **_kwargs): |
| 2253 | if not started.is_set(): |
| 2254 | started.set() |
| 2255 | self.assertTrue(release.wait(timeout=10), "first search was not released") |
| 2256 | return result |
| 2257 | |
| 2258 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 2259 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", side_effect=slow_first_search), \ |
| 2260 | ThreadPoolExecutor(max_workers=2) as pool: |
| 2261 | first = pool.submit( |
| 2262 | youtube_yt.search_youtube, "Ghostty terminal", self.FROM, "2026-10-01", |
| 2263 | freshness_mode="evergreen_ok", |
| 2264 | ) |
| 2265 | try: |
| 2266 | self.assertTrue(started.wait(timeout=5), "first search did not start") |
| 2267 | second = pool.submit( |
| 2268 | youtube_yt.search_youtube, "Ghostty terminal", self.FROM, self.TO, |
| 2269 | freshness_mode="evergreen_ok", |
| 2270 | ) |
| 2271 | later = second.result(timeout=5) |
| 2272 | finally: |
| 2273 | release.set() |
| 2274 | earlier = first.result(timeout=5) |
| 2275 | |
| 2276 | self.assertEqual({i["video_id"] for i in earlier["items"]}, {"v0"}) |
| 2277 | self.assertEqual({i["video_id"] for i in later["items"]}, {"v0", "v1"}) |
| 2278 | |
| 2279 | def test_search_and_transcribe_threads_freshness_mode(self): |
| 2280 | from lib.subproc import SubprocResult |
| 2281 | result = SubprocResult( |
| 2282 | returncode=0, stdout=self._ytdlp_stdout(["2017-03-01", "2020-05-05"]), stderr="", |
| 2283 | ) |
| 2284 | with mock.patch.object(youtube_yt, "is_ytdlp_installed", return_value=True), \ |
| 2285 | mock.patch.object(youtube_yt.subproc, "run_with_timeout", return_value=result), \ |
| 2286 | mock.patch.object(youtube_yt, "fetch_transcripts_parallel", return_value={}): |
| 2287 | recent = youtube_yt.search_and_transcribe( |
| 2288 | "Ghostty terminal", self.FROM, self.TO, freshness_mode="balanced_recent", |
| 2289 | ) |
| 2290 | youtube_yt.reset_search_cache() |
| 2291 | evergreen = youtube_yt.search_and_transcribe( |
| 2292 | "Ghostty terminal", self.FROM, self.TO, freshness_mode="evergreen_ok", |
| 2293 | ) |
| 2294 | self.assertEqual(recent["items"], []) |
| 2295 | self.assertEqual({i["video_id"] for i in evergreen["items"]}, {"v0", "v1"}) |
| 2296 | |
| 2297 | def _sc_search(self, dates, freshness_mode): |
| 2298 | raw = [ |
| 2299 | {"id": f"s{i}", "title": f"Ghostty video {i}", "views": 100 + i, "upload_date": d} |
| 2300 | for i, d in enumerate(dates) |
| 2301 | ] |
| 2302 | with mock.patch.object(youtube_yt, "_sc_youtube_search", return_value=raw), \ |
| 2303 | mock.patch.object(youtube_yt, "_sc_fetch_transcript", return_value="transcript"): |
| 2304 | return youtube_yt.search_youtube_sc( |
| 2305 | "Ghostty terminal", self.FROM, self.TO, token="dummy-key", |
| 2306 | freshness_mode=freshness_mode, |
| 2307 | ) |
| 2308 | |
| 2309 | def test_sc_balanced_recent_with_no_in_range_videos_keeps_nothing(self): |
| 2310 | out = self._sc_search(["2017-03-01", "2020-05-05"], "balanced_recent") |
| 2311 | self.assertEqual(out["items"], []) |
| 2312 | |
| 2313 | def test_sc_strict_recent_keeps_only_in_range_videos(self): |
| 2314 | out = self._sc_search(["2026-10-01", "2017-03-01"], "strict_recent") |
| 2315 | self.assertEqual([i["video_id"] for i in out["items"]], ["s0"]) |
| 2316 | |
| 2317 | def test_sc_evergreen_ok_still_keeps_older_videos(self): |
| 2318 | out = self._sc_search(["2017-03-01", "2020-05-05"], "evergreen_ok") |
| 2319 | self.assertEqual({i["video_id"] for i in out["items"]}, {"s0", "s1"}) |
| 2320 | |
| 2321 | def test_sc_unknown_mode_keeps_todays_soft_fallback(self): |
| 2322 | out = self._sc_search(["2017-03-01", "2020-05-05"], None) |
| 2323 | self.assertEqual({i["video_id"] for i in out["items"]}, {"s0", "s1"}) |
| 2324 | |
| 2325 | def test_ytdlp_drops_videos_published_after_window_end(self): |
| 2326 | # --as-of window: videos uploaded after TO are neither in range nor a fallback. |
| 2327 | dates = ["2026-10-20", "2026-11-01", "2026-12-01", "2026-10-01", "2017-03-01", self.TO] |
| 2328 | out = self._search(dates, "evergreen_ok") |
| 2329 | self.assertEqual({i["video_id"] for i in out["items"]}, {"v3", "v4", "v5"}) |
| 2330 | |
| 2331 | def test_sc_drops_videos_published_after_window_end(self): |
| 2332 | out = self._sc_search( |
| 2333 | ["2026-10-20", "2026-11-01", "2026-12-01", "2017-03-01", self.TO], "evergreen_ok", |
| 2334 | ) |
| 2335 | self.assertEqual({i["video_id"] for i in out["items"]}, {"s3", "s4"}) |
| 2336 | |
| 2337 | def test_sc_search_reads_documented_response_shape(self): |
| 2338 | # Shape of a /v1/youtube/search video per docs.scrapecreators.com: |
| 2339 | # camelCase counts/dates and `channel` as an object. |
| 2340 | def video(vid, published, views): |
| 2341 | return { |
| 2342 | "type": "video", |
| 2343 | "id": vid, |
| 2344 | "url": f"https://www.youtube.com/watch?v={vid}", |
| 2345 | "title": f"Ghostty terminal review {vid}", |
| 2346 | "thumbnail": "https://i.ytimg.com/vi/x/hqdefault.jpg", |
| 2347 | "channel": { |
| 2348 | "id": "UCx", "title": "Terminal Weekly", |
| 2349 | "handle": "@terminalweekly", "thumbnail": "https://yt3.ggpht.com/x", |
| 2350 | }, |
| 2351 | "viewCountText": f"{views:,} views", |
| 2352 | "viewCountInt": views, |
| 2353 | "publishedTimeText": "3 weeks ago", |
| 2354 | "publishedTime": published, |
| 2355 | "lengthText": "4:14", |
| 2356 | "lengthSeconds": 254, |
| 2357 | } |
| 2358 | |
| 2359 | raw = [ |
| 2360 | video("in1", "2026-09-20T17:08:46.499Z", 14860), |
| 2361 | video("in2", "2026-10-05T09:00:00.000Z", 462705), |
| 2362 | video("old", "2017-03-01T12:00:00.000Z", 999999), |
| 2363 | ] |
| 2364 | with mock.patch.object(youtube_yt, "_sc_youtube_search", return_value=raw), \ |
| 2365 | mock.patch.object(youtube_yt, "_sc_fetch_transcript", return_value="transcript"): |
| 2366 | out = youtube_yt.search_youtube_sc( |
| 2367 | "Ghostty terminal", self.FROM, self.TO, token="dummy-key", |
| 2368 | freshness_mode="balanced_recent", |
| 2369 | ) |
| 2370 | |
| 2371 | items = out["items"] |
| 2372 | self.assertEqual([i["video_id"] for i in items], ["in2", "in1"]) |
| 2373 | by_id = {i["video_id"]: i for i in items} |
| 2374 | self.assertEqual(by_id["in1"]["date"], "2026-09-20") |
| 2375 | self.assertEqual(by_id["in2"]["engagement"]["views"], 462705) |
| 2376 | self.assertEqual(by_id["in1"]["channel_name"], "Terminal Weekly") |
| 2377 | self.assertEqual(by_id["in1"]["duration"], 254) |
| 2378 | |
| 2379 | |
| 2380 | if __name__ == "__main__": |
| 2381 | unittest.main() |
| 2382 |