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.

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