[test_utils] add test for smuggling a smuggled url
[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     InAdvancePagedList,
37     intlist_to_bytes,
38     is_html,
39     js_to_json,
40     limit_length,
41     ohdave_rsa_encrypt,
42     OnDemandPagedList,
43     orderedSet,
44     parse_duration,
45     parse_filesize,
46     parse_count,
47     parse_iso8601,
48     read_batch_urls,
49     sanitize_filename,
50     sanitize_path,
51     prepend_extension,
52     replace_extension,
53     remove_start,
54     remove_end,
55     remove_quotes,
56     shell_quote,
57     smuggle_url,
58     str_to_int,
59     strip_jsonp,
60     timeconvert,
61     unescapeHTML,
62     unified_strdate,
63     unified_timestamp,
64     unsmuggle_url,
65     uppercase_escape,
66     lowercase_escape,
67     url_basename,
68     urlencode_postdata,
69     urshift,
70     update_url_query,
71     version_tuple,
72     xpath_with_ns,
73     xpath_element,
74     xpath_text,
75     xpath_attr,
76     render_table,
77     match_str,
78     parse_dfxp_time_expr,
79     dfxp2srt,
80     cli_option,
81     cli_valueless_option,
82     cli_bool_option,
83 )
84 from youtube_dl.compat import (
85     compat_chr,
86     compat_etree_fromstring,
87     compat_urlparse,
88     compat_parse_qs,
89 )
90
91
92 class TestUtil(unittest.TestCase):
93     def test_timeconvert(self):
94         self.assertTrue(timeconvert('') is None)
95         self.assertTrue(timeconvert('bougrg') is None)
96
97     def test_sanitize_filename(self):
98         self.assertEqual(sanitize_filename('abc'), 'abc')
99         self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
100
101         self.assertEqual(sanitize_filename('123'), '123')
102
103         self.assertEqual('abc_de', sanitize_filename('abc/de'))
104         self.assertFalse('/' in sanitize_filename('abc/de///'))
105
106         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
107         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
108         self.assertEqual('yes no', sanitize_filename('yes? no'))
109         self.assertEqual('this - that', sanitize_filename('this: that'))
110
111         self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
112         aumlaut = 'ä'
113         self.assertEqual(sanitize_filename(aumlaut), aumlaut)
114         tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
115         self.assertEqual(sanitize_filename(tests), tests)
116
117         self.assertEqual(
118             sanitize_filename('New World record at 0:12:34'),
119             'New World record at 0_12_34')
120
121         self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
122         self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
123         self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
124         self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
125
126         forbidden = '"\0\\/'
127         for fc in forbidden:
128             for fbc in forbidden:
129                 self.assertTrue(fbc not in sanitize_filename(fc))
130
131     def test_sanitize_filename_restricted(self):
132         self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
133         self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
134
135         self.assertEqual(sanitize_filename('123', restricted=True), '123')
136
137         self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
138         self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
139
140         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
141         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
142         self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
143         self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
144
145         tests = 'aäb\u4e2d\u56fd\u7684c'
146         self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
147         self.assertTrue(sanitize_filename('\xf6', restricted=True) != '')  # No empty filename
148
149         forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
150         for fc in forbidden:
151             for fbc in forbidden:
152                 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
153
154         # Handle a common case more neatly
155         self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
156         self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
157         # .. but make sure the file name is never empty
158         self.assertTrue(sanitize_filename('-', restricted=True) != '')
159         self.assertTrue(sanitize_filename(':', restricted=True) != '')
160
161         self.assertEqual(sanitize_filename(
162             'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
163             'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYPssaaaaaaaeceeeeiiiionooooooooeuuuuuypy')
164
165     def test_sanitize_ids(self):
166         self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
167         self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
168         self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
169
170     def test_sanitize_path(self):
171         if sys.platform != 'win32':
172             return
173
174         self.assertEqual(sanitize_path('abc'), 'abc')
175         self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
176         self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
177         self.assertEqual(sanitize_path('abc|def'), 'abc#def')
178         self.assertEqual(sanitize_path('<>:"|?*'), '#######')
179         self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
180         self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
181
182         self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
183         self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
184
185         self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
186         self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
187         self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
188         self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
189
190         self.assertEqual(
191             sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
192             'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
193
194         self.assertEqual(
195             sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
196             'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
197         self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
198         self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
199         self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
200
201         self.assertEqual(sanitize_path('../abc'), '..\\abc')
202         self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
203         self.assertEqual(sanitize_path('./abc'), 'abc')
204         self.assertEqual(sanitize_path('./../abc'), '..\\abc')
205
206     def test_prepend_extension(self):
207         self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
208         self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
209         self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
210         self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
211         self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
212         self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
213
214     def test_replace_extension(self):
215         self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
216         self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
217         self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
218         self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
219         self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
220         self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
221
222     def test_remove_start(self):
223         self.assertEqual(remove_start(None, 'A - '), None)
224         self.assertEqual(remove_start('A - B', 'A - '), 'B')
225         self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
226
227     def test_remove_end(self):
228         self.assertEqual(remove_end(None, ' - B'), None)
229         self.assertEqual(remove_end('A - B', ' - B'), 'A')
230         self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
231
232     def test_remove_quotes(self):
233         self.assertEqual(remove_quotes(None), None)
234         self.assertEqual(remove_quotes('"'), '"')
235         self.assertEqual(remove_quotes("'"), "'")
236         self.assertEqual(remove_quotes(';'), ';')
237         self.assertEqual(remove_quotes('";'), '";')
238         self.assertEqual(remove_quotes('""'), '')
239         self.assertEqual(remove_quotes('";"'), ';')
240
241     def test_ordered_set(self):
242         self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
243         self.assertEqual(orderedSet([]), [])
244         self.assertEqual(orderedSet([1]), [1])
245         # keep the list ordered
246         self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
247
248     def test_unescape_html(self):
249         self.assertEqual(unescapeHTML('%20;'), '%20;')
250         self.assertEqual(unescapeHTML('&#x2F;'), '/')
251         self.assertEqual(unescapeHTML('&#47;'), '/')
252         self.assertEqual(unescapeHTML('&eacute;'), 'é')
253         self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
254         # HTML5 entities
255         self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
256
257     def test_date_from_str(self):
258         self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
259         self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
260         self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
261         self.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
262         self.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
263
264     def test_daterange(self):
265         _20century = DateRange("19000101", "20000101")
266         self.assertFalse("17890714" in _20century)
267         _ac = DateRange("00010101")
268         self.assertTrue("19690721" in _ac)
269         _firstmilenium = DateRange(end="10000101")
270         self.assertTrue("07110427" in _firstmilenium)
271
272     def test_unified_dates(self):
273         self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
274         self.assertEqual(unified_strdate('8/7/2009'), '20090708')
275         self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
276         self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
277         self.assertEqual(unified_strdate('1968 12 10'), '19681210')
278         self.assertEqual(unified_strdate('1968-12-10'), '19681210')
279         self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
280         self.assertEqual(
281             unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
282             '20141126')
283         self.assertEqual(
284             unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
285             '20150202')
286         self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
287         self.assertEqual(unified_strdate('25-09-2014'), '20140925')
288         self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
289         self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
290
291     def test_unified_timestamps(self):
292         self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
293         self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
294         self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
295         self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
296         self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
297         self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
298         self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
299         self.assertEqual(
300             unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
301             1417001400)
302         self.assertEqual(
303             unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
304             1422902860)
305         self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
306         self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
307         self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
308         self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
309
310     def test_determine_ext(self):
311         self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
312         self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
313         self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
314         self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
315         self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
316
317     def test_find_xpath_attr(self):
318         testxml = '''<root>
319             <node/>
320             <node x="a"/>
321             <node x="a" y="c" />
322             <node x="b" y="d" />
323             <node x="" />
324         </root>'''
325         doc = compat_etree_fromstring(testxml)
326
327         self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
328         self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
329         self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
330         self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
331         self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
332         self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
333         self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
334         self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
335         self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
336         self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
337         self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
338
339     def test_xpath_with_ns(self):
340         testxml = '''<root xmlns:media="http://example.com/">
341             <media:song>
342                 <media:author>The Author</media:author>
343                 <url>http://server.com/download.mp3</url>
344             </media:song>
345         </root>'''
346         doc = compat_etree_fromstring(testxml)
347         find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
348         self.assertTrue(find('media:song') is not None)
349         self.assertEqual(find('media:song/media:author').text, 'The Author')
350         self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
351
352     def test_xpath_element(self):
353         doc = xml.etree.ElementTree.Element('root')
354         div = xml.etree.ElementTree.SubElement(doc, 'div')
355         p = xml.etree.ElementTree.SubElement(div, 'p')
356         p.text = 'Foo'
357         self.assertEqual(xpath_element(doc, 'div/p'), p)
358         self.assertEqual(xpath_element(doc, ['div/p']), p)
359         self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
360         self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
361         self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
362         self.assertTrue(xpath_element(doc, 'div/bar') is None)
363         self.assertTrue(xpath_element(doc, ['div/bar']) is None)
364         self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
365         self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
366         self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
367         self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
368
369     def test_xpath_text(self):
370         testxml = '''<root>
371             <div>
372                 <p>Foo</p>
373             </div>
374         </root>'''
375         doc = compat_etree_fromstring(testxml)
376         self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
377         self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
378         self.assertTrue(xpath_text(doc, 'div/bar') is None)
379         self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
380
381     def test_xpath_attr(self):
382         testxml = '''<root>
383             <div>
384                 <p x="a">Foo</p>
385             </div>
386         </root>'''
387         doc = compat_etree_fromstring(testxml)
388         self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
389         self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
390         self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
391         self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
392         self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
393         self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
394         self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
395
396     def test_smuggle_url(self):
397         data = {"ö": "ö", "abc": [3]}
398         url = 'https://foo.bar/baz?x=y#a'
399         smug_url = smuggle_url(url, data)
400         unsmug_url, unsmug_data = unsmuggle_url(smug_url)
401         self.assertEqual(url, unsmug_url)
402         self.assertEqual(data, unsmug_data)
403
404         res_url, res_data = unsmuggle_url(url)
405         self.assertEqual(res_url, url)
406         self.assertEqual(res_data, None)
407
408         smug_url = smuggle_url(url, {'a': 'b'})
409         smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
410         res_url, res_data = unsmuggle_url(smug_smug_url)
411         self.assertEqual(res_url, url)
412         self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
413
414     def test_shell_quote(self):
415         args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
416         self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
417
418     def test_str_to_int(self):
419         self.assertEqual(str_to_int('123,456'), 123456)
420         self.assertEqual(str_to_int('123.456'), 123456)
421
422     def test_url_basename(self):
423         self.assertEqual(url_basename('http://foo.de/'), '')
424         self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
425         self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
426         self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
427         self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
428         self.assertEqual(
429             url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
430             'trailer.mp4')
431
432     def test_parse_duration(self):
433         self.assertEqual(parse_duration(None), None)
434         self.assertEqual(parse_duration(False), None)
435         self.assertEqual(parse_duration('invalid'), None)
436         self.assertEqual(parse_duration('1'), 1)
437         self.assertEqual(parse_duration('1337:12'), 80232)
438         self.assertEqual(parse_duration('9:12:43'), 33163)
439         self.assertEqual(parse_duration('12:00'), 720)
440         self.assertEqual(parse_duration('00:01:01'), 61)
441         self.assertEqual(parse_duration('x:y'), None)
442         self.assertEqual(parse_duration('3h11m53s'), 11513)
443         self.assertEqual(parse_duration('3h 11m 53s'), 11513)
444         self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
445         self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
446         self.assertEqual(parse_duration('62m45s'), 3765)
447         self.assertEqual(parse_duration('6m59s'), 419)
448         self.assertEqual(parse_duration('49s'), 49)
449         self.assertEqual(parse_duration('0h0m0s'), 0)
450         self.assertEqual(parse_duration('0m0s'), 0)
451         self.assertEqual(parse_duration('0s'), 0)
452         self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
453         self.assertEqual(parse_duration('T30M38S'), 1838)
454         self.assertEqual(parse_duration('5 s'), 5)
455         self.assertEqual(parse_duration('3 min'), 180)
456         self.assertEqual(parse_duration('2.5 hours'), 9000)
457         self.assertEqual(parse_duration('02:03:04'), 7384)
458         self.assertEqual(parse_duration('01:02:03:04'), 93784)
459         self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
460         self.assertEqual(parse_duration('87 Min.'), 5220)
461         self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
462
463     def test_fix_xml_ampersands(self):
464         self.assertEqual(
465             fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
466         self.assertEqual(
467             fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
468             '"&amp;x=y&amp;wrong;&amp;z=a')
469         self.assertEqual(
470             fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
471             '&amp;&apos;&gt;&lt;&quot;')
472         self.assertEqual(
473             fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
474         self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
475
476     def test_paged_list(self):
477         def testPL(size, pagesize, sliceargs, expected):
478             def get_page(pagenum):
479                 firstid = pagenum * pagesize
480                 upto = min(size, pagenum * pagesize + pagesize)
481                 for i in range(firstid, upto):
482                     yield i
483
484             pl = OnDemandPagedList(get_page, pagesize)
485             got = pl.getslice(*sliceargs)
486             self.assertEqual(got, expected)
487
488             iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
489             got = iapl.getslice(*sliceargs)
490             self.assertEqual(got, expected)
491
492         testPL(5, 2, (), [0, 1, 2, 3, 4])
493         testPL(5, 2, (1,), [1, 2, 3, 4])
494         testPL(5, 2, (2,), [2, 3, 4])
495         testPL(5, 2, (4,), [4])
496         testPL(5, 2, (0, 3), [0, 1, 2])
497         testPL(5, 2, (1, 4), [1, 2, 3])
498         testPL(5, 2, (2, 99), [2, 3, 4])
499         testPL(5, 2, (20, 99), [])
500
501     def test_read_batch_urls(self):
502         f = io.StringIO('''\xef\xbb\xbf foo
503             bar\r
504             baz
505             # More after this line\r
506             ; or after this
507             bam''')
508         self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
509
510     def test_urlencode_postdata(self):
511         data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
512         self.assertTrue(isinstance(data, bytes))
513
514     def test_update_url_query(self):
515         def query_dict(url):
516             return compat_parse_qs(compat_urlparse.urlparse(url).query)
517         self.assertEqual(query_dict(update_url_query(
518             'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
519             query_dict('http://example.com/path?quality=HD&format=mp4'))
520         self.assertEqual(query_dict(update_url_query(
521             'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
522             query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
523         self.assertEqual(query_dict(update_url_query(
524             'http://example.com/path', {'fields': 'id,formats,subtitles'})),
525             query_dict('http://example.com/path?fields=id,formats,subtitles'))
526         self.assertEqual(query_dict(update_url_query(
527             'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
528             query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
529         self.assertEqual(query_dict(update_url_query(
530             'http://example.com/path?manifest=f4m', {'manifest': []})),
531             query_dict('http://example.com/path'))
532         self.assertEqual(query_dict(update_url_query(
533             'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
534             query_dict('http://example.com/path?system=LINUX'))
535         self.assertEqual(query_dict(update_url_query(
536             'http://example.com/path', {'fields': b'id,formats,subtitles'})),
537             query_dict('http://example.com/path?fields=id,formats,subtitles'))
538         self.assertEqual(query_dict(update_url_query(
539             'http://example.com/path', {'width': 1080, 'height': 720})),
540             query_dict('http://example.com/path?width=1080&height=720'))
541         self.assertEqual(query_dict(update_url_query(
542             'http://example.com/path', {'bitrate': 5020.43})),
543             query_dict('http://example.com/path?bitrate=5020.43'))
544         self.assertEqual(query_dict(update_url_query(
545             'http://example.com/path', {'test': '第二行тест'})),
546             query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
547
548     def test_dict_get(self):
549         FALSE_VALUES = {
550             'none': None,
551             'false': False,
552             'zero': 0,
553             'empty_string': '',
554             'empty_list': [],
555         }
556         d = FALSE_VALUES.copy()
557         d['a'] = 42
558         self.assertEqual(dict_get(d, 'a'), 42)
559         self.assertEqual(dict_get(d, 'b'), None)
560         self.assertEqual(dict_get(d, 'b', 42), 42)
561         self.assertEqual(dict_get(d, ('a', )), 42)
562         self.assertEqual(dict_get(d, ('b', 'a', )), 42)
563         self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
564         self.assertEqual(dict_get(d, ('b', 'c', )), None)
565         self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
566         for key, false_value in FALSE_VALUES.items():
567             self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
568             self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
569
570     def test_encode_compat_str(self):
571         self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
572         self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
573
574     def test_parse_iso8601(self):
575         self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
576         self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
577         self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
578         self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
579         self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
580         self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
581
582     def test_strip_jsonp(self):
583         stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
584         d = json.loads(stripped)
585         self.assertEqual(d, [{"id": "532cb", "x": 3}])
586
587         stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
588         d = json.loads(stripped)
589         self.assertEqual(d, {'STATUS': 'OK'})
590
591         stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
592         d = json.loads(stripped)
593         self.assertEqual(d, {'status': 'success'})
594
595     def test_uppercase_escape(self):
596         self.assertEqual(uppercase_escape('aä'), 'aä')
597         self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
598
599     def test_lowercase_escape(self):
600         self.assertEqual(lowercase_escape('aä'), 'aä')
601         self.assertEqual(lowercase_escape('\\u0026'), '&')
602
603     def test_limit_length(self):
604         self.assertEqual(limit_length(None, 12), None)
605         self.assertEqual(limit_length('foo', 12), 'foo')
606         self.assertTrue(
607             limit_length('foo bar baz asd', 12).startswith('foo bar'))
608         self.assertTrue('...' in limit_length('foo bar baz asd', 12))
609
610     def test_escape_rfc3986(self):
611         reserved = "!*'();:@&=+$,/?#[]"
612         unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
613         self.assertEqual(escape_rfc3986(reserved), reserved)
614         self.assertEqual(escape_rfc3986(unreserved), unreserved)
615         self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
616         self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
617         self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
618         self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
619
620     def test_escape_url(self):
621         self.assertEqual(
622             escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
623             'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
624         )
625         self.assertEqual(
626             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'),
627             'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
628         )
629         self.assertEqual(
630             escape_url('http://тест.рф/фрагмент'),
631             'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
632         )
633         self.assertEqual(
634             escape_url('http://тест.рф/абв?абв=абв#абв'),
635             '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'
636         )
637         self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
638
639     def test_js_to_json_realworld(self):
640         inp = '''{
641             'clip':{'provider':'pseudo'}
642         }'''
643         self.assertEqual(js_to_json(inp), '''{
644             "clip":{"provider":"pseudo"}
645         }''')
646         json.loads(js_to_json(inp))
647
648         inp = '''{
649             'playlist':[{'controls':{'all':null}}]
650         }'''
651         self.assertEqual(js_to_json(inp), '''{
652             "playlist":[{"controls":{"all":null}}]
653         }''')
654
655         inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
656         self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
657
658         inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
659         json_code = js_to_json(inp)
660         self.assertEqual(json.loads(json_code), json.loads(inp))
661
662         inp = '''{
663             0:{src:'skipped', type: 'application/dash+xml'},
664             1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
665         }'''
666         self.assertEqual(js_to_json(inp), '''{
667             "0":{"src":"skipped", "type": "application/dash+xml"},
668             "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
669         }''')
670
671         inp = '''{"foo":101}'''
672         self.assertEqual(js_to_json(inp), '''{"foo":101}''')
673
674     def test_js_to_json_edgecases(self):
675         on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
676         self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
677
678         on = js_to_json('{"abc": true}')
679         self.assertEqual(json.loads(on), {'abc': True})
680
681         # Ignore JavaScript code as well
682         on = js_to_json('''{
683             "x": 1,
684             y: "a",
685             z: some.code
686         }''')
687         d = json.loads(on)
688         self.assertEqual(d['x'], 1)
689         self.assertEqual(d['y'], 'a')
690
691         on = js_to_json('["abc", "def",]')
692         self.assertEqual(json.loads(on), ['abc', 'def'])
693
694         on = js_to_json('{"abc": "def",}')
695         self.assertEqual(json.loads(on), {'abc': 'def'})
696
697         on = js_to_json('{ 0: /* " \n */ ",]" , }')
698         self.assertEqual(json.loads(on), {'0': ',]'})
699
700         on = js_to_json(r'["<p>x<\/p>"]')
701         self.assertEqual(json.loads(on), ['<p>x</p>'])
702
703         on = js_to_json(r'["\xaa"]')
704         self.assertEqual(json.loads(on), ['\u00aa'])
705
706         on = js_to_json("['a\\\nb']")
707         self.assertEqual(json.loads(on), ['ab'])
708
709         on = js_to_json('{0xff:0xff}')
710         self.assertEqual(json.loads(on), {'255': 255})
711
712         on = js_to_json('{077:077}')
713         self.assertEqual(json.loads(on), {'63': 63})
714
715         on = js_to_json('{42:42}')
716         self.assertEqual(json.loads(on), {'42': 42})
717
718     def test_extract_attributes(self):
719         self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
720         self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
721         self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
722         self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
723         self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
724         self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
725         self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
726         self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'})  # XML
727         self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
728         self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'})  # HTML 3.2
729         self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'})  # HTML 4.0
730         self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
731         self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
732         self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
733         self.assertEqual(extract_attributes('<e x >'), {'x': None})
734         self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
735         self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
736         self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
737         self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
738         self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
739         self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
740         self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
741         self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'})  # Names lowercased
742         self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
743         self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
744         self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
745         self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
746         self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
747         # "Narrow" Python builds don't support unicode code points outside BMP.
748         try:
749             compat_chr(0x10000)
750             supports_outside_bmp = True
751         except ValueError:
752             supports_outside_bmp = False
753         if supports_outside_bmp:
754             self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
755
756     def test_clean_html(self):
757         self.assertEqual(clean_html('a:\nb'), 'a: b')
758         self.assertEqual(clean_html('a:\n   "b"'), 'a:    "b"')
759
760     def test_intlist_to_bytes(self):
761         self.assertEqual(
762             intlist_to_bytes([0, 1, 127, 128, 255]),
763             b'\x00\x01\x7f\x80\xff')
764
765     def test_args_to_str(self):
766         self.assertEqual(
767             args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
768             'foo ba/r -baz \'2 be\' \'\''
769         )
770
771     def test_parse_filesize(self):
772         self.assertEqual(parse_filesize(None), None)
773         self.assertEqual(parse_filesize(''), None)
774         self.assertEqual(parse_filesize('91 B'), 91)
775         self.assertEqual(parse_filesize('foobar'), None)
776         self.assertEqual(parse_filesize('2 MiB'), 2097152)
777         self.assertEqual(parse_filesize('5 GB'), 5000000000)
778         self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
779         self.assertEqual(parse_filesize('1,24 KB'), 1240)
780
781     def test_parse_count(self):
782         self.assertEqual(parse_count(None), None)
783         self.assertEqual(parse_count(''), None)
784         self.assertEqual(parse_count('0'), 0)
785         self.assertEqual(parse_count('1000'), 1000)
786         self.assertEqual(parse_count('1.000'), 1000)
787         self.assertEqual(parse_count('1.1k'), 1100)
788         self.assertEqual(parse_count('1.1kk'), 1100000)
789         self.assertEqual(parse_count('1.1kk '), 1100000)
790         self.assertEqual(parse_count('1.1kk views'), 1100000)
791
792     def test_version_tuple(self):
793         self.assertEqual(version_tuple('1'), (1,))
794         self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
795         self.assertEqual(version_tuple('10.1-6'), (10, 1, 6))  # avconv style
796
797     def test_detect_exe_version(self):
798         self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
799 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
800 configuration: --prefix=/usr --extra-'''), '1.2.1')
801         self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
802 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
803         self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
804 Trying to open render node...
805 Success at /dev/dri/renderD128.
806 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
807
808     def test_age_restricted(self):
809         self.assertFalse(age_restricted(None, 10))  # unrestricted content
810         self.assertFalse(age_restricted(1, None))  # unrestricted policy
811         self.assertFalse(age_restricted(8, 10))
812         self.assertTrue(age_restricted(18, 14))
813         self.assertFalse(age_restricted(18, 18))
814
815     def test_is_html(self):
816         self.assertFalse(is_html(b'\x49\x44\x43<html'))
817         self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
818         self.assertTrue(is_html(  # UTF-8 with BOM
819             b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
820         self.assertTrue(is_html(  # UTF-16-LE
821             b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
822         ))
823         self.assertTrue(is_html(  # UTF-16-BE
824             b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
825         ))
826         self.assertTrue(is_html(  # UTF-32-BE
827             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'))
828         self.assertTrue(is_html(  # UTF-32-LE
829             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'))
830
831     def test_render_table(self):
832         self.assertEqual(
833             render_table(
834                 ['a', 'bcd'],
835                 [[123, 4], [9999, 51]]),
836             'a    bcd\n'
837             '123  4\n'
838             '9999 51')
839
840     def test_match_str(self):
841         self.assertRaises(ValueError, match_str, 'xy>foobar', {})
842         self.assertFalse(match_str('xy', {'x': 1200}))
843         self.assertTrue(match_str('!xy', {'x': 1200}))
844         self.assertTrue(match_str('x', {'x': 1200}))
845         self.assertFalse(match_str('!x', {'x': 1200}))
846         self.assertTrue(match_str('x', {'x': 0}))
847         self.assertFalse(match_str('x>0', {'x': 0}))
848         self.assertFalse(match_str('x>0', {}))
849         self.assertTrue(match_str('x>?0', {}))
850         self.assertTrue(match_str('x>1K', {'x': 1200}))
851         self.assertFalse(match_str('x>2K', {'x': 1200}))
852         self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
853         self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
854         self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
855         self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
856         self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
857         self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
858         self.assertFalse(match_str(
859             'like_count > 100 & dislike_count <? 50 & description',
860             {'like_count': 90, 'description': 'foo'}))
861         self.assertTrue(match_str(
862             'like_count > 100 & dislike_count <? 50 & description',
863             {'like_count': 190, 'description': 'foo'}))
864         self.assertFalse(match_str(
865             'like_count > 100 & dislike_count <? 50 & description',
866             {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
867         self.assertFalse(match_str(
868             'like_count > 100 & dislike_count <? 50 & description',
869             {'like_count': 190, 'dislike_count': 10}))
870
871     def test_parse_dfxp_time_expr(self):
872         self.assertEqual(parse_dfxp_time_expr(None), None)
873         self.assertEqual(parse_dfxp_time_expr(''), None)
874         self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
875         self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
876         self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
877         self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
878         self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
879
880     def test_dfxp2srt(self):
881         dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
882             <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
883             <body>
884                 <div xml:lang="en">
885                     <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
886                     <p begin="1" end="2">第二行<br/>♪♪</p>
887                     <p begin="2" dur="1"><span>Third<br/>Line</span></p>
888                     <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
889                     <p begin="-1" end="-1">Ignore, two</p>
890                     <p begin="3" dur="-1">Ignored, three</p>
891                 </div>
892             </body>
893             </tt>'''
894         srt_data = '''1
895 00:00:00,000 --> 00:00:01,000
896 The following line contains Chinese characters and special symbols
897
898 2
899 00:00:01,000 --> 00:00:02,000
900 第二行
901 ♪♪
902
903 3
904 00:00:02,000 --> 00:00:03,000
905 Third
906 Line
907
908 '''
909         self.assertEqual(dfxp2srt(dfxp_data), srt_data)
910
911         dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
912             <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
913             <body>
914                 <div xml:lang="en">
915                     <p begin="0" end="1">The first line</p>
916                 </div>
917             </body>
918             </tt>'''
919         srt_data = '''1
920 00:00:00,000 --> 00:00:01,000
921 The first line
922
923 '''
924         self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
925
926     def test_cli_option(self):
927         self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
928         self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
929         self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
930
931     def test_cli_valueless_option(self):
932         self.assertEqual(cli_valueless_option(
933             {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
934         self.assertEqual(cli_valueless_option(
935             {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
936         self.assertEqual(cli_valueless_option(
937             {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
938         self.assertEqual(cli_valueless_option(
939             {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
940         self.assertEqual(cli_valueless_option(
941             {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
942         self.assertEqual(cli_valueless_option(
943             {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
944
945     def test_cli_bool_option(self):
946         self.assertEqual(
947             cli_bool_option(
948                 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
949             ['--no-check-certificate', 'true'])
950         self.assertEqual(
951             cli_bool_option(
952                 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
953             ['--no-check-certificate=true'])
954         self.assertEqual(
955             cli_bool_option(
956                 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
957             ['--check-certificate', 'false'])
958         self.assertEqual(
959             cli_bool_option(
960                 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
961             ['--check-certificate=false'])
962         self.assertEqual(
963             cli_bool_option(
964                 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
965             ['--check-certificate', 'true'])
966         self.assertEqual(
967             cli_bool_option(
968                 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
969             ['--check-certificate=true'])
970
971     def test_ohdave_rsa_encrypt(self):
972         N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
973         e = 65537
974
975         self.assertEqual(
976             ohdave_rsa_encrypt(b'aa111222', e, N),
977             '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
978
979     def test_encode_base_n(self):
980         self.assertEqual(encode_base_n(0, 30), '0')
981         self.assertEqual(encode_base_n(80, 30), '2k')
982
983         custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
984         self.assertEqual(encode_base_n(0, 30, custom_table), '9')
985         self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
986
987         self.assertRaises(ValueError, encode_base_n, 0, 70)
988         self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
989
990     def test_urshift(self):
991         self.assertEqual(urshift(3, 1), 1)
992         self.assertEqual(urshift(-3, 1), 2147483646)
993
994 if __name__ == '__main__':
995     unittest.main()