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.

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