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.

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