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.

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