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.

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