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.

1259 lines
57 KiB

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