]> git.bitcoin.ninja Git - youtube-dl/blob - test/test_utils.py
Merge pull request #7322 from remitamine/vgtv
[youtube-dl] / test / test_utils.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
13 # Various small unit tests
14 import io
15 import json
16 import xml.etree.ElementTree
17
18 from youtube_dl.utils import (
19     age_restricted,
20     args_to_str,
21     clean_html,
22     DateRange,
23     detect_exe_version,
24     determine_ext,
25     encode_compat_str,
26     encodeFilename,
27     escape_rfc3986,
28     escape_url,
29     ExtractorError,
30     find_xpath_attr,
31     fix_xml_ampersands,
32     InAdvancePagedList,
33     intlist_to_bytes,
34     is_html,
35     js_to_json,
36     limit_length,
37     OnDemandPagedList,
38     orderedSet,
39     parse_duration,
40     parse_filesize,
41     parse_iso8601,
42     read_batch_urls,
43     sanitize_filename,
44     sanitize_path,
45     prepend_extension,
46     replace_extension,
47     remove_quotes,
48     shell_quote,
49     smuggle_url,
50     str_to_int,
51     strip_jsonp,
52     struct_unpack,
53     timeconvert,
54     unescapeHTML,
55     unified_strdate,
56     unsmuggle_url,
57     uppercase_escape,
58     lowercase_escape,
59     url_basename,
60     urlencode_postdata,
61     version_tuple,
62     xpath_with_ns,
63     xpath_element,
64     xpath_text,
65     xpath_attr,
66     render_table,
67     match_str,
68     parse_dfxp_time_expr,
69     dfxp2srt,
70     cli_option,
71     cli_valueless_option,
72     cli_bool_option,
73 )
74 from youtube_dl.compat import (
75     compat_etree_fromstring,
76 )
77
78
79 class TestUtil(unittest.TestCase):
80     def test_timeconvert(self):
81         self.assertTrue(timeconvert('') is None)
82         self.assertTrue(timeconvert('bougrg') is None)
83
84     def test_sanitize_filename(self):
85         self.assertEqual(sanitize_filename('abc'), 'abc')
86         self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
87
88         self.assertEqual(sanitize_filename('123'), '123')
89
90         self.assertEqual('abc_de', sanitize_filename('abc/de'))
91         self.assertFalse('/' in sanitize_filename('abc/de///'))
92
93         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
94         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
95         self.assertEqual('yes no', sanitize_filename('yes? no'))
96         self.assertEqual('this - that', sanitize_filename('this: that'))
97
98         self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
99         aumlaut = 'ä'
100         self.assertEqual(sanitize_filename(aumlaut), aumlaut)
101         tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
102         self.assertEqual(sanitize_filename(tests), tests)
103
104         self.assertEqual(
105             sanitize_filename('New World record at 0:12:34'),
106             'New World record at 0_12_34')
107
108         self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
109         self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
110         self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
111         self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
112
113         forbidden = '"\0\\/'
114         for fc in forbidden:
115             for fbc in forbidden:
116                 self.assertTrue(fbc not in sanitize_filename(fc))
117
118     def test_sanitize_filename_restricted(self):
119         self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
120         self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
121
122         self.assertEqual(sanitize_filename('123', restricted=True), '123')
123
124         self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
125         self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
126
127         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
128         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
129         self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
130         self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
131
132         tests = 'a\xe4b\u4e2d\u56fd\u7684c'
133         self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
134         self.assertTrue(sanitize_filename('\xf6', restricted=True) != '')  # No empty filename
135
136         forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
137         for fc in forbidden:
138             for fbc in forbidden:
139                 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
140
141         # Handle a common case more neatly
142         self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
143         self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
144         # .. but make sure the file name is never empty
145         self.assertTrue(sanitize_filename('-', restricted=True) != '')
146         self.assertTrue(sanitize_filename(':', restricted=True) != '')
147
148     def test_sanitize_ids(self):
149         self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
150         self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
151         self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
152
153     def test_sanitize_path(self):
154         if sys.platform != 'win32':
155             return
156
157         self.assertEqual(sanitize_path('abc'), 'abc')
158         self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
159         self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
160         self.assertEqual(sanitize_path('abc|def'), 'abc#def')
161         self.assertEqual(sanitize_path('<>:"|?*'), '#######')
162         self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
163         self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
164
165         self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
166         self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
167
168         self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
169         self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
170         self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
171         self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
172
173         self.assertEqual(
174             sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
175             'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
176
177         self.assertEqual(
178             sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
179             'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
180         self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
181         self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
182         self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
183
184         self.assertEqual(sanitize_path('../abc'), '..\\abc')
185         self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
186         self.assertEqual(sanitize_path('./abc'), 'abc')
187         self.assertEqual(sanitize_path('./../abc'), '..\\abc')
188
189     def test_prepend_extension(self):
190         self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
191         self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
192         self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
193         self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
194         self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
195         self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
196
197     def test_replace_extension(self):
198         self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
199         self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
200         self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
201         self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
202         self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
203         self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
204
205     def test_remove_quotes(self):
206         self.assertEqual(remove_quotes(None), None)
207         self.assertEqual(remove_quotes('"'), '"')
208         self.assertEqual(remove_quotes("'"), "'")
209         self.assertEqual(remove_quotes(';'), ';')
210         self.assertEqual(remove_quotes('";'), '";')
211         self.assertEqual(remove_quotes('""'), '')
212         self.assertEqual(remove_quotes('";"'), ';')
213
214     def test_ordered_set(self):
215         self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
216         self.assertEqual(orderedSet([]), [])
217         self.assertEqual(orderedSet([1]), [1])
218         # keep the list ordered
219         self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
220
221     def test_unescape_html(self):
222         self.assertEqual(unescapeHTML('%20;'), '%20;')
223         self.assertEqual(unescapeHTML('&#x2F;'), '/')
224         self.assertEqual(unescapeHTML('&#47;'), '/')
225         self.assertEqual(unescapeHTML('&eacute;'), 'é')
226         self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
227
228     def test_daterange(self):
229         _20century = DateRange("19000101", "20000101")
230         self.assertFalse("17890714" in _20century)
231         _ac = DateRange("00010101")
232         self.assertTrue("19690721" in _ac)
233         _firstmilenium = DateRange(end="10000101")
234         self.assertTrue("07110427" in _firstmilenium)
235
236     def test_unified_dates(self):
237         self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
238         self.assertEqual(unified_strdate('8/7/2009'), '20090708')
239         self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
240         self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
241         self.assertEqual(unified_strdate('1968 12 10'), '19681210')
242         self.assertEqual(unified_strdate('1968-12-10'), '19681210')
243         self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
244         self.assertEqual(
245             unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
246             '20141126')
247         self.assertEqual(
248             unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
249             '20150202')
250         self.assertEqual(unified_strdate('25-09-2014'), '20140925')
251         self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
252
253     def test_determine_ext(self):
254         self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
255         self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
256         self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
257         self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
258         self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
259
260     def test_find_xpath_attr(self):
261         testxml = '''<root>
262             <node/>
263             <node x="a"/>
264             <node x="a" y="c" />
265             <node x="b" y="d" />
266             <node x="" />
267         </root>'''
268         doc = compat_etree_fromstring(testxml)
269
270         self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
271         self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
272         self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
273         self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
274         self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
275         self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
276         self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
277         self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
278         self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
279         self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
280         self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
281
282     def test_xpath_with_ns(self):
283         testxml = '''<root xmlns:media="http://example.com/">
284             <media:song>
285                 <media:author>The Author</media:author>
286                 <url>http://server.com/download.mp3</url>
287             </media:song>
288         </root>'''
289         doc = compat_etree_fromstring(testxml)
290         find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
291         self.assertTrue(find('media:song') is not None)
292         self.assertEqual(find('media:song/media:author').text, 'The Author')
293         self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
294
295     def test_xpath_element(self):
296         doc = xml.etree.ElementTree.Element('root')
297         div = xml.etree.ElementTree.SubElement(doc, 'div')
298         p = xml.etree.ElementTree.SubElement(div, 'p')
299         p.text = 'Foo'
300         self.assertEqual(xpath_element(doc, 'div/p'), p)
301         self.assertEqual(xpath_element(doc, ['div/p']), p)
302         self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
303         self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
304         self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
305         self.assertTrue(xpath_element(doc, 'div/bar') is None)
306         self.assertTrue(xpath_element(doc, ['div/bar']) is None)
307         self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
308         self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
309         self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
310         self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
311
312     def test_xpath_text(self):
313         testxml = '''<root>
314             <div>
315                 <p>Foo</p>
316             </div>
317         </root>'''
318         doc = compat_etree_fromstring(testxml)
319         self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
320         self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
321         self.assertTrue(xpath_text(doc, 'div/bar') is None)
322         self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
323
324     def test_xpath_attr(self):
325         testxml = '''<root>
326             <div>
327                 <p x="a">Foo</p>
328             </div>
329         </root>'''
330         doc = compat_etree_fromstring(testxml)
331         self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
332         self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
333         self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
334         self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
335         self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
336         self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
337         self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
338
339     def test_smuggle_url(self):
340         data = {"ö": "ö", "abc": [3]}
341         url = 'https://foo.bar/baz?x=y#a'
342         smug_url = smuggle_url(url, data)
343         unsmug_url, unsmug_data = unsmuggle_url(smug_url)
344         self.assertEqual(url, unsmug_url)
345         self.assertEqual(data, unsmug_data)
346
347         res_url, res_data = unsmuggle_url(url)
348         self.assertEqual(res_url, url)
349         self.assertEqual(res_data, None)
350
351     def test_shell_quote(self):
352         args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
353         self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
354
355     def test_str_to_int(self):
356         self.assertEqual(str_to_int('123,456'), 123456)
357         self.assertEqual(str_to_int('123.456'), 123456)
358
359     def test_url_basename(self):
360         self.assertEqual(url_basename('http://foo.de/'), '')
361         self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
362         self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
363         self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
364         self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
365         self.assertEqual(
366             url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
367             'trailer.mp4')
368
369     def test_parse_duration(self):
370         self.assertEqual(parse_duration(None), None)
371         self.assertEqual(parse_duration(False), None)
372         self.assertEqual(parse_duration('invalid'), None)
373         self.assertEqual(parse_duration('1'), 1)
374         self.assertEqual(parse_duration('1337:12'), 80232)
375         self.assertEqual(parse_duration('9:12:43'), 33163)
376         self.assertEqual(parse_duration('12:00'), 720)
377         self.assertEqual(parse_duration('00:01:01'), 61)
378         self.assertEqual(parse_duration('x:y'), None)
379         self.assertEqual(parse_duration('3h11m53s'), 11513)
380         self.assertEqual(parse_duration('3h 11m 53s'), 11513)
381         self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
382         self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
383         self.assertEqual(parse_duration('62m45s'), 3765)
384         self.assertEqual(parse_duration('6m59s'), 419)
385         self.assertEqual(parse_duration('49s'), 49)
386         self.assertEqual(parse_duration('0h0m0s'), 0)
387         self.assertEqual(parse_duration('0m0s'), 0)
388         self.assertEqual(parse_duration('0s'), 0)
389         self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
390         self.assertEqual(parse_duration('T30M38S'), 1838)
391         self.assertEqual(parse_duration('5 s'), 5)
392         self.assertEqual(parse_duration('3 min'), 180)
393         self.assertEqual(parse_duration('2.5 hours'), 9000)
394         self.assertEqual(parse_duration('02:03:04'), 7384)
395         self.assertEqual(parse_duration('01:02:03:04'), 93784)
396         self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
397         self.assertEqual(parse_duration('87 Min.'), 5220)
398
399     def test_fix_xml_ampersands(self):
400         self.assertEqual(
401             fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
402         self.assertEqual(
403             fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
404             '"&amp;x=y&amp;wrong;&amp;z=a')
405         self.assertEqual(
406             fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
407             '&amp;&apos;&gt;&lt;&quot;')
408         self.assertEqual(
409             fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
410         self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
411
412     def test_paged_list(self):
413         def testPL(size, pagesize, sliceargs, expected):
414             def get_page(pagenum):
415                 firstid = pagenum * pagesize
416                 upto = min(size, pagenum * pagesize + pagesize)
417                 for i in range(firstid, upto):
418                     yield i
419
420             pl = OnDemandPagedList(get_page, pagesize)
421             got = pl.getslice(*sliceargs)
422             self.assertEqual(got, expected)
423
424             iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
425             got = iapl.getslice(*sliceargs)
426             self.assertEqual(got, expected)
427
428         testPL(5, 2, (), [0, 1, 2, 3, 4])
429         testPL(5, 2, (1,), [1, 2, 3, 4])
430         testPL(5, 2, (2,), [2, 3, 4])
431         testPL(5, 2, (4,), [4])
432         testPL(5, 2, (0, 3), [0, 1, 2])
433         testPL(5, 2, (1, 4), [1, 2, 3])
434         testPL(5, 2, (2, 99), [2, 3, 4])
435         testPL(5, 2, (20, 99), [])
436
437     def test_struct_unpack(self):
438         self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
439
440     def test_read_batch_urls(self):
441         f = io.StringIO('''\xef\xbb\xbf foo
442             bar\r
443             baz
444             # More after this line\r
445             ; or after this
446             bam''')
447         self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
448
449     def test_urlencode_postdata(self):
450         data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
451         self.assertTrue(isinstance(data, bytes))
452
453     def test_encode_compat_str(self):
454         self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
455         self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
456
457     def test_parse_iso8601(self):
458         self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
459         self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
460         self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
461         self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
462         self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
463         self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
464
465     def test_strip_jsonp(self):
466         stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
467         d = json.loads(stripped)
468         self.assertEqual(d, [{"id": "532cb", "x": 3}])
469
470         stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
471         d = json.loads(stripped)
472         self.assertEqual(d, {'STATUS': 'OK'})
473
474     def test_uppercase_escape(self):
475         self.assertEqual(uppercase_escape('aä'), 'aä')
476         self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
477
478     def test_lowercase_escape(self):
479         self.assertEqual(lowercase_escape('aä'), 'aä')
480         self.assertEqual(lowercase_escape('\\u0026'), '&')
481
482     def test_limit_length(self):
483         self.assertEqual(limit_length(None, 12), None)
484         self.assertEqual(limit_length('foo', 12), 'foo')
485         self.assertTrue(
486             limit_length('foo bar baz asd', 12).startswith('foo bar'))
487         self.assertTrue('...' in limit_length('foo bar baz asd', 12))
488
489     def test_escape_rfc3986(self):
490         reserved = "!*'();:@&=+$,/?#[]"
491         unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
492         self.assertEqual(escape_rfc3986(reserved), reserved)
493         self.assertEqual(escape_rfc3986(unreserved), unreserved)
494         self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
495         self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
496         self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
497         self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
498
499     def test_escape_url(self):
500         self.assertEqual(
501             escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
502             'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
503         )
504         self.assertEqual(
505             escape_url('http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erklärt/Das-Erste/Video?documentId=22673108&bcastId=5290'),
506             'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
507         )
508         self.assertEqual(
509             escape_url('http://тест.рф/фрагмент'),
510             'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
511         )
512         self.assertEqual(
513             escape_url('http://тест.рф/абв?абв=абв#абв'),
514             'http://тест.рф/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
515         )
516         self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
517
518     def test_js_to_json_realworld(self):
519         inp = '''{
520             'clip':{'provider':'pseudo'}
521         }'''
522         self.assertEqual(js_to_json(inp), '''{
523             "clip":{"provider":"pseudo"}
524         }''')
525         json.loads(js_to_json(inp))
526
527         inp = '''{
528             'playlist':[{'controls':{'all':null}}]
529         }'''
530         self.assertEqual(js_to_json(inp), '''{
531             "playlist":[{"controls":{"all":null}}]
532         }''')
533
534         inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
535         self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
536
537         inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
538         json_code = js_to_json(inp)
539         self.assertEqual(json.loads(json_code), json.loads(inp))
540
541     def test_js_to_json_edgecases(self):
542         on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
543         self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
544
545         on = js_to_json('{"abc": true}')
546         self.assertEqual(json.loads(on), {'abc': True})
547
548         # Ignore JavaScript code as well
549         on = js_to_json('''{
550             "x": 1,
551             y: "a",
552             z: some.code
553         }''')
554         d = json.loads(on)
555         self.assertEqual(d['x'], 1)
556         self.assertEqual(d['y'], 'a')
557
558         on = js_to_json('["abc", "def",]')
559         self.assertEqual(json.loads(on), ['abc', 'def'])
560
561         on = js_to_json('{"abc": "def",}')
562         self.assertEqual(json.loads(on), {'abc': 'def'})
563
564     def test_clean_html(self):
565         self.assertEqual(clean_html('a:\nb'), 'a: b')
566         self.assertEqual(clean_html('a:\n   "b"'), 'a:    "b"')
567
568     def test_intlist_to_bytes(self):
569         self.assertEqual(
570             intlist_to_bytes([0, 1, 127, 128, 255]),
571             b'\x00\x01\x7f\x80\xff')
572
573     def test_args_to_str(self):
574         self.assertEqual(
575             args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
576             'foo ba/r -baz \'2 be\' \'\''
577         )
578
579     def test_parse_filesize(self):
580         self.assertEqual(parse_filesize(None), None)
581         self.assertEqual(parse_filesize(''), None)
582         self.assertEqual(parse_filesize('91 B'), 91)
583         self.assertEqual(parse_filesize('foobar'), None)
584         self.assertEqual(parse_filesize('2 MiB'), 2097152)
585         self.assertEqual(parse_filesize('5 GB'), 5000000000)
586         self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
587         self.assertEqual(parse_filesize('1,24 KB'), 1240)
588
589     def test_version_tuple(self):
590         self.assertEqual(version_tuple('1'), (1,))
591         self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
592         self.assertEqual(version_tuple('10.1-6'), (10, 1, 6))  # avconv style
593
594     def test_detect_exe_version(self):
595         self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
596 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
597 configuration: --prefix=/usr --extra-'''), '1.2.1')
598         self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
599 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
600         self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
601 Trying to open render node...
602 Success at /dev/dri/renderD128.
603 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
604
605     def test_age_restricted(self):
606         self.assertFalse(age_restricted(None, 10))  # unrestricted content
607         self.assertFalse(age_restricted(1, None))  # unrestricted policy
608         self.assertFalse(age_restricted(8, 10))
609         self.assertTrue(age_restricted(18, 14))
610         self.assertFalse(age_restricted(18, 18))
611
612     def test_is_html(self):
613         self.assertFalse(is_html(b'\x49\x44\x43<html'))
614         self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
615         self.assertTrue(is_html(  # UTF-8 with BOM
616             b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
617         self.assertTrue(is_html(  # UTF-16-LE
618             b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
619         ))
620         self.assertTrue(is_html(  # UTF-16-BE
621             b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
622         ))
623         self.assertTrue(is_html(  # UTF-32-BE
624             b'\x00\x00\xFE\xFF\x00\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4'))
625         self.assertTrue(is_html(  # UTF-32-LE
626             b'\xFF\xFE\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4\x00\x00\x00'))
627
628     def test_render_table(self):
629         self.assertEqual(
630             render_table(
631                 ['a', 'bcd'],
632                 [[123, 4], [9999, 51]]),
633             'a    bcd\n'
634             '123  4\n'
635             '9999 51')
636
637     def test_match_str(self):
638         self.assertRaises(ValueError, match_str, 'xy>foobar', {})
639         self.assertFalse(match_str('xy', {'x': 1200}))
640         self.assertTrue(match_str('!xy', {'x': 1200}))
641         self.assertTrue(match_str('x', {'x': 1200}))
642         self.assertFalse(match_str('!x', {'x': 1200}))
643         self.assertTrue(match_str('x', {'x': 0}))
644         self.assertFalse(match_str('x>0', {'x': 0}))
645         self.assertFalse(match_str('x>0', {}))
646         self.assertTrue(match_str('x>?0', {}))
647         self.assertTrue(match_str('x>1K', {'x': 1200}))
648         self.assertFalse(match_str('x>2K', {'x': 1200}))
649         self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
650         self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
651         self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
652         self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
653         self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
654         self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
655         self.assertFalse(match_str(
656             'like_count > 100 & dislike_count <? 50 & description',
657             {'like_count': 90, 'description': 'foo'}))
658         self.assertTrue(match_str(
659             'like_count > 100 & dislike_count <? 50 & description',
660             {'like_count': 190, 'description': 'foo'}))
661         self.assertFalse(match_str(
662             'like_count > 100 & dislike_count <? 50 & description',
663             {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
664         self.assertFalse(match_str(
665             'like_count > 100 & dislike_count <? 50 & description',
666             {'like_count': 190, 'dislike_count': 10}))
667
668     def test_parse_dfxp_time_expr(self):
669         self.assertEqual(parse_dfxp_time_expr(None), None)
670         self.assertEqual(parse_dfxp_time_expr(''), None)
671         self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
672         self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
673         self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
674         self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
675         self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
676
677     def test_dfxp2srt(self):
678         dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
679             <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
680             <body>
681                 <div xml:lang="en">
682                     <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
683                     <p begin="1" end="2">第二行<br/>♪♪</p>
684                     <p begin="2" dur="1"><span>Third<br/>Line</span></p>
685                     <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
686                     <p begin="-1" end="-1">Ignore, two</p>
687                     <p begin="3" dur="-1">Ignored, three</p>
688                 </div>
689             </body>
690             </tt>'''
691         srt_data = '''1
692 00:00:00,000 --> 00:00:01,000
693 The following line contains Chinese characters and special symbols
694
695 2
696 00:00:01,000 --> 00:00:02,000
697 第二行
698 ♪♪
699
700 3
701 00:00:02,000 --> 00:00:03,000
702 Third
703 Line
704
705 '''
706         self.assertEqual(dfxp2srt(dfxp_data), srt_data)
707
708         dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
709             <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
710             <body>
711                 <div xml:lang="en">
712                     <p begin="0" end="1">The first line</p>
713                 </div>
714             </body>
715             </tt>'''
716         srt_data = '''1
717 00:00:00,000 --> 00:00:01,000
718 The first line
719
720 '''
721         self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
722
723     def test_cli_option(self):
724         self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
725         self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
726         self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
727
728     def test_cli_valueless_option(self):
729         self.assertEqual(cli_valueless_option(
730             {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
731         self.assertEqual(cli_valueless_option(
732             {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
733         self.assertEqual(cli_valueless_option(
734             {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
735         self.assertEqual(cli_valueless_option(
736             {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
737         self.assertEqual(cli_valueless_option(
738             {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
739         self.assertEqual(cli_valueless_option(
740             {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
741
742     def test_cli_bool_option(self):
743         self.assertEqual(
744             cli_bool_option(
745                 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
746             ['--no-check-certificate', 'true'])
747         self.assertEqual(
748             cli_bool_option(
749                 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
750             ['--no-check-certificate=true'])
751         self.assertEqual(
752             cli_bool_option(
753                 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
754             ['--check-certificate', 'false'])
755         self.assertEqual(
756             cli_bool_option(
757                 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
758             ['--check-certificate=false'])
759         self.assertEqual(
760             cli_bool_option(
761                 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
762             ['--check-certificate', 'true'])
763         self.assertEqual(
764             cli_bool_option(
765                 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
766             ['--check-certificate=true'])
767
768
769 if __name__ == '__main__':
770     unittest.main()