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.

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