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.

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