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.

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