[utils] Fixup some common URL's typos in sanitize_url (closes #15649)
[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     encode_base_n,
22     clean_html,
23     date_from_str,
24     DateRange,
25     detect_exe_version,
26     determine_ext,
27     dict_get,
28     encode_compat_str,
29     encodeFilename,
30     escape_rfc3986,
31     escape_url,
32     extract_attributes,
33     ExtractorError,
34     find_xpath_attr,
35     fix_xml_ampersands,
36     get_element_by_class,
37     get_element_by_attribute,
38     get_elements_by_class,
39     get_elements_by_attribute,
40     InAdvancePagedList,
41     intlist_to_bytes,
42     is_html,
43     js_to_json,
44     limit_length,
45     mimetype2ext,
46     month_by_name,
47     multipart_encode,
48     ohdave_rsa_encrypt,
49     OnDemandPagedList,
50     orderedSet,
51     parse_age_limit,
52     parse_duration,
53     parse_filesize,
54     parse_count,
55     parse_iso8601,
56     pkcs1pad,
57     read_batch_urls,
58     sanitize_filename,
59     sanitize_path,
60     sanitize_url,
61     expand_path,
62     prepend_extension,
63     replace_extension,
64     remove_start,
65     remove_end,
66     remove_quotes,
67     shell_quote,
68     smuggle_url,
69     str_to_int,
70     strip_jsonp,
71     timeconvert,
72     unescapeHTML,
73     unified_strdate,
74     unified_timestamp,
75     unsmuggle_url,
76     uppercase_escape,
77     lowercase_escape,
78     url_basename,
79     base_url,
80     urljoin,
81     urlencode_postdata,
82     urshift,
83     update_url_query,
84     version_tuple,
85     xpath_with_ns,
86     xpath_element,
87     xpath_text,
88     xpath_attr,
89     render_table,
90     match_str,
91     parse_dfxp_time_expr,
92     dfxp2srt,
93     cli_option,
94     cli_valueless_option,
95     cli_bool_option,
96     parse_codecs,
97 )
98 from youtube_dl.compat import (
99     compat_chr,
100     compat_etree_fromstring,
101     compat_getenv,
102     compat_os_name,
103     compat_setenv,
104     compat_urlparse,
105     compat_parse_qs,
106 )
107
108
109 class TestUtil(unittest.TestCase):
110     def test_timeconvert(self):
111         self.assertTrue(timeconvert('') is None)
112         self.assertTrue(timeconvert('bougrg') is None)
113
114     def test_sanitize_filename(self):
115         self.assertEqual(sanitize_filename('abc'), 'abc')
116         self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
117
118         self.assertEqual(sanitize_filename('123'), '123')
119
120         self.assertEqual('abc_de', sanitize_filename('abc/de'))
121         self.assertFalse('/' in sanitize_filename('abc/de///'))
122
123         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
124         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
125         self.assertEqual('yes no', sanitize_filename('yes? no'))
126         self.assertEqual('this - that', sanitize_filename('this: that'))
127
128         self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
129         aumlaut = 'ä'
130         self.assertEqual(sanitize_filename(aumlaut), aumlaut)
131         tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
132         self.assertEqual(sanitize_filename(tests), tests)
133
134         self.assertEqual(
135             sanitize_filename('New World record at 0:12:34'),
136             'New World record at 0_12_34')
137
138         self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
139         self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
140         self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
141         self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
142
143         forbidden = '"\0\\/'
144         for fc in forbidden:
145             for fbc in forbidden:
146                 self.assertTrue(fbc not in sanitize_filename(fc))
147
148     def test_sanitize_filename_restricted(self):
149         self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
150         self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
151
152         self.assertEqual(sanitize_filename('123', restricted=True), '123')
153
154         self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
155         self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
156
157         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
158         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
159         self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
160         self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
161
162         tests = 'aäb\u4e2d\u56fd\u7684c'
163         self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
164         self.assertTrue(sanitize_filename('\xf6', restricted=True) != '')  # No empty filename
165
166         forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
167         for fc in forbidden:
168             for fbc in forbidden:
169                 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
170
171         # Handle a common case more neatly
172         self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
173         self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
174         # .. but make sure the file name is never empty
175         self.assertTrue(sanitize_filename('-', restricted=True) != '')
176         self.assertTrue(sanitize_filename(':', restricted=True) != '')
177
178         self.assertEqual(sanitize_filename(
179             'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
180             'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYPssaaaaaaaeceeeeiiiionooooooooeuuuuuypy')
181
182     def test_sanitize_ids(self):
183         self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
184         self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
185         self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
186
187     def test_sanitize_path(self):
188         if sys.platform != 'win32':
189             return
190
191         self.assertEqual(sanitize_path('abc'), 'abc')
192         self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
193         self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
194         self.assertEqual(sanitize_path('abc|def'), 'abc#def')
195         self.assertEqual(sanitize_path('<>:"|?*'), '#######')
196         self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
197         self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
198
199         self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
200         self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
201
202         self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
203         self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
204         self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
205         self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
206
207         self.assertEqual(
208             sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
209             'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
210
211         self.assertEqual(
212             sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
213             'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
214         self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
215         self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
216         self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
217
218         self.assertEqual(sanitize_path('../abc'), '..\\abc')
219         self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
220         self.assertEqual(sanitize_path('./abc'), 'abc')
221         self.assertEqual(sanitize_path('./../abc'), '..\\abc')
222
223     def test_sanitize_url(self):
224         self.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
225         self.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
226         self.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
227         self.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
228
229     def test_expand_path(self):
230         def env(var):
231             return '%{0}%'.format(var) if sys.platform == 'win32' else '${0}'.format(var)
232
233         compat_setenv('YOUTUBE_DL_EXPATH_PATH', 'expanded')
234         self.assertEqual(expand_path(env('YOUTUBE_DL_EXPATH_PATH')), 'expanded')
235         self.assertEqual(expand_path(env('HOME')), compat_getenv('HOME'))
236         self.assertEqual(expand_path('~'), compat_getenv('HOME'))
237         self.assertEqual(
238             expand_path('~/%s' % env('YOUTUBE_DL_EXPATH_PATH')),
239             '%s/expanded' % compat_getenv('HOME'))
240
241     def test_prepend_extension(self):
242         self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
243         self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
244         self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
245         self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
246         self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
247         self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
248
249     def test_replace_extension(self):
250         self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
251         self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
252         self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
253         self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
254         self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
255         self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
256
257     def test_remove_start(self):
258         self.assertEqual(remove_start(None, 'A - '), None)
259         self.assertEqual(remove_start('A - B', 'A - '), 'B')
260         self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
261
262     def test_remove_end(self):
263         self.assertEqual(remove_end(None, ' - B'), None)
264         self.assertEqual(remove_end('A - B', ' - B'), 'A')
265         self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
266
267     def test_remove_quotes(self):
268         self.assertEqual(remove_quotes(None), None)
269         self.assertEqual(remove_quotes('"'), '"')
270         self.assertEqual(remove_quotes("'"), "'")
271         self.assertEqual(remove_quotes(';'), ';')
272         self.assertEqual(remove_quotes('";'), '";')
273         self.assertEqual(remove_quotes('""'), '')
274         self.assertEqual(remove_quotes('";"'), ';')
275
276     def test_ordered_set(self):
277         self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
278         self.assertEqual(orderedSet([]), [])
279         self.assertEqual(orderedSet([1]), [1])
280         # keep the list ordered
281         self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
282
283     def test_unescape_html(self):
284         self.assertEqual(unescapeHTML('%20;'), '%20;')
285         self.assertEqual(unescapeHTML('&#x2F;'), '/')
286         self.assertEqual(unescapeHTML('&#47;'), '/')
287         self.assertEqual(unescapeHTML('&eacute;'), 'é')
288         self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
289         self.assertEqual(unescapeHTML('&a&quot;'), '&a"')
290         # HTML5 entities
291         self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
292
293     def test_date_from_str(self):
294         self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
295         self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
296         self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
297         self.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
298         self.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
299
300     def test_daterange(self):
301         _20century = DateRange("19000101", "20000101")
302         self.assertFalse("17890714" in _20century)
303         _ac = DateRange("00010101")
304         self.assertTrue("19690721" in _ac)
305         _firstmilenium = DateRange(end="10000101")
306         self.assertTrue("07110427" in _firstmilenium)
307
308     def test_unified_dates(self):
309         self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
310         self.assertEqual(unified_strdate('8/7/2009'), '20090708')
311         self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
312         self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
313         self.assertEqual(unified_strdate('1968 12 10'), '19681210')
314         self.assertEqual(unified_strdate('1968-12-10'), '19681210')
315         self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
316         self.assertEqual(
317             unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
318             '20141126')
319         self.assertEqual(
320             unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
321             '20150202')
322         self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
323         self.assertEqual(unified_strdate('25-09-2014'), '20140925')
324         self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
325         self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
326         self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
327         self.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
328         self.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
329         self.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
330
331     def test_unified_timestamps(self):
332         self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
333         self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
334         self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
335         self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
336         self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
337         self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
338         self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
339         self.assertEqual(
340             unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
341             1417001400)
342         self.assertEqual(
343             unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
344             1422902860)
345         self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
346         self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
347         self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
348         self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
349         self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
350         self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
351         self.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
352         self.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
353         self.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
354
355     def test_determine_ext(self):
356         self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
357         self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
358         self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
359         self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
360         self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
361
362     def test_find_xpath_attr(self):
363         testxml = '''<root>
364             <node/>
365             <node x="a"/>
366             <node x="a" y="c" />
367             <node x="b" y="d" />
368             <node x="" />
369         </root>'''
370         doc = compat_etree_fromstring(testxml)
371
372         self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
373         self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
374         self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
375         self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
376         self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
377         self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
378         self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
379         self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
380         self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
381         self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
382         self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
383
384     def test_xpath_with_ns(self):
385         testxml = '''<root xmlns:media="http://example.com/">
386             <media:song>
387                 <media:author>The Author</media:author>
388                 <url>http://server.com/download.mp3</url>
389             </media:song>
390         </root>'''
391         doc = compat_etree_fromstring(testxml)
392         find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
393         self.assertTrue(find('media:song') is not None)
394         self.assertEqual(find('media:song/media:author').text, 'The Author')
395         self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
396
397     def test_xpath_element(self):
398         doc = xml.etree.ElementTree.Element('root')
399         div = xml.etree.ElementTree.SubElement(doc, 'div')
400         p = xml.etree.ElementTree.SubElement(div, 'p')
401         p.text = 'Foo'
402         self.assertEqual(xpath_element(doc, 'div/p'), p)
403         self.assertEqual(xpath_element(doc, ['div/p']), p)
404         self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
405         self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
406         self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
407         self.assertTrue(xpath_element(doc, 'div/bar') is None)
408         self.assertTrue(xpath_element(doc, ['div/bar']) is None)
409         self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
410         self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
411         self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
412         self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
413
414     def test_xpath_text(self):
415         testxml = '''<root>
416             <div>
417                 <p>Foo</p>
418             </div>
419         </root>'''
420         doc = compat_etree_fromstring(testxml)
421         self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
422         self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
423         self.assertTrue(xpath_text(doc, 'div/bar') is None)
424         self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
425
426     def test_xpath_attr(self):
427         testxml = '''<root>
428             <div>
429                 <p x="a">Foo</p>
430             </div>
431         </root>'''
432         doc = compat_etree_fromstring(testxml)
433         self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
434         self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
435         self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
436         self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
437         self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
438         self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
439         self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
440
441     def test_smuggle_url(self):
442         data = {"ö": "ö", "abc": [3]}
443         url = 'https://foo.bar/baz?x=y#a'
444         smug_url = smuggle_url(url, data)
445         unsmug_url, unsmug_data = unsmuggle_url(smug_url)
446         self.assertEqual(url, unsmug_url)
447         self.assertEqual(data, unsmug_data)
448
449         res_url, res_data = unsmuggle_url(url)
450         self.assertEqual(res_url, url)
451         self.assertEqual(res_data, None)
452
453         smug_url = smuggle_url(url, {'a': 'b'})
454         smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
455         res_url, res_data = unsmuggle_url(smug_smug_url)
456         self.assertEqual(res_url, url)
457         self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
458
459     def test_shell_quote(self):
460         args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
461         self.assertEqual(
462             shell_quote(args),
463             """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
464
465     def test_str_to_int(self):
466         self.assertEqual(str_to_int('123,456'), 123456)
467         self.assertEqual(str_to_int('123.456'), 123456)
468
469     def test_url_basename(self):
470         self.assertEqual(url_basename('http://foo.de/'), '')
471         self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
472         self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
473         self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
474         self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
475         self.assertEqual(
476             url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
477             'trailer.mp4')
478
479     def test_base_url(self):
480         self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
481         self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
482         self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
483         self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
484         self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
485
486     def test_urljoin(self):
487         self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
488         self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
489         self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
490         self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
491         self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
492         self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
493         self.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
494         self.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
495         self.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
496         self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
497         self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
498         self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
499         self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
500         self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
501         self.assertEqual(urljoin('http://foo.de/', None), None)
502         self.assertEqual(urljoin('http://foo.de/', ''), None)
503         self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
504         self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
505
506     def test_parse_age_limit(self):
507         self.assertEqual(parse_age_limit(None), None)
508         self.assertEqual(parse_age_limit(False), None)
509         self.assertEqual(parse_age_limit('invalid'), None)
510         self.assertEqual(parse_age_limit(0), 0)
511         self.assertEqual(parse_age_limit(18), 18)
512         self.assertEqual(parse_age_limit(21), 21)
513         self.assertEqual(parse_age_limit(22), None)
514         self.assertEqual(parse_age_limit('18'), 18)
515         self.assertEqual(parse_age_limit('18+'), 18)
516         self.assertEqual(parse_age_limit('PG-13'), 13)
517         self.assertEqual(parse_age_limit('TV-14'), 14)
518         self.assertEqual(parse_age_limit('TV-MA'), 17)
519
520     def test_parse_duration(self):
521         self.assertEqual(parse_duration(None), None)
522         self.assertEqual(parse_duration(False), None)
523         self.assertEqual(parse_duration('invalid'), None)
524         self.assertEqual(parse_duration('1'), 1)
525         self.assertEqual(parse_duration('1337:12'), 80232)
526         self.assertEqual(parse_duration('9:12:43'), 33163)
527         self.assertEqual(parse_duration('12:00'), 720)
528         self.assertEqual(parse_duration('00:01:01'), 61)
529         self.assertEqual(parse_duration('x:y'), None)
530         self.assertEqual(parse_duration('3h11m53s'), 11513)
531         self.assertEqual(parse_duration('3h 11m 53s'), 11513)
532         self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
533         self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
534         self.assertEqual(parse_duration('62m45s'), 3765)
535         self.assertEqual(parse_duration('6m59s'), 419)
536         self.assertEqual(parse_duration('49s'), 49)
537         self.assertEqual(parse_duration('0h0m0s'), 0)
538         self.assertEqual(parse_duration('0m0s'), 0)
539         self.assertEqual(parse_duration('0s'), 0)
540         self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
541         self.assertEqual(parse_duration('T30M38S'), 1838)
542         self.assertEqual(parse_duration('5 s'), 5)
543         self.assertEqual(parse_duration('3 min'), 180)
544         self.assertEqual(parse_duration('2.5 hours'), 9000)
545         self.assertEqual(parse_duration('02:03:04'), 7384)
546         self.assertEqual(parse_duration('01:02:03:04'), 93784)
547         self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
548         self.assertEqual(parse_duration('87 Min.'), 5220)
549         self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
550         self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
551         self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
552
553     def test_fix_xml_ampersands(self):
554         self.assertEqual(
555             fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
556         self.assertEqual(
557             fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
558             '"&amp;x=y&amp;wrong;&amp;z=a')
559         self.assertEqual(
560             fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
561             '&amp;&apos;&gt;&lt;&quot;')
562         self.assertEqual(
563             fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
564         self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
565
566     def test_paged_list(self):
567         def testPL(size, pagesize, sliceargs, expected):
568             def get_page(pagenum):
569                 firstid = pagenum * pagesize
570                 upto = min(size, pagenum * pagesize + pagesize)
571                 for i in range(firstid, upto):
572                     yield i
573
574             pl = OnDemandPagedList(get_page, pagesize)
575             got = pl.getslice(*sliceargs)
576             self.assertEqual(got, expected)
577
578             iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
579             got = iapl.getslice(*sliceargs)
580             self.assertEqual(got, expected)
581
582         testPL(5, 2, (), [0, 1, 2, 3, 4])
583         testPL(5, 2, (1,), [1, 2, 3, 4])
584         testPL(5, 2, (2,), [2, 3, 4])
585         testPL(5, 2, (4,), [4])
586         testPL(5, 2, (0, 3), [0, 1, 2])
587         testPL(5, 2, (1, 4), [1, 2, 3])
588         testPL(5, 2, (2, 99), [2, 3, 4])
589         testPL(5, 2, (20, 99), [])
590
591     def test_read_batch_urls(self):
592         f = io.StringIO('''\xef\xbb\xbf foo
593             bar\r
594             baz
595             # More after this line\r
596             ; or after this
597             bam''')
598         self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
599
600     def test_urlencode_postdata(self):
601         data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
602         self.assertTrue(isinstance(data, bytes))
603
604     def test_update_url_query(self):
605         def query_dict(url):
606             return compat_parse_qs(compat_urlparse.urlparse(url).query)
607         self.assertEqual(query_dict(update_url_query(
608             'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
609             query_dict('http://example.com/path?quality=HD&format=mp4'))
610         self.assertEqual(query_dict(update_url_query(
611             'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
612             query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
613         self.assertEqual(query_dict(update_url_query(
614             'http://example.com/path', {'fields': 'id,formats,subtitles'})),
615             query_dict('http://example.com/path?fields=id,formats,subtitles'))
616         self.assertEqual(query_dict(update_url_query(
617             'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
618             query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
619         self.assertEqual(query_dict(update_url_query(
620             'http://example.com/path?manifest=f4m', {'manifest': []})),
621             query_dict('http://example.com/path'))
622         self.assertEqual(query_dict(update_url_query(
623             'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
624             query_dict('http://example.com/path?system=LINUX'))
625         self.assertEqual(query_dict(update_url_query(
626             'http://example.com/path', {'fields': b'id,formats,subtitles'})),
627             query_dict('http://example.com/path?fields=id,formats,subtitles'))
628         self.assertEqual(query_dict(update_url_query(
629             'http://example.com/path', {'width': 1080, 'height': 720})),
630             query_dict('http://example.com/path?width=1080&height=720'))
631         self.assertEqual(query_dict(update_url_query(
632             'http://example.com/path', {'bitrate': 5020.43})),
633             query_dict('http://example.com/path?bitrate=5020.43'))
634         self.assertEqual(query_dict(update_url_query(
635             'http://example.com/path', {'test': '第二行тест'})),
636             query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
637
638     def test_multipart_encode(self):
639         self.assertEqual(
640             multipart_encode({b'field': b'value'}, boundary='AAAAAA')[0],
641             b'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
642         self.assertEqual(
643             multipart_encode({'欄位'.encode('utf-8'): '值'.encode('utf-8')}, boundary='AAAAAA')[0],
644             b'--AAAAAA\r\nContent-Disposition: form-data; name="\xe6\xac\x84\xe4\xbd\x8d"\r\n\r\n\xe5\x80\xbc\r\n--AAAAAA--\r\n')
645         self.assertRaises(
646             ValueError, multipart_encode, {b'field': b'value'}, boundary='value')
647
648     def test_dict_get(self):
649         FALSE_VALUES = {
650             'none': None,
651             'false': False,
652             'zero': 0,
653             'empty_string': '',
654             'empty_list': [],
655         }
656         d = FALSE_VALUES.copy()
657         d['a'] = 42
658         self.assertEqual(dict_get(d, 'a'), 42)
659         self.assertEqual(dict_get(d, 'b'), None)
660         self.assertEqual(dict_get(d, 'b', 42), 42)
661         self.assertEqual(dict_get(d, ('a', )), 42)
662         self.assertEqual(dict_get(d, ('b', 'a', )), 42)
663         self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
664         self.assertEqual(dict_get(d, ('b', 'c', )), None)
665         self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
666         for key, false_value in FALSE_VALUES.items():
667             self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
668             self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
669
670     def test_encode_compat_str(self):
671         self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
672         self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
673
674     def test_parse_iso8601(self):
675         self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
676         self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
677         self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
678         self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
679         self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
680         self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
681
682     def test_strip_jsonp(self):
683         stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
684         d = json.loads(stripped)
685         self.assertEqual(d, [{"id": "532cb", "x": 3}])
686
687         stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
688         d = json.loads(stripped)
689         self.assertEqual(d, {'STATUS': 'OK'})
690
691         stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
692         d = json.loads(stripped)
693         self.assertEqual(d, {'status': 'success'})
694
695         stripped = strip_jsonp('window.cb && window.cb({"status": "success"});')
696         d = json.loads(stripped)
697         self.assertEqual(d, {'status': 'success'})
698
699         stripped = strip_jsonp('window.cb && cb({"status": "success"});')
700         d = json.loads(stripped)
701         self.assertEqual(d, {'status': 'success'})
702
703     def test_uppercase_escape(self):
704         self.assertEqual(uppercase_escape('aä'), 'aä')
705         self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
706
707     def test_lowercase_escape(self):
708         self.assertEqual(lowercase_escape('aä'), 'aä')
709         self.assertEqual(lowercase_escape('\\u0026'), '&')
710
711     def test_limit_length(self):
712         self.assertEqual(limit_length(None, 12), None)
713         self.assertEqual(limit_length('foo', 12), 'foo')
714         self.assertTrue(
715             limit_length('foo bar baz asd', 12).startswith('foo bar'))
716         self.assertTrue('...' in limit_length('foo bar baz asd', 12))
717
718     def test_mimetype2ext(self):
719         self.assertEqual(mimetype2ext(None), None)
720         self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
721         self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
722         self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
723         self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
724         self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
725
726     def test_month_by_name(self):
727         self.assertEqual(month_by_name(None), None)
728         self.assertEqual(month_by_name('December', 'en'), 12)
729         self.assertEqual(month_by_name('décembre', 'fr'), 12)
730         self.assertEqual(month_by_name('December'), 12)
731         self.assertEqual(month_by_name('décembre'), None)
732         self.assertEqual(month_by_name('Unknown', 'unknown'), None)
733
734     def test_parse_codecs(self):
735         self.assertEqual(parse_codecs(''), {})
736         self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
737             'vcodec': 'avc1.77.30',
738             'acodec': 'mp4a.40.2',
739         })
740         self.assertEqual(parse_codecs('mp4a.40.2'), {
741             'vcodec': 'none',
742             'acodec': 'mp4a.40.2',
743         })
744         self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
745             'vcodec': 'avc1.42001e',
746             'acodec': 'mp4a.40.5',
747         })
748         self.assertEqual(parse_codecs('avc3.640028'), {
749             'vcodec': 'avc3.640028',
750             'acodec': 'none',
751         })
752         self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
753             'vcodec': 'h264',
754             'acodec': 'aac',
755         })
756
757     def test_escape_rfc3986(self):
758         reserved = "!*'();:@&=+$,/?#[]"
759         unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
760         self.assertEqual(escape_rfc3986(reserved), reserved)
761         self.assertEqual(escape_rfc3986(unreserved), unreserved)
762         self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
763         self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
764         self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
765         self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
766
767     def test_escape_url(self):
768         self.assertEqual(
769             escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
770             'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
771         )
772         self.assertEqual(
773             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'),
774             'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
775         )
776         self.assertEqual(
777             escape_url('http://тест.рф/фрагмент'),
778             'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
779         )
780         self.assertEqual(
781             escape_url('http://тест.рф/абв?абв=абв#абв'),
782             'http://xn--e1aybc.xn--p1ai/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
783         )
784         self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
785
786     def test_js_to_json_realworld(self):
787         inp = '''{
788             'clip':{'provider':'pseudo'}
789         }'''
790         self.assertEqual(js_to_json(inp), '''{
791             "clip":{"provider":"pseudo"}
792         }''')
793         json.loads(js_to_json(inp))
794
795         inp = '''{
796             'playlist':[{'controls':{'all':null}}]
797         }'''
798         self.assertEqual(js_to_json(inp), '''{
799             "playlist":[{"controls":{"all":null}}]
800         }''')
801
802         inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
803         self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
804
805         inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
806         json_code = js_to_json(inp)
807         self.assertEqual(json.loads(json_code), json.loads(inp))
808
809         inp = '''{
810             0:{src:'skipped', type: 'application/dash+xml'},
811             1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
812         }'''
813         self.assertEqual(js_to_json(inp), '''{
814             "0":{"src":"skipped", "type": "application/dash+xml"},
815             "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
816         }''')
817
818         inp = '''{"foo":101}'''
819         self.assertEqual(js_to_json(inp), '''{"foo":101}''')
820
821         inp = '''{"duration": "00:01:07"}'''
822         self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
823
824         inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
825         self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
826
827     def test_js_to_json_edgecases(self):
828         on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
829         self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
830
831         on = js_to_json('{"abc": true}')
832         self.assertEqual(json.loads(on), {'abc': True})
833
834         # Ignore JavaScript code as well
835         on = js_to_json('''{
836             "x": 1,
837             y: "a",
838             z: some.code
839         }''')
840         d = json.loads(on)
841         self.assertEqual(d['x'], 1)
842         self.assertEqual(d['y'], 'a')
843
844         on = js_to_json('["abc", "def",]')
845         self.assertEqual(json.loads(on), ['abc', 'def'])
846
847         on = js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
848         self.assertEqual(json.loads(on), ['abc', 'def'])
849
850         on = js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
851         self.assertEqual(json.loads(on), ['abc', 'def'])
852
853         on = js_to_json('{"abc": "def",}')
854         self.assertEqual(json.loads(on), {'abc': 'def'})
855
856         on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
857         self.assertEqual(json.loads(on), {'abc': 'def'})
858
859         on = js_to_json('{ 0: /* " \n */ ",]" , }')
860         self.assertEqual(json.loads(on), {'0': ',]'})
861
862         on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
863         self.assertEqual(json.loads(on), {'0': ',]'})
864
865         on = js_to_json('{ 0: // comment\n1 }')
866         self.assertEqual(json.loads(on), {'0': 1})
867
868         on = js_to_json(r'["<p>x<\/p>"]')
869         self.assertEqual(json.loads(on), ['<p>x</p>'])
870
871         on = js_to_json(r'["\xaa"]')
872         self.assertEqual(json.loads(on), ['\u00aa'])
873
874         on = js_to_json("['a\\\nb']")
875         self.assertEqual(json.loads(on), ['ab'])
876
877         on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
878         self.assertEqual(json.loads(on), ['ab'])
879
880         on = js_to_json('{0xff:0xff}')
881         self.assertEqual(json.loads(on), {'255': 255})
882
883         on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
884         self.assertEqual(json.loads(on), {'255': 255})
885
886         on = js_to_json('{077:077}')
887         self.assertEqual(json.loads(on), {'63': 63})
888
889         on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
890         self.assertEqual(json.loads(on), {'63': 63})
891
892         on = js_to_json('{42:42}')
893         self.assertEqual(json.loads(on), {'42': 42})
894
895         on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
896         self.assertEqual(json.loads(on), {'42': 42})
897
898         on = js_to_json('{42:4.2e1}')
899         self.assertEqual(json.loads(on), {'42': 42.0})
900
901     def test_js_to_json_malformed(self):
902         self.assertEqual(js_to_json('42a1'), '42"a1"')
903         self.assertEqual(js_to_json('42a-1'), '42"a"-1')
904
905     def test_extract_attributes(self):
906         self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
907         self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
908         self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
909         self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
910         self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
911         self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
912         self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
913         self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'})  # XML
914         self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
915         self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'})  # HTML 3.2
916         self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'})  # HTML 4.0
917         self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
918         self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
919         self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
920         self.assertEqual(extract_attributes('<e x >'), {'x': None})
921         self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
922         self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
923         self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
924         self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
925         self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
926         self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
927         self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
928         self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'})  # Names lowercased
929         self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
930         self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
931         self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
932         self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
933         self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
934         # "Narrow" Python builds don't support unicode code points outside BMP.
935         try:
936             compat_chr(0x10000)
937             supports_outside_bmp = True
938         except ValueError:
939             supports_outside_bmp = False
940         if supports_outside_bmp:
941             self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
942         # Malformed HTML should not break attributes extraction on older Python
943         self.assertEqual(extract_attributes('<mal"formed/>'), {})
944
945     def test_clean_html(self):
946         self.assertEqual(clean_html('a:\nb'), 'a: b')
947         self.assertEqual(clean_html('a:\n   "b"'), 'a:    "b"')
948         self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
949
950     def test_intlist_to_bytes(self):
951         self.assertEqual(
952             intlist_to_bytes([0, 1, 127, 128, 255]),
953             b'\x00\x01\x7f\x80\xff')
954
955     def test_args_to_str(self):
956         self.assertEqual(
957             args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
958             'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""'
959         )
960
961     def test_parse_filesize(self):
962         self.assertEqual(parse_filesize(None), None)
963         self.assertEqual(parse_filesize(''), None)
964         self.assertEqual(parse_filesize('91 B'), 91)
965         self.assertEqual(parse_filesize('foobar'), None)
966         self.assertEqual(parse_filesize('2 MiB'), 2097152)
967         self.assertEqual(parse_filesize('5 GB'), 5000000000)
968         self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
969         self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
970         self.assertEqual(parse_filesize('1,24 KB'), 1240)
971         self.assertEqual(parse_filesize('1,24 kb'), 1240)
972         self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
973
974     def test_parse_count(self):
975         self.assertEqual(parse_count(None), None)
976         self.assertEqual(parse_count(''), None)
977         self.assertEqual(parse_count('0'), 0)
978         self.assertEqual(parse_count('1000'), 1000)
979         self.assertEqual(parse_count('1.000'), 1000)
980         self.assertEqual(parse_count('1.1k'), 1100)
981         self.assertEqual(parse_count('1.1kk'), 1100000)
982         self.assertEqual(parse_count('1.1kk '), 1100000)
983         self.assertEqual(parse_count('1.1kk views'), 1100000)
984
985     def test_version_tuple(self):
986         self.assertEqual(version_tuple('1'), (1,))
987         self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
988         self.assertEqual(version_tuple('10.1-6'), (10, 1, 6))  # avconv style
989
990     def test_detect_exe_version(self):
991         self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
992 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
993 configuration: --prefix=/usr --extra-'''), '1.2.1')
994         self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
995 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
996         self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
997 Trying to open render node...
998 Success at /dev/dri/renderD128.
999 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
1000
1001     def test_age_restricted(self):
1002         self.assertFalse(age_restricted(None, 10))  # unrestricted content
1003         self.assertFalse(age_restricted(1, None))  # unrestricted policy
1004         self.assertFalse(age_restricted(8, 10))
1005         self.assertTrue(age_restricted(18, 14))
1006         self.assertFalse(age_restricted(18, 18))
1007
1008     def test_is_html(self):
1009         self.assertFalse(is_html(b'\x49\x44\x43<html'))
1010         self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
1011         self.assertTrue(is_html(  # UTF-8 with BOM
1012             b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
1013         self.assertTrue(is_html(  # UTF-16-LE
1014             b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
1015         ))
1016         self.assertTrue(is_html(  # UTF-16-BE
1017             b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
1018         ))
1019         self.assertTrue(is_html(  # UTF-32-BE
1020             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'))
1021         self.assertTrue(is_html(  # UTF-32-LE
1022             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'))
1023
1024     def test_render_table(self):
1025         self.assertEqual(
1026             render_table(
1027                 ['a', 'bcd'],
1028                 [[123, 4], [9999, 51]]),
1029             'a    bcd\n'
1030             '123  4\n'
1031             '9999 51')
1032
1033     def test_match_str(self):
1034         self.assertRaises(ValueError, match_str, 'xy>foobar', {})
1035         self.assertFalse(match_str('xy', {'x': 1200}))
1036         self.assertTrue(match_str('!xy', {'x': 1200}))
1037         self.assertTrue(match_str('x', {'x': 1200}))
1038         self.assertFalse(match_str('!x', {'x': 1200}))
1039         self.assertTrue(match_str('x', {'x': 0}))
1040         self.assertFalse(match_str('x>0', {'x': 0}))
1041         self.assertFalse(match_str('x>0', {}))
1042         self.assertTrue(match_str('x>?0', {}))
1043         self.assertTrue(match_str('x>1K', {'x': 1200}))
1044         self.assertFalse(match_str('x>2K', {'x': 1200}))
1045         self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
1046         self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
1047         self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
1048         self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
1049         self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
1050         self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
1051         self.assertFalse(match_str(
1052             'like_count > 100 & dislike_count <? 50 & description',
1053             {'like_count': 90, 'description': 'foo'}))
1054         self.assertTrue(match_str(
1055             'like_count > 100 & dislike_count <? 50 & description',
1056             {'like_count': 190, 'description': 'foo'}))
1057         self.assertFalse(match_str(
1058             'like_count > 100 & dislike_count <? 50 & description',
1059             {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
1060         self.assertFalse(match_str(
1061             'like_count > 100 & dislike_count <? 50 & description',
1062             {'like_count': 190, 'dislike_count': 10}))
1063
1064     def test_parse_dfxp_time_expr(self):
1065         self.assertEqual(parse_dfxp_time_expr(None), None)
1066         self.assertEqual(parse_dfxp_time_expr(''), None)
1067         self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
1068         self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
1069         self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
1070         self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
1071         self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
1072
1073     def test_dfxp2srt(self):
1074         dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
1075             <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1076             <body>
1077                 <div xml:lang="en">
1078                     <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
1079                     <p begin="1" end="2">第二行<br/>♪♪</p>
1080                     <p begin="2" dur="1"><span>Third<br/>Line</span></p>
1081                     <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
1082                     <p begin="-1" end="-1">Ignore, two</p>
1083                     <p begin="3" dur="-1">Ignored, three</p>
1084                 </div>
1085             </body>
1086             </tt>'''.encode('utf-8')
1087         srt_data = '''1
1088 00:00:00,000 --> 00:00:01,000
1089 The following line contains Chinese characters and special symbols
1090
1091 2
1092 00:00:01,000 --> 00:00:02,000
1093 第二行
1094 ♪♪
1095
1096 3
1097 00:00:02,000 --> 00:00:03,000
1098 Third
1099 Line
1100
1101 '''
1102         self.assertEqual(dfxp2srt(dfxp_data), srt_data)
1103
1104         dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
1105             <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1106             <body>
1107                 <div xml:lang="en">
1108                     <p begin="0" end="1">The first line</p>
1109                 </div>
1110             </body>
1111             </tt>'''.encode('utf-8')
1112         srt_data = '''1
1113 00:00:00,000 --> 00:00:01,000
1114 The first line
1115
1116 '''
1117         self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
1118
1119         dfxp_data_with_style = '''<?xml version="1.0" encoding="utf-8"?>
1120 <tt xmlns="http://www.w3.org/2006/10/ttaf1" xmlns:ttp="http://www.w3.org/2006/10/ttaf1#parameter" ttp:timeBase="media" xmlns:tts="http://www.w3.org/2006/10/ttaf1#style" xml:lang="en" xmlns:ttm="http://www.w3.org/2006/10/ttaf1#metadata">
1121   <head>
1122     <styling>
1123       <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
1124       <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
1125       <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
1126       <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
1127     </styling>
1128   </head>
1129   <body tts:textAlign="center" style="s0">
1130     <div>
1131       <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
1132       <p style="s2" begin="00:00:02.08" id="p0" end="00:00:05.84"><span tts:color="lime">part 1<br /></span><span tts:color="cyan">part 2</span></p>
1133       <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
1134       <p style="s1" tts:textDecoration="underline" begin="00:00:09.56" id="p2" end="00:00:12.36"><span style="s2" tts:color="lime">inner<br /> </span>style</p>
1135     </div>
1136   </body>
1137 </tt>'''.encode('utf-8')
1138         srt_data = '''1
1139 00:00:02,080 --> 00:00:05,839
1140 <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
1141
1142 2
1143 00:00:02,080 --> 00:00:05,839
1144 <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
1145 </font>part 2</font></b>
1146
1147 3
1148 00:00:05,839 --> 00:00:09,560
1149 <u><font color="lime">line 3
1150 part 3</font></u>
1151
1152 4
1153 00:00:09,560 --> 00:00:12,359
1154 <i><u><font color="yellow"><font color="lime">inner
1155  </font>style</font></u></i>
1156
1157 '''
1158         self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
1159
1160         dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
1161             <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1162             <body>
1163                 <div xml:lang="en">
1164                     <p begin="0" end="1">Line 1</p>
1165                     <p begin="1" end="2">第二行</p>
1166                 </div>
1167             </body>
1168             </tt>'''.encode('utf-16')
1169         srt_data = '''1
1170 00:00:00,000 --> 00:00:01,000
1171 Line 1
1172
1173 2
1174 00:00:01,000 --> 00:00:02,000
1175 第二行
1176
1177 '''
1178         self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
1179
1180     def test_cli_option(self):
1181         self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
1182         self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
1183         self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
1184         self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
1185
1186     def test_cli_valueless_option(self):
1187         self.assertEqual(cli_valueless_option(
1188             {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
1189         self.assertEqual(cli_valueless_option(
1190             {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
1191         self.assertEqual(cli_valueless_option(
1192             {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
1193         self.assertEqual(cli_valueless_option(
1194             {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
1195         self.assertEqual(cli_valueless_option(
1196             {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
1197         self.assertEqual(cli_valueless_option(
1198             {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
1199
1200     def test_cli_bool_option(self):
1201         self.assertEqual(
1202             cli_bool_option(
1203                 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
1204             ['--no-check-certificate', 'true'])
1205         self.assertEqual(
1206             cli_bool_option(
1207                 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
1208             ['--no-check-certificate=true'])
1209         self.assertEqual(
1210             cli_bool_option(
1211                 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1212             ['--check-certificate', 'false'])
1213         self.assertEqual(
1214             cli_bool_option(
1215                 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1216             ['--check-certificate=false'])
1217         self.assertEqual(
1218             cli_bool_option(
1219                 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1220             ['--check-certificate', 'true'])
1221         self.assertEqual(
1222             cli_bool_option(
1223                 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1224             ['--check-certificate=true'])
1225         self.assertEqual(
1226             cli_bool_option(
1227                 {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1228             [])
1229
1230     def test_ohdave_rsa_encrypt(self):
1231         N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
1232         e = 65537
1233
1234         self.assertEqual(
1235             ohdave_rsa_encrypt(b'aa111222', e, N),
1236             '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
1237
1238     def test_pkcs1pad(self):
1239         data = [1, 2, 3]
1240         padded_data = pkcs1pad(data, 32)
1241         self.assertEqual(padded_data[:2], [0, 2])
1242         self.assertEqual(padded_data[28:], [0, 1, 2, 3])
1243
1244         self.assertRaises(ValueError, pkcs1pad, data, 8)
1245
1246     def test_encode_base_n(self):
1247         self.assertEqual(encode_base_n(0, 30), '0')
1248         self.assertEqual(encode_base_n(80, 30), '2k')
1249
1250         custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
1251         self.assertEqual(encode_base_n(0, 30, custom_table), '9')
1252         self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
1253
1254         self.assertRaises(ValueError, encode_base_n, 0, 70)
1255         self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
1256
1257     def test_urshift(self):
1258         self.assertEqual(urshift(3, 1), 1)
1259         self.assertEqual(urshift(-3, 1), 2147483646)
1260
1261     def test_get_element_by_class(self):
1262         html = '''
1263             <span class="foo bar">nice</span>
1264         '''
1265
1266         self.assertEqual(get_element_by_class('foo', html), 'nice')
1267         self.assertEqual(get_element_by_class('no-such-class', html), None)
1268
1269     def test_get_element_by_attribute(self):
1270         html = '''
1271             <span class="foo bar">nice</span>
1272         '''
1273
1274         self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
1275         self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
1276         self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
1277
1278         html = '''
1279             <div itemprop="author" itemscope>foo</div>
1280         '''
1281
1282         self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
1283
1284     def test_get_elements_by_class(self):
1285         html = '''
1286             <span class="foo bar">nice</span><span class="foo bar">also nice</span>
1287         '''
1288
1289         self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
1290         self.assertEqual(get_elements_by_class('no-such-class', html), [])
1291
1292     def test_get_elements_by_attribute(self):
1293         html = '''
1294             <span class="foo bar">nice</span><span class="foo bar">also nice</span>
1295         '''
1296
1297         self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
1298         self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
1299         self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
1300
1301
1302 if __name__ == '__main__':
1303     unittest.main()