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