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.

414 lines
17 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. find_xpath_attr,
  23. fix_xml_ampersands,
  24. InAdvancePagedList,
  25. intlist_to_bytes,
  26. js_to_json,
  27. limit_length,
  28. OnDemandPagedList,
  29. orderedSet,
  30. parse_duration,
  31. parse_filesize,
  32. parse_iso8601,
  33. read_batch_urls,
  34. sanitize_filename,
  35. shell_quote,
  36. smuggle_url,
  37. str_to_int,
  38. strip_jsonp,
  39. struct_unpack,
  40. timeconvert,
  41. unescapeHTML,
  42. unified_strdate,
  43. unsmuggle_url,
  44. uppercase_escape,
  45. url_basename,
  46. urlencode_postdata,
  47. version_tuple,
  48. xpath_with_ns,
  49. )
  50. class TestUtil(unittest.TestCase):
  51. def test_timeconvert(self):
  52. self.assertTrue(timeconvert('') is None)
  53. self.assertTrue(timeconvert('bougrg') is None)
  54. def test_sanitize_filename(self):
  55. self.assertEqual(sanitize_filename('abc'), 'abc')
  56. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  57. self.assertEqual(sanitize_filename('123'), '123')
  58. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  59. self.assertFalse('/' in sanitize_filename('abc/de///'))
  60. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  61. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  62. self.assertEqual('yes no', sanitize_filename('yes? no'))
  63. self.assertEqual('this - that', sanitize_filename('this: that'))
  64. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  65. aumlaut = 'ä'
  66. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  67. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  68. self.assertEqual(sanitize_filename(tests), tests)
  69. forbidden = '"\0\\/'
  70. for fc in forbidden:
  71. for fbc in forbidden:
  72. self.assertTrue(fbc not in sanitize_filename(fc))
  73. def test_sanitize_filename_restricted(self):
  74. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  75. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  76. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  77. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  78. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  79. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  80. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  81. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  82. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  83. tests = 'a\xe4b\u4e2d\u56fd\u7684c'
  84. self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
  85. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  86. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  87. for fc in forbidden:
  88. for fbc in forbidden:
  89. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  90. # Handle a common case more neatly
  91. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  92. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  93. # .. but make sure the file name is never empty
  94. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  95. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  96. def test_sanitize_ids(self):
  97. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  98. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  99. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  100. def test_ordered_set(self):
  101. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  102. self.assertEqual(orderedSet([]), [])
  103. self.assertEqual(orderedSet([1]), [1])
  104. # keep the list ordered
  105. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  106. def test_unescape_html(self):
  107. self.assertEqual(unescapeHTML('%20;'), '%20;')
  108. self.assertEqual(
  109. unescapeHTML('&eacute;'), 'é')
  110. def test_daterange(self):
  111. _20century = DateRange("19000101", "20000101")
  112. self.assertFalse("17890714" in _20century)
  113. _ac = DateRange("00010101")
  114. self.assertTrue("19690721" in _ac)
  115. _firstmilenium = DateRange(end="10000101")
  116. self.assertTrue("07110427" in _firstmilenium)
  117. def test_unified_dates(self):
  118. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  119. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  120. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  121. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  122. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  123. self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
  124. self.assertEqual(
  125. unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
  126. '20141126')
  127. def test_find_xpath_attr(self):
  128. testxml = '''<root>
  129. <node/>
  130. <node x="a"/>
  131. <node x="a" y="c" />
  132. <node x="b" y="d" />
  133. </root>'''
  134. doc = xml.etree.ElementTree.fromstring(testxml)
  135. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  136. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  137. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  138. def test_xpath_with_ns(self):
  139. testxml = '''<root xmlns:media="http://example.com/">
  140. <media:song>
  141. <media:author>The Author</media:author>
  142. <url>http://server.com/download.mp3</url>
  143. </media:song>
  144. </root>'''
  145. doc = xml.etree.ElementTree.fromstring(testxml)
  146. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  147. self.assertTrue(find('media:song') is not None)
  148. self.assertEqual(find('media:song/media:author').text, 'The Author')
  149. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  150. def test_smuggle_url(self):
  151. data = {"ö": "ö", "abc": [3]}
  152. url = 'https://foo.bar/baz?x=y#a'
  153. smug_url = smuggle_url(url, data)
  154. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  155. self.assertEqual(url, unsmug_url)
  156. self.assertEqual(data, unsmug_data)
  157. res_url, res_data = unsmuggle_url(url)
  158. self.assertEqual(res_url, url)
  159. self.assertEqual(res_data, None)
  160. def test_shell_quote(self):
  161. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  162. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  163. def test_str_to_int(self):
  164. self.assertEqual(str_to_int('123,456'), 123456)
  165. self.assertEqual(str_to_int('123.456'), 123456)
  166. def test_url_basename(self):
  167. self.assertEqual(url_basename('http://foo.de/'), '')
  168. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  169. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  170. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  171. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  172. self.assertEqual(
  173. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  174. 'trailer.mp4')
  175. def test_parse_duration(self):
  176. self.assertEqual(parse_duration(None), None)
  177. self.assertEqual(parse_duration('1'), 1)
  178. self.assertEqual(parse_duration('1337:12'), 80232)
  179. self.assertEqual(parse_duration('9:12:43'), 33163)
  180. self.assertEqual(parse_duration('12:00'), 720)
  181. self.assertEqual(parse_duration('00:01:01'), 61)
  182. self.assertEqual(parse_duration('x:y'), None)
  183. self.assertEqual(parse_duration('3h11m53s'), 11513)
  184. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  185. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  186. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  187. self.assertEqual(parse_duration('62m45s'), 3765)
  188. self.assertEqual(parse_duration('6m59s'), 419)
  189. self.assertEqual(parse_duration('49s'), 49)
  190. self.assertEqual(parse_duration('0h0m0s'), 0)
  191. self.assertEqual(parse_duration('0m0s'), 0)
  192. self.assertEqual(parse_duration('0s'), 0)
  193. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  194. self.assertEqual(parse_duration('T30M38S'), 1838)
  195. self.assertEqual(parse_duration('5 s'), 5)
  196. self.assertEqual(parse_duration('3 min'), 180)
  197. self.assertEqual(parse_duration('2.5 hours'), 9000)
  198. def test_fix_xml_ampersands(self):
  199. self.assertEqual(
  200. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  201. self.assertEqual(
  202. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  203. '"&amp;x=y&amp;wrong;&amp;z=a')
  204. self.assertEqual(
  205. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  206. '&amp;&apos;&gt;&lt;&quot;')
  207. self.assertEqual(
  208. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  209. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  210. def test_paged_list(self):
  211. def testPL(size, pagesize, sliceargs, expected):
  212. def get_page(pagenum):
  213. firstid = pagenum * pagesize
  214. upto = min(size, pagenum * pagesize + pagesize)
  215. for i in range(firstid, upto):
  216. yield i
  217. pl = OnDemandPagedList(get_page, pagesize)
  218. got = pl.getslice(*sliceargs)
  219. self.assertEqual(got, expected)
  220. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  221. got = iapl.getslice(*sliceargs)
  222. self.assertEqual(got, expected)
  223. testPL(5, 2, (), [0, 1, 2, 3, 4])
  224. testPL(5, 2, (1,), [1, 2, 3, 4])
  225. testPL(5, 2, (2,), [2, 3, 4])
  226. testPL(5, 2, (4,), [4])
  227. testPL(5, 2, (0, 3), [0, 1, 2])
  228. testPL(5, 2, (1, 4), [1, 2, 3])
  229. testPL(5, 2, (2, 99), [2, 3, 4])
  230. testPL(5, 2, (20, 99), [])
  231. def test_struct_unpack(self):
  232. self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
  233. def test_read_batch_urls(self):
  234. f = io.StringIO('''\xef\xbb\xbf foo
  235. bar\r
  236. baz
  237. # More after this line\r
  238. ; or after this
  239. bam''')
  240. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  241. def test_urlencode_postdata(self):
  242. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  243. self.assertTrue(isinstance(data, bytes))
  244. def test_parse_iso8601(self):
  245. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  246. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  247. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  248. self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
  249. def test_strip_jsonp(self):
  250. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  251. d = json.loads(stripped)
  252. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  253. stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
  254. d = json.loads(stripped)
  255. self.assertEqual(d, {'STATUS': 'OK'})
  256. def test_uppercase_escape(self):
  257. self.assertEqual(uppercase_escape(''), '')
  258. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  259. def test_limit_length(self):
  260. self.assertEqual(limit_length(None, 12), None)
  261. self.assertEqual(limit_length('foo', 12), 'foo')
  262. self.assertTrue(
  263. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  264. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  265. def test_escape_rfc3986(self):
  266. reserved = "!*'();:@&=+$,/?#[]"
  267. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  268. self.assertEqual(escape_rfc3986(reserved), reserved)
  269. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  270. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  271. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  272. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  273. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  274. def test_escape_url(self):
  275. self.assertEqual(
  276. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  277. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  278. )
  279. self.assertEqual(
  280. 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'),
  281. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  282. )
  283. self.assertEqual(
  284. escape_url('http://тест.рф/фрагмент'),
  285. 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  286. )
  287. self.assertEqual(
  288. escape_url('http://тест.рф/абв?абв=абв#абв'),
  289. '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'
  290. )
  291. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  292. def test_js_to_json_realworld(self):
  293. inp = '''{
  294. 'clip':{'provider':'pseudo'}
  295. }'''
  296. self.assertEqual(js_to_json(inp), '''{
  297. "clip":{"provider":"pseudo"}
  298. }''')
  299. json.loads(js_to_json(inp))
  300. inp = '''{
  301. 'playlist':[{'controls':{'all':null}}]
  302. }'''
  303. self.assertEqual(js_to_json(inp), '''{
  304. "playlist":[{"controls":{"all":null}}]
  305. }''')
  306. def test_js_to_json_edgecases(self):
  307. on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
  308. self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
  309. on = js_to_json('{"abc": true}')
  310. self.assertEqual(json.loads(on), {'abc': True})
  311. def test_clean_html(self):
  312. self.assertEqual(clean_html('a:\nb'), 'a: b')
  313. self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
  314. def test_intlist_to_bytes(self):
  315. self.assertEqual(
  316. intlist_to_bytes([0, 1, 127, 128, 255]),
  317. b'\x00\x01\x7f\x80\xff')
  318. def test_args_to_str(self):
  319. self.assertEqual(
  320. args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
  321. 'foo ba/r -baz \'2 be\' \'\''
  322. )
  323. def test_parse_filesize(self):
  324. self.assertEqual(parse_filesize(None), None)
  325. self.assertEqual(parse_filesize(''), None)
  326. self.assertEqual(parse_filesize('91 B'), 91)
  327. self.assertEqual(parse_filesize('foobar'), None)
  328. self.assertEqual(parse_filesize('2 MiB'), 2097152)
  329. self.assertEqual(parse_filesize('5 GB'), 5000000000)
  330. self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
  331. self.assertEqual(parse_filesize('1,24 KB'), 1240)
  332. def test_version_tuple(self):
  333. self.assertEqual(version_tuple('1'), (1,))
  334. self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
  335. self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
  336. def test_detect_exe_version(self):
  337. self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
  338. built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
  339. configuration: --prefix=/usr --extra-'''), '1.2.1')
  340. self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
  341. built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
  342. self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
  343. Trying to open render node...
  344. Success at /dev/dri/renderD128.
  345. ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
  346. def test_age_restricted(self):
  347. self.assertFalse(age_restricted(None, 10)) # unrestricted content
  348. self.assertFalse(age_restricted(1, None)) # unrestricted policy
  349. self.assertFalse(age_restricted(8, 10))
  350. self.assertTrue(age_restricted(18, 14))
  351. self.assertFalse(age_restricted(18, 18))
  352. if __name__ == '__main__':
  353. unittest.main()