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.

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