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.

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