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.

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