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.

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