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.

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