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.

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