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.

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