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.

334 lines
14 KiB

  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. DateRange,
  15. encodeFilename,
  16. find_xpath_attr,
  17. fix_xml_ampersands,
  18. get_meta_content,
  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. )
  43. class TestUtil(unittest.TestCase):
  44. def test_timeconvert(self):
  45. self.assertTrue(timeconvert('') is None)
  46. self.assertTrue(timeconvert('bougrg') is None)
  47. def test_sanitize_filename(self):
  48. self.assertEqual(sanitize_filename('abc'), 'abc')
  49. self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
  50. self.assertEqual(sanitize_filename('123'), '123')
  51. self.assertEqual('abc_de', sanitize_filename('abc/de'))
  52. self.assertFalse('/' in sanitize_filename('abc/de///'))
  53. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
  54. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
  55. self.assertEqual('yes no', sanitize_filename('yes? no'))
  56. self.assertEqual('this - that', sanitize_filename('this: that'))
  57. self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
  58. aumlaut = 'ä'
  59. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  60. tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
  61. self.assertEqual(sanitize_filename(tests), tests)
  62. forbidden = '"\0\\/'
  63. for fc in forbidden:
  64. for fbc in forbidden:
  65. self.assertTrue(fbc not in sanitize_filename(fc))
  66. def test_sanitize_filename_restricted(self):
  67. self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
  68. self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
  69. self.assertEqual(sanitize_filename('123', restricted=True), '123')
  70. self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
  71. self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
  72. self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
  73. self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
  74. self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
  75. self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
  76. tests = 'a\xe4b\u4e2d\u56fd\u7684c'
  77. self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
  78. self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
  79. forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
  80. for fc in forbidden:
  81. for fbc in forbidden:
  82. self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
  83. # Handle a common case more neatly
  84. self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  85. self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
  86. # .. but make sure the file name is never empty
  87. self.assertTrue(sanitize_filename('-', restricted=True) != '')
  88. self.assertTrue(sanitize_filename(':', restricted=True) != '')
  89. def test_sanitize_ids(self):
  90. self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
  91. self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
  92. self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
  93. def test_ordered_set(self):
  94. self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
  95. self.assertEqual(orderedSet([]), [])
  96. self.assertEqual(orderedSet([1]), [1])
  97. #keep the list ordered
  98. self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
  99. def test_unescape_html(self):
  100. self.assertEqual(unescapeHTML('%20;'), '%20;')
  101. self.assertEqual(
  102. unescapeHTML('&eacute;'), 'é')
  103. def test_daterange(self):
  104. _20century = DateRange("19000101","20000101")
  105. self.assertFalse("17890714" in _20century)
  106. _ac = DateRange("00010101")
  107. self.assertTrue("19690721" in _ac)
  108. _firstmilenium = DateRange(end="10000101")
  109. self.assertTrue("07110427" in _firstmilenium)
  110. def test_unified_dates(self):
  111. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  112. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  113. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  114. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  115. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  116. def test_find_xpath_attr(self):
  117. testxml = '''<root>
  118. <node/>
  119. <node x="a"/>
  120. <node x="a" y="c" />
  121. <node x="b" y="d" />
  122. </root>'''
  123. doc = xml.etree.ElementTree.fromstring(testxml)
  124. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  125. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  126. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  127. def test_meta_parser(self):
  128. testhtml = '''
  129. <head>
  130. <meta name="description" content="foo &amp; bar">
  131. <meta content='Plato' name='author'/>
  132. </head>
  133. '''
  134. get_meta = lambda name: get_meta_content(name, testhtml)
  135. self.assertEqual(get_meta('description'), 'foo & bar')
  136. self.assertEqual(get_meta('author'), 'Plato')
  137. def test_xpath_with_ns(self):
  138. testxml = '''<root xmlns:media="http://example.com/">
  139. <media:song>
  140. <media:author>The Author</media:author>
  141. <url>http://server.com/download.mp3</url>
  142. </media:song>
  143. </root>'''
  144. doc = xml.etree.ElementTree.fromstring(testxml)
  145. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  146. self.assertTrue(find('media:song') is not None)
  147. self.assertEqual(find('media:song/media:author').text, 'The Author')
  148. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  149. def test_smuggle_url(self):
  150. data = {u"ö": u"ö", u"abc": [3]}
  151. url = 'https://foo.bar/baz?x=y#a'
  152. smug_url = smuggle_url(url, data)
  153. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  154. self.assertEqual(url, unsmug_url)
  155. self.assertEqual(data, unsmug_data)
  156. res_url, res_data = unsmuggle_url(url)
  157. self.assertEqual(res_url, url)
  158. self.assertEqual(res_data, None)
  159. def test_shell_quote(self):
  160. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  161. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  162. def test_str_to_int(self):
  163. self.assertEqual(str_to_int('123,456'), 123456)
  164. self.assertEqual(str_to_int('123.456'), 123456)
  165. def test_url_basename(self):
  166. self.assertEqual(url_basename('http://foo.de/'), '')
  167. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  168. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  169. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  170. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  171. self.assertEqual(
  172. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  173. 'trailer.mp4')
  174. def test_parse_duration(self):
  175. self.assertEqual(parse_duration(None), None)
  176. self.assertEqual(parse_duration('1'), 1)
  177. self.assertEqual(parse_duration('1337:12'), 80232)
  178. self.assertEqual(parse_duration('9:12:43'), 33163)
  179. self.assertEqual(parse_duration('12:00'), 720)
  180. self.assertEqual(parse_duration('00:01:01'), 61)
  181. self.assertEqual(parse_duration('x:y'), None)
  182. self.assertEqual(parse_duration('3h11m53s'), 11513)
  183. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  184. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  185. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  186. self.assertEqual(parse_duration('62m45s'), 3765)
  187. self.assertEqual(parse_duration('6m59s'), 419)
  188. self.assertEqual(parse_duration('49s'), 49)
  189. self.assertEqual(parse_duration('0h0m0s'), 0)
  190. self.assertEqual(parse_duration('0m0s'), 0)
  191. self.assertEqual(parse_duration('0s'), 0)
  192. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  193. def test_fix_xml_ampersands(self):
  194. self.assertEqual(
  195. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  196. self.assertEqual(
  197. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  198. '"&amp;x=y&amp;wrong;&amp;z=a')
  199. self.assertEqual(
  200. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  201. '&amp;&apos;&gt;&lt;&quot;')
  202. self.assertEqual(
  203. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  204. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  205. def test_paged_list(self):
  206. def testPL(size, pagesize, sliceargs, expected):
  207. def get_page(pagenum):
  208. firstid = pagenum * pagesize
  209. upto = min(size, pagenum * pagesize + pagesize)
  210. for i in range(firstid, upto):
  211. yield i
  212. pl = OnDemandPagedList(get_page, pagesize)
  213. got = pl.getslice(*sliceargs)
  214. self.assertEqual(got, expected)
  215. iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
  216. got = iapl.getslice(*sliceargs)
  217. self.assertEqual(got, expected)
  218. testPL(5, 2, (), [0, 1, 2, 3, 4])
  219. testPL(5, 2, (1,), [1, 2, 3, 4])
  220. testPL(5, 2, (2,), [2, 3, 4])
  221. testPL(5, 2, (4,), [4])
  222. testPL(5, 2, (0, 3), [0, 1, 2])
  223. testPL(5, 2, (1, 4), [1, 2, 3])
  224. testPL(5, 2, (2, 99), [2, 3, 4])
  225. testPL(5, 2, (20, 99), [])
  226. def test_struct_unpack(self):
  227. self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
  228. def test_read_batch_urls(self):
  229. f = io.StringIO('''\xef\xbb\xbf foo
  230. bar\r
  231. baz
  232. # More after this line\r
  233. ; or after this
  234. bam''')
  235. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  236. def test_urlencode_postdata(self):
  237. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  238. self.assertTrue(isinstance(data, bytes))
  239. def test_parse_iso8601(self):
  240. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  241. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  242. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  243. def test_strip_jsonp(self):
  244. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  245. d = json.loads(stripped)
  246. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  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. if __name__ == '__main__':
  284. unittest.main()