[extractor/crunchyroll:beta] Improve handling of hardsubs (#5041)
[yt-dlp3.git] / test / test_YoutubeDL.py
blob60e457108433faf63d71186dda821c420520f2f4
1 #!/usr/bin/env python3
3 # Allow direct execution
4 import os
5 import sys
6 import unittest
8 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11 import copy
12 import json
13 import urllib.error
15 from test.helper import FakeYDL, assertRegexpMatches
16 from yt_dlp import YoutubeDL
17 from yt_dlp.compat import compat_os_name
18 from yt_dlp.extractor import YoutubeIE
19 from yt_dlp.extractor.common import InfoExtractor
20 from yt_dlp.postprocessor.common import PostProcessor
21 from yt_dlp.utils import (
22 ExtractorError,
23 LazyList,
24 OnDemandPagedList,
25 int_or_none,
26 match_filter_func,
29 TEST_URL = 'http://localhost/sample.mp4'
32 class YDL(FakeYDL):
33 def __init__(self, *args, **kwargs):
34 super().__init__(*args, **kwargs)
35 self.downloaded_info_dicts = []
36 self.msgs = []
38 def process_info(self, info_dict):
39 self.downloaded_info_dicts.append(info_dict.copy())
41 def to_screen(self, msg, *args, **kwargs):
42 self.msgs.append(msg)
44 def dl(self, *args, **kwargs):
45 assert False, 'Downloader must not be invoked for test_YoutubeDL'
48 def _make_result(formats, **kwargs):
49 res = {
50 'formats': formats,
51 'id': 'testid',
52 'title': 'testttitle',
53 'extractor': 'testex',
54 'extractor_key': 'TestEx',
55 'webpage_url': 'http://example.com/watch?v=shenanigans',
57 res.update(**kwargs)
58 return res
61 class TestFormatSelection(unittest.TestCase):
62 def test_prefer_free_formats(self):
63 # Same resolution => download webm
64 ydl = YDL()
65 ydl.params['prefer_free_formats'] = True
66 formats = [
67 {'ext': 'webm', 'height': 460, 'url': TEST_URL},
68 {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
70 info_dict = _make_result(formats)
71 yie = YoutubeIE(ydl)
72 yie._sort_formats(info_dict['formats'])
73 ydl.process_ie_result(info_dict)
74 downloaded = ydl.downloaded_info_dicts[0]
75 self.assertEqual(downloaded['ext'], 'webm')
77 # Different resolution => download best quality (mp4)
78 ydl = YDL()
79 ydl.params['prefer_free_formats'] = True
80 formats = [
81 {'ext': 'webm', 'height': 720, 'url': TEST_URL},
82 {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
84 info_dict['formats'] = formats
85 yie = YoutubeIE(ydl)
86 yie._sort_formats(info_dict['formats'])
87 ydl.process_ie_result(info_dict)
88 downloaded = ydl.downloaded_info_dicts[0]
89 self.assertEqual(downloaded['ext'], 'mp4')
91 # No prefer_free_formats => prefer mp4 and webm
92 ydl = YDL()
93 ydl.params['prefer_free_formats'] = False
94 formats = [
95 {'ext': 'webm', 'height': 720, 'url': TEST_URL},
96 {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
97 {'ext': 'flv', 'height': 720, 'url': TEST_URL},
99 info_dict['formats'] = formats
100 yie = YoutubeIE(ydl)
101 yie._sort_formats(info_dict['formats'])
102 ydl.process_ie_result(info_dict)
103 downloaded = ydl.downloaded_info_dicts[0]
104 self.assertEqual(downloaded['ext'], 'mp4')
106 ydl = YDL()
107 ydl.params['prefer_free_formats'] = False
108 formats = [
109 {'ext': 'flv', 'height': 720, 'url': TEST_URL},
110 {'ext': 'webm', 'height': 720, 'url': TEST_URL},
112 info_dict['formats'] = formats
113 yie = YoutubeIE(ydl)
114 yie._sort_formats(info_dict['formats'])
115 ydl.process_ie_result(info_dict)
116 downloaded = ydl.downloaded_info_dicts[0]
117 self.assertEqual(downloaded['ext'], 'webm')
119 def test_format_selection(self):
120 formats = [
121 {'format_id': '35', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
122 {'format_id': 'example-with-dashes', 'ext': 'webm', 'preference': 1, 'url': TEST_URL},
123 {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
124 {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
125 {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
127 info_dict = _make_result(formats)
129 def test(inp, *expected, multi=False):
130 ydl = YDL({
131 'format': inp,
132 'allow_multiple_video_streams': multi,
133 'allow_multiple_audio_streams': multi,
135 ydl.process_ie_result(info_dict.copy())
136 downloaded = map(lambda x: x['format_id'], ydl.downloaded_info_dicts)
137 self.assertEqual(list(downloaded), list(expected))
139 test('20/47', '47')
140 test('20/71/worst', '35')
141 test(None, '2')
142 test('webm/mp4', '47')
143 test('3gp/40/mp4', '35')
144 test('example-with-dashes', 'example-with-dashes')
145 test('all', '2', '47', '45', 'example-with-dashes', '35')
146 test('mergeall', '2+47+45+example-with-dashes+35', multi=True)
148 def test_format_selection_audio(self):
149 formats = [
150 {'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
151 {'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
152 {'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': TEST_URL},
153 {'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': TEST_URL},
155 info_dict = _make_result(formats)
157 ydl = YDL({'format': 'bestaudio'})
158 ydl.process_ie_result(info_dict.copy())
159 downloaded = ydl.downloaded_info_dicts[0]
160 self.assertEqual(downloaded['format_id'], 'audio-high')
162 ydl = YDL({'format': 'worstaudio'})
163 ydl.process_ie_result(info_dict.copy())
164 downloaded = ydl.downloaded_info_dicts[0]
165 self.assertEqual(downloaded['format_id'], 'audio-low')
167 formats = [
168 {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
169 {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
171 info_dict = _make_result(formats)
173 ydl = YDL({'format': 'bestaudio/worstaudio/best'})
174 ydl.process_ie_result(info_dict.copy())
175 downloaded = ydl.downloaded_info_dicts[0]
176 self.assertEqual(downloaded['format_id'], 'vid-high')
178 def test_format_selection_audio_exts(self):
179 formats = [
180 {'format_id': 'mp3-64', 'ext': 'mp3', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
181 {'format_id': 'ogg-64', 'ext': 'ogg', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
182 {'format_id': 'aac-64', 'ext': 'aac', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
183 {'format_id': 'mp3-32', 'ext': 'mp3', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
184 {'format_id': 'aac-32', 'ext': 'aac', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
187 info_dict = _make_result(formats)
188 ydl = YDL({'format': 'best'})
189 ie = YoutubeIE(ydl)
190 ie._sort_formats(info_dict['formats'])
191 ydl.process_ie_result(copy.deepcopy(info_dict))
192 downloaded = ydl.downloaded_info_dicts[0]
193 self.assertEqual(downloaded['format_id'], 'aac-64')
195 ydl = YDL({'format': 'mp3'})
196 ie = YoutubeIE(ydl)
197 ie._sort_formats(info_dict['formats'])
198 ydl.process_ie_result(copy.deepcopy(info_dict))
199 downloaded = ydl.downloaded_info_dicts[0]
200 self.assertEqual(downloaded['format_id'], 'mp3-64')
202 ydl = YDL({'prefer_free_formats': True})
203 ie = YoutubeIE(ydl)
204 ie._sort_formats(info_dict['formats'])
205 ydl.process_ie_result(copy.deepcopy(info_dict))
206 downloaded = ydl.downloaded_info_dicts[0]
207 self.assertEqual(downloaded['format_id'], 'ogg-64')
209 def test_format_selection_video(self):
210 formats = [
211 {'format_id': 'dash-video-low', 'ext': 'mp4', 'preference': 1, 'acodec': 'none', 'url': TEST_URL},
212 {'format_id': 'dash-video-high', 'ext': 'mp4', 'preference': 2, 'acodec': 'none', 'url': TEST_URL},
213 {'format_id': 'vid', 'ext': 'mp4', 'preference': 3, 'url': TEST_URL},
215 info_dict = _make_result(formats)
217 ydl = YDL({'format': 'bestvideo'})
218 ydl.process_ie_result(info_dict.copy())
219 downloaded = ydl.downloaded_info_dicts[0]
220 self.assertEqual(downloaded['format_id'], 'dash-video-high')
222 ydl = YDL({'format': 'worstvideo'})
223 ydl.process_ie_result(info_dict.copy())
224 downloaded = ydl.downloaded_info_dicts[0]
225 self.assertEqual(downloaded['format_id'], 'dash-video-low')
227 ydl = YDL({'format': 'bestvideo[format_id^=dash][format_id$=low]'})
228 ydl.process_ie_result(info_dict.copy())
229 downloaded = ydl.downloaded_info_dicts[0]
230 self.assertEqual(downloaded['format_id'], 'dash-video-low')
232 formats = [
233 {'format_id': 'vid-vcodec-dot', 'ext': 'mp4', 'preference': 1, 'vcodec': 'avc1.123456', 'acodec': 'none', 'url': TEST_URL},
235 info_dict = _make_result(formats)
237 ydl = YDL({'format': 'bestvideo[vcodec=avc1.123456]'})
238 ydl.process_ie_result(info_dict.copy())
239 downloaded = ydl.downloaded_info_dicts[0]
240 self.assertEqual(downloaded['format_id'], 'vid-vcodec-dot')
242 def test_format_selection_string_ops(self):
243 formats = [
244 {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL},
245 {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL},
247 info_dict = _make_result(formats)
249 # equals (=)
250 ydl = YDL({'format': '[format_id=abc-cba]'})
251 ydl.process_ie_result(info_dict.copy())
252 downloaded = ydl.downloaded_info_dicts[0]
253 self.assertEqual(downloaded['format_id'], 'abc-cba')
255 # does not equal (!=)
256 ydl = YDL({'format': '[format_id!=abc-cba]'})
257 ydl.process_ie_result(info_dict.copy())
258 downloaded = ydl.downloaded_info_dicts[0]
259 self.assertEqual(downloaded['format_id'], 'zxc-cxz')
261 ydl = YDL({'format': '[format_id!=abc-cba][format_id!=zxc-cxz]'})
262 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
264 # starts with (^=)
265 ydl = YDL({'format': '[format_id^=abc]'})
266 ydl.process_ie_result(info_dict.copy())
267 downloaded = ydl.downloaded_info_dicts[0]
268 self.assertEqual(downloaded['format_id'], 'abc-cba')
270 # does not start with (!^=)
271 ydl = YDL({'format': '[format_id!^=abc]'})
272 ydl.process_ie_result(info_dict.copy())
273 downloaded = ydl.downloaded_info_dicts[0]
274 self.assertEqual(downloaded['format_id'], 'zxc-cxz')
276 ydl = YDL({'format': '[format_id!^=abc][format_id!^=zxc]'})
277 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
279 # ends with ($=)
280 ydl = YDL({'format': '[format_id$=cba]'})
281 ydl.process_ie_result(info_dict.copy())
282 downloaded = ydl.downloaded_info_dicts[0]
283 self.assertEqual(downloaded['format_id'], 'abc-cba')
285 # does not end with (!$=)
286 ydl = YDL({'format': '[format_id!$=cba]'})
287 ydl.process_ie_result(info_dict.copy())
288 downloaded = ydl.downloaded_info_dicts[0]
289 self.assertEqual(downloaded['format_id'], 'zxc-cxz')
291 ydl = YDL({'format': '[format_id!$=cba][format_id!$=cxz]'})
292 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
294 # contains (*=)
295 ydl = YDL({'format': '[format_id*=bc-cb]'})
296 ydl.process_ie_result(info_dict.copy())
297 downloaded = ydl.downloaded_info_dicts[0]
298 self.assertEqual(downloaded['format_id'], 'abc-cba')
300 # does not contain (!*=)
301 ydl = YDL({'format': '[format_id!*=bc-cb]'})
302 ydl.process_ie_result(info_dict.copy())
303 downloaded = ydl.downloaded_info_dicts[0]
304 self.assertEqual(downloaded['format_id'], 'zxc-cxz')
306 ydl = YDL({'format': '[format_id!*=abc][format_id!*=zxc]'})
307 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
309 ydl = YDL({'format': '[format_id!*=-]'})
310 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
312 def test_youtube_format_selection(self):
313 # FIXME: Rewrite in accordance with the new format sorting options
314 return
316 order = [
317 '38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '17', '36', '13',
318 # Apple HTTP Live Streaming
319 '96', '95', '94', '93', '92', '132', '151',
320 # 3D
321 '85', '84', '102', '83', '101', '82', '100',
322 # Dash video
323 '137', '248', '136', '247', '135', '246',
324 '245', '244', '134', '243', '133', '242', '160',
325 # Dash audio
326 '141', '172', '140', '171', '139',
329 def format_info(f_id):
330 info = YoutubeIE._formats[f_id].copy()
332 # XXX: In real cases InfoExtractor._parse_mpd_formats() fills up 'acodec'
333 # and 'vcodec', while in tests such information is incomplete since
334 # commit a6c2c24479e5f4827ceb06f64d855329c0a6f593
335 # test_YoutubeDL.test_youtube_format_selection is broken without
336 # this fix
337 if 'acodec' in info and 'vcodec' not in info:
338 info['vcodec'] = 'none'
339 elif 'vcodec' in info and 'acodec' not in info:
340 info['acodec'] = 'none'
342 info['format_id'] = f_id
343 info['url'] = 'url:' + f_id
344 return info
345 formats_order = [format_info(f_id) for f_id in order]
347 info_dict = _make_result(list(formats_order), extractor='youtube')
348 ydl = YDL({'format': 'bestvideo+bestaudio'})
349 yie = YoutubeIE(ydl)
350 yie._sort_formats(info_dict['formats'])
351 ydl.process_ie_result(info_dict)
352 downloaded = ydl.downloaded_info_dicts[0]
353 self.assertEqual(downloaded['format_id'], '248+172')
354 self.assertEqual(downloaded['ext'], 'mp4')
356 info_dict = _make_result(list(formats_order), extractor='youtube')
357 ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'})
358 yie = YoutubeIE(ydl)
359 yie._sort_formats(info_dict['formats'])
360 ydl.process_ie_result(info_dict)
361 downloaded = ydl.downloaded_info_dicts[0]
362 self.assertEqual(downloaded['format_id'], '38')
364 info_dict = _make_result(list(formats_order), extractor='youtube')
365 ydl = YDL({'format': 'bestvideo/best,bestaudio'})
366 yie = YoutubeIE(ydl)
367 yie._sort_formats(info_dict['formats'])
368 ydl.process_ie_result(info_dict)
369 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
370 self.assertEqual(downloaded_ids, ['137', '141'])
372 info_dict = _make_result(list(formats_order), extractor='youtube')
373 ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
374 yie = YoutubeIE(ydl)
375 yie._sort_formats(info_dict['formats'])
376 ydl.process_ie_result(info_dict)
377 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
378 self.assertEqual(downloaded_ids, ['137+141', '248+141'])
380 info_dict = _make_result(list(formats_order), extractor='youtube')
381 ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])[height<=720]+bestaudio'})
382 yie = YoutubeIE(ydl)
383 yie._sort_formats(info_dict['formats'])
384 ydl.process_ie_result(info_dict)
385 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
386 self.assertEqual(downloaded_ids, ['136+141', '247+141'])
388 info_dict = _make_result(list(formats_order), extractor='youtube')
389 ydl = YDL({'format': '(bestvideo[ext=none]/bestvideo[ext=webm])+bestaudio'})
390 yie = YoutubeIE(ydl)
391 yie._sort_formats(info_dict['formats'])
392 ydl.process_ie_result(info_dict)
393 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
394 self.assertEqual(downloaded_ids, ['248+141'])
396 for f1, f2 in zip(formats_order, formats_order[1:]):
397 info_dict = _make_result([f1, f2], extractor='youtube')
398 ydl = YDL({'format': 'best/bestvideo'})
399 yie = YoutubeIE(ydl)
400 yie._sort_formats(info_dict['formats'])
401 ydl.process_ie_result(info_dict)
402 downloaded = ydl.downloaded_info_dicts[0]
403 self.assertEqual(downloaded['format_id'], f1['format_id'])
405 info_dict = _make_result([f2, f1], extractor='youtube')
406 ydl = YDL({'format': 'best/bestvideo'})
407 yie = YoutubeIE(ydl)
408 yie._sort_formats(info_dict['formats'])
409 ydl.process_ie_result(info_dict)
410 downloaded = ydl.downloaded_info_dicts[0]
411 self.assertEqual(downloaded['format_id'], f1['format_id'])
413 def test_audio_only_extractor_format_selection(self):
414 # For extractors with incomplete formats (all formats are audio-only or
415 # video-only) best and worst should fallback to corresponding best/worst
416 # video-only or audio-only formats (as per
417 # https://github.com/ytdl-org/youtube-dl/pull/5556)
418 formats = [
419 {'format_id': 'low', 'ext': 'mp3', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
420 {'format_id': 'high', 'ext': 'mp3', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
422 info_dict = _make_result(formats)
424 ydl = YDL({'format': 'best'})
425 ydl.process_ie_result(info_dict.copy())
426 downloaded = ydl.downloaded_info_dicts[0]
427 self.assertEqual(downloaded['format_id'], 'high')
429 ydl = YDL({'format': 'worst'})
430 ydl.process_ie_result(info_dict.copy())
431 downloaded = ydl.downloaded_info_dicts[0]
432 self.assertEqual(downloaded['format_id'], 'low')
434 def test_format_not_available(self):
435 formats = [
436 {'format_id': 'regular', 'ext': 'mp4', 'height': 360, 'url': TEST_URL},
437 {'format_id': 'video', 'ext': 'mp4', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
439 info_dict = _make_result(formats)
441 # This must fail since complete video-audio format does not match filter
442 # and extractor does not provide incomplete only formats (i.e. only
443 # video-only or audio-only).
444 ydl = YDL({'format': 'best[height>360]'})
445 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
447 def test_format_selection_issue_10083(self):
448 # See https://github.com/ytdl-org/youtube-dl/issues/10083
449 formats = [
450 {'format_id': 'regular', 'height': 360, 'url': TEST_URL},
451 {'format_id': 'video', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
452 {'format_id': 'audio', 'vcodec': 'none', 'url': TEST_URL},
454 info_dict = _make_result(formats)
456 ydl = YDL({'format': 'best[height>360]/bestvideo[height>360]+bestaudio'})
457 ydl.process_ie_result(info_dict.copy())
458 self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'video+audio')
460 def test_invalid_format_specs(self):
461 def assert_syntax_error(format_spec):
462 self.assertRaises(SyntaxError, YDL, {'format': format_spec})
464 assert_syntax_error('bestvideo,,best')
465 assert_syntax_error('+bestaudio')
466 assert_syntax_error('bestvideo+')
467 assert_syntax_error('/')
468 assert_syntax_error('[720<height]')
470 def test_format_filtering(self):
471 formats = [
472 {'format_id': 'A', 'filesize': 500, 'width': 1000},
473 {'format_id': 'B', 'filesize': 1000, 'width': 500},
474 {'format_id': 'C', 'filesize': 1000, 'width': 400},
475 {'format_id': 'D', 'filesize': 2000, 'width': 600},
476 {'format_id': 'E', 'filesize': 3000},
477 {'format_id': 'F'},
478 {'format_id': 'G', 'filesize': 1000000},
480 for f in formats:
481 f['url'] = 'http://_/'
482 f['ext'] = 'unknown'
483 info_dict = _make_result(formats)
485 ydl = YDL({'format': 'best[filesize<3000]'})
486 ydl.process_ie_result(info_dict)
487 downloaded = ydl.downloaded_info_dicts[0]
488 self.assertEqual(downloaded['format_id'], 'D')
490 ydl = YDL({'format': 'best[filesize<=3000]'})
491 ydl.process_ie_result(info_dict)
492 downloaded = ydl.downloaded_info_dicts[0]
493 self.assertEqual(downloaded['format_id'], 'E')
495 ydl = YDL({'format': 'best[filesize <= ? 3000]'})
496 ydl.process_ie_result(info_dict)
497 downloaded = ydl.downloaded_info_dicts[0]
498 self.assertEqual(downloaded['format_id'], 'F')
500 ydl = YDL({'format': 'best [filesize = 1000] [width>450]'})
501 ydl.process_ie_result(info_dict)
502 downloaded = ydl.downloaded_info_dicts[0]
503 self.assertEqual(downloaded['format_id'], 'B')
505 ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
506 ydl.process_ie_result(info_dict)
507 downloaded = ydl.downloaded_info_dicts[0]
508 self.assertEqual(downloaded['format_id'], 'C')
510 ydl = YDL({'format': '[filesize>?1]'})
511 ydl.process_ie_result(info_dict)
512 downloaded = ydl.downloaded_info_dicts[0]
513 self.assertEqual(downloaded['format_id'], 'G')
515 ydl = YDL({'format': '[filesize<1M]'})
516 ydl.process_ie_result(info_dict)
517 downloaded = ydl.downloaded_info_dicts[0]
518 self.assertEqual(downloaded['format_id'], 'E')
520 ydl = YDL({'format': '[filesize<1MiB]'})
521 ydl.process_ie_result(info_dict)
522 downloaded = ydl.downloaded_info_dicts[0]
523 self.assertEqual(downloaded['format_id'], 'G')
525 ydl = YDL({'format': 'all[width>=400][width<=600]'})
526 ydl.process_ie_result(info_dict)
527 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
528 self.assertEqual(downloaded_ids, ['D', 'C', 'B'])
530 ydl = YDL({'format': 'best[height<40]'})
531 try:
532 ydl.process_ie_result(info_dict)
533 except ExtractorError:
534 pass
535 self.assertEqual(ydl.downloaded_info_dicts, [])
537 def test_default_format_spec(self):
538 ydl = YDL({'simulate': True})
539 self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
541 ydl = YDL({})
542 self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
544 ydl = YDL({'simulate': True})
545 self.assertEqual(ydl._default_format_spec({'is_live': True}), 'bestvideo*+bestaudio/best')
547 ydl = YDL({'outtmpl': '-'})
548 self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
550 ydl = YDL({})
551 self.assertEqual(ydl._default_format_spec({}, download=False), 'bestvideo*+bestaudio/best')
552 self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
555 class TestYoutubeDL(unittest.TestCase):
556 def test_subtitles(self):
557 def s_formats(lang, autocaption=False):
558 return [{
559 'ext': ext,
560 'url': f'http://localhost/video.{lang}.{ext}',
561 '_auto': autocaption,
562 } for ext in ['vtt', 'srt', 'ass']]
563 subtitles = {l: s_formats(l) for l in ['en', 'fr', 'es']}
564 auto_captions = {l: s_formats(l, True) for l in ['it', 'pt', 'es']}
565 info_dict = {
566 'id': 'test',
567 'title': 'Test',
568 'url': 'http://localhost/video.mp4',
569 'subtitles': subtitles,
570 'automatic_captions': auto_captions,
571 'extractor': 'TEST',
572 'webpage_url': 'http://example.com/watch?v=shenanigans',
575 def get_info(params={}):
576 params.setdefault('simulate', True)
577 ydl = YDL(params)
578 ydl.report_warning = lambda *args, **kargs: None
579 return ydl.process_video_result(info_dict, download=False)
581 result = get_info()
582 self.assertFalse(result.get('requested_subtitles'))
583 self.assertEqual(result['subtitles'], subtitles)
584 self.assertEqual(result['automatic_captions'], auto_captions)
586 result = get_info({'writesubtitles': True})
587 subs = result['requested_subtitles']
588 self.assertTrue(subs)
589 self.assertEqual(set(subs.keys()), {'en'})
590 self.assertTrue(subs['en'].get('data') is None)
591 self.assertEqual(subs['en']['ext'], 'ass')
593 result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
594 subs = result['requested_subtitles']
595 self.assertEqual(subs['en']['ext'], 'srt')
597 result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
598 subs = result['requested_subtitles']
599 self.assertTrue(subs)
600 self.assertEqual(set(subs.keys()), {'es', 'fr'})
602 result = get_info({'writesubtitles': True, 'subtitleslangs': ['all', '-en']})
603 subs = result['requested_subtitles']
604 self.assertTrue(subs)
605 self.assertEqual(set(subs.keys()), {'es', 'fr'})
607 result = get_info({'writesubtitles': True, 'subtitleslangs': ['en', 'fr', '-en']})
608 subs = result['requested_subtitles']
609 self.assertTrue(subs)
610 self.assertEqual(set(subs.keys()), {'fr'})
612 result = get_info({'writesubtitles': True, 'subtitleslangs': ['-en', 'en']})
613 subs = result['requested_subtitles']
614 self.assertTrue(subs)
615 self.assertEqual(set(subs.keys()), {'en'})
617 result = get_info({'writesubtitles': True, 'subtitleslangs': ['e.+']})
618 subs = result['requested_subtitles']
619 self.assertTrue(subs)
620 self.assertEqual(set(subs.keys()), {'es', 'en'})
622 result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
623 subs = result['requested_subtitles']
624 self.assertTrue(subs)
625 self.assertEqual(set(subs.keys()), {'es', 'pt'})
626 self.assertFalse(subs['es']['_auto'])
627 self.assertTrue(subs['pt']['_auto'])
629 result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
630 subs = result['requested_subtitles']
631 self.assertTrue(subs)
632 self.assertEqual(set(subs.keys()), {'es', 'pt'})
633 self.assertTrue(subs['es']['_auto'])
634 self.assertTrue(subs['pt']['_auto'])
636 def test_add_extra_info(self):
637 test_dict = {
638 'extractor': 'Foo',
640 extra_info = {
641 'extractor': 'Bar',
642 'playlist': 'funny videos',
644 YDL.add_extra_info(test_dict, extra_info)
645 self.assertEqual(test_dict['extractor'], 'Foo')
646 self.assertEqual(test_dict['playlist'], 'funny videos')
648 outtmpl_info = {
649 'id': '1234',
650 'ext': 'mp4',
651 'width': None,
652 'height': 1080,
653 'filesize': 1024,
654 'title1': '$PATH',
655 'title2': '%PATH%',
656 'title3': 'foo/bar\\test',
657 'title4': 'foo "bar" test',
658 'title5': 'áéí 𝐀',
659 'timestamp': 1618488000,
660 'duration': 100000,
661 'playlist_index': 1,
662 'playlist_autonumber': 2,
663 '__last_playlist_index': 100,
664 'n_entries': 10,
665 'formats': [
666 {'id': 'id 1', 'height': 1080, 'width': 1920},
667 {'id': 'id 2', 'height': 720},
668 {'id': 'id 3'}
672 def test_prepare_outtmpl_and_filename(self):
673 def test(tmpl, expected, *, info=None, **params):
674 params['outtmpl'] = tmpl
675 ydl = FakeYDL(params)
676 ydl._num_downloads = 1
677 self.assertEqual(ydl.validate_outtmpl(tmpl), None)
679 out = ydl.evaluate_outtmpl(tmpl, info or self.outtmpl_info)
680 fname = ydl.prepare_filename(info or self.outtmpl_info)
682 if not isinstance(expected, (list, tuple)):
683 expected = (expected, expected)
684 for (name, got), expect in zip((('outtmpl', out), ('filename', fname)), expected):
685 if callable(expect):
686 self.assertTrue(expect(got), f'Wrong {name} from {tmpl}')
687 else:
688 self.assertEqual(got, expect, f'Wrong {name} from {tmpl}')
690 # Side-effects
691 original_infodict = dict(self.outtmpl_info)
692 test('foo.bar', 'foo.bar')
693 original_infodict['epoch'] = self.outtmpl_info.get('epoch')
694 self.assertTrue(isinstance(original_infodict['epoch'], int))
695 test('%(epoch)d', int_or_none)
696 self.assertEqual(original_infodict, self.outtmpl_info)
698 # Auto-generated fields
699 test('%(id)s.%(ext)s', '1234.mp4')
700 test('%(duration_string)s', ('27:46:40', '27-46-40'))
701 test('%(resolution)s', '1080p')
702 test('%(playlist_index)s', '001')
703 test('%(playlist_autonumber)s', '02')
704 test('%(autonumber)s', '00001')
705 test('%(autonumber+2)03d', '005', autonumber_start=3)
706 test('%(autonumber)s', '001', autonumber_size=3)
708 # Escaping %
709 test('%', '%')
710 test('%%', '%')
711 test('%%%%', '%%')
712 test('%s', '%s')
713 test('%%%s', '%%s')
714 test('%d', '%d')
715 test('%abc%', '%abc%')
716 test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
717 test('%%%(height)s', '%1080')
718 test('%(width)06d.%(ext)s', 'NA.mp4')
719 test('%(width)06d.%%(ext)s', 'NA.%(ext)s')
720 test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
722 # ID sanitization
723 test('%(id)s', '_abcd', info={'id': '_abcd'})
724 test('%(some_id)s', '_abcd', info={'some_id': '_abcd'})
725 test('%(formats.0.id)s', '_abcd', info={'formats': [{'id': '_abcd'}]})
726 test('%(id)s', '-abcd', info={'id': '-abcd'})
727 test('%(id)s', '.abcd', info={'id': '.abcd'})
728 test('%(id)s', 'ab__cd', info={'id': 'ab__cd'})
729 test('%(id)s', ('ab:cd', 'ab:cd'), info={'id': 'ab:cd'})
730 test('%(id.0)s', '-', info={'id': '--'})
732 # Invalid templates
733 self.assertTrue(isinstance(YoutubeDL.validate_outtmpl('%(title)'), ValueError))
734 test('%(invalid@tmpl|def)s', 'none', outtmpl_na_placeholder='none')
735 test('%(..)s', 'NA')
736 test('%(formats.{id)s', 'NA')
738 # Entire info_dict
739 def expect_same_infodict(out):
740 got_dict = json.loads(out)
741 for info_field, expected in self.outtmpl_info.items():
742 self.assertEqual(got_dict.get(info_field), expected, info_field)
743 return True
745 test('%()j', (expect_same_infodict, str))
747 # NA placeholder
748 NA_TEST_OUTTMPL = '%(uploader_date)s-%(width)d-%(x|def)s-%(id)s.%(ext)s'
749 test(NA_TEST_OUTTMPL, 'NA-NA-def-1234.mp4')
750 test(NA_TEST_OUTTMPL, 'none-none-def-1234.mp4', outtmpl_na_placeholder='none')
751 test(NA_TEST_OUTTMPL, '--def-1234.mp4', outtmpl_na_placeholder='')
752 test('%(non_existent.0)s', 'NA')
754 # String formatting
755 FMT_TEST_OUTTMPL = '%%(height)%s.%%(ext)s'
756 test(FMT_TEST_OUTTMPL % 's', '1080.mp4')
757 test(FMT_TEST_OUTTMPL % 'd', '1080.mp4')
758 test(FMT_TEST_OUTTMPL % '6d', ' 1080.mp4')
759 test(FMT_TEST_OUTTMPL % '-6d', '1080 .mp4')
760 test(FMT_TEST_OUTTMPL % '06d', '001080.mp4')
761 test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
762 test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
763 test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
764 test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
765 test(FMT_TEST_OUTTMPL % ' 0 6d', ' 01080.mp4')
767 # Type casting
768 test('%(id)d', '1234')
769 test('%(height)c', '1')
770 test('%(ext)c', 'm')
771 test('%(id)d %(id)r', "1234 '1234'")
772 test('%(id)r %(height)r', "'1234' 1080")
773 test('%(ext)s-%(ext|def)d', 'mp4-def')
774 test('%(width|0)04d', '0000')
775 test('a%(width|)d', 'a', outtmpl_na_placeholder='none')
777 FORMATS = self.outtmpl_info['formats']
778 sanitize = lambda x: x.replace(':', ':').replace('"', """).replace('\n', ' ')
780 # Custom type casting
781 test('%(formats.:.id)l', 'id 1, id 2, id 3')
782 test('%(formats.:.id)#l', ('id 1\nid 2\nid 3', 'id 1 id 2 id 3'))
783 test('%(ext)l', 'mp4')
784 test('%(formats.:.id) 18l', ' id 1, id 2, id 3')
785 test('%(formats)j', (json.dumps(FORMATS), sanitize(json.dumps(FORMATS))))
786 test('%(formats)#j', (json.dumps(FORMATS, indent=4), sanitize(json.dumps(FORMATS, indent=4))))
787 test('%(title5).3B', 'á')
788 test('%(title5)U', 'áéí 𝐀')
789 test('%(title5)#U', 'a\u0301e\u0301i\u0301 𝐀')
790 test('%(title5)+U', 'áéí A')
791 test('%(title5)+#U', 'a\u0301e\u0301i\u0301 A')
792 test('%(height)D', '1k')
793 test('%(filesize)#D', '1Ki')
794 test('%(height)5.2D', ' 1.08k')
795 test('%(title4)#S', 'foo_bar_test')
796 test('%(title4).10S', ('foo "bar" ', 'foo "bar"' + ('#' if compat_os_name == 'nt' else ' ')))
797 if compat_os_name == 'nt':
798 test('%(title4)q', ('"foo \\"bar\\" test"', ""foo ⧹"bar⧹" test""))
799 test('%(formats.:.id)#q', ('"id 1" "id 2" "id 3"', '"id 1" "id 2" "id 3"'))
800 test('%(formats.0.id)#q', ('"id 1"', '"id 1"'))
801 else:
802 test('%(title4)q', ('\'foo "bar" test\'', '\'foo "bar" test\''))
803 test('%(formats.:.id)#q', "'id 1' 'id 2' 'id 3'")
804 test('%(formats.0.id)#q', "'id 1'")
806 # Internal formatting
807 test('%(timestamp-1000>%H-%M-%S)s', '11-43-20')
808 test('%(title|%)s %(title|%%)s', '% %%')
809 test('%(id+1-height+3)05d', '00158')
810 test('%(width+100)05d', 'NA')
811 test('%(formats.0) 15s', ('% 15s' % FORMATS[0], '% 15s' % sanitize(str(FORMATS[0]))))
812 test('%(formats.0)r', (repr(FORMATS[0]), sanitize(repr(FORMATS[0]))))
813 test('%(height.0)03d', '001')
814 test('%(-height.0)04d', '-001')
815 test('%(formats.-1.id)s', FORMATS[-1]['id'])
816 test('%(formats.0.id.-1)d', FORMATS[0]['id'][-1])
817 test('%(formats.3)s', 'NA')
818 test('%(formats.:2:-1)r', repr(FORMATS[:2:-1]))
819 test('%(formats.0.id.-1+id)f', '1235.000000')
820 test('%(formats.0.id.-1+formats.1.id.-1)d', '3')
821 out = json.dumps([{'id': f['id'], 'height.:2': str(f['height'])[:2]}
822 if 'height' in f else {'id': f['id']}
823 for f in FORMATS])
824 test('%(formats.:.{id,height.:2})j', (out, sanitize(out)))
825 test('%(formats.:.{id,height}.id)l', ', '.join(f['id'] for f in FORMATS))
826 test('%(.{id,title})j', ('{"id": "1234"}', '{"id": "1234"}'))
828 # Alternates
829 test('%(title,id)s', '1234')
830 test('%(width-100,height+20|def)d', '1100')
831 test('%(width-100,height+width|def)s', 'def')
832 test('%(timestamp-x>%H\\,%M\\,%S,timestamp>%H\\,%M\\,%S)s', '12,00,00')
834 # Replacement
835 test('%(id&foo)s.bar', 'foo.bar')
836 test('%(title&foo)s.bar', 'NA.bar')
837 test('%(title&foo|baz)s.bar', 'baz.bar')
838 test('%(x,id&foo|baz)s.bar', 'foo.bar')
839 test('%(x,title&foo|baz)s.bar', 'baz.bar')
841 # Laziness
842 def gen():
843 yield from range(5)
844 raise self.assertTrue(False, 'LazyList should not be evaluated till here')
845 test('%(key.4)s', '4', info={'key': LazyList(gen())})
847 # Empty filename
848 test('%(foo|)s-%(bar|)s.%(ext)s', '-.mp4')
849 # test('%(foo|)s.%(ext)s', ('.mp4', '_.mp4')) # fixme
850 # test('%(foo|)s', ('', '_')) # fixme
852 # Environment variable expansion for prepare_filename
853 os.environ['__yt_dlp_var'] = 'expanded'
854 envvar = '%__yt_dlp_var%' if compat_os_name == 'nt' else '$__yt_dlp_var'
855 test(envvar, (envvar, 'expanded'))
856 if compat_os_name == 'nt':
857 test('%s%', ('%s%', '%s%'))
858 os.environ['s'] = 'expanded'
859 test('%s%', ('%s%', 'expanded')) # %s% should be expanded before escaping %s
860 os.environ['(test)s'] = 'expanded'
861 test('%(test)s%', ('NA%', 'expanded')) # Environment should take priority over template
863 # Path expansion and escaping
864 test('Hello %(title1)s', 'Hello $PATH')
865 test('Hello %(title2)s', 'Hello %PATH%')
866 test('%(title3)s', ('foo/bar\\test', 'foo⧸bar⧹test'))
867 test('folder/%(title3)s', ('folder/foo/bar\\test', 'folder%sfoo⧸bar⧹test' % os.path.sep))
869 def test_format_note(self):
870 ydl = YoutubeDL()
871 self.assertEqual(ydl._format_note({}), '')
872 assertRegexpMatches(self, ydl._format_note({
873 'vbr': 10,
874 }), r'^\s*10k$')
875 assertRegexpMatches(self, ydl._format_note({
876 'fps': 30,
877 }), r'^30fps$')
879 def test_postprocessors(self):
880 filename = 'post-processor-testfile.mp4'
881 audiofile = filename + '.mp3'
883 class SimplePP(PostProcessor):
884 def run(self, info):
885 with open(audiofile, 'wt') as f:
886 f.write('EXAMPLE')
887 return [info['filepath']], info
889 def run_pp(params, PP):
890 with open(filename, 'wt') as f:
891 f.write('EXAMPLE')
892 ydl = YoutubeDL(params)
893 ydl.add_post_processor(PP())
894 ydl.post_process(filename, {'filepath': filename})
896 run_pp({'keepvideo': True}, SimplePP)
897 self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
898 self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
899 os.unlink(filename)
900 os.unlink(audiofile)
902 run_pp({'keepvideo': False}, SimplePP)
903 self.assertFalse(os.path.exists(filename), '%s exists' % filename)
904 self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
905 os.unlink(audiofile)
907 class ModifierPP(PostProcessor):
908 def run(self, info):
909 with open(info['filepath'], 'wt') as f:
910 f.write('MODIFIED')
911 return [], info
913 run_pp({'keepvideo': False}, ModifierPP)
914 self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
915 os.unlink(filename)
917 def test_match_filter(self):
918 first = {
919 'id': '1',
920 'url': TEST_URL,
921 'title': 'one',
922 'extractor': 'TEST',
923 'duration': 30,
924 'filesize': 10 * 1024,
925 'playlist_id': '42',
926 'uploader': "變態妍字幕版 太妍 тест",
927 'creator': "тест ' 123 ' тест--",
928 'webpage_url': 'http://example.com/watch?v=shenanigans',
930 second = {
931 'id': '2',
932 'url': TEST_URL,
933 'title': 'two',
934 'extractor': 'TEST',
935 'duration': 10,
936 'description': 'foo',
937 'filesize': 5 * 1024,
938 'playlist_id': '43',
939 'uploader': "тест 123",
940 'webpage_url': 'http://example.com/watch?v=SHENANIGANS',
942 videos = [first, second]
944 def get_videos(filter_=None):
945 ydl = YDL({'match_filter': filter_, 'simulate': True})
946 for v in videos:
947 ydl.process_ie_result(v, download=True)
948 return [v['id'] for v in ydl.downloaded_info_dicts]
950 res = get_videos()
951 self.assertEqual(res, ['1', '2'])
953 def f(v, incomplete):
954 if v['id'] == '1':
955 return None
956 else:
957 return 'Video id is not 1'
958 res = get_videos(f)
959 self.assertEqual(res, ['1'])
961 f = match_filter_func('duration < 30')
962 res = get_videos(f)
963 self.assertEqual(res, ['2'])
965 f = match_filter_func('description = foo')
966 res = get_videos(f)
967 self.assertEqual(res, ['2'])
969 f = match_filter_func('description =? foo')
970 res = get_videos(f)
971 self.assertEqual(res, ['1', '2'])
973 f = match_filter_func('filesize > 5KiB')
974 res = get_videos(f)
975 self.assertEqual(res, ['1'])
977 f = match_filter_func('playlist_id = 42')
978 res = get_videos(f)
979 self.assertEqual(res, ['1'])
981 f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
982 res = get_videos(f)
983 self.assertEqual(res, ['1'])
985 f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
986 res = get_videos(f)
987 self.assertEqual(res, ['2'])
989 f = match_filter_func('creator = "тест \' 123 \' тест--"')
990 res = get_videos(f)
991 self.assertEqual(res, ['1'])
993 f = match_filter_func("creator = 'тест \\' 123 \\' тест--'")
994 res = get_videos(f)
995 self.assertEqual(res, ['1'])
997 f = match_filter_func(r"creator = 'тест \' 123 \' тест--' & duration > 30")
998 res = get_videos(f)
999 self.assertEqual(res, [])
1001 def test_playlist_items_selection(self):
1002 INDICES, PAGE_SIZE = list(range(1, 11)), 3
1004 def entry(i, evaluated):
1005 evaluated.append(i)
1006 return {
1007 'id': str(i),
1008 'title': str(i),
1009 'url': TEST_URL,
1012 def pagedlist_entries(evaluated):
1013 def page_func(n):
1014 start = PAGE_SIZE * n
1015 for i in INDICES[start: start + PAGE_SIZE]:
1016 yield entry(i, evaluated)
1017 return OnDemandPagedList(page_func, PAGE_SIZE)
1019 def page_num(i):
1020 return (i + PAGE_SIZE - 1) // PAGE_SIZE
1022 def generator_entries(evaluated):
1023 for i in INDICES:
1024 yield entry(i, evaluated)
1026 def list_entries(evaluated):
1027 return list(generator_entries(evaluated))
1029 def lazylist_entries(evaluated):
1030 return LazyList(generator_entries(evaluated))
1032 def get_downloaded_info_dicts(params, entries):
1033 ydl = YDL(params)
1034 ydl.process_ie_result({
1035 '_type': 'playlist',
1036 'id': 'test',
1037 'extractor': 'test:playlist',
1038 'extractor_key': 'test:playlist',
1039 'webpage_url': 'http://example.com',
1040 'entries': entries,
1042 return ydl.downloaded_info_dicts
1044 def test_selection(params, expected_ids, evaluate_all=False):
1045 expected_ids = list(expected_ids)
1046 if evaluate_all:
1047 generator_eval = pagedlist_eval = INDICES
1048 elif not expected_ids:
1049 generator_eval = pagedlist_eval = []
1050 else:
1051 generator_eval = INDICES[0: max(expected_ids)]
1052 pagedlist_eval = INDICES[PAGE_SIZE * page_num(min(expected_ids)) - PAGE_SIZE:
1053 PAGE_SIZE * page_num(max(expected_ids))]
1055 for name, func, expected_eval in (
1056 ('list', list_entries, INDICES),
1057 ('Generator', generator_entries, generator_eval),
1058 # ('LazyList', lazylist_entries, generator_eval), # Generator and LazyList follow the exact same code path
1059 ('PagedList', pagedlist_entries, pagedlist_eval),
1061 evaluated = []
1062 entries = func(evaluated)
1063 results = [(v['playlist_autonumber'] - 1, (int(v['id']), v['playlist_index']))
1064 for v in get_downloaded_info_dicts(params, entries)]
1065 self.assertEqual(results, list(enumerate(zip(expected_ids, expected_ids))), f'Entries of {name} for {params}')
1066 self.assertEqual(sorted(evaluated), expected_eval, f'Evaluation of {name} for {params}')
1068 test_selection({}, INDICES)
1069 test_selection({'playlistend': 20}, INDICES, True)
1070 test_selection({'playlistend': 2}, INDICES[:2])
1071 test_selection({'playliststart': 11}, [], True)
1072 test_selection({'playliststart': 2}, INDICES[1:])
1073 test_selection({'playlist_items': '2-4'}, INDICES[1:4])
1074 test_selection({'playlist_items': '2,4'}, [2, 4])
1075 test_selection({'playlist_items': '20'}, [], True)
1076 test_selection({'playlist_items': '0'}, [])
1078 # Tests for https://github.com/ytdl-org/youtube-dl/issues/10591
1079 test_selection({'playlist_items': '2-4,3-4,3'}, [2, 3, 4])
1080 test_selection({'playlist_items': '4,2'}, [4, 2])
1082 # Tests for https://github.com/yt-dlp/yt-dlp/issues/720
1083 # https://github.com/yt-dlp/yt-dlp/issues/302
1084 test_selection({'playlistreverse': True}, INDICES[::-1])
1085 test_selection({'playliststart': 2, 'playlistreverse': True}, INDICES[:0:-1])
1086 test_selection({'playlist_items': '2,4', 'playlistreverse': True}, [4, 2])
1087 test_selection({'playlist_items': '4,2'}, [4, 2])
1089 # Tests for --playlist-items start:end:step
1090 test_selection({'playlist_items': ':'}, INDICES, True)
1091 test_selection({'playlist_items': '::1'}, INDICES, True)
1092 test_selection({'playlist_items': '::-1'}, INDICES[::-1], True)
1093 test_selection({'playlist_items': ':6'}, INDICES[:6])
1094 test_selection({'playlist_items': ':-6'}, INDICES[:-5], True)
1095 test_selection({'playlist_items': '-1:6:-2'}, INDICES[:4:-2], True)
1096 test_selection({'playlist_items': '9:-6:-2'}, INDICES[8:3:-2], True)
1098 test_selection({'playlist_items': '1:inf:2'}, INDICES[::2], True)
1099 test_selection({'playlist_items': '-2:inf'}, INDICES[-2:], True)
1100 test_selection({'playlist_items': ':inf:-1'}, [], True)
1101 test_selection({'playlist_items': '0-2:2'}, [2])
1102 test_selection({'playlist_items': '1-:2'}, INDICES[::2], True)
1103 test_selection({'playlist_items': '0--2:2'}, INDICES[1:-1:2], True)
1105 test_selection({'playlist_items': '10::3'}, [10], True)
1106 test_selection({'playlist_items': '-1::3'}, [10], True)
1107 test_selection({'playlist_items': '11::3'}, [], True)
1108 test_selection({'playlist_items': '-15::2'}, INDICES[1::2], True)
1109 test_selection({'playlist_items': '-15::15'}, [], True)
1111 def test_urlopen_no_file_protocol(self):
1112 # see https://github.com/ytdl-org/youtube-dl/issues/8227
1113 ydl = YDL()
1114 self.assertRaises(urllib.error.URLError, ydl.urlopen, 'file:///etc/passwd')
1116 def test_do_not_override_ie_key_in_url_transparent(self):
1117 ydl = YDL()
1119 class Foo1IE(InfoExtractor):
1120 _VALID_URL = r'foo1:'
1122 def _real_extract(self, url):
1123 return {
1124 '_type': 'url_transparent',
1125 'url': 'foo2:',
1126 'ie_key': 'Foo2',
1127 'title': 'foo1 title',
1128 'id': 'foo1_id',
1131 class Foo2IE(InfoExtractor):
1132 _VALID_URL = r'foo2:'
1134 def _real_extract(self, url):
1135 return {
1136 '_type': 'url',
1137 'url': 'foo3:',
1138 'ie_key': 'Foo3',
1141 class Foo3IE(InfoExtractor):
1142 _VALID_URL = r'foo3:'
1144 def _real_extract(self, url):
1145 return _make_result([{'url': TEST_URL}], title='foo3 title')
1147 ydl.add_info_extractor(Foo1IE(ydl))
1148 ydl.add_info_extractor(Foo2IE(ydl))
1149 ydl.add_info_extractor(Foo3IE(ydl))
1150 ydl.extract_info('foo1:')
1151 downloaded = ydl.downloaded_info_dicts[0]
1152 self.assertEqual(downloaded['url'], TEST_URL)
1153 self.assertEqual(downloaded['title'], 'foo1 title')
1154 self.assertEqual(downloaded['id'], 'testid')
1155 self.assertEqual(downloaded['extractor'], 'testex')
1156 self.assertEqual(downloaded['extractor_key'], 'TestEx')
1158 # Test case for https://github.com/ytdl-org/youtube-dl/issues/27064
1159 def test_ignoreerrors_for_playlist_with_url_transparent_iterable_entries(self):
1161 class _YDL(YDL):
1162 def __init__(self, *args, **kwargs):
1163 super().__init__(*args, **kwargs)
1165 def trouble(self, s, tb=None):
1166 pass
1168 ydl = _YDL({
1169 'format': 'extra',
1170 'ignoreerrors': True,
1173 class VideoIE(InfoExtractor):
1174 _VALID_URL = r'video:(?P<id>\d+)'
1176 def _real_extract(self, url):
1177 video_id = self._match_id(url)
1178 formats = [{
1179 'format_id': 'default',
1180 'url': 'url:',
1182 if video_id == '0':
1183 raise ExtractorError('foo')
1184 if video_id == '2':
1185 formats.append({
1186 'format_id': 'extra',
1187 'url': TEST_URL,
1189 return {
1190 'id': video_id,
1191 'title': 'Video %s' % video_id,
1192 'formats': formats,
1195 class PlaylistIE(InfoExtractor):
1196 _VALID_URL = r'playlist:'
1198 def _entries(self):
1199 for n in range(3):
1200 video_id = str(n)
1201 yield {
1202 '_type': 'url_transparent',
1203 'ie_key': VideoIE.ie_key(),
1204 'id': video_id,
1205 'url': 'video:%s' % video_id,
1206 'title': 'Video Transparent %s' % video_id,
1209 def _real_extract(self, url):
1210 return self.playlist_result(self._entries())
1212 ydl.add_info_extractor(VideoIE(ydl))
1213 ydl.add_info_extractor(PlaylistIE(ydl))
1214 info = ydl.extract_info('playlist:')
1215 entries = info['entries']
1216 self.assertEqual(len(entries), 3)
1217 self.assertTrue(entries[0] is None)
1218 self.assertTrue(entries[1] is None)
1219 self.assertEqual(len(ydl.downloaded_info_dicts), 1)
1220 downloaded = ydl.downloaded_info_dicts[0]
1221 entries[2].pop('requested_downloads', None)
1222 self.assertEqual(entries[2], downloaded)
1223 self.assertEqual(downloaded['url'], TEST_URL)
1224 self.assertEqual(downloaded['title'], 'Video Transparent 2')
1225 self.assertEqual(downloaded['id'], '2')
1226 self.assertEqual(downloaded['extractor'], 'Video')
1227 self.assertEqual(downloaded['extractor_key'], 'Video')
1230 if __name__ == '__main__':
1231 unittest.main()