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