You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

907 lines
41 KiB

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