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