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