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.

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