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.

748 lines
32 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. def test_find_xpath_attr(self):
  209. testxml = '''<root>
  210. <node/>
  211. <node x="a"/>
  212. <node x="a" y="c" />
  213. <node x="b" y="d" />
  214. <node x="" />
  215. </root>'''
  216. doc = compat_etree_fromstring(testxml)
  217. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
  218. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  219. self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
  220. self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
  221. self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
  222. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  223. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
  224. self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
  225. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  226. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
  227. self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
  228. def test_xpath_with_ns(self):
  229. testxml = '''<root xmlns:media="http://example.com/">
  230. <media:song>
  231. <media:author>The Author</media:author>
  232. <url>http://server.com/download.mp3</url>
  233. </media:song>
  234. </root>'''
  235. doc = compat_etree_fromstring(testxml)
  236. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  237. self.assertTrue(find('media:song') is not None)
  238. self.assertEqual(find('media:song/media:author').text, 'The Author')
  239. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  240. def test_xpath_element(self):
  241. doc = xml.etree.ElementTree.Element('root')
  242. div = xml.etree.ElementTree.SubElement(doc, 'div')
  243. p = xml.etree.ElementTree.SubElement(div, 'p')
  244. p.text = 'Foo'
  245. self.assertEqual(xpath_element(doc, 'div/p'), p)
  246. self.assertEqual(xpath_element(doc, ['div/p']), p)
  247. self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
  248. self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
  249. self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
  250. self.assertTrue(xpath_element(doc, 'div/bar') is None)
  251. self.assertTrue(xpath_element(doc, ['div/bar']) is None)
  252. self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
  253. self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
  254. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
  255. self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
  256. def test_xpath_text(self):
  257. testxml = '''<root>
  258. <div>
  259. <p>Foo</p>
  260. </div>
  261. </root>'''
  262. doc = compat_etree_fromstring(testxml)
  263. self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
  264. self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
  265. self.assertTrue(xpath_text(doc, 'div/bar') is None)
  266. self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
  267. def test_xpath_attr(self):
  268. testxml = '''<root>
  269. <div>
  270. <p x="a">Foo</p>
  271. </div>
  272. </root>'''
  273. doc = compat_etree_fromstring(testxml)
  274. self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
  275. self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
  276. self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
  277. self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
  278. self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
  279. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
  280. self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
  281. def test_smuggle_url(self):
  282. data = {"ö": "ö", "abc": [3]}
  283. url = 'https://foo.bar/baz?x=y#a'
  284. smug_url = smuggle_url(url, data)
  285. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  286. self.assertEqual(url, unsmug_url)
  287. self.assertEqual(data, unsmug_data)
  288. res_url, res_data = unsmuggle_url(url)
  289. self.assertEqual(res_url, url)
  290. self.assertEqual(res_data, None)
  291. def test_shell_quote(self):
  292. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  293. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  294. def test_str_to_int(self):
  295. self.assertEqual(str_to_int('123,456'), 123456)
  296. self.assertEqual(str_to_int('123.456'), 123456)
  297. def test_url_basename(self):
  298. self.assertEqual(url_basename('http://foo.de/'), '')
  299. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  300. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  301. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  302. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  303. self.assertEqual(
  304. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  305. 'trailer.mp4')
  306. def test_parse_duration(self):
  307. self.assertEqual(parse_duration(None), None)
  308. self.assertEqual(parse_duration(False), None)
  309. self.assertEqual(parse_duration('invalid'), None)
  310. self.assertEqual(parse_duration('1'), 1)
  311. self.assertEqual(parse_duration('1337:12'), 80232)
  312. self.assertEqual(parse_duration('9:12:43'), 33163)
  313. self.assertEqual(parse_duration('12:00'), 720)
  314. self.assertEqual(parse_duration('00:01:01'), 61)
  315. self.assertEqual(parse_duration('x:y'), None)
  316. self.assertEqual(parse_duration('3h11m53s'), 11513)
  317. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  318. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  319. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  320. self.assertEqual(parse_duration('62m45s'), 3765)
  321. self.assertEqual(parse_duration('6m59s'), 419)
  322. self.assertEqual(parse_duration('49s'), 49)
  323. self.assertEqual(parse_duration('0h0m0s'), 0)
  324. self.assertEqual(parse_duration('0m0s'), 0)
  325. self.assertEqual(parse_duration('0s'), 0)
  326. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  327. self.assertEqual(parse_duration('T30M38S'), 1838)
  328. self.assertEqual(parse_duration('5 s'), 5)
  329. self.assertEqual(parse_duration('3 min'), 180)
  330. self.assertEqual(parse_duration('2.5 hours'), 9000)
  331. self.assertEqual(parse_duration('02:03:04'), 7384)
  332. self.assertEqual(parse_duration('01:02:03:04'), 93784)
  333. self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
  334. self.assertEqual(parse_duration('87 Min.'), 5220)
  335. def test_fix_xml_ampersands(self):
  336. self.assertEqual(
  337. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  338. self.assertEqual(
  339. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  340. '"&amp;x=y&amp;wrong;&amp;z=a')
  341. self.assertEqual(
  342. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  343. '&amp;&apos;&gt;&lt;&quot;')
  344. self.assertEqual(
  345. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  346. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  347. def test_paged_list(self):
  348. def testPL(size, pagesize, sliceargs, expected):
  349. def get_page(pagenum):
  350. firstid = pagenum * pagesize
  351. upto = min(size, pagenum * pagesize + pagesize)
  352. for i in range(firstid, upto):
  353. yield i
  354. pl = OnDemandPagedList(get_page, pagesize)
  355. got = pl.getslice(*sliceargs)
  356. self.assertEqual(got, expected)
  357. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  358. got = iapl.getslice(*sliceargs)
  359. self.assertEqual(got, expected)
  360. testPL(5, 2, (), [0, 1, 2, 3, 4])
  361. testPL(5, 2, (1,), [1, 2, 3, 4])
  362. testPL(5, 2, (2,), [2, 3, 4])
  363. testPL(5, 2, (4,), [4])
  364. testPL(5, 2, (0, 3), [0, 1, 2])
  365. testPL(5, 2, (1, 4), [1, 2, 3])
  366. testPL(5, 2, (2, 99), [2, 3, 4])
  367. testPL(5, 2, (20, 99), [])
  368. def test_struct_unpack(self):
  369. self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
  370. def test_read_batch_urls(self):
  371. f = io.StringIO('''\xef\xbb\xbf foo
  372. bar\r
  373. baz
  374. # More after this line\r
  375. ; or after this
  376. bam''')
  377. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  378. def test_urlencode_postdata(self):
  379. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  380. self.assertTrue(isinstance(data, bytes))
  381. def test_parse_iso8601(self):
  382. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  383. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  384. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  385. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  386. self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
  387. self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
  388. def test_strip_jsonp(self):
  389. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  390. d = json.loads(stripped)
  391. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  392. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  393. d = json.loads(stripped)
  394. self.assertEqual(d, {'STATUS': 'OK'})
  395. def test_uppercase_escape(self):
  396. self.assertEqual(uppercase_escape(''), '')
  397. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  398. def test_lowercase_escape(self):
  399. self.assertEqual(lowercase_escape(''), '')
  400. self.assertEqual(lowercase_escape('\\u0026'), '&')
  401. def test_limit_length(self):
  402. self.assertEqual(limit_length(None, 12), None)
  403. self.assertEqual(limit_length('foo', 12), 'foo')
  404. self.assertTrue(
  405. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  406. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  407. def test_escape_rfc3986(self):
  408. reserved = "!*'();:@&=+$,/?#[]"
  409. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  410. self.assertEqual(escape_rfc3986(reserved), reserved)
  411. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  412. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  413. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  414. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  415. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  416. def test_escape_url(self):
  417. self.assertEqual(
  418. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  419. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  420. )
  421. self.assertEqual(
  422. 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'),
  423. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  424. )
  425. self.assertEqual(
  426. escape_url('http://тест.рф/фрагмент'),
  427. 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  428. )
  429. self.assertEqual(
  430. escape_url('http://тест.рф/абв?абв=абв#абв'),
  431. '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'
  432. )
  433. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  434. def test_js_to_json_realworld(self):
  435. inp = '''{
  436. 'clip':{'provider':'pseudo'}
  437. }'''
  438. self.assertEqual(js_to_json(inp), '''{
  439. "clip":{"provider":"pseudo"}
  440. }''')
  441. json.loads(js_to_json(inp))
  442. inp = '''{
  443. 'playlist':[{'controls':{'all':null}}]
  444. }'''
  445. self.assertEqual(js_to_json(inp), '''{
  446. "playlist":[{"controls":{"all":null}}]
  447. }''')
  448. inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
  449. self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
  450. inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
  451. json_code = js_to_json(inp)
  452. self.assertEqual(json.loads(json_code), json.loads(inp))
  453. def test_js_to_json_edgecases(self):
  454. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  455. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  456. on = js_to_json('{"abc": true}')
  457. self.assertEqual(json.loads(on), {'abc': True})
  458. # Ignore JavaScript code as well
  459. on = js_to_json('''{
  460. "x": 1,
  461. y: "a",
  462. z: some.code
  463. }''')
  464. d = json.loads(on)
  465. self.assertEqual(d['x'], 1)
  466. self.assertEqual(d['y'], 'a')
  467. on = js_to_json('["abc", "def",]')
  468. self.assertEqual(json.loads(on), ['abc', 'def'])
  469. on = js_to_json('{"abc": "def",}')
  470. self.assertEqual(json.loads(on), {'abc': 'def'})
  471. def test_clean_html(self):
  472. self.assertEqual(clean_html('a:\nb'), 'a: b')
  473. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  474. def test_intlist_to_bytes(self):
  475. self.assertEqual(
  476. intlist_to_bytes([0, 1, 127, 128, 255]),
  477. b'\x00\x01\x7f\x80\xff')
  478. def test_args_to_str(self):
  479. self.assertEqual(
  480. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  481. 'foo ba/r -baz \'2 be\' \'\''
  482. )
  483. def test_parse_filesize(self):
  484. self.assertEqual(parse_filesize(None), None)
  485. self.assertEqual(parse_filesize(''), None)
  486. self.assertEqual(parse_filesize('91 B'), 91)
  487. self.assertEqual(parse_filesize('foobar'), None)
  488. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  489. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  490. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  491. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  492. def test_version_tuple(self):
  493. self.assertEqual(version_tuple('1'), (1,))
  494. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  495. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  496. def test_detect_exe_version(self):
  497. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  498. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  499. configuration: --prefix=/usr --extra-'''), '1.2.1')
  500. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  501. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  502. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  503. Trying to open render node...
  504. Success at /dev/dri/renderD128.
  505. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  506. def test_age_restricted(self):
  507. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  508. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  509. self.assertFalse(age_restricted(8, 10))
  510. self.assertTrue(age_restricted(18, 14))
  511. self.assertFalse(age_restricted(18, 18))
  512. def test_is_html(self):
  513. self.assertFalse(is_html(b'\x49\x44\x43<html'))
  514. self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
  515. self.assertTrue(is_html( # UTF-8 with BOM
  516. b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
  517. self.assertTrue(is_html( # UTF-16-LE
  518. b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
  519. ))
  520. self.assertTrue(is_html( # UTF-16-BE
  521. b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
  522. ))
  523. self.assertTrue(is_html( # UTF-32-BE
  524. 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'))
  525. self.assertTrue(is_html( # UTF-32-LE
  526. 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'))
  527. def test_render_table(self):
  528. self.assertEqual(
  529. render_table(
  530. ['a', 'bcd'],
  531. [[123, 4], [9999, 51]]),
  532. 'a bcd\n'
  533. '123 4\n'
  534. '9999 51')
  535. def test_match_str(self):
  536. self.assertRaises(ValueError, match_str, 'xy>foobar', {})
  537. self.assertFalse(match_str('xy', {'x': 1200}))
  538. self.assertTrue(match_str('!xy', {'x': 1200}))
  539. self.assertTrue(match_str('x', {'x': 1200}))
  540. self.assertFalse(match_str('!x', {'x': 1200}))
  541. self.assertTrue(match_str('x', {'x': 0}))
  542. self.assertFalse(match_str('x>0', {'x': 0}))
  543. self.assertFalse(match_str('x>0', {}))
  544. self.assertTrue(match_str('x>?0', {}))
  545. self.assertTrue(match_str('x>1K', {'x': 1200}))
  546. self.assertFalse(match_str('x>2K', {'x': 1200}))
  547. self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
  548. self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
  549. self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
  550. self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
  551. self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
  552. self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
  553. self.assertFalse(match_str(
  554. 'like_count > 100 & dislike_count <? 50 & description',
  555. {'like_count': 90, 'description': 'foo'}))
  556. self.assertTrue(match_str(
  557. 'like_count > 100 & dislike_count <? 50 & description',
  558. {'like_count': 190, 'description': 'foo'}))
  559. self.assertFalse(match_str(
  560. 'like_count > 100 & dislike_count <? 50 & description',
  561. {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
  562. self.assertFalse(match_str(
  563. 'like_count > 100 & dislike_count <? 50 & description',
  564. {'like_count': 190, 'dislike_count': 10}))
  565. def test_parse_dfxp_time_expr(self):
  566. self.assertEqual(parse_dfxp_time_expr(None), 0.0)
  567. self.assertEqual(parse_dfxp_time_expr(''), 0.0)
  568. self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
  569. self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
  570. self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
  571. self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
  572. def test_dfxp2srt(self):
  573. dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
  574. <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  575. <body>
  576. <div xml:lang="en">
  577. <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
  578. <p begin="1" end="2"><br/></p>
  579. <p begin="2" dur="1"><span>Third<br/>Line</span></p>
  580. </div>
  581. </body>
  582. </tt>'''
  583. srt_data = '''1
  584. 00:00:00,000 --> 00:00:01,000
  585. The following line contains Chinese characters and special symbols
  586. 2
  587. 00:00:01,000 --> 00:00:02,000
  588. 3
  589. 00:00:02,000 --> 00:00:03,000
  590. Third
  591. Line
  592. '''
  593. self.assertEqual(dfxp2srt(dfxp_data), srt_data)
  594. dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
  595. <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
  596. <body>
  597. <div xml:lang="en">
  598. <p begin="0" end="1">The first line</p>
  599. </div>
  600. </body>
  601. </tt>'''
  602. srt_data = '''1
  603. 00:00:00,000 --> 00:00:01,000
  604. The first line
  605. '''
  606. self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
  607. def test_cli_option(self):
  608. self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
  609. self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
  610. self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
  611. def test_cli_valueless_option(self):
  612. self.assertEqual(cli_valueless_option(
  613. {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
  614. self.assertEqual(cli_valueless_option(
  615. {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
  616. self.assertEqual(cli_valueless_option(
  617. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
  618. self.assertEqual(cli_valueless_option(
  619. {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
  620. self.assertEqual(cli_valueless_option(
  621. {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
  622. self.assertEqual(cli_valueless_option(
  623. {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
  624. def test_cli_bool_option(self):
  625. self.assertEqual(
  626. cli_bool_option(
  627. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
  628. ['--no-check-certificate', 'true'])
  629. self.assertEqual(
  630. cli_bool_option(
  631. {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
  632. ['--no-check-certificate=true'])
  633. self.assertEqual(
  634. cli_bool_option(
  635. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  636. ['--check-certificate', 'false'])
  637. self.assertEqual(
  638. cli_bool_option(
  639. {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  640. ['--check-certificate=false'])
  641. self.assertEqual(
  642. cli_bool_option(
  643. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
  644. ['--check-certificate', 'true'])
  645. self.assertEqual(
  646. cli_bool_option(
  647. {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
  648. ['--check-certificate=true'])
  649. if __name__ == '__main__':
  650. unittest.main()