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