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.

288 lines
11 KiB

  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. # Allow direct execution
  4. import os
  5. import sys
  6. import unittest
  7. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  8. # Various small unit tests
  9. import io
  10. import json
  11. import xml.etree.ElementTree
  12. #from youtube_dl.utils import htmlentity_transform
  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. if sys.version_info < (3, 0):
  40. _compat_str = lambda b: b.decode('unicode-escape')
  41. else:
  42. _compat_str = lambda s: s
  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 = _compat_str('\xe4')
  59. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  60. tests = _compat_str('\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 = _compat_str('a\xe4b\u4e2d\u56fd\u7684c')
  77. self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
  78. self.assertTrue(sanitize_filename(_compat_str('\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(_compat_str('\u5927\u58f0\u5e26 - Song'), restricted=True), 'Song')
  85. self.assertEqual(sanitize_filename(_compat_str('\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(_compat_str('%20;')), _compat_str('%20;'))
  101. def test_daterange(self):
  102. _20century = DateRange("19000101","20000101")
  103. self.assertFalse("17890714" in _20century)
  104. _ac = DateRange("00010101")
  105. self.assertTrue("19690721" in _ac)
  106. _firstmilenium = DateRange(end="10000101")
  107. self.assertTrue("07110427" in _firstmilenium)
  108. def test_unified_dates(self):
  109. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  110. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  111. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  112. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  113. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  114. def test_find_xpath_attr(self):
  115. testxml = u'''<root>
  116. <node/>
  117. <node x="a"/>
  118. <node x="a" y="c" />
  119. <node x="b" y="d" />
  120. </root>'''
  121. doc = xml.etree.ElementTree.fromstring(testxml)
  122. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  123. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  124. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  125. def test_meta_parser(self):
  126. testhtml = u'''
  127. <head>
  128. <meta name="description" content="foo &amp; bar">
  129. <meta content='Plato' name='author'/>
  130. </head>
  131. '''
  132. get_meta = lambda name: get_meta_content(name, testhtml)
  133. self.assertEqual(get_meta('description'), u'foo & bar')
  134. self.assertEqual(get_meta('author'), 'Plato')
  135. def test_xpath_with_ns(self):
  136. testxml = u'''<root xmlns:media="http://example.com/">
  137. <media:song>
  138. <media:author>The Author</media:author>
  139. <url>http://server.com/download.mp3</url>
  140. </media:song>
  141. </root>'''
  142. doc = xml.etree.ElementTree.fromstring(testxml)
  143. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  144. self.assertTrue(find('media:song') is not None)
  145. self.assertEqual(find('media:song/media:author').text, u'The Author')
  146. self.assertEqual(find('media:song/url').text, u'http://server.com/download.mp3')
  147. def test_smuggle_url(self):
  148. data = {u"ö": u"ö", u"abc": [3]}
  149. url = 'https://foo.bar/baz?x=y#a'
  150. smug_url = smuggle_url(url, data)
  151. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  152. self.assertEqual(url, unsmug_url)
  153. self.assertEqual(data, unsmug_data)
  154. res_url, res_data = unsmuggle_url(url)
  155. self.assertEqual(res_url, url)
  156. self.assertEqual(res_data, None)
  157. def test_shell_quote(self):
  158. args = ['ffmpeg', '-i', encodeFilename(u'ñ€ß\'.mp4')]
  159. self.assertEqual(shell_quote(args), u"""ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  160. def test_str_to_int(self):
  161. self.assertEqual(str_to_int('123,456'), 123456)
  162. self.assertEqual(str_to_int('123.456'), 123456)
  163. def test_url_basename(self):
  164. self.assertEqual(url_basename(u'http://foo.de/'), u'')
  165. self.assertEqual(url_basename(u'http://foo.de/bar/baz'), u'baz')
  166. self.assertEqual(url_basename(u'http://foo.de/bar/baz?x=y'), u'baz')
  167. self.assertEqual(url_basename(u'http://foo.de/bar/baz#x=y'), u'baz')
  168. self.assertEqual(url_basename(u'http://foo.de/bar/baz/'), u'baz')
  169. self.assertEqual(
  170. url_basename(u'http://media.w3.org/2010/05/sintel/trailer.mp4'),
  171. u'trailer.mp4')
  172. def test_parse_duration(self):
  173. self.assertEqual(parse_duration(None), None)
  174. self.assertEqual(parse_duration('1'), 1)
  175. self.assertEqual(parse_duration('1337:12'), 80232)
  176. self.assertEqual(parse_duration('9:12:43'), 33163)
  177. self.assertEqual(parse_duration('12:00'), 720)
  178. self.assertEqual(parse_duration('00:01:01'), 61)
  179. self.assertEqual(parse_duration('x:y'), None)
  180. self.assertEqual(parse_duration('3h11m53s'), 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. def test_fix_xml_ampersands(self):
  188. self.assertEqual(
  189. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  190. self.assertEqual(
  191. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  192. '"&amp;x=y&amp;wrong;&amp;z=a')
  193. self.assertEqual(
  194. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  195. '&amp;&apos;&gt;&lt;&quot;')
  196. self.assertEqual(
  197. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  198. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  199. def test_paged_list(self):
  200. def testPL(size, pagesize, sliceargs, expected):
  201. def get_page(pagenum):
  202. firstid = pagenum * pagesize
  203. upto = min(size, pagenum * pagesize + pagesize)
  204. for i in range(firstid, upto):
  205. yield i
  206. pl = PagedList(get_page, pagesize)
  207. got = pl.getslice(*sliceargs)
  208. self.assertEqual(got, expected)
  209. testPL(5, 2, (), [0, 1, 2, 3, 4])
  210. testPL(5, 2, (1,), [1, 2, 3, 4])
  211. testPL(5, 2, (2,), [2, 3, 4])
  212. testPL(5, 2, (4,), [4])
  213. testPL(5, 2, (0, 3), [0, 1, 2])
  214. testPL(5, 2, (1, 4), [1, 2, 3])
  215. testPL(5, 2, (2, 99), [2, 3, 4])
  216. testPL(5, 2, (20, 99), [])
  217. def test_struct_unpack(self):
  218. self.assertEqual(struct_unpack(u'!B', b'\x00'), (0,))
  219. def test_read_batch_urls(self):
  220. f = io.StringIO(u'''\xef\xbb\xbf foo
  221. bar\r
  222. baz
  223. # More after this line\r
  224. ; or after this
  225. bam''')
  226. self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam'])
  227. def test_urlencode_postdata(self):
  228. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  229. self.assertTrue(isinstance(data, bytes))
  230. def test_parse_iso8601(self):
  231. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  232. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  233. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  234. def test_strip_jsonp(self):
  235. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  236. d = json.loads(stripped)
  237. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  238. def test_uppercase_escpae(self):
  239. self.assertEqual(uppercase_escape(u''), u'')
  240. self.assertEqual(uppercase_escape(u'\\U0001d550'), u'𝕐')
  241. if __name__ == '__main__':
  242. unittest.main()