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.

270 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. urlencode_postdata,
  33. xpath_with_ns,
  34. )
  35. if sys.version_info < (3, 0):
  36. _compat_str = lambda b: b.decode('unicode-escape')
  37. else:
  38. _compat_str = lambda s: s
  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 = _compat_str('\xe4')
  55. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  56. tests = _compat_str('\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 = _compat_str('a\xe4b\u4e2d\u56fd\u7684c')
  73. self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
  74. self.assertTrue(sanitize_filename(_compat_str('\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(_compat_str('\u5927\u58f0\u5e26 - Song'), restricted=True), 'Song')
  81. self.assertEqual(sanitize_filename(_compat_str('\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(_compat_str('%20;')), _compat_str('%20;'))
  97. def test_daterange(self):
  98. _20century = DateRange("19000101","20000101")
  99. self.assertFalse("17890714" in _20century)
  100. _ac = DateRange("00010101")
  101. self.assertTrue("19690721" in _ac)
  102. _firstmilenium = DateRange(end="10000101")
  103. self.assertTrue("07110427" in _firstmilenium)
  104. def test_unified_dates(self):
  105. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  106. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  107. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  108. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  109. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  110. def test_find_xpath_attr(self):
  111. testxml = u'''<root>
  112. <node/>
  113. <node x="a"/>
  114. <node x="a" y="c" />
  115. <node x="b" y="d" />
  116. </root>'''
  117. doc = xml.etree.ElementTree.fromstring(testxml)
  118. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  119. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  120. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  121. def test_meta_parser(self):
  122. testhtml = u'''
  123. <head>
  124. <meta name="description" content="foo &amp; bar">
  125. <meta content='Plato' name='author'/>
  126. </head>
  127. '''
  128. get_meta = lambda name: get_meta_content(name, testhtml)
  129. self.assertEqual(get_meta('description'), u'foo & bar')
  130. self.assertEqual(get_meta('author'), 'Plato')
  131. def test_xpath_with_ns(self):
  132. testxml = u'''<root xmlns:media="http://example.com/">
  133. <media:song>
  134. <media:author>The Author</media:author>
  135. <url>http://server.com/download.mp3</url>
  136. </media:song>
  137. </root>'''
  138. doc = xml.etree.ElementTree.fromstring(testxml)
  139. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  140. self.assertTrue(find('media:song') is not None)
  141. self.assertEqual(find('media:song/media:author').text, u'The Author')
  142. self.assertEqual(find('media:song/url').text, u'http://server.com/download.mp3')
  143. def test_smuggle_url(self):
  144. data = {u"ö": u"ö", u"abc": [3]}
  145. url = 'https://foo.bar/baz?x=y#a'
  146. smug_url = smuggle_url(url, data)
  147. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  148. self.assertEqual(url, unsmug_url)
  149. self.assertEqual(data, unsmug_data)
  150. res_url, res_data = unsmuggle_url(url)
  151. self.assertEqual(res_url, url)
  152. self.assertEqual(res_data, None)
  153. def test_shell_quote(self):
  154. args = ['ffmpeg', '-i', encodeFilename(u'ñ€ß\'.mp4')]
  155. self.assertEqual(shell_quote(args), u"""ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  156. def test_str_to_int(self):
  157. self.assertEqual(str_to_int('123,456'), 123456)
  158. self.assertEqual(str_to_int('123.456'), 123456)
  159. def test_url_basename(self):
  160. self.assertEqual(url_basename(u'http://foo.de/'), u'')
  161. self.assertEqual(url_basename(u'http://foo.de/bar/baz'), 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#x=y'), u'baz')
  164. self.assertEqual(url_basename(u'http://foo.de/bar/baz/'), u'baz')
  165. self.assertEqual(
  166. url_basename(u'http://media.w3.org/2010/05/sintel/trailer.mp4'),
  167. u'trailer.mp4')
  168. def test_parse_duration(self):
  169. self.assertEqual(parse_duration(None), None)
  170. self.assertEqual(parse_duration('1'), 1)
  171. self.assertEqual(parse_duration('1337:12'), 80232)
  172. self.assertEqual(parse_duration('9:12:43'), 33163)
  173. self.assertEqual(parse_duration('12:00'), 720)
  174. self.assertEqual(parse_duration('00:01:01'), 61)
  175. self.assertEqual(parse_duration('x:y'), None)
  176. self.assertEqual(parse_duration('3h11m53s'), 11513)
  177. self.assertEqual(parse_duration('62m45s'), 3765)
  178. self.assertEqual(parse_duration('6m59s'), 419)
  179. self.assertEqual(parse_duration('49s'), 49)
  180. self.assertEqual(parse_duration('0h0m0s'), 0)
  181. self.assertEqual(parse_duration('0m0s'), 0)
  182. self.assertEqual(parse_duration('0s'), 0)
  183. def test_fix_xml_ampersands(self):
  184. self.assertEqual(
  185. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  186. self.assertEqual(
  187. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  188. '"&amp;x=y&amp;wrong;&amp;z=a')
  189. self.assertEqual(
  190. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  191. '&amp;&apos;&gt;&lt;&quot;')
  192. self.assertEqual(
  193. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  194. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  195. def test_paged_list(self):
  196. def testPL(size, pagesize, sliceargs, expected):
  197. def get_page(pagenum):
  198. firstid = pagenum * pagesize
  199. upto = min(size, pagenum * pagesize + pagesize)
  200. for i in range(firstid, upto):
  201. yield i
  202. pl = PagedList(get_page, pagesize)
  203. got = pl.getslice(*sliceargs)
  204. self.assertEqual(got, expected)
  205. testPL(5, 2, (), [0, 1, 2, 3, 4])
  206. testPL(5, 2, (1,), [1, 2, 3, 4])
  207. testPL(5, 2, (2,), [2, 3, 4])
  208. testPL(5, 2, (4,), [4])
  209. testPL(5, 2, (0, 3), [0, 1, 2])
  210. testPL(5, 2, (1, 4), [1, 2, 3])
  211. testPL(5, 2, (2, 99), [2, 3, 4])
  212. testPL(5, 2, (20, 99), [])
  213. def test_struct_unpack(self):
  214. self.assertEqual(struct_unpack(u'!B', b'\x00'), (0,))
  215. def test_read_batch_urls(self):
  216. f = io.StringIO(u'''\xef\xbb\xbf foo
  217. bar\r
  218. baz
  219. # More after this line\r
  220. ; or after this
  221. bam''')
  222. self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam'])
  223. def test_urlencode_postdata(self):
  224. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  225. self.assertTrue(isinstance(data, bytes))
  226. if __name__ == '__main__':
  227. unittest.main()