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.

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