[YoutubeDL] Add negation support for string comparisons in format selection expressio...
[youtube-dl] / test / test_YoutubeDL.py
1 #!/usr/bin/env python
2 # coding: utf-8
3
4 from __future__ import unicode_literals
5
6 # Allow direct execution
7 import os
8 import sys
9 import unittest
10 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
12 import copy
13
14 from test.helper import FakeYDL, assertRegexpMatches
15 from youtube_dl import YoutubeDL
16 from youtube_dl.compat import compat_str, compat_urllib_error
17 from youtube_dl.extractor import YoutubeIE
18 from youtube_dl.extractor.common import InfoExtractor
19 from youtube_dl.postprocessor.common import PostProcessor
20 from youtube_dl.utils import ExtractorError, match_filter_func
21
22 TEST_URL = 'http://localhost/sample.mp4'
23
24
25 class YDL(FakeYDL):
26     def __init__(self, *args, **kwargs):
27         super(YDL, self).__init__(*args, **kwargs)
28         self.downloaded_info_dicts = []
29         self.msgs = []
30
31     def process_info(self, info_dict):
32         self.downloaded_info_dicts.append(info_dict)
33
34     def to_screen(self, msg):
35         self.msgs.append(msg)
36
37
38 def _make_result(formats, **kwargs):
39     res = {
40         'formats': formats,
41         'id': 'testid',
42         'title': 'testttitle',
43         'extractor': 'testex',
44         'extractor_key': 'TestEx',
45     }
46     res.update(**kwargs)
47     return res
48
49
50 class TestFormatSelection(unittest.TestCase):
51     def test_prefer_free_formats(self):
52         # Same resolution => download webm
53         ydl = YDL()
54         ydl.params['prefer_free_formats'] = True
55         formats = [
56             {'ext': 'webm', 'height': 460, 'url': TEST_URL},
57             {'ext': 'mp4', 'height': 460, 'url': TEST_URL},
58         ]
59         info_dict = _make_result(formats)
60         yie = YoutubeIE(ydl)
61         yie._sort_formats(info_dict['formats'])
62         ydl.process_ie_result(info_dict)
63         downloaded = ydl.downloaded_info_dicts[0]
64         self.assertEqual(downloaded['ext'], 'webm')
65
66         # Different resolution => download best quality (mp4)
67         ydl = YDL()
68         ydl.params['prefer_free_formats'] = True
69         formats = [
70             {'ext': 'webm', 'height': 720, 'url': TEST_URL},
71             {'ext': 'mp4', 'height': 1080, 'url': TEST_URL},
72         ]
73         info_dict['formats'] = formats
74         yie = YoutubeIE(ydl)
75         yie._sort_formats(info_dict['formats'])
76         ydl.process_ie_result(info_dict)
77         downloaded = ydl.downloaded_info_dicts[0]
78         self.assertEqual(downloaded['ext'], 'mp4')
79
80         # No prefer_free_formats => prefer mp4 and flv for greater compatibility
81         ydl = YDL()
82         ydl.params['prefer_free_formats'] = False
83         formats = [
84             {'ext': 'webm', 'height': 720, 'url': TEST_URL},
85             {'ext': 'mp4', 'height': 720, 'url': TEST_URL},
86             {'ext': 'flv', 'height': 720, 'url': TEST_URL},
87         ]
88         info_dict['formats'] = formats
89         yie = YoutubeIE(ydl)
90         yie._sort_formats(info_dict['formats'])
91         ydl.process_ie_result(info_dict)
92         downloaded = ydl.downloaded_info_dicts[0]
93         self.assertEqual(downloaded['ext'], 'mp4')
94
95         ydl = YDL()
96         ydl.params['prefer_free_formats'] = False
97         formats = [
98             {'ext': 'flv', 'height': 720, 'url': TEST_URL},
99             {'ext': 'webm', 'height': 720, 'url': TEST_URL},
100         ]
101         info_dict['formats'] = formats
102         yie = YoutubeIE(ydl)
103         yie._sort_formats(info_dict['formats'])
104         ydl.process_ie_result(info_dict)
105         downloaded = ydl.downloaded_info_dicts[0]
106         self.assertEqual(downloaded['ext'], 'flv')
107
108     def test_format_selection(self):
109         formats = [
110             {'format_id': '35', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
111             {'format_id': 'example-with-dashes', 'ext': 'webm', 'preference': 1, 'url': TEST_URL},
112             {'format_id': '45', 'ext': 'webm', 'preference': 2, 'url': TEST_URL},
113             {'format_id': '47', 'ext': 'webm', 'preference': 3, 'url': TEST_URL},
114             {'format_id': '2', 'ext': 'flv', 'preference': 4, 'url': TEST_URL},
115         ]
116         info_dict = _make_result(formats)
117
118         ydl = YDL({'format': '20/47'})
119         ydl.process_ie_result(info_dict.copy())
120         downloaded = ydl.downloaded_info_dicts[0]
121         self.assertEqual(downloaded['format_id'], '47')
122
123         ydl = YDL({'format': '20/71/worst'})
124         ydl.process_ie_result(info_dict.copy())
125         downloaded = ydl.downloaded_info_dicts[0]
126         self.assertEqual(downloaded['format_id'], '35')
127
128         ydl = YDL()
129         ydl.process_ie_result(info_dict.copy())
130         downloaded = ydl.downloaded_info_dicts[0]
131         self.assertEqual(downloaded['format_id'], '2')
132
133         ydl = YDL({'format': 'webm/mp4'})
134         ydl.process_ie_result(info_dict.copy())
135         downloaded = ydl.downloaded_info_dicts[0]
136         self.assertEqual(downloaded['format_id'], '47')
137
138         ydl = YDL({'format': '3gp/40/mp4'})
139         ydl.process_ie_result(info_dict.copy())
140         downloaded = ydl.downloaded_info_dicts[0]
141         self.assertEqual(downloaded['format_id'], '35')
142
143         ydl = YDL({'format': 'example-with-dashes'})
144         ydl.process_ie_result(info_dict.copy())
145         downloaded = ydl.downloaded_info_dicts[0]
146         self.assertEqual(downloaded['format_id'], 'example-with-dashes')
147
148     def test_format_selection_audio(self):
149         formats = [
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},
154         ]
155         info_dict = _make_result(formats)
156
157         ydl = YDL({'format': 'bestaudio'})
158         ydl.process_ie_result(info_dict.copy())
159         downloaded = ydl.downloaded_info_dicts[0]
160         self.assertEqual(downloaded['format_id'], 'audio-high')
161
162         ydl = YDL({'format': 'worstaudio'})
163         ydl.process_ie_result(info_dict.copy())
164         downloaded = ydl.downloaded_info_dicts[0]
165         self.assertEqual(downloaded['format_id'], 'audio-low')
166
167         formats = [
168             {'format_id': 'vid-low', 'ext': 'mp4', 'preference': 1, 'url': TEST_URL},
169             {'format_id': 'vid-high', 'ext': 'mp4', 'preference': 2, 'url': TEST_URL},
170         ]
171         info_dict = _make_result(formats)
172
173         ydl = YDL({'format': 'bestaudio/worstaudio/best'})
174         ydl.process_ie_result(info_dict.copy())
175         downloaded = ydl.downloaded_info_dicts[0]
176         self.assertEqual(downloaded['format_id'], 'vid-high')
177
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
209     def test_format_selection_video(self):
210         formats = [
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},
214         ]
215         info_dict = _make_result(formats)
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
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
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
242     def test_format_selection_string_ops(self):
243         formats = [
244             {'format_id': 'abc-cba', 'ext': 'mp4', 'url': TEST_URL},
245         ]
246         info_dict = _make_result(formats)
247
248         # equals (=)
249         ydl = YDL({'format': '[format_id=abc-cba]'})
250         ydl.process_ie_result(info_dict.copy())
251         downloaded = ydl.downloaded_info_dicts[0]
252         self.assertEqual(downloaded['format_id'], 'abc-cba')
253
254         # does not equal (!=)
255         ydl = YDL({'format': '[format_id!=abc-cba]'})
256         self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
257
258         # starts with (^=)
259         ydl = YDL({'format': '[format_id^=abc]'})
260         ydl.process_ie_result(info_dict.copy())
261         downloaded = ydl.downloaded_info_dicts[0]
262         self.assertEqual(downloaded['format_id'], 'abc-cba')
263
264         # does not start with (!^=)
265         ydl = YDL({'format': '[format_id!^=abc-cba]'})
266         self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
267
268         # ends with ($=)
269         ydl = YDL({'format': '[format_id$=cba]'})
270         ydl.process_ie_result(info_dict.copy())
271         downloaded = ydl.downloaded_info_dicts[0]
272         self.assertEqual(downloaded['format_id'], 'abc-cba')
273
274         # does not end with (!$=)
275         ydl = YDL({'format': '[format_id!$=abc-cba]'})
276         self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
277
278         # contains (*=)
279         ydl = YDL({'format': '[format_id*=-]'})
280         ydl.process_ie_result(info_dict.copy())
281         downloaded = ydl.downloaded_info_dicts[0]
282         self.assertEqual(downloaded['format_id'], 'abc-cba')
283
284         # does not contain (!*=)
285         ydl = YDL({'format': '[format_id!*=-]'})
286         self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
287
288     def test_youtube_format_selection(self):
289         order = [
290             '38', '37', '46', '22', '45', '35', '44', '18', '34', '43', '6', '5', '17', '36', '13',
291             # Apple HTTP Live Streaming
292             '96', '95', '94', '93', '92', '132', '151',
293             # 3D
294             '85', '84', '102', '83', '101', '82', '100',
295             # Dash video
296             '137', '248', '136', '247', '135', '246',
297             '245', '244', '134', '243', '133', '242', '160',
298             # Dash audio
299             '141', '172', '140', '171', '139',
300         ]
301
302         def format_info(f_id):
303             info = YoutubeIE._formats[f_id].copy()
304
305             # XXX: In real cases InfoExtractor._parse_mpd_formats() fills up 'acodec'
306             # and 'vcodec', while in tests such information is incomplete since
307             # commit a6c2c24479e5f4827ceb06f64d855329c0a6f593
308             # test_YoutubeDL.test_youtube_format_selection is broken without
309             # this fix
310             if 'acodec' in info and 'vcodec' not in info:
311                 info['vcodec'] = 'none'
312             elif 'vcodec' in info and 'acodec' not in info:
313                 info['acodec'] = 'none'
314
315             info['format_id'] = f_id
316             info['url'] = 'url:' + f_id
317             return info
318         formats_order = [format_info(f_id) for f_id in order]
319
320         info_dict = _make_result(list(formats_order), extractor='youtube')
321         ydl = YDL({'format': 'bestvideo+bestaudio'})
322         yie = YoutubeIE(ydl)
323         yie._sort_formats(info_dict['formats'])
324         ydl.process_ie_result(info_dict)
325         downloaded = ydl.downloaded_info_dicts[0]
326         self.assertEqual(downloaded['format_id'], '137+141')
327         self.assertEqual(downloaded['ext'], 'mp4')
328
329         info_dict = _make_result(list(formats_order), extractor='youtube')
330         ydl = YDL({'format': 'bestvideo[height>=999999]+bestaudio/best'})
331         yie = YoutubeIE(ydl)
332         yie._sort_formats(info_dict['formats'])
333         ydl.process_ie_result(info_dict)
334         downloaded = ydl.downloaded_info_dicts[0]
335         self.assertEqual(downloaded['format_id'], '38')
336
337         info_dict = _make_result(list(formats_order), extractor='youtube')
338         ydl = YDL({'format': 'bestvideo/best,bestaudio'})
339         yie = YoutubeIE(ydl)
340         yie._sort_formats(info_dict['formats'])
341         ydl.process_ie_result(info_dict)
342         downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
343         self.assertEqual(downloaded_ids, ['137', '141'])
344
345         info_dict = _make_result(list(formats_order), extractor='youtube')
346         ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])+bestaudio'})
347         yie = YoutubeIE(ydl)
348         yie._sort_formats(info_dict['formats'])
349         ydl.process_ie_result(info_dict)
350         downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
351         self.assertEqual(downloaded_ids, ['137+141', '248+141'])
352
353         info_dict = _make_result(list(formats_order), extractor='youtube')
354         ydl = YDL({'format': '(bestvideo[ext=mp4],bestvideo[ext=webm])[height<=720]+bestaudio'})
355         yie = YoutubeIE(ydl)
356         yie._sort_formats(info_dict['formats'])
357         ydl.process_ie_result(info_dict)
358         downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
359         self.assertEqual(downloaded_ids, ['136+141', '247+141'])
360
361         info_dict = _make_result(list(formats_order), extractor='youtube')
362         ydl = YDL({'format': '(bestvideo[ext=none]/bestvideo[ext=webm])+bestaudio'})
363         yie = YoutubeIE(ydl)
364         yie._sort_formats(info_dict['formats'])
365         ydl.process_ie_result(info_dict)
366         downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
367         self.assertEqual(downloaded_ids, ['248+141'])
368
369         for f1, f2 in zip(formats_order, formats_order[1:]):
370             info_dict = _make_result([f1, f2], extractor='youtube')
371             ydl = YDL({'format': 'best/bestvideo'})
372             yie = YoutubeIE(ydl)
373             yie._sort_formats(info_dict['formats'])
374             ydl.process_ie_result(info_dict)
375             downloaded = ydl.downloaded_info_dicts[0]
376             self.assertEqual(downloaded['format_id'], f1['format_id'])
377
378             info_dict = _make_result([f2, f1], extractor='youtube')
379             ydl = YDL({'format': 'best/bestvideo'})
380             yie = YoutubeIE(ydl)
381             yie._sort_formats(info_dict['formats'])
382             ydl.process_ie_result(info_dict)
383             downloaded = ydl.downloaded_info_dicts[0]
384             self.assertEqual(downloaded['format_id'], f1['format_id'])
385
386     def test_audio_only_extractor_format_selection(self):
387         # For extractors with incomplete formats (all formats are audio-only or
388         # video-only) best and worst should fallback to corresponding best/worst
389         # video-only or audio-only formats (as per
390         # https://github.com/rg3/youtube-dl/pull/5556)
391         formats = [
392             {'format_id': 'low', 'ext': 'mp3', 'preference': 1, 'vcodec': 'none', 'url': TEST_URL},
393             {'format_id': 'high', 'ext': 'mp3', 'preference': 2, 'vcodec': 'none', 'url': TEST_URL},
394         ]
395         info_dict = _make_result(formats)
396
397         ydl = YDL({'format': 'best'})
398         ydl.process_ie_result(info_dict.copy())
399         downloaded = ydl.downloaded_info_dicts[0]
400         self.assertEqual(downloaded['format_id'], 'high')
401
402         ydl = YDL({'format': 'worst'})
403         ydl.process_ie_result(info_dict.copy())
404         downloaded = ydl.downloaded_info_dicts[0]
405         self.assertEqual(downloaded['format_id'], 'low')
406
407     def test_format_not_available(self):
408         formats = [
409             {'format_id': 'regular', 'ext': 'mp4', 'height': 360, 'url': TEST_URL},
410             {'format_id': 'video', 'ext': 'mp4', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
411         ]
412         info_dict = _make_result(formats)
413
414         # This must fail since complete video-audio format does not match filter
415         # and extractor does not provide incomplete only formats (i.e. only
416         # video-only or audio-only).
417         ydl = YDL({'format': 'best[height>360]'})
418         self.assertRaises(ExtractorError, ydl.process_ie_result, info_dict.copy())
419
420     def test_format_selection_issue_10083(self):
421         # See https://github.com/rg3/youtube-dl/issues/10083
422         formats = [
423             {'format_id': 'regular', 'height': 360, 'url': TEST_URL},
424             {'format_id': 'video', 'height': 720, 'acodec': 'none', 'url': TEST_URL},
425             {'format_id': 'audio', 'vcodec': 'none', 'url': TEST_URL},
426         ]
427         info_dict = _make_result(formats)
428
429         ydl = YDL({'format': 'best[height>360]/bestvideo[height>360]+bestaudio'})
430         ydl.process_ie_result(info_dict.copy())
431         self.assertEqual(ydl.downloaded_info_dicts[0]['format_id'], 'video+audio')
432
433     def test_invalid_format_specs(self):
434         def assert_syntax_error(format_spec):
435             ydl = YDL({'format': format_spec})
436             info_dict = _make_result([{'format_id': 'foo', 'url': TEST_URL}])
437             self.assertRaises(SyntaxError, ydl.process_ie_result, info_dict)
438
439         assert_syntax_error('bestvideo,,best')
440         assert_syntax_error('+bestaudio')
441         assert_syntax_error('bestvideo+')
442         assert_syntax_error('/')
443
444     def test_format_filtering(self):
445         formats = [
446             {'format_id': 'A', 'filesize': 500, 'width': 1000},
447             {'format_id': 'B', 'filesize': 1000, 'width': 500},
448             {'format_id': 'C', 'filesize': 1000, 'width': 400},
449             {'format_id': 'D', 'filesize': 2000, 'width': 600},
450             {'format_id': 'E', 'filesize': 3000},
451             {'format_id': 'F'},
452             {'format_id': 'G', 'filesize': 1000000},
453         ]
454         for f in formats:
455             f['url'] = 'http://_/'
456             f['ext'] = 'unknown'
457         info_dict = _make_result(formats)
458
459         ydl = YDL({'format': 'best[filesize<3000]'})
460         ydl.process_ie_result(info_dict)
461         downloaded = ydl.downloaded_info_dicts[0]
462         self.assertEqual(downloaded['format_id'], 'D')
463
464         ydl = YDL({'format': 'best[filesize<=3000]'})
465         ydl.process_ie_result(info_dict)
466         downloaded = ydl.downloaded_info_dicts[0]
467         self.assertEqual(downloaded['format_id'], 'E')
468
469         ydl = YDL({'format': 'best[filesize <= ? 3000]'})
470         ydl.process_ie_result(info_dict)
471         downloaded = ydl.downloaded_info_dicts[0]
472         self.assertEqual(downloaded['format_id'], 'F')
473
474         ydl = YDL({'format': 'best [filesize = 1000] [width>450]'})
475         ydl.process_ie_result(info_dict)
476         downloaded = ydl.downloaded_info_dicts[0]
477         self.assertEqual(downloaded['format_id'], 'B')
478
479         ydl = YDL({'format': 'best [filesize = 1000] [width!=450]'})
480         ydl.process_ie_result(info_dict)
481         downloaded = ydl.downloaded_info_dicts[0]
482         self.assertEqual(downloaded['format_id'], 'C')
483
484         ydl = YDL({'format': '[filesize>?1]'})
485         ydl.process_ie_result(info_dict)
486         downloaded = ydl.downloaded_info_dicts[0]
487         self.assertEqual(downloaded['format_id'], 'G')
488
489         ydl = YDL({'format': '[filesize<1M]'})
490         ydl.process_ie_result(info_dict)
491         downloaded = ydl.downloaded_info_dicts[0]
492         self.assertEqual(downloaded['format_id'], 'E')
493
494         ydl = YDL({'format': '[filesize<1MiB]'})
495         ydl.process_ie_result(info_dict)
496         downloaded = ydl.downloaded_info_dicts[0]
497         self.assertEqual(downloaded['format_id'], 'G')
498
499         ydl = YDL({'format': 'all[width>=400][width<=600]'})
500         ydl.process_ie_result(info_dict)
501         downloaded_ids = [info['format_id'] for info in ydl.downloaded_info_dicts]
502         self.assertEqual(downloaded_ids, ['B', 'C', 'D'])
503
504         ydl = YDL({'format': 'best[height<40]'})
505         try:
506             ydl.process_ie_result(info_dict)
507         except ExtractorError:
508             pass
509         self.assertEqual(ydl.downloaded_info_dicts, [])
510
511     def test_default_format_spec(self):
512         ydl = YDL({'simulate': True})
513         self.assertEqual(ydl._default_format_spec({}), 'bestvideo+bestaudio/best')
514
515         ydl = YDL({})
516         self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
517
518         ydl = YDL({'simulate': True})
519         self.assertEqual(ydl._default_format_spec({'is_live': True}), 'bestvideo+bestaudio/best')
520
521         ydl = YDL({'outtmpl': '-'})
522         self.assertEqual(ydl._default_format_spec({}), 'best/bestvideo+bestaudio')
523
524         ydl = YDL({})
525         self.assertEqual(ydl._default_format_spec({}, download=False), 'bestvideo+bestaudio/best')
526         self.assertEqual(ydl._default_format_spec({'is_live': True}), 'best/bestvideo+bestaudio')
527
528
529 class TestYoutubeDL(unittest.TestCase):
530     def test_subtitles(self):
531         def s_formats(lang, autocaption=False):
532             return [{
533                 'ext': ext,
534                 'url': 'http://localhost/video.%s.%s' % (lang, ext),
535                 '_auto': autocaption,
536             } for ext in ['vtt', 'srt', 'ass']]
537         subtitles = dict((l, s_formats(l)) for l in ['en', 'fr', 'es'])
538         auto_captions = dict((l, s_formats(l, True)) for l in ['it', 'pt', 'es'])
539         info_dict = {
540             'id': 'test',
541             'title': 'Test',
542             'url': 'http://localhost/video.mp4',
543             'subtitles': subtitles,
544             'automatic_captions': auto_captions,
545             'extractor': 'TEST',
546         }
547
548         def get_info(params={}):
549             params.setdefault('simulate', True)
550             ydl = YDL(params)
551             ydl.report_warning = lambda *args, **kargs: None
552             return ydl.process_video_result(info_dict, download=False)
553
554         result = get_info()
555         self.assertFalse(result.get('requested_subtitles'))
556         self.assertEqual(result['subtitles'], subtitles)
557         self.assertEqual(result['automatic_captions'], auto_captions)
558
559         result = get_info({'writesubtitles': True})
560         subs = result['requested_subtitles']
561         self.assertTrue(subs)
562         self.assertEqual(set(subs.keys()), set(['en']))
563         self.assertTrue(subs['en'].get('data') is None)
564         self.assertEqual(subs['en']['ext'], 'ass')
565
566         result = get_info({'writesubtitles': True, 'subtitlesformat': 'foo/srt'})
567         subs = result['requested_subtitles']
568         self.assertEqual(subs['en']['ext'], 'srt')
569
570         result = get_info({'writesubtitles': True, 'subtitleslangs': ['es', 'fr', 'it']})
571         subs = result['requested_subtitles']
572         self.assertTrue(subs)
573         self.assertEqual(set(subs.keys()), set(['es', 'fr']))
574
575         result = get_info({'writesubtitles': True, 'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
576         subs = result['requested_subtitles']
577         self.assertTrue(subs)
578         self.assertEqual(set(subs.keys()), set(['es', 'pt']))
579         self.assertFalse(subs['es']['_auto'])
580         self.assertTrue(subs['pt']['_auto'])
581
582         result = get_info({'writeautomaticsub': True, 'subtitleslangs': ['es', 'pt']})
583         subs = result['requested_subtitles']
584         self.assertTrue(subs)
585         self.assertEqual(set(subs.keys()), set(['es', 'pt']))
586         self.assertTrue(subs['es']['_auto'])
587         self.assertTrue(subs['pt']['_auto'])
588
589     def test_add_extra_info(self):
590         test_dict = {
591             'extractor': 'Foo',
592         }
593         extra_info = {
594             'extractor': 'Bar',
595             'playlist': 'funny videos',
596         }
597         YDL.add_extra_info(test_dict, extra_info)
598         self.assertEqual(test_dict['extractor'], 'Foo')
599         self.assertEqual(test_dict['playlist'], 'funny videos')
600
601     def test_prepare_filename(self):
602         info = {
603             'id': '1234',
604             'ext': 'mp4',
605             'width': None,
606             'height': 1080,
607             'title1': '$PATH',
608             'title2': '%PATH%',
609         }
610
611         def fname(templ):
612             ydl = YoutubeDL({'outtmpl': templ})
613             return ydl.prepare_filename(info)
614         self.assertEqual(fname('%(id)s.%(ext)s'), '1234.mp4')
615         self.assertEqual(fname('%(id)s-%(width)s.%(ext)s'), '1234-NA.mp4')
616         # Replace missing fields with 'NA'
617         self.assertEqual(fname('%(uploader_date)s-%(id)s.%(ext)s'), 'NA-1234.mp4')
618         self.assertEqual(fname('%(height)d.%(ext)s'), '1080.mp4')
619         self.assertEqual(fname('%(height)6d.%(ext)s'), '  1080.mp4')
620         self.assertEqual(fname('%(height)-6d.%(ext)s'), '1080  .mp4')
621         self.assertEqual(fname('%(height)06d.%(ext)s'), '001080.mp4')
622         self.assertEqual(fname('%(height) 06d.%(ext)s'), ' 01080.mp4')
623         self.assertEqual(fname('%(height)   06d.%(ext)s'), ' 01080.mp4')
624         self.assertEqual(fname('%(height)0 6d.%(ext)s'), ' 01080.mp4')
625         self.assertEqual(fname('%(height)0   6d.%(ext)s'), ' 01080.mp4')
626         self.assertEqual(fname('%(height)   0   6d.%(ext)s'), ' 01080.mp4')
627         self.assertEqual(fname('%%'), '%')
628         self.assertEqual(fname('%%%%'), '%%')
629         self.assertEqual(fname('%%(height)06d.%(ext)s'), '%(height)06d.mp4')
630         self.assertEqual(fname('%(width)06d.%(ext)s'), 'NA.mp4')
631         self.assertEqual(fname('%(width)06d.%%(ext)s'), 'NA.%(ext)s')
632         self.assertEqual(fname('%%(width)06d.%(ext)s'), '%(width)06d.mp4')
633         self.assertEqual(fname('Hello %(title1)s'), 'Hello $PATH')
634         self.assertEqual(fname('Hello %(title2)s'), 'Hello %PATH%')
635
636     def test_format_note(self):
637         ydl = YoutubeDL()
638         self.assertEqual(ydl._format_note({}), '')
639         assertRegexpMatches(self, ydl._format_note({
640             'vbr': 10,
641         }), r'^\s*10k$')
642         assertRegexpMatches(self, ydl._format_note({
643             'fps': 30,
644         }), r'^30fps$')
645
646     def test_postprocessors(self):
647         filename = 'post-processor-testfile.mp4'
648         audiofile = filename + '.mp3'
649
650         class SimplePP(PostProcessor):
651             def run(self, info):
652                 with open(audiofile, 'wt') as f:
653                     f.write('EXAMPLE')
654                 return [info['filepath']], info
655
656         def run_pp(params, PP):
657             with open(filename, 'wt') as f:
658                 f.write('EXAMPLE')
659             ydl = YoutubeDL(params)
660             ydl.add_post_processor(PP())
661             ydl.post_process(filename, {'filepath': filename})
662
663         run_pp({'keepvideo': True}, SimplePP)
664         self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
665         self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
666         os.unlink(filename)
667         os.unlink(audiofile)
668
669         run_pp({'keepvideo': False}, SimplePP)
670         self.assertFalse(os.path.exists(filename), '%s exists' % filename)
671         self.assertTrue(os.path.exists(audiofile), '%s doesn\'t exist' % audiofile)
672         os.unlink(audiofile)
673
674         class ModifierPP(PostProcessor):
675             def run(self, info):
676                 with open(info['filepath'], 'wt') as f:
677                     f.write('MODIFIED')
678                 return [], info
679
680         run_pp({'keepvideo': False}, ModifierPP)
681         self.assertTrue(os.path.exists(filename), '%s doesn\'t exist' % filename)
682         os.unlink(filename)
683
684     def test_match_filter(self):
685         class FilterYDL(YDL):
686             def __init__(self, *args, **kwargs):
687                 super(FilterYDL, self).__init__(*args, **kwargs)
688                 self.params['simulate'] = True
689
690             def process_info(self, info_dict):
691                 super(YDL, self).process_info(info_dict)
692
693             def _match_entry(self, info_dict, incomplete):
694                 res = super(FilterYDL, self)._match_entry(info_dict, incomplete)
695                 if res is None:
696                     self.downloaded_info_dicts.append(info_dict)
697                 return res
698
699         first = {
700             'id': '1',
701             'url': TEST_URL,
702             'title': 'one',
703             'extractor': 'TEST',
704             'duration': 30,
705             'filesize': 10 * 1024,
706             'playlist_id': '42',
707             'uploader': "變態妍字幕版 太妍 тест",
708             'creator': "тест ' 123 ' тест--",
709         }
710         second = {
711             'id': '2',
712             'url': TEST_URL,
713             'title': 'two',
714             'extractor': 'TEST',
715             'duration': 10,
716             'description': 'foo',
717             'filesize': 5 * 1024,
718             'playlist_id': '43',
719             'uploader': "тест 123",
720         }
721         videos = [first, second]
722
723         def get_videos(filter_=None):
724             ydl = FilterYDL({'match_filter': filter_})
725             for v in videos:
726                 ydl.process_ie_result(v, download=True)
727             return [v['id'] for v in ydl.downloaded_info_dicts]
728
729         res = get_videos()
730         self.assertEqual(res, ['1', '2'])
731
732         def f(v):
733             if v['id'] == '1':
734                 return None
735             else:
736                 return 'Video id is not 1'
737         res = get_videos(f)
738         self.assertEqual(res, ['1'])
739
740         f = match_filter_func('duration < 30')
741         res = get_videos(f)
742         self.assertEqual(res, ['2'])
743
744         f = match_filter_func('description = foo')
745         res = get_videos(f)
746         self.assertEqual(res, ['2'])
747
748         f = match_filter_func('description =? foo')
749         res = get_videos(f)
750         self.assertEqual(res, ['1', '2'])
751
752         f = match_filter_func('filesize > 5KiB')
753         res = get_videos(f)
754         self.assertEqual(res, ['1'])
755
756         f = match_filter_func('playlist_id = 42')
757         res = get_videos(f)
758         self.assertEqual(res, ['1'])
759
760         f = match_filter_func('uploader = "變態妍字幕版 太妍 тест"')
761         res = get_videos(f)
762         self.assertEqual(res, ['1'])
763
764         f = match_filter_func('uploader != "變態妍字幕版 太妍 тест"')
765         res = get_videos(f)
766         self.assertEqual(res, ['2'])
767
768         f = match_filter_func('creator = "тест \' 123 \' тест--"')
769         res = get_videos(f)
770         self.assertEqual(res, ['1'])
771
772         f = match_filter_func("creator = 'тест \\' 123 \\' тест--'")
773         res = get_videos(f)
774         self.assertEqual(res, ['1'])
775
776         f = match_filter_func(r"creator = 'тест \' 123 \' тест--' & duration > 30")
777         res = get_videos(f)
778         self.assertEqual(res, [])
779
780     def test_playlist_items_selection(self):
781         entries = [{
782             'id': compat_str(i),
783             'title': compat_str(i),
784             'url': TEST_URL,
785         } for i in range(1, 5)]
786         playlist = {
787             '_type': 'playlist',
788             'id': 'test',
789             'entries': entries,
790             'extractor': 'test:playlist',
791             'extractor_key': 'test:playlist',
792             'webpage_url': 'http://example.com',
793         }
794
795         def get_ids(params):
796             ydl = YDL(params)
797             # make a copy because the dictionary can be modified
798             ydl.process_ie_result(playlist.copy())
799             return [int(v['id']) for v in ydl.downloaded_info_dicts]
800
801         result = get_ids({})
802         self.assertEqual(result, [1, 2, 3, 4])
803
804         result = get_ids({'playlistend': 10})
805         self.assertEqual(result, [1, 2, 3, 4])
806
807         result = get_ids({'playlistend': 2})
808         self.assertEqual(result, [1, 2])
809
810         result = get_ids({'playliststart': 10})
811         self.assertEqual(result, [])
812
813         result = get_ids({'playliststart': 2})
814         self.assertEqual(result, [2, 3, 4])
815
816         result = get_ids({'playlist_items': '2-4'})
817         self.assertEqual(result, [2, 3, 4])
818
819         result = get_ids({'playlist_items': '2,4'})
820         self.assertEqual(result, [2, 4])
821
822         result = get_ids({'playlist_items': '10'})
823         self.assertEqual(result, [])
824
825         result = get_ids({'playlist_items': '3-10'})
826         self.assertEqual(result, [3, 4])
827
828         result = get_ids({'playlist_items': '2-4,3-4,3'})
829         self.assertEqual(result, [2, 3, 4])
830
831     def test_urlopen_no_file_protocol(self):
832         # see https://github.com/rg3/youtube-dl/issues/8227
833         ydl = YDL()
834         self.assertRaises(compat_urllib_error.URLError, ydl.urlopen, 'file:///etc/passwd')
835
836     def test_do_not_override_ie_key_in_url_transparent(self):
837         ydl = YDL()
838
839         class Foo1IE(InfoExtractor):
840             _VALID_URL = r'foo1:'
841
842             def _real_extract(self, url):
843                 return {
844                     '_type': 'url_transparent',
845                     'url': 'foo2:',
846                     'ie_key': 'Foo2',
847                     'title': 'foo1 title',
848                     'id': 'foo1_id',
849                 }
850
851         class Foo2IE(InfoExtractor):
852             _VALID_URL = r'foo2:'
853
854             def _real_extract(self, url):
855                 return {
856                     '_type': 'url',
857                     'url': 'foo3:',
858                     'ie_key': 'Foo3',
859                 }
860
861         class Foo3IE(InfoExtractor):
862             _VALID_URL = r'foo3:'
863
864             def _real_extract(self, url):
865                 return _make_result([{'url': TEST_URL}], title='foo3 title')
866
867         ydl.add_info_extractor(Foo1IE(ydl))
868         ydl.add_info_extractor(Foo2IE(ydl))
869         ydl.add_info_extractor(Foo3IE(ydl))
870         ydl.extract_info('foo1:')
871         downloaded = ydl.downloaded_info_dicts[0]
872         self.assertEqual(downloaded['url'], TEST_URL)
873         self.assertEqual(downloaded['title'], 'foo1 title')
874         self.assertEqual(downloaded['id'], 'testid')
875         self.assertEqual(downloaded['extractor'], 'testex')
876         self.assertEqual(downloaded['extractor_key'], 'TestEx')
877
878
879 if __name__ == '__main__':
880     unittest.main()