]> jfr.im git - yt-dlp.git/blame - test/test_YoutubeDL.py
[cleanup] Upgrade syntax
[yt-dlp.git] / test / test_YoutubeDL.py
CommitLineData
cc52de43 1#!/usr/bin/env python3
5d254f77
PH
2# Allow direct execution
3import os
e028d0d1
JMF
4import sys
5import unittest
5d254f77 6sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
e028d0d1 7
0217c783 8import copy
7d1eb38a 9import json
0217c783 10
c57f7757 11from test.helper import FakeYDL, assertRegexpMatches
7a5c1cfe 12from yt_dlp import YoutubeDL
901130bb 13from yt_dlp.compat import compat_os_name, compat_setenv, compat_str, compat_urllib_error
7a5c1cfe
P
14from yt_dlp.extractor import YoutubeIE
15from yt_dlp.extractor.common import InfoExtractor
16from yt_dlp.postprocessor.common import PostProcessor
6e84b215 17from yt_dlp.utils import ExtractorError, int_or_none, match_filter_func, LazyList
e028d0d1 18
8508557e
JMF
19TEST_URL = 'http://localhost/sample.mp4'
20
e028d0d1
JMF
21
22class YDL(FakeYDL):
f4d96df0 23 def __init__(self, *args, **kwargs):
86e5f3ed 24 super().__init__(*args, **kwargs)
e028d0d1 25 self.downloaded_info_dicts = []
f4d96df0 26 self.msgs = []
5d254f77 27
e028d0d1 28 def process_info(self, info_dict):
09b49e1f 29 self.downloaded_info_dicts.append(info_dict.copy())
e028d0d1 30
f4d96df0
PH
31 def to_screen(self, msg):
32 self.msgs.append(msg)
33
b5ac45b1 34 def dl(self, *args, **kwargs):
35 assert False, 'Downloader must not be invoked for test_YoutubeDL'
36
5d254f77 37
3537b93d
PH
38def _make_result(formats, **kwargs):
39 res = {
40 'formats': formats,
41 'id': 'testid',
42 'title': 'testttitle',
43 'extractor': 'testex',
0396806f 44 'extractor_key': 'TestEx',
732044af 45 'webpage_url': 'http://example.com/watch?v=shenanigans',
3537b93d
PH
46 }
47 res.update(**kwargs)
48 return res
49
50
e028d0d1
JMF
51class TestFormatSelection(unittest.TestCase):
52 def test_prefer_free_formats(self):
53 # Same resolution => download webm
54 ydl = YDL()
55 ydl.params['prefer_free_formats'] = True
5d254f77 56 formats = [
8508557e
JMF
57 {'ext': 'webm', 'height': 460, 'url': TEST_URL},
58 {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
5d254f77 59 ]
3537b93d 60 info_dict = _make_result(formats)
3d4a70b8
PH
61 yie = YoutubeIE(ydl)
62 yie._sort_formats(info_dict['formats'])
e028d0d1
JMF
63 ydl.process_ie_result(info_dict)
64 downloaded = ydl.downloaded_info_dicts[0]
89087418 65 self.assertEqual(downloaded['ext'], 'webm')
e028d0d1
JMF
66
67 # Different resolution => download best quality (mp4)
68 ydl = YDL()
69 ydl.params['prefer_free_formats'] = True
5d254f77 70 formats = [
8508557e
JMF
71 {'ext': 'webm', 'height': 720, 'url': TEST_URL},
72 {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
5d254f77 73 ]
89087418 74 info_dict['formats'] = formats
3d4a70b8
PH
75 yie = YoutubeIE(ydl)
76 yie._sort_formats(info_dict['formats'])
e028d0d1
JMF
77 ydl.process_ie_result(info_dict)
78 downloaded = ydl.downloaded_info_dicts[0]
89087418 79 self.assertEqual(downloaded['ext'], 'mp4')
e028d0d1 80
5d0c5371 81 # No prefer_free_formats => prefer mp4 and webm
e028d0d1
JMF
82 ydl = YDL()
83 ydl.params['prefer_free_formats'] = False
5d254f77 84 formats = [
8508557e
JMF
85 {'ext': 'webm', 'height': 720, 'url': TEST_URL},
86 {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
87 {'ext': 'flv', 'height': 720, 'url': TEST_URL},
5d254f77 88 ]
89087418 89 info_dict['formats'] = formats
3d4a70b8
PH
90 yie = YoutubeIE(ydl)
91 yie._sort_formats(info_dict['formats'])
92 ydl.process_ie_result(info_dict)
93 downloaded = ydl.downloaded_info_dicts[0]
89087418 94 self.assertEqual(downloaded['ext'], 'mp4')
3d4a70b8
PH
95
96 ydl = YDL()
97 ydl.params['prefer_free_formats'] = False
98 formats = [
8508557e
JMF
99 {'ext': 'flv', 'height': 720, 'url': TEST_URL},
100 {'ext': 'webm', 'height': 720, 'url': TEST_URL},
3d4a70b8 101 ]
89087418 102 info_dict['formats'] = formats
3d4a70b8
PH
103 yie = YoutubeIE(ydl)
104 yie._sort_formats(info_dict['formats'])
e028d0d1
JMF
105 ydl.process_ie_result(info_dict)
106 downloaded = ydl.downloaded_info_dicts[0]
5d0c5371 107 self.assertEqual(downloaded['ext'], 'webm')
e028d0d1 108
a9c58ad9
JMF
109 def test_format_selection(self):
110 formats = [
8508557e 111 {'format_id': '35', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
232541df 112 {'format_id': 'example-with-dashes', 'ext': 'webm', 'preference': 1, 'url': TEST_URL},
8508557e
JMF
113 {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
114 {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
115 {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
a9c58ad9 116 ]
3537b93d 117 info_dict = _make_result(formats)
a9c58ad9 118
b5ac45b1 119 def test(inp, *expected, multi=False):
120 ydl = YDL({
121 'format': inp,
122 'allow_multiple_video_streams': multi,
123 'allow_multiple_audio_streams': multi,
124 })
125 ydl.process_ie_result(info_dict.copy())
126 downloaded = map(lambda x: x['format_id'], ydl.downloaded_info_dicts)
127 self.assertEqual(list(downloaded), list(expected))
128
129 test('20/47', '47')
130 test('20/71/worst', '35')
131 test(None, '2')
132 test('webm/mp4', '47')
133 test('3gp/40/mp4', '35')
134 test('example-with-dashes', 'example-with-dashes')
dd2a987d 135 test('all', '2', '47', '45', 'example-with-dashes', '35')
b5ac45b1 136 test('mergeall', '2+47+45+example-with-dashes+35', multi=True)
232541df 137
ba7678f9
PH
138 def test_format_selection_audio(self):
139 formats = [
8508557e
JMF
140 {'format_id': 'audio-low', 'ext': 'webm', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
141 {'format_id': 'audio-mid', 'ext': 'webm', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
142 {'format_id': 'audio-high', 'ext': 'flv', 'preference': 3, 'vcodec': 'none', 'url': TEST_URL},
143 {'format_id': 'vid', 'ext': 'mp4', 'preference': 4, 'url': TEST_URL},
ba7678f9 144 ]
3537b93d 145 info_dict = _make_result(formats)
ba7678f9 146
89087418 147 ydl = YDL({'format': 'bestaudio'})
ba7678f9
PH
148 ydl.process_ie_result(info_dict.copy())
149 downloaded = ydl.downloaded_info_dicts[0]
89087418 150 self.assertEqual(downloaded['format_id'], 'audio-high')
ba7678f9 151
89087418 152 ydl = YDL({'format': 'worstaudio'})
ba7678f9
PH
153 ydl.process_ie_result(info_dict.copy())
154 downloaded = ydl.downloaded_info_dicts[0]
89087418 155 self.assertEqual(downloaded['format_id'], 'audio-low')
ba7678f9
PH
156
157 formats = [
8508557e
JMF
158 {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
159 {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
ba7678f9 160 ]
3537b93d 161 info_dict = _make_result(formats)
ba7678f9 162
89087418 163 ydl = YDL({'format': 'bestaudio/worstaudio/best'})
ba7678f9
PH
164 ydl.process_ie_result(info_dict.copy())
165 downloaded = ydl.downloaded_info_dicts[0]
89087418 166 self.assertEqual(downloaded['format_id'], 'vid-high')
ba7678f9 167
0217c783
PH
168 def test_format_selection_audio_exts(self):
169 formats = [
170 {'format_id': 'mp3-64', 'ext': 'mp3', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
171 {'format_id': 'ogg-64', 'ext': 'ogg', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
172 {'format_id': 'aac-64', 'ext': 'aac', 'abr': 64, 'url': 'http://_', 'vcodec': 'none'},
173 {'format_id': 'mp3-32', 'ext': 'mp3', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
174 {'format_id': 'aac-32', 'ext': 'aac', 'abr': 32, 'url': 'http://_', 'vcodec': 'none'},
175 ]
176
177 info_dict = _make_result(formats)
178 ydl = YDL({'format': 'best'})
179 ie = YoutubeIE(ydl)
180 ie._sort_formats(info_dict['formats'])
181 ydl.process_ie_result(copy.deepcopy(info_dict))
182 downloaded = ydl.downloaded_info_dicts[0]
183 self.assertEqual(downloaded['format_id'], 'aac-64')
184
185 ydl = YDL({'format': 'mp3'})
186 ie = YoutubeIE(ydl)
187 ie._sort_formats(info_dict['formats'])
188 ydl.process_ie_result(copy.deepcopy(info_dict))
189 downloaded = ydl.downloaded_info_dicts[0]
190 self.assertEqual(downloaded['format_id'], 'mp3-64')
191
192 ydl = YDL({'prefer_free_formats': True})
193 ie = YoutubeIE(ydl)
194 ie._sort_formats(info_dict['formats'])
195 ydl.process_ie_result(copy.deepcopy(info_dict))
196 downloaded = ydl.downloaded_info_dicts[0]
197 self.assertEqual(downloaded['format_id'], 'ogg-64')
198
bc6d5978
JMF
199 def test_format_selection_video(self):
200 formats = [
8508557e
JMF
201 {'format_id': 'dash-video-low', 'ext': 'mp4', 'preference': 1, 'acodec': 'none', 'url': TEST_URL},
202 {'format_id': 'dash-video-high', 'ext': 'mp4', 'preference': 2, 'acodec': 'none', 'url': TEST_URL},
203 {'format_id': 'vid', 'ext': 'mp4', 'preference': 3, 'url': TEST_URL},
bc6d5978 204 ]
3537b93d 205 info_dict = _make_result(formats)
bc6d5978
JMF
206
207 ydl = YDL({'format': 'bestvideo'})
208 ydl.process_ie_result(info_dict.copy())
209 downloaded = ydl.downloaded_info_dicts[0]
210 self.assertEqual(downloaded['format_id'], 'dash-video-high')
211
212 ydl = YDL({'format': 'worstvideo'})
213 ydl.process_ie_result(info_dict.copy())
214 downloaded = ydl.downloaded_info_dicts[0]
215 self.assertEqual(downloaded['format_id'], 'dash-video-low')
216
4c3b16d5
S
217 ydl = YDL({'format': 'bestvideo[format_id^=dash][format_id$=low]'})
218 ydl.process_ie_result(info_dict.copy())
219 downloaded = ydl.downloaded_info_dicts[0]
220 self.assertEqual(downloaded['format_id'], 'dash-video-low')
221
b913348d 222 formats = [
223 {'format_id': 'vid-vcodec-dot', 'ext': 'mp4', 'preference': 1, 'vcodec': 'avc1.123456', 'acodec': 'none', 'url': TEST_URL},
224 ]
225 info_dict = _make_result(formats)
226
227 ydl = YDL({'format': 'bestvideo[vcodec=avc1.123456]'})
228 ydl.process_ie_result(info_dict.copy())
229 downloaded = ydl.downloaded_info_dicts[0]
230 self.assertEqual(downloaded['format_id'], 'vid-vcodec-dot')
231
2cc779f4
S
232 def test_format_selection_string_ops(self):
233 formats = [
234 {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL},
e118a879 235 {'format_id': 'zxc-cxz', 'ext': 'webm', 'url': TEST_URL},
2cc779f4
S
236 ]
237 info_dict = _make_result(formats)
238
239 # equals (=)
240 ydl = YDL({'format': '[format_id=abc-cba]'})
241 ydl.process_ie_result(info_dict.copy())
242 downloaded = ydl.downloaded_info_dicts[0]
243 self.assertEqual(downloaded['format_id'], 'abc-cba')
244
245 # does not equal (!=)
246 ydl = YDL({'format': '[format_id!=abc-cba]'})
e118a879
S
247 ydl.process_ie_result(info_dict.copy())
248 downloaded = ydl.downloaded_info_dicts[0]
249 self.assertEqual(downloaded['format_id'], 'zxc-cxz')
250
251 ydl = YDL({'format': '[format_id!=abc-cba][format_id!=zxc-cxz]'})
2cc779f4
S
252 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
253
254 # starts with (^=)
255 ydl = YDL({'format': '[format_id^=abc]'})
256 ydl.process_ie_result(info_dict.copy())
257 downloaded = ydl.downloaded_info_dicts[0]
258 self.assertEqual(downloaded['format_id'], 'abc-cba')
259
260 # does not start with (!^=)
e118a879
S
261 ydl = YDL({'format': '[format_id!^=abc]'})
262 ydl.process_ie_result(info_dict.copy())
263 downloaded = ydl.downloaded_info_dicts[0]
264 self.assertEqual(downloaded['format_id'], 'zxc-cxz')
265
266 ydl = YDL({'format': '[format_id!^=abc][format_id!^=zxc]'})
2cc779f4
S
267 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
268
269 # ends with ($=)
270 ydl = YDL({'format': '[format_id$=cba]'})
271 ydl.process_ie_result(info_dict.copy())
272 downloaded = ydl.downloaded_info_dicts[0]
273 self.assertEqual(downloaded['format_id'], 'abc-cba')
274
275 # does not end with (!$=)
e118a879
S
276 ydl = YDL({'format': '[format_id!$=cba]'})
277 ydl.process_ie_result(info_dict.copy())
278 downloaded = ydl.downloaded_info_dicts[0]
279 self.assertEqual(downloaded['format_id'], 'zxc-cxz')
280
281 ydl = YDL({'format': '[format_id!$=cba][format_id!$=cxz]'})
2cc779f4
S
282 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
283
284 # contains (*=)
e118a879 285 ydl = YDL({'format': '[format_id*=bc-cb]'})
2cc779f4
S
286 ydl.process_ie_result(info_dict.copy())
287 downloaded = ydl.downloaded_info_dicts[0]
288 self.assertEqual(downloaded['format_id'], 'abc-cba')
289
290 # does not contain (!*=)
e118a879
S
291 ydl = YDL({'format': '[format_id!*=bc-cb]'})
292 ydl.process_ie_result(info_dict.copy())
293 downloaded = ydl.downloaded_info_dicts[0]
294 self.assertEqual(downloaded['format_id'], 'zxc-cxz')
295
296 ydl = YDL({'format': '[format_id!*=abc][format_id!*=zxc]'})
297 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
298
2cc779f4
S
299 ydl = YDL({'format': '[format_id!*=-]'})
300 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
301
3d4a70b8 302 def test_youtube_format_selection(self):
a7191c6f 303 # FIXME: Rewrite in accordance with the new format sorting options
5d0c5371 304 return
5d0c5371 305
3d4a70b8 306 order = [
86bf2905 307 '38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '17', '36', '13',
3d4a70b8
PH
308 # Apple HTTP Live Streaming
309 '96', '95', '94', '93', '92', '132', '151',
310 # 3D
311 '85', '84', '102', '83', '101', '82', '100',
312 # Dash video
c11125f9 313 '137', '248', '136', '247', '135', '246',
3d4a70b8
PH
314 '245', '244', '134', '243', '133', '242', '160',
315 # Dash audio
a053c349 316 '141', '172', '140', '171', '139',
3d4a70b8
PH
317 ]
318
67134eab
JMF
319 def format_info(f_id):
320 info = YoutubeIE._formats[f_id].copy()
1df41411 321
91cb6b50 322 # XXX: In real cases InfoExtractor._parse_mpd_formats() fills up 'acodec'
1df41411
YCH
323 # and 'vcodec', while in tests such information is incomplete since
324 # commit a6c2c24479e5f4827ceb06f64d855329c0a6f593
325 # test_YoutubeDL.test_youtube_format_selection is broken without
326 # this fix
327 if 'acodec' in info and 'vcodec' not in info:
328 info['vcodec'] = 'none'
329 elif 'vcodec' in info and 'acodec' not in info:
330 info['acodec'] = 'none'
331
67134eab
JMF
332 info['format_id'] = f_id
333 info['url'] = 'url:' + f_id
334 return info
335 formats_order = [format_info(f_id) for f_id in order]
336
337 info_dict = _make_result(list(formats_order), extractor='youtube')
338 ydl = YDL({'format': 'bestvideo+bestaudio'})
339 yie = YoutubeIE(ydl)
340 yie._sort_formats(info_dict['formats'])
341 ydl.process_ie_result(info_dict)
342 downloaded = ydl.downloaded_info_dicts[0]
5d0c5371 343 self.assertEqual(downloaded['format_id'], '248+172')
67134eab 344 self.assertEqual(downloaded['ext'], 'mp4')
3d4a70b8 345
cf2ac6df
JMF
346 info_dict = _make_result(list(formats_order), extractor='youtube')
347 ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'})
348 yie = YoutubeIE(ydl)
349 yie._sort_formats(info_dict['formats'])
350 ydl.process_ie_result(info_dict)
351 downloaded = ydl.downloaded_info_dicts[0]
352 self.assertEqual(downloaded['format_id'], '38')
353
f5f4a27a
JMF
354 info_dict = _make_result(list(formats_order), extractor='youtube')
355 ydl = YDL({'format': 'bestvideo/best,bestaudio'})
356 yie = YoutubeIE(ydl)
357 yie._sort_formats(info_dict['formats'])
358 ydl.process_ie_result(info_dict)
359 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
360 self.assertEqual(downloaded_ids, ['137', '141'])
361
0130afb7
JMF
362 info_dict = _make_result(list(formats_order), extractor='youtube')
363 ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
364 yie = YoutubeIE(ydl)
365 yie._sort_formats(info_dict['formats'])
366 ydl.process_ie_result(info_dict)
367 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
368 self.assertEqual(downloaded_ids, ['137+141', '248+141'])
369
370 info_dict = _make_result(list(formats_order), extractor='youtube')
371 ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])[height<=720]+bestaudio'})
372 yie = YoutubeIE(ydl)
373 yie._sort_formats(info_dict['formats'])
374 ydl.process_ie_result(info_dict)
375 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
376 self.assertEqual(downloaded_ids, ['136+141', '247+141'])
377
378 info_dict = _make_result(list(formats_order), extractor='youtube')
379 ydl = YDL({'format': '(bestvideo[ext=none]/bestvideo[ext=webm])+bestaudio'})
380 yie = YoutubeIE(ydl)
381 yie._sort_formats(info_dict['formats'])
382 ydl.process_ie_result(info_dict)
383 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
384 self.assertEqual(downloaded_ids, ['248+141'])
385
67134eab 386 for f1, f2 in zip(formats_order, formats_order[1:]):
3537b93d 387 info_dict = _make_result([f1, f2], extractor='youtube')
8dd54188 388 ydl = YDL({'format': 'best/bestvideo'})
3d4a70b8
PH
389 yie = YoutubeIE(ydl)
390 yie._sort_formats(info_dict['formats'])
391 ydl.process_ie_result(info_dict)
392 downloaded = ydl.downloaded_info_dicts[0]
67134eab 393 self.assertEqual(downloaded['format_id'], f1['format_id'])
3d4a70b8 394
3537b93d 395 info_dict = _make_result([f2, f1], extractor='youtube')
8dd54188 396 ydl = YDL({'format': 'best/bestvideo'})
3d4a70b8
PH
397 yie = YoutubeIE(ydl)
398 yie._sort_formats(info_dict['formats'])
399 ydl.process_ie_result(info_dict)
400 downloaded = ydl.downloaded_info_dicts[0]
67134eab 401 self.assertEqual(downloaded['format_id'], f1['format_id'])
3d4a70b8 402
317f7ab6
S
403 def test_audio_only_extractor_format_selection(self):
404 # For extractors with incomplete formats (all formats are audio-only or
405 # video-only) best and worst should fallback to corresponding best/worst
406 # video-only or audio-only formats (as per
067aa17e 407 # https://github.com/ytdl-org/youtube-dl/pull/5556)
317f7ab6
S
408 formats = [
409 {'format_id': 'low', 'ext': 'mp3', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
410 {'format_id': 'high', 'ext': 'mp3', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
411 ]
412 info_dict = _make_result(formats)
413
414 ydl = YDL({'format': 'best'})
415 ydl.process_ie_result(info_dict.copy())
416 downloaded = ydl.downloaded_info_dicts[0]
417 self.assertEqual(downloaded['format_id'], 'high')
418
419 ydl = YDL({'format': 'worst'})
420 ydl.process_ie_result(info_dict.copy())
421 downloaded = ydl.downloaded_info_dicts[0]
422 self.assertEqual(downloaded['format_id'], 'low')
423
424 def test_format_not_available(self):
425 formats = [
426 {'format_id': 'regular', 'ext': 'mp4', 'height': 360, 'url': TEST_URL},
427 {'format_id': 'video', 'ext': 'mp4', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
428 ]
429 info_dict = _make_result(formats)
430
431 # This must fail since complete video-audio format does not match filter
432 # and extractor does not provide incomplete only formats (i.e. only
433 # video-only or audio-only).
434 ydl = YDL({'format': 'best[height>360]'})
435 self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
436
8cda78ef 437 def test_format_selection_issue_10083(self):
067aa17e 438 # See https://github.com/ytdl-org/youtube-dl/issues/10083
8cda78ef
S
439 formats = [
440 {'format_id': 'regular', 'height': 360, 'url': TEST_URL},
441 {'format_id': 'video', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
442 {'format_id': 'audio', 'vcodec': 'none', 'url': TEST_URL},
443 ]
444 info_dict = _make_result(formats)
445
446 ydl = YDL({'format': 'best[height>360]/bestvideo[height>360]+bestaudio'})
447 ydl.process_ie_result(info_dict.copy())
448 self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'video+audio')
449
0a31a350
JMF
450 def test_invalid_format_specs(self):
451 def assert_syntax_error(format_spec):
187986a8 452 self.assertRaises(SyntaxError, YDL, {'format': format_spec})
0a31a350
JMF
453
454 assert_syntax_error('bestvideo,,best')
455 assert_syntax_error('+bestaudio')
456 assert_syntax_error('bestvideo+')
d96d604e 457 assert_syntax_error('/')
187986a8 458 assert_syntax_error('[720<height]')
0a31a350 459
083c9df9
PH
460 def test_format_filtering(self):
461 formats = [
462 {'format_id': 'A', 'filesize': 500, 'width': 1000},
463 {'format_id': 'B', 'filesize': 1000, 'width': 500},
464 {'format_id': 'C', 'filesize': 1000, 'width': 400},
465 {'format_id': 'D', 'filesize': 2000, 'width': 600},
466 {'format_id': 'E', 'filesize': 3000},
467 {'format_id': 'F'},
468 {'format_id': 'G', 'filesize': 1000000},
469 ]
470 for f in formats:
471 f['url'] = 'http://_/'
472 f['ext'] = 'unknown'
473 info_dict = _make_result(formats)
474
475 ydl = YDL({'format': 'best[filesize<3000]'})
476 ydl.process_ie_result(info_dict)
477 downloaded = ydl.downloaded_info_dicts[0]
478 self.assertEqual(downloaded['format_id'], 'D')
479
480 ydl = YDL({'format': 'best[filesize<=3000]'})
481 ydl.process_ie_result(info_dict)
482 downloaded = ydl.downloaded_info_dicts[0]
483 self.assertEqual(downloaded['format_id'], 'E')
484
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'], 'F')
489
490 ydl = YDL({'format': 'best [filesize = 1000] [width>450]'})
491 ydl.process_ie_result(info_dict)
492 downloaded = ydl.downloaded_info_dicts[0]
493 self.assertEqual(downloaded['format_id'], 'B')
494
495 ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
496 ydl.process_ie_result(info_dict)
497 downloaded = ydl.downloaded_info_dicts[0]
498 self.assertEqual(downloaded['format_id'], 'C')
499
500 ydl = YDL({'format': '[filesize>?1]'})
501 ydl.process_ie_result(info_dict)
502 downloaded = ydl.downloaded_info_dicts[0]
503 self.assertEqual(downloaded['format_id'], 'G')
504
505 ydl = YDL({'format': '[filesize<1M]'})
506 ydl.process_ie_result(info_dict)
507 downloaded = ydl.downloaded_info_dicts[0]
508 self.assertEqual(downloaded['format_id'], 'E')
509
510 ydl = YDL({'format': '[filesize<1MiB]'})
511 ydl.process_ie_result(info_dict)
512 downloaded = ydl.downloaded_info_dicts[0]
513 self.assertEqual(downloaded['format_id'], 'G')
514
5acfa126
JMF
515 ydl = YDL({'format': 'all[width>=400][width<=600]'})
516 ydl.process_ie_result(info_dict)
517 downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
dd2a987d 518 self.assertEqual(downloaded_ids, ['D', 'C', 'B'])
5acfa126 519
bb8e5536
JMF
520 ydl = YDL({'format': 'best[height<40]'})
521 try:
522 ydl.process_ie_result(info_dict)
523 except ExtractorError:
524 pass
525 self.assertEqual(ydl.downloaded_info_dicts, [])
526
0017d9ad
S
527 def test_default_format_spec(self):
528 ydl = YDL({'simulate': True})
5d0c5371 529 self.assertEqual(ydl._default_format_spec({}), 'bestvideo*+bestaudio/best')
0017d9ad 530
d08dcd2d
S
531 ydl = YDL({})
532 self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
af0f7428 533
d08dcd2d 534 ydl = YDL({'simulate': True})
5d0c5371 535 self.assertEqual(ydl._default_format_spec({'is_live': True}), 'bestvideo*+bestaudio/best')
af0f7428 536
0017d9ad 537 ydl = YDL({'outtmpl': '-'})
af0f7428 538 self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
0017d9ad
S
539
540 ydl = YDL({})
5d0c5371 541 self.assertEqual(ydl._default_format_spec({}, download=False), 'bestvideo*+bestaudio/best')
af0f7428 542 self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
0017d9ad 543
f20bf146
JMF
544
545class TestYoutubeDL(unittest.TestCase):
ab84349b
JMF
546 def test_subtitles(self):
547 def s_formats(lang, autocaption=False):
548 return [{
549 'ext': ext,
86e5f3ed 550 'url': f'http://localhost/video.{lang}.{ext}',
ab84349b
JMF
551 '_auto': autocaption,
552 } for ext in ['vtt', 'srt', 'ass']]
86e5f3ed 553 subtitles = {l: s_formats(l) for l in ['en', 'fr', 'es']}
554 auto_captions = {l: s_formats(l, True) for l in ['it', 'pt', 'es']}
ab84349b
JMF
555 info_dict = {
556 'id': 'test',
557 'title': 'Test',
558 'url': 'http://localhost/video.mp4',
559 'subtitles': subtitles,
560 'automatic_captions': auto_captions,
561 'extractor': 'TEST',
732044af 562 'webpage_url': 'http://example.com/watch?v=shenanigans',
ab84349b
JMF
563 }
564
565 def get_info(params={}):
566 params.setdefault('simulate', True)
567 ydl = YDL(params)
568 ydl.report_warning = lambda *args, **kargs: None
569 return ydl.process_video_result(info_dict, download=False)
570
571 result = get_info()
572 self.assertFalse(result.get('requested_subtitles'))
573 self.assertEqual(result['subtitles'], subtitles)
574 self.assertEqual(result['automatic_captions'], auto_captions)
575
576 result = get_info({'writesubtitles': True})
577 subs = result['requested_subtitles']
578 self.assertTrue(subs)
86e5f3ed 579 self.assertEqual(set(subs.keys()), {'en'})
ab84349b
JMF
580 self.assertTrue(subs['en'].get('data') is None)
581 self.assertEqual(subs['en']['ext'], 'ass')
582
583 result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
584 subs = result['requested_subtitles']
585 self.assertEqual(subs['en']['ext'], 'srt')
586
587 result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
588 subs = result['requested_subtitles']
589 self.assertTrue(subs)
86e5f3ed 590 self.assertEqual(set(subs.keys()), {'es', 'fr'})
ab84349b 591
c32b0aab 592 result = get_info({'writesubtitles': True, 'subtitleslangs': ['all', '-en']})
593 subs = result['requested_subtitles']
594 self.assertTrue(subs)
86e5f3ed 595 self.assertEqual(set(subs.keys()), {'es', 'fr'})
c32b0aab 596
597 result = get_info({'writesubtitles': True, 'subtitleslangs': ['en', 'fr', '-en']})
598 subs = result['requested_subtitles']
599 self.assertTrue(subs)
86e5f3ed 600 self.assertEqual(set(subs.keys()), {'fr'})
c32b0aab 601
602 result = get_info({'writesubtitles': True, 'subtitleslangs': ['-en', 'en']})
603 subs = result['requested_subtitles']
604 self.assertTrue(subs)
86e5f3ed 605 self.assertEqual(set(subs.keys()), {'en'})
c32b0aab 606
607 result = get_info({'writesubtitles': True, 'subtitleslangs': ['e.+']})
608 subs = result['requested_subtitles']
609 self.assertTrue(subs)
86e5f3ed 610 self.assertEqual(set(subs.keys()), {'es', 'en'})
c32b0aab 611
ab84349b
JMF
612 result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
613 subs = result['requested_subtitles']
614 self.assertTrue(subs)
86e5f3ed 615 self.assertEqual(set(subs.keys()), {'es', 'pt'})
ab84349b
JMF
616 self.assertFalse(subs['es']['_auto'])
617 self.assertTrue(subs['pt']['_auto'])
618
98c70d6f
JMF
619 result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
620 subs = result['requested_subtitles']
621 self.assertTrue(subs)
86e5f3ed 622 self.assertEqual(set(subs.keys()), {'es', 'pt'})
98c70d6f
JMF
623 self.assertTrue(subs['es']['_auto'])
624 self.assertTrue(subs['pt']['_auto'])
625
b6c45014
JMF
626 def test_add_extra_info(self):
627 test_dict = {
628 'extractor': 'Foo',
629 }
630 extra_info = {
631 'extractor': 'Bar',
632 'playlist': 'funny videos',
633 }
634 YDL.add_extra_info(test_dict, extra_info)
635 self.assertEqual(test_dict['extractor'], 'Foo')
636 self.assertEqual(test_dict['playlist'], 'funny videos')
637
752cda38 638 outtmpl_info = {
639 'id': '1234',
640 'ext': 'mp4',
641 'width': None,
642 'height': 1080,
abbeeebc 643 'filesize': 1024,
752cda38 644 'title1': '$PATH',
645 'title2': '%PATH%',
87ea7dfc 646 'title3': 'foo/bar\\test',
7d1eb38a 647 'title4': 'foo "bar" test',
524e2e4f 648 'title5': 'áéí 𝐀',
752cda38 649 'timestamp': 1618488000,
650 'duration': 100000,
651 'playlist_index': 1,
e6f21b3d 652 'playlist_autonumber': 2,
752cda38 653 '_last_playlist_index': 100,
654 'n_entries': 10,
4476d2c7 655 'formats': [{'id': 'id 1'}, {'id': 'id 2'}, {'id': 'id 3'}]
752cda38 656 }
657
5c6542ce 658 def test_prepare_outtmpl_and_filename(self):
9fea350f 659 def test(tmpl, expected, *, info=None, **params):
752cda38 660 params['outtmpl'] = tmpl
661 ydl = YoutubeDL(params)
662 ydl._num_downloads = 1
5c6542ce 663 self.assertEqual(ydl.validate_outtmpl(tmpl), None)
752cda38 664
819e0531 665 out = ydl.evaluate_outtmpl(tmpl, info or self.outtmpl_info)
9fea350f 666 fname = ydl.prepare_filename(info or self.outtmpl_info)
5c6542ce 667
2b8a2973 668 if not isinstance(expected, (list, tuple)):
669 expected = (expected, expected)
670 for (name, got), expect in zip((('outtmpl', out), ('filename', fname)), expected):
671 if callable(expect):
672 self.assertTrue(expect(got), f'Wrong {name} from {tmpl}')
673 else:
674 self.assertEqual(got, expect, f'Wrong {name} from {tmpl}')
5c6542ce 675
6e84b215 676 # Side-effects
677 original_infodict = dict(self.outtmpl_info)
678 test('foo.bar', 'foo.bar')
679 original_infodict['epoch'] = self.outtmpl_info.get('epoch')
680 self.assertTrue(isinstance(original_infodict['epoch'], int))
681 test('%(epoch)d', int_or_none)
682 self.assertEqual(original_infodict, self.outtmpl_info)
683
5c6542ce 684 # Auto-generated fields
685 test('%(id)s.%(ext)s', '1234.mp4')
686 test('%(duration_string)s', ('27:46:40', '27-46-40'))
5c6542ce 687 test('%(resolution)s', '1080p')
688 test('%(playlist_index)s', '001')
e6f21b3d 689 test('%(playlist_autonumber)s', '02')
5c6542ce 690 test('%(autonumber)s', '00001')
691 test('%(autonumber+2)03d', '005', autonumber_start=3)
692 test('%(autonumber)s', '001', autonumber_size=3)
693
694 # Escaping %
901130bb 695 test('%', '%')
5c6542ce 696 test('%%', '%')
697 test('%%%%', '%%')
901130bb 698 test('%s', '%s')
699 test('%%%s', '%%s')
700 test('%d', '%d')
701 test('%abc%', '%abc%')
5c6542ce 702 test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
901130bb 703 test('%%%(height)s', '%1080')
5c6542ce 704 test('%(width)06d.%(ext)s', 'NA.mp4')
705 test('%(width)06d.%%(ext)s', 'NA.%(ext)s')
706 test('%%(width)06d.%(ext)s', '%(width)06d.mp4')
707
9fea350f 708 # ID sanitization
709 test('%(id)s', '_abcd', info={'id': '_abcd'})
710 test('%(some_id)s', '_abcd', info={'some_id': '_abcd'})
711 test('%(formats.0.id)s', '_abcd', info={'formats': [{'id': '_abcd'}]})
712 test('%(id)s', '-abcd', info={'id': '-abcd'})
713 test('%(id)s', '.abcd', info={'id': '.abcd'})
714 test('%(id)s', 'ab__cd', info={'id': 'ab__cd'})
715 test('%(id)s', ('ab:cd', 'ab -cd'), info={'id': 'ab:cd'})
e0fd9573 716 test('%(id.0)s', '-', info={'id': '--'})
9fea350f 717
5c6542ce 718 # Invalid templates
5c6542ce 719 self.assertTrue(isinstance(YoutubeDL.validate_outtmpl('%(title)'), ValueError))
720 test('%(invalid@tmpl|def)s', 'none', outtmpl_na_placeholder='none')
2b8a2973 721 test('%(..)s', 'NA')
722
723 # Entire info_dict
724 def expect_same_infodict(out):
725 got_dict = json.loads(out)
726 for info_field, expected in self.outtmpl_info.items():
727 self.assertEqual(got_dict.get(info_field), expected, info_field)
728 return True
729
730 test('%()j', (expect_same_infodict, str))
5c6542ce 731
732 # NA placeholder
752cda38 733 NA_TEST_OUTTMPL = '%(uploader_date)s-%(width)d-%(x|def)s-%(id)s.%(ext)s'
5c6542ce 734 test(NA_TEST_OUTTMPL, 'NA-NA-def-1234.mp4')
735 test(NA_TEST_OUTTMPL, 'none-none-def-1234.mp4', outtmpl_na_placeholder='none')
736 test(NA_TEST_OUTTMPL, '--def-1234.mp4', outtmpl_na_placeholder='')
582fad70 737 test('%(non_existent.0)s', 'NA')
752cda38 738
5c6542ce 739 # String formatting
752cda38 740 FMT_TEST_OUTTMPL = '%%(height)%s.%%(ext)s'
5c6542ce 741 test(FMT_TEST_OUTTMPL % 's', '1080.mp4')
742 test(FMT_TEST_OUTTMPL % 'd', '1080.mp4')
743 test(FMT_TEST_OUTTMPL % '6d', ' 1080.mp4')
744 test(FMT_TEST_OUTTMPL % '-6d', '1080 .mp4')
745 test(FMT_TEST_OUTTMPL % '06d', '001080.mp4')
746 test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
747 test(FMT_TEST_OUTTMPL % ' 06d', ' 01080.mp4')
748 test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
749 test(FMT_TEST_OUTTMPL % '0 6d', ' 01080.mp4')
750 test(FMT_TEST_OUTTMPL % ' 0 6d', ' 01080.mp4')
751
752 # Type casting
753 test('%(id)d', '1234')
754 test('%(height)c', '1')
755 test('%(ext)c', 'm')
756 test('%(id)d %(id)r', "1234 '1234'")
757 test('%(id)r %(height)r', "'1234' 1080")
758 test('%(ext)s-%(ext|def)d', 'mp4-def')
759 test('%(width|0)04d', '0000')
760 test('a%(width|)d', 'a', outtmpl_na_placeholder='none')
761
752cda38 762 FORMATS = self.outtmpl_info['formats']
4476d2c7 763 sanitize = lambda x: x.replace(':', ' -').replace('"', "'").replace('\n', ' ')
7d1eb38a 764
765 # Custom type casting
4476d2c7 766 test('%(formats.:.id)l', 'id 1, id 2, id 3')
767 test('%(formats.:.id)#l', ('id 1\nid 2\nid 3', 'id 1 id 2 id 3'))
7d1eb38a 768 test('%(ext)l', 'mp4')
4476d2c7 769 test('%(formats.:.id) 18l', ' id 1, id 2, id 3')
7d1eb38a 770 test('%(formats)j', (json.dumps(FORMATS), sanitize(json.dumps(FORMATS))))
4476d2c7 771 test('%(formats)#j', (json.dumps(FORMATS, indent=4), sanitize(json.dumps(FORMATS, indent=4))))
f5aa5cfb 772 test('%(title5).3B', 'á')
524e2e4f 773 test('%(title5)U', 'áéí 𝐀')
774 test('%(title5)#U', 'a\u0301e\u0301i\u0301 𝐀')
775 test('%(title5)+U', 'áéí A')
776 test('%(title5)+#U', 'a\u0301e\u0301i\u0301 A')
abbeeebc 777 test('%(height)D', '1k')
778 test('%(filesize)#D', '1Ki')
779 test('%(height)5.2D', ' 1.08k')
37893bb0 780 test('%(title4)#S', 'foo_bar_test')
781 test('%(title4).10S', ('foo \'bar\' ', 'foo \'bar\'' + ('#' if compat_os_name == 'nt' else ' ')))
7d1eb38a 782 if compat_os_name == 'nt':
783 test('%(title4)q', ('"foo \\"bar\\" test"', "'foo _'bar_' test'"))
4476d2c7 784 test('%(formats.:.id)#q', ('"id 1" "id 2" "id 3"', "'id 1' 'id 2' 'id 3'"))
785 test('%(formats.0.id)#q', ('"id 1"', "'id 1'"))
7d1eb38a 786 else:
787 test('%(title4)q', ('\'foo "bar" test\'', "'foo 'bar' test'"))
4476d2c7 788 test('%(formats.:.id)#q', "'id 1' 'id 2' 'id 3'")
789 test('%(formats.0.id)#q', "'id 1'")
7d1eb38a 790
791 # Internal formatting
5c6542ce 792 test('%(timestamp-1000>%H-%M-%S)s', '11-43-20')
901130bb 793 test('%(title|%)s %(title|%%)s', '% %%')
5c6542ce 794 test('%(id+1-height+3)05d', '00158')
795 test('%(width+100)05d', 'NA')
7d1eb38a 796 test('%(formats.0) 15s', ('% 15s' % FORMATS[0], '% 15s' % sanitize(str(FORMATS[0]))))
797 test('%(formats.0)r', (repr(FORMATS[0]), sanitize(repr(FORMATS[0]))))
5c6542ce 798 test('%(height.0)03d', '001')
799 test('%(-height.0)04d', '-001')
800 test('%(formats.-1.id)s', FORMATS[-1]['id'])
801 test('%(formats.0.id.-1)d', FORMATS[0]['id'][-1])
802 test('%(formats.3)s', 'NA')
803 test('%(formats.:2:-1)r', repr(FORMATS[:2:-1]))
804 test('%(formats.0.id.-1+id)f', '1235.000000')
385a27fa 805 test('%(formats.0.id.-1+formats.1.id.-1)d', '3')
5c6542ce 806
7c37ff97 807 # Alternates
808 test('%(title,id)s', '1234')
809 test('%(width-100,height+20|def)d', '1100')
810 test('%(width-100,height+width|def)s', 'def')
811 test('%(timestamp-x>%H\\,%M\\,%S,timestamp>%H\\,%M\\,%S)s', '12,00,00')
812
e0fd9573 813 # Replacement
814 test('%(id&foo)s.bar', 'foo.bar')
815 test('%(title&foo)s.bar', 'NA.bar')
816 test('%(title&foo|baz)s.bar', 'baz.bar')
34baa9fd 817 test('%(x,id&foo|baz)s.bar', 'foo.bar')
818 test('%(x,title&foo|baz)s.bar', 'baz.bar')
e0fd9573 819
6e84b215 820 # Laziness
821 def gen():
822 yield from range(5)
823 raise self.assertTrue(False, 'LazyList should not be evaluated till here')
824 test('%(key.4)s', '4', info={'key': LazyList(gen())})
825
5c6542ce 826 # Empty filename
827 test('%(foo|)s-%(bar|)s.%(ext)s', '-.mp4')
828 # test('%(foo|)s.%(ext)s', ('.mp4', '_.mp4')) # fixme
829 # test('%(foo|)s', ('', '_')) # fixme
830
901130bb 831 # Environment variable expansion for prepare_filename
832 compat_setenv('__yt_dlp_var', 'expanded')
833 envvar = '%__yt_dlp_var%' if compat_os_name == 'nt' else '$__yt_dlp_var'
834 test(envvar, (envvar, 'expanded'))
b836dc94 835 if compat_os_name == 'nt':
836 test('%s%', ('%s%', '%s%'))
837 compat_setenv('s', 'expanded')
838 test('%s%', ('%s%', 'expanded')) # %s% should be expanded before escaping %s
839 compat_setenv('(test)s', 'expanded')
840 test('%(test)s%', ('NA%', 'expanded')) # Environment should take priority over template
901130bb 841
5c6542ce 842 # Path expansion and escaping
843 test('Hello %(title1)s', 'Hello $PATH')
844 test('Hello %(title2)s', 'Hello %PATH%')
845 test('%(title3)s', ('foo/bar\\test', 'foo_bar_test'))
846 test('folder/%(title3)s', ('folder/foo/bar\\test', 'folder%sfoo_bar_test' % os.path.sep))
26e63931 847
c57f7757
PH
848 def test_format_note(self):
849 ydl = YoutubeDL()
850 self.assertEqual(ydl._format_note({}), '')
851 assertRegexpMatches(self, ydl._format_note({
852 'vbr': 10,
398dea32 853 }), r'^\s*10k$')
5d583bdf
S
854 assertRegexpMatches(self, ydl._format_note({
855 'fps': 30,
398dea32 856 }), r'^30fps$')
5d583bdf 857
2b4ecde2
JMF
858 def test_postprocessors(self):
859 filename = 'post-processor-testfile.mp4'
860 audiofile = filename + '.mp3'
861
862 class SimplePP(PostProcessor):
863 def run(self, info):
2b4ecde2
JMF
864 with open(audiofile, 'wt') as f:
865 f.write('EXAMPLE')
592e97e8 866 return [info['filepath']], info
2b4ecde2 867
592e97e8 868 def run_pp(params, PP):
2b4ecde2
JMF
869 with open(filename, 'wt') as f:
870 f.write('EXAMPLE')
871 ydl = YoutubeDL(params)
592e97e8 872 ydl.add_post_processor(PP())
2b4ecde2
JMF
873 ydl.post_process(filename, {'filepath': filename})
874
592e97e8 875 run_pp({'keepvideo': True}, SimplePP)
2b4ecde2
JMF
876 self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
877 self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
878 os.unlink(filename)
879 os.unlink(audiofile)
880
592e97e8 881 run_pp({'keepvideo': False}, SimplePP)
2b4ecde2
JMF
882 self.assertFalse(os.path.exists(filename), '%s exists' % filename)
883 self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
884 os.unlink(audiofile)
885
592e97e8
JMF
886 class ModifierPP(PostProcessor):
887 def run(self, info):
888 with open(info['filepath'], 'wt') as f:
889 f.write('MODIFIED')
890 return [], info
891
892 run_pp({'keepvideo': False}, ModifierPP)
893 self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
894 os.unlink(filename)
895
531980d8 896 def test_match_filter(self):
531980d8
JMF
897 first = {
898 'id': '1',
899 'url': TEST_URL,
900 'title': 'one',
901 'extractor': 'TEST',
902 'duration': 30,
903 'filesize': 10 * 1024,
e5a088dc 904 'playlist_id': '42',
db13c16e
S
905 'uploader': "變態妍字幕版 太妍 тест",
906 'creator': "тест ' 123 ' тест--",
732044af 907 'webpage_url': 'http://example.com/watch?v=shenanigans',
531980d8
JMF
908 }
909 second = {
910 'id': '2',
911 'url': TEST_URL,
912 'title': 'two',
913 'extractor': 'TEST',
914 'duration': 10,
915 'description': 'foo',
916 'filesize': 5 * 1024,
e5a088dc 917 'playlist_id': '43',
db13c16e 918 'uploader': "тест 123",
732044af 919 'webpage_url': 'http://example.com/watch?v=SHENANIGANS',
531980d8
JMF
920 }
921 videos = [first, second]
922
923 def get_videos(filter_=None):
09b49e1f 924 ydl = YDL({'match_filter': filter_, 'simulate': True})
531980d8
JMF
925 for v in videos:
926 ydl.process_ie_result(v, download=True)
927 return [v['id'] for v in ydl.downloaded_info_dicts]
928
929 res = get_videos()
930 self.assertEqual(res, ['1', '2'])
931
6db9c4d5 932 def f(v, incomplete):
531980d8
JMF
933 if v['id'] == '1':
934 return None
935 else:
936 return 'Video id is not 1'
937 res = get_videos(f)
938 self.assertEqual(res, ['1'])
939
940 f = match_filter_func('duration < 30')
941 res = get_videos(f)
942 self.assertEqual(res, ['2'])
943
944 f = match_filter_func('description = foo')
945 res = get_videos(f)
946 self.assertEqual(res, ['2'])
947
948 f = match_filter_func('description =? foo')
949 res = get_videos(f)
950 self.assertEqual(res, ['1', '2'])
951
952 f = match_filter_func('filesize > 5KiB')
953 res = get_videos(f)
954 self.assertEqual(res, ['1'])
955
e5a088dc
S
956 f = match_filter_func('playlist_id = 42')
957 res = get_videos(f)
958 self.assertEqual(res, ['1'])
959
db13c16e
S
960 f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
961 res = get_videos(f)
962 self.assertEqual(res, ['1'])
963
964 f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
965 res = get_videos(f)
966 self.assertEqual(res, ['2'])
967
968 f = match_filter_func('creator = "тест \' 123 \' тест--"')
969 res = get_videos(f)
970 self.assertEqual(res, ['1'])
971
972 f = match_filter_func("creator = 'тест \\' 123 \\' тест--'")
973 res = get_videos(f)
974 self.assertEqual(res, ['1'])
975
976 f = match_filter_func(r"creator = 'тест \' 123 \' тест--' & duration > 30")
977 res = get_videos(f)
978 self.assertEqual(res, [])
979
e9eaf3fb
JMF
980 def test_playlist_items_selection(self):
981 entries = [{
982 'id': compat_str(i),
983 'title': compat_str(i),
984 'url': TEST_URL,
985 } for i in range(1, 5)]
986 playlist = {
987 '_type': 'playlist',
988 'id': 'test',
989 'entries': entries,
990 'extractor': 'test:playlist',
991 'extractor_key': 'test:playlist',
992 'webpage_url': 'http://example.com',
993 }
994
4e9e1e24 995 def get_downloaded_info_dicts(params):
e9eaf3fb 996 ydl = YDL(params)
e0abaab2
S
997 # make a deep copy because the dictionary and nested entries
998 # can be modified
999 ydl.process_ie_result(copy.deepcopy(playlist))
4e9e1e24
S
1000 return ydl.downloaded_info_dicts
1001
9e598870 1002 def test_selection(params, expected_ids):
1003 results = [
1004 (v['playlist_autonumber'] - 1, (int(v['id']), v['playlist_index']))
1005 for v in get_downloaded_info_dicts(params)]
1006 self.assertEqual(results, list(enumerate(zip(expected_ids, expected_ids))))
1007
1008 test_selection({}, [1, 2, 3, 4])
1009 test_selection({'playlistend': 10}, [1, 2, 3, 4])
1010 test_selection({'playlistend': 2}, [1, 2])
1011 test_selection({'playliststart': 10}, [])
1012 test_selection({'playliststart': 2}, [2, 3, 4])
1013 test_selection({'playlist_items': '2-4'}, [2, 3, 4])
1014 test_selection({'playlist_items': '2,4'}, [2, 4])
1015 test_selection({'playlist_items': '10'}, [])
ff1c7fc9 1016 test_selection({'playlist_items': '0'}, [])
cd6fc19e 1017
4e9e1e24 1018 # Tests for https://github.com/ytdl-org/youtube-dl/issues/10591
9e598870 1019 test_selection({'playlist_items': '2-4,3-4,3'}, [2, 3, 4])
1020 test_selection({'playlist_items': '4,2'}, [4, 2])
1021
1022 # Tests for https://github.com/yt-dlp/yt-dlp/issues/720
1023 # https://github.com/yt-dlp/yt-dlp/issues/302
1024 test_selection({'playlistreverse': True}, [4, 3, 2, 1])
1025 test_selection({'playliststart': 2, 'playlistreverse': True}, [4, 3, 2])
1026 test_selection({'playlist_items': '2,4', 'playlistreverse': True}, [4, 2])
1027 test_selection({'playlist_items': '4,2'}, [4, 2])
4e9e1e24 1028
e37afbe0 1029 def test_urlopen_no_file_protocol(self):
067aa17e 1030 # see https://github.com/ytdl-org/youtube-dl/issues/8227
e37afbe0
JMF
1031 ydl = YDL()
1032 self.assertRaises(compat_urllib_error.URLError, ydl.urlopen, 'file:///etc/passwd')
1033
b286f201
YCH
1034 def test_do_not_override_ie_key_in_url_transparent(self):
1035 ydl = YDL()
1036
1037 class Foo1IE(InfoExtractor):
1038 _VALID_URL = r'foo1:'
1039
1040 def _real_extract(self, url):
1041 return {
1042 '_type': 'url_transparent',
1043 'url': 'foo2:',
1044 'ie_key': 'Foo2',
0396806f
S
1045 'title': 'foo1 title',
1046 'id': 'foo1_id',
b286f201
YCH
1047 }
1048
1049 class Foo2IE(InfoExtractor):
1050 _VALID_URL = r'foo2:'
1051
1052 def _real_extract(self, url):
1053 return {
1054 '_type': 'url',
1055 'url': 'foo3:',
1056 'ie_key': 'Foo3',
1057 }
1058
1059 class Foo3IE(InfoExtractor):
1060 _VALID_URL = r'foo3:'
1061
1062 def _real_extract(self, url):
51350db5 1063 return _make_result([{'url': TEST_URL}], title='foo3 title')
b286f201
YCH
1064
1065 ydl.add_info_extractor(Foo1IE(ydl))
1066 ydl.add_info_extractor(Foo2IE(ydl))
1067 ydl.add_info_extractor(Foo3IE(ydl))
1068 ydl.extract_info('foo1:')
1069 downloaded = ydl.downloaded_info_dicts[0]
1070 self.assertEqual(downloaded['url'], TEST_URL)
51350db5 1071 self.assertEqual(downloaded['title'], 'foo1 title')
0396806f
S
1072 self.assertEqual(downloaded['id'], 'testid')
1073 self.assertEqual(downloaded['extractor'], 'testex')
1074 self.assertEqual(downloaded['extractor_key'], 'TestEx')
b286f201 1075
a0566bbf 1076 # Test case for https://github.com/ytdl-org/youtube-dl/issues/27064
1077 def test_ignoreerrors_for_playlist_with_url_transparent_iterable_entries(self):
1078
1079 class _YDL(YDL):
1080 def __init__(self, *args, **kwargs):
86e5f3ed 1081 super().__init__(*args, **kwargs)
a0566bbf 1082
1083 def trouble(self, s, tb=None):
1084 pass
1085
1086 ydl = _YDL({
1087 'format': 'extra',
1088 'ignoreerrors': True,
1089 })
1090
1091 class VideoIE(InfoExtractor):
1092 _VALID_URL = r'video:(?P<id>\d+)'
1093
1094 def _real_extract(self, url):
1095 video_id = self._match_id(url)
1096 formats = [{
1097 'format_id': 'default',
1098 'url': 'url:',
1099 }]
1100 if video_id == '0':
1101 raise ExtractorError('foo')
1102 if video_id == '2':
1103 formats.append({
1104 'format_id': 'extra',
1105 'url': TEST_URL,
1106 })
1107 return {
1108 'id': video_id,
1109 'title': 'Video %s' % video_id,
1110 'formats': formats,
1111 }
1112
1113 class PlaylistIE(InfoExtractor):
1114 _VALID_URL = r'playlist:'
1115
1116 def _entries(self):
1117 for n in range(3):
1118 video_id = compat_str(n)
1119 yield {
1120 '_type': 'url_transparent',
1121 'ie_key': VideoIE.ie_key(),
1122 'id': video_id,
1123 'url': 'video:%s' % video_id,
1124 'title': 'Video Transparent %s' % video_id,
1125 }
1126
1127 def _real_extract(self, url):
1128 return self.playlist_result(self._entries())
1129
1130 ydl.add_info_extractor(VideoIE(ydl))
1131 ydl.add_info_extractor(PlaylistIE(ydl))
1132 info = ydl.extract_info('playlist:')
1133 entries = info['entries']
1134 self.assertEqual(len(entries), 3)
1135 self.assertTrue(entries[0] is None)
1136 self.assertTrue(entries[1] is None)
1137 self.assertEqual(len(ydl.downloaded_info_dicts), 1)
1138 downloaded = ydl.downloaded_info_dicts[0]
9e907ebd 1139 entries[2].pop('requested_downloads', None)
a0566bbf 1140 self.assertEqual(entries[2], downloaded)
1141 self.assertEqual(downloaded['url'], TEST_URL)
1142 self.assertEqual(downloaded['title'], 'Video Transparent 2')
1143 self.assertEqual(downloaded['id'], '2')
1144 self.assertEqual(downloaded['extractor'], 'Video')
1145 self.assertEqual(downloaded['extractor_key'], 'Video')
1146
2b4ecde2 1147
e028d0d1
JMF
1148if __name__ == '__main__':
1149 unittest.main()