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.

751 lines
33 KiB

10 years ago
10 years ago
10 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. clean_html,
  17. DateRange,
  18. detect_exe_version,
  19. determine_ext,
  20. encodeFilename,
  21. escape_rfc3986,
  22. escape_url,
  23. ExtractorError,
  24. find_xpath_attr,
  25. fix_xml_ampersands,
  26. InAdvancePagedList,
  27. intlist_to_bytes,
  28. is_html,
  29. js_to_json,
  30. limit_length,
  31. OnDemandPagedList,
  32. orderedSet,
  33. parse_duration,
  34. parse_filesize,
  35. parse_iso8601,
  36. read_batch_urls,
  37. sanitize_filename,
  38. sanitize_path,
  39. prepend_extension,
  40. replace_extension,
  41. shell_quote,
  42. smuggle_url,
  43. str_to_int,
  44. strip_jsonp,
  45. struct_unpack,
  46. timeconvert,
  47. unescapeHTML,
  48. unified_strdate,
  49. unsmuggle_url,
  50. uppercase_escape,
  51. lowercase_escape,
  52. url_basename,
  53. urlencode_postdata,
  54. version_tuple,
  55. xpath_with_ns,
  56. xpath_element,
  57. xpath_text,
  58. xpath_attr,
  59. render_table,
  60. match_str,
  61. parse_dfxp_time_expr,
  62. dfxp2srt,
  63. cli_option,
  64. cli_valueless_option,
  65. cli_bool_option,
  66. )
  67. from youtube_dl.compat import (
  68. compat_etree_fromstring,
  69. )
  70. class TestUtil(unittest.TestCase):
  71. def test_timeconvert(self):
  72. self.assertTrue(timeconvert('') is None)
  73. self.assertTrue(timeconvert('bougrg') is None)
  74. def test_sanitize_filename(self):
  75. self.assertEqual(sanitize_filename('abc'), 'abc')
  76. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  77. self.assertEqual(sanitize_filename('123'), '123')
  78. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  79. self.assertFalse('/' in sanitize_filename('abc/de///'))
  80. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  81. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  82. self.assertEqual('yes no', sanitize_filename('yes? no'))
  83. self.assertEqual('this - that', sanitize_filename('this: that'))
  84. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  85. aumlaut = 'ä'
  86. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  87. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  88. self.assertEqual(sanitize_filename(tests), tests)
  89. self.assertEqual(
  90. sanitize_filename('New World record at 0:12:34'),
  91. 'New World record at 0_12_34')
  92. self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
  93. self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
  94. self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
  95. self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
  96. forbidden = '"\0\\/'
  97. for fc in forbidden:
  98. for fbc in forbidden:
  99. self.assertTrue(fbc not in sanitize_filename(fc))
  100. def test_sanitize_filename_restricted(self):
  101. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  102. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  103. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  104. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  105. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  106. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  107. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  108. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  109. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  110. tests = 'a\xe4b\u4e2d\u56fd\u7684c'
  111. self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
  112. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  113. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  114. for fc in forbidden:
  115. for fbc in forbidden:
  116. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  117. # Handle a common case more neatly
  118. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  119. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  120. # .. but make sure the file name is never empty
  121. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  122. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  123. def test_sanitize_ids(self):
  124. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  125. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  126. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  127. def test_sanitize_path(self):
  128. if sys.platform != 'win32':
  129. return
  130. self.assertEqual(sanitize_path('abc'), 'abc')
  131. self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
  132. self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
  133. self.assertEqual(sanitize_path('abc|def'), 'abc#def')
  134. self.assertEqual(sanitize_path('<>:"|?*'), '#######')
  135. self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
  136. self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
  137. self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
  138. self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
  139. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  140. self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
  141. self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
  142. self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
  143. self.assertEqual(
  144. sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
  145. 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
  146. self.assertEqual(
  147. sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
  148. 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
  149. self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
  150. self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
  151. self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
  152. self.assertEqual(sanitize_path('../abc'), '..\\abc')
  153. self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
  154. self.assertEqual(sanitize_path('./abc'), 'abc')
  155. self.assertEqual(sanitize_path('./../abc'), '..\\abc')
  156. def test_prepend_extension(self):
  157. self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
  158. self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
  159. self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  160. self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
  161. self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
  162. self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
  163. def test_replace_extension(self):
  164. self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
  165. self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
  166. self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
  167. self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
  168. self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
  169. self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
  170. def test_ordered_set(self):
  171. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  172. self.assertEqual(orderedSet([]), [])
  173. self.assertEqual(orderedSet([1]), [1])
  174. # keep the list ordered
  175. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  176. def test_unescape_html(self):
  177. self.assertEqual(unescapeHTML('%20;'), '%20;')
  178. self.assertEqual(unescapeHTML('&#x2F;'), '/')
  179. self.assertEqual(unescapeHTML('&#47;'), '/')
  180. self.assertEqual(unescapeHTML('&eacute;'), 'é')
  181. self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
  182. def test_daterange(self):
  183. _20century = DateRange("19000101", "20000101")
  184. self.assertFalse("17890714" in _20century)
  185. _ac = DateRange("00010101")
  186. self.assertTrue("19690721" in _ac)
  187. _firstmilenium = DateRange(end="10000101")
  188. self.assertTrue("07110427" in _firstmilenium)
  189. def test_unified_dates(self):
  190. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  191. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  192. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  193. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  194. self.assertEqual(unified_strdate('1968 12 10'), '19681210')
  195. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  196. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  197. self.assertEqual(
  198. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  199. '20141126')
  200. self.assertEqual(
  201. unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
  202. '20150202')
  203. self.assertEqual(unified_strdate('25-09-2014'), '20140925')
  204. self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
  205. def test_determine_ext(self):
  206. self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
  207. self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
  208. self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
  209. self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
  210. self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
  211. def test_find_xpath_attr(self):
  212. testxml = '''<root>
  213. <node/>
  214. <node x="a"/>
  215. <node x="a" y="c" />
  216. <node x="b" y="d" />
  217. <node x="" />
  218. </root>'''
  219. doc = compat_etree_fromstring(testxml)
  220. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  221. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  222. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  223. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  224. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  225. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  226. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  227. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  228. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  229. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  230. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  231. def test_xpath_with_ns(self):
  232. testxml = '''<root xmlns:media="http://example.com/">
  233. <media:song>
  234. <media:author>The Author</media:author>
  235. <url>http://server.com/download.mp3</url>
  236. </media:song>
  237. </root>'''
  238. doc = compat_etree_fromstring(testxml)
  239. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  240. self.assertTrue(find('media:song') is not None)
  241. self.assertEqual(find('media:song/media:author').text, 'The Author')
  242. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  243. def test_xpath_element(self):
  244. doc = xml.etree.ElementTree.Element('root')
  245. div = xml.etree.ElementTree.SubElement(doc, 'div')
  246. p = xml.etree.ElementTree.SubElement(div, 'p')
  247. p.text = 'Foo'
  248. self.assertEqual(xpath_element(doc, 'div/p'), p)
  249. self.assertEqual(xpath_element(doc, ['div/p']), p)
  250. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  251. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  252. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  253. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  254. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  255. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  256. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  257. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  258. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  259. def test_xpath_text(self):
  260. testxml = '''<root>
  261. <div>
  262. <p>Foo</p>
  263. </div>
  264. </root>'''
  265. doc = compat_etree_fromstring(testxml)
  266. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  267. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  268. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  269. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  270. def test_xpath_attr(self):
  271. testxml = '''<root>
  272. <div>
  273. <p x="a">Foo</p>
  274. </div>
  275. </root>'''
  276. doc = compat_etree_fromstring(testxml)
  277. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  278. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  279. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  280. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  281. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  282. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  283. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  284. def test_smuggle_url(self):
  285. data = {"ö": "ö", "abc": [3]}
  286. url = 'https://foo.bar/baz?x=y#a'
  287. smug_url = smuggle_url(url, data)
  288. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  289. self.assertEqual(url, unsmug_url)
  290. self.assertEqual(data, unsmug_data)
  291. res_url, res_data = unsmuggle_url(url)
  292. self.assertEqual(res_url, url)
  293. self.assertEqual(res_data, None)
  294. def test_shell_quote(self):
  295. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  296. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  297. def test_str_to_int(self):
  298. self.assertEqual(str_to_int('123,456'), 123456)
  299. self.assertEqual(str_to_int('123.456'), 123456)
  300. def test_url_basename(self):
  301. self.assertEqual(url_basename('http://foo.de/'), '')
  302. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  303. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  304. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  305. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  306. self.assertEqual(
  307. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  308. 'trailer.mp4')
  309. def test_parse_duration(self):
  310. self.assertEqual(parse_duration(None), None)
  311. self.assertEqual(parse_duration(False), None)
  312. self.assertEqual(parse_duration('invalid'), None)
  313. self.assertEqual(parse_duration('1'), 1)
  314. self.assertEqual(parse_duration('1337:12'), 80232)
  315. self.assertEqual(parse_duration('9:12:43'), 33163)
  316. self.assertEqual(parse_duration('12:00'), 720)
  317. self.assertEqual(parse_duration('00:01:01'), 61)
  318. self.assertEqual(parse_duration('x:y'), None)
  319. self.assertEqual(parse_duration('3h11m53s'), 11513)
  320. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  321. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  322. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  323. self.assertEqual(parse_duration('62m45s'), 3765)
  324. self.assertEqual(parse_duration('6m59s'), 419)
  325. self.assertEqual(parse_duration('49s'), 49)
  326. self.assertEqual(parse_duration('0h0m0s'), 0)
  327. self.assertEqual(parse_duration('0m0s'), 0)
  328. self.assertEqual(parse_duration('0s'), 0)
  329. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  330. self.assertEqual(parse_duration('T30M38S'), 1838)
  331. self.assertEqual(parse_duration('5 s'), 5)
  332. self.assertEqual(parse_duration('3 min'), 180)
  333. self.assertEqual(parse_duration('2.5 hours'), 9000)
  334. self.assertEqual(parse_duration('02:03:04'), 7384)
  335. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  336. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  337. self.assertEqual(parse_duration('87 Min.'), 5220)
  338. def test_fix_xml_ampersands(self):
  339. self.assertEqual(
  340. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  341. self.assertEqual(
  342. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  343. '"&amp;x=y&amp;wrong;&amp;z=a')
  344. self.assertEqual(
  345. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  346. '&amp;&apos;&gt;&lt;&quot;')
  347. self.assertEqual(
  348. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  349. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  350. def test_paged_list(self):
  351. def testPL(size, pagesize, sliceargs, expected):
  352. def get_page(pagenum):
  353. firstid = pagenum * pagesize
  354. upto = min(size, pagenum * pagesize + pagesize)
  355. for i in range(firstid, upto):
  356. yield i
  357. pl = OnDemandPagedList(get_page, pagesize)
  358. got = pl.getslice(*sliceargs)
  359. self.assertEqual(got, expected)
  360. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  361. got = iapl.getslice(*sliceargs)
  362. self.assertEqual(got, expected)
  363. testPL(5, 2, (), [0, 1, 2, 3, 4])
  364. testPL(5, 2, (1,), [1, 2, 3, 4])
  365. testPL(5, 2, (2,), [2, 3, 4])
  366. testPL(5, 2, (4,), [4])
  367. testPL(5, 2, (0, 3), [0, 1, 2])
  368. testPL(5, 2, (1, 4), [1, 2, 3])
  369. testPL(5, 2, (2, 99), [2, 3, 4])
  370. testPL(5, 2, (20, 99), [])
  371. def test_struct_unpack(self):
  372. self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
  373. def test_read_batch_urls(self):
  374. f = io.StringIO('''\xef\xbb\xbf foo
  375. bar\r
  376. baz
  377. # More after this line\r
  378. ; or after this
  379. bam''')
  380. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  381. def test_urlencode_postdata(self):
  382. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  383. self.assertTrue(isinstance(data, bytes))
  384. def test_parse_iso8601(self):
  385. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  386. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  387. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  388. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  389. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  390. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  391. def test_strip_jsonp(self):
  392. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  393. d = json.loads(stripped)
  394. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  395. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  396. d = json.loads(stripped)
  397. self.assertEqual(d, {'STATUS': 'OK'})
  398. def test_uppercase_escape(self):
  399. self.assertEqual(uppercase_escape(''), '')
  400. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  401. def test_lowercase_escape(self):
  402. self.assertEqual(lowercase_escape(''), '')
  403. self.assertEqual(lowercase_escape('\\u0026'), '&')
  404. def test_limit_length(self):
  405. self.assertEqual(limit_length(None, 12), None)
  406. self.assertEqual(limit_length('foo', 12), 'foo')
  407. self.assertTrue(
  408. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  409. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  410. def test_escape_rfc3986(self):
  411. reserved = "!*'();:@&=+$,/?#[]"
  412. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  413. self.assertEqual(escape_rfc3986(reserved), reserved)
  414. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  415. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  416. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  417. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  418. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  419. def test_escape_url(self):
  420. self.assertEqual(
  421. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  422. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  423. )
  424. self.assertEqual(
  425. 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'),
  426. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  427. )
  428. self.assertEqual(
  429. escape_url('http://тест.рф/фрагмент'),
  430. 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  431. )
  432. self.assertEqual(
  433. escape_url('http://тест.рф/абв?абв=абв#абв'),
  434. 'http://тест.рф/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
  435. )
  436. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  437. def test_js_to_json_realworld(self):
  438. inp = '''{
  439. 'clip':{'provider':'pseudo'}
  440. }'''
  441. self.assertEqual(js_to_json(inp), '''{
  442. "clip":{"provider":"pseudo"}
  443. }''')
  444. json.loads(js_to_json(inp))
  445. inp = '''{
  446. 'playlist':[{'controls':{'all':null}}]
  447. }'''
  448. self.assertEqual(js_to_json(inp), '''{
  449. "playlist":[{"controls":{"all":null}}]
  450. }''')
  451. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  452. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  453. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  454. json_code = js_to_json(inp)
  455. self.assertEqual(json.loads(json_code), json.loads(inp))
  456. def test_js_to_json_edgecases(self):
  457. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  458. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  459. on = js_to_json('{"abc": true}')
  460. self.assertEqual(json.loads(on), {'abc': True})
  461. # Ignore JavaScript code as well
  462. on = js_to_json('''{
  463. "x": 1,
  464. y: "a",
  465. z: some.code
  466. }''')
  467. d = json.loads(on)
  468. self.assertEqual(d['x'], 1)
  469. self.assertEqual(d['y'], 'a')
  470. on = js_to_json('["abc", "def",]')
  471. self.assertEqual(json.loads(on), ['abc', 'def'])
  472. on = js_to_json('{"abc": "def",}')
  473. self.assertEqual(json.loads(on), {'abc': 'def'})
  474. def test_clean_html(self):
  475. self.assertEqual(clean_html('a:\nb'), 'a: b')
  476. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  477. def test_intlist_to_bytes(self):
  478. self.assertEqual(
  479. intlist_to_bytes([0, 1, 127, 128, 255]),
  480. b'\x00\x01\x7f\x80\xff')
  481. def test_args_to_str(self):
  482. self.assertEqual(
  483. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  484. 'foo ba/r -baz \'2 be\' \'\''
  485. )
  486. def test_parse_filesize(self):
  487. self.assertEqual(parse_filesize(None), None)
  488. self.assertEqual(parse_filesize(''), None)
  489. self.assertEqual(parse_filesize('91 B'), 91)
  490. self.assertEqual(parse_filesize('foobar'), None)
  491. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  492. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  493. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  494. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  495. def test_version_tuple(self):
  496. self.assertEqual(version_tuple('1'), (1,))
  497. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  498. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  499. def test_detect_exe_version(self):
  500. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  501. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  502. configuration: --prefix=/usr --extra-'''), '1.2.1')
  503. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  504. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  505. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  506. Trying to open render node...
  507. Success at /dev/dri/renderD128.
  508. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  509. def test_age_restricted(self):
  510. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  511. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  512. self.assertFalse(age_restricted(8, 10))
  513. self.assertTrue(age_restricted(18, 14))
  514. self.assertFalse(age_restricted(18, 18))
  515. def test_is_html(self):
  516. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  517. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  518. self.assertTrue(is_html( # UTF-8 with BOM
  519. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  520. self.assertTrue(is_html( # UTF-16-LE
  521. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  522. ))
  523. self.assertTrue(is_html( # UTF-16-BE
  524. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  525. ))
  526. self.assertTrue(is_html( # UTF-32-BE
  527. 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'))
  528. self.assertTrue(is_html( # UTF-32-LE
  529. 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'))
  530. def test_render_table(self):
  531. self.assertEqual(
  532. render_table(
  533. ['a', 'bcd'],
  534. [[123, 4], [9999, 51]]),
  535. 'a bcd\n'
  536. '123 4\n'
  537. '9999 51')
  538. def test_match_str(self):
  539. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  540. self.assertFalse(match_str('xy', {'x': 1200}))
  541. self.assertTrue(match_str('!xy', {'x': 1200}))
  542. self.assertTrue(match_str('x', {'x': 1200}))
  543. self.assertFalse(match_str('!x', {'x': 1200}))
  544. self.assertTrue(match_str('x', {'x': 0}))
  545. self.assertFalse(match_str('x>0', {'x': 0}))
  546. self.assertFalse(match_str('x>0', {}))
  547. self.assertTrue(match_str('x>?0', {}))
  548. self.assertTrue(match_str('x>1K', {'x': 1200}))
  549. self.assertFalse(match_str('x>2K', {'x': 1200}))
  550. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  551. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  552. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  553. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  554. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  555. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  556. self.assertFalse(match_str(
  557. 'like_count > 100 & dislike_count <? 50 & description',
  558. {'like_count': 90, 'description': 'foo'}))
  559. self.assertTrue(match_str(
  560. 'like_count > 100 & dislike_count <? 50 & description',
  561. {'like_count': 190, 'description': 'foo'}))
  562. self.assertFalse(match_str(
  563. 'like_count > 100 & dislike_count <? 50 & description',
  564. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  565. self.assertFalse(match_str(
  566. 'like_count > 100 & dislike_count <? 50 & description',
  567. {'like_count': 190, 'dislike_count': 10}))
  568. def test_parse_dfxp_time_expr(self):
  569. self.assertEqual(parse_dfxp_time_expr(None), 0.0)
  570. self.assertEqual(parse_dfxp_time_expr(''), 0.0)
  571. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  572. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  573. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  574. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  575. def test_dfxp2srt(self):
  576. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  577. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  578. <body>
  579. <div xml:lang="en">
  580. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  581. <p begin="1" end="2"><br/></p>
  582. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  583. </div>
  584. </body>
  585. </tt>'''
  586. srt_data = '''1
  587. 00:00:00,000 --> 00:00:01,000
  588. The following line contains Chinese characters and special symbols
  589. 2
  590. 00:00:01,000 --> 00:00:02,000
  591. 3
  592. 00:00:02,000 --> 00:00:03,000
  593. Third
  594. Line
  595. '''
  596. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  597. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  598. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  599. <body>
  600. <div xml:lang="en">
  601. <p begin="0" end="1">The first line</p>
  602. </div>
  603. </body>
  604. </tt>'''
  605. srt_data = '''1
  606. 00:00:00,000 --> 00:00:01,000
  607. The first line
  608. '''
  609. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  610. def test_cli_option(self):
  611. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  612. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  613. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  614. def test_cli_valueless_option(self):
  615. self.assertEqual(cli_valueless_option(
  616. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  617. self.assertEqual(cli_valueless_option(
  618. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  619. self.assertEqual(cli_valueless_option(
  620. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  621. self.assertEqual(cli_valueless_option(
  622. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  623. self.assertEqual(cli_valueless_option(
  624. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  625. self.assertEqual(cli_valueless_option(
  626. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  627. def test_cli_bool_option(self):
  628. self.assertEqual(
  629. cli_bool_option(
  630. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  631. ['--no-check-certificate', 'true'])
  632. self.assertEqual(
  633. cli_bool_option(
  634. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  635. ['--no-check-certificate=true'])
  636. self.assertEqual(
  637. cli_bool_option(
  638. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  639. ['--check-certificate', 'false'])
  640. self.assertEqual(
  641. cli_bool_option(
  642. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  643. ['--check-certificate=false'])
  644. self.assertEqual(
  645. cli_bool_option(
  646. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  647. ['--check-certificate', 'true'])
  648. self.assertEqual(
  649. cli_bool_option(
  650. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  651. ['--check-certificate=true'])
  652. if __name__ == '__main__':
  653. unittest.main()