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.

329 lines
13 KiB

  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import unicode_literals
  4. # Allow direct execution
  5. import os
  6. import sys
  7. import unittest
  8. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  9. # Various small unit tests
  10. import io
  11. import json
  12. import xml.etree.ElementTree
  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. limit_length,
  39. escape_rfc3986,
  40. escape_url,
  41. )
  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 = 'ä'
  58. self.assertEqual(sanitize_filename(aumlaut), aumlaut)
  59. tests = '\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 = 'a\xe4b\u4e2d\u56fd\u7684c'
  76. self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
  77. self.assertTrue(sanitize_filename('\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('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
  84. self.assertEqual(sanitize_filename('\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('%20;'), '%20;')
  100. self.assertEqual(
  101. unescapeHTML('&eacute;'), 'é')
  102. def test_daterange(self):
  103. _20century = DateRange("19000101","20000101")
  104. self.assertFalse("17890714" in _20century)
  105. _ac = DateRange("00010101")
  106. self.assertTrue("19690721" in _ac)
  107. _firstmilenium = DateRange(end="10000101")
  108. self.assertTrue("07110427" in _firstmilenium)
  109. def test_unified_dates(self):
  110. self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
  111. self.assertEqual(unified_strdate('8/7/2009'), '20090708')
  112. self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
  113. self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
  114. self.assertEqual(unified_strdate('1968-12-10'), '19681210')
  115. def test_find_xpath_attr(self):
  116. testxml = '''<root>
  117. <node/>
  118. <node x="a"/>
  119. <node x="a" y="c" />
  120. <node x="b" y="d" />
  121. </root>'''
  122. doc = xml.etree.ElementTree.fromstring(testxml)
  123. self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
  124. self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
  125. self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
  126. def test_meta_parser(self):
  127. testhtml = '''
  128. <head>
  129. <meta name="description" content="foo &amp; bar">
  130. <meta content='Plato' name='author'/>
  131. </head>
  132. '''
  133. get_meta = lambda name: get_meta_content(name, testhtml)
  134. self.assertEqual(get_meta('description'), 'foo & bar')
  135. self.assertEqual(get_meta('author'), 'Plato')
  136. def test_xpath_with_ns(self):
  137. testxml = '''<root xmlns:media="http://example.com/">
  138. <media:song>
  139. <media:author>The Author</media:author>
  140. <url>http://server.com/download.mp3</url>
  141. </media:song>
  142. </root>'''
  143. doc = xml.etree.ElementTree.fromstring(testxml)
  144. find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
  145. self.assertTrue(find('media:song') is not None)
  146. self.assertEqual(find('media:song/media:author').text, 'The Author')
  147. self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
  148. def test_smuggle_url(self):
  149. data = {u"ö": u"ö", u"abc": [3]}
  150. url = 'https://foo.bar/baz?x=y#a'
  151. smug_url = smuggle_url(url, data)
  152. unsmug_url, unsmug_data = unsmuggle_url(smug_url)
  153. self.assertEqual(url, unsmug_url)
  154. self.assertEqual(data, unsmug_data)
  155. res_url, res_data = unsmuggle_url(url)
  156. self.assertEqual(res_url, url)
  157. self.assertEqual(res_data, None)
  158. def test_shell_quote(self):
  159. args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
  160. self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
  161. def test_str_to_int(self):
  162. self.assertEqual(str_to_int('123,456'), 123456)
  163. self.assertEqual(str_to_int('123.456'), 123456)
  164. def test_url_basename(self):
  165. self.assertEqual(url_basename('http://foo.de/'), '')
  166. self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
  167. self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
  168. self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
  169. self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
  170. self.assertEqual(
  171. url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
  172. 'trailer.mp4')
  173. def test_parse_duration(self):
  174. self.assertEqual(parse_duration(None), None)
  175. self.assertEqual(parse_duration('1'), 1)
  176. self.assertEqual(parse_duration('1337:12'), 80232)
  177. self.assertEqual(parse_duration('9:12:43'), 33163)
  178. self.assertEqual(parse_duration('12:00'), 720)
  179. self.assertEqual(parse_duration('00:01:01'), 61)
  180. self.assertEqual(parse_duration('x:y'), None)
  181. self.assertEqual(parse_duration('3h11m53s'), 11513)
  182. self.assertEqual(parse_duration('3h 11m 53s'), 11513)
  183. self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
  184. self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
  185. self.assertEqual(parse_duration('62m45s'), 3765)
  186. self.assertEqual(parse_duration('6m59s'), 419)
  187. self.assertEqual(parse_duration('49s'), 49)
  188. self.assertEqual(parse_duration('0h0m0s'), 0)
  189. self.assertEqual(parse_duration('0m0s'), 0)
  190. self.assertEqual(parse_duration('0s'), 0)
  191. self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
  192. def test_fix_xml_ampersands(self):
  193. self.assertEqual(
  194. fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
  195. self.assertEqual(
  196. fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
  197. '"&amp;x=y&amp;wrong;&amp;z=a')
  198. self.assertEqual(
  199. fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
  200. '&amp;&apos;&gt;&lt;&quot;')
  201. self.assertEqual(
  202. fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
  203. self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
  204. def test_paged_list(self):
  205. def testPL(size, pagesize, sliceargs, expected):
  206. def get_page(pagenum):
  207. firstid = pagenum * pagesize
  208. upto = min(size, pagenum * pagesize + pagesize)
  209. for i in range(firstid, upto):
  210. yield i
  211. pl = PagedList(get_page, pagesize)
  212. got = pl.getslice(*sliceargs)
  213. self.assertEqual(got, expected)
  214. testPL(5, 2, (), [0, 1, 2, 3, 4])
  215. testPL(5, 2, (1,), [1, 2, 3, 4])
  216. testPL(5, 2, (2,), [2, 3, 4])
  217. testPL(5, 2, (4,), [4])
  218. testPL(5, 2, (0, 3), [0, 1, 2])
  219. testPL(5, 2, (1, 4), [1, 2, 3])
  220. testPL(5, 2, (2, 99), [2, 3, 4])
  221. testPL(5, 2, (20, 99), [])
  222. def test_struct_unpack(self):
  223. self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
  224. def test_read_batch_urls(self):
  225. f = io.StringIO('''\xef\xbb\xbf foo
  226. bar\r
  227. baz
  228. # More after this line\r
  229. ; or after this
  230. bam''')
  231. self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
  232. def test_urlencode_postdata(self):
  233. data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
  234. self.assertTrue(isinstance(data, bytes))
  235. def test_parse_iso8601(self):
  236. self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
  237. self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
  238. self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
  239. def test_strip_jsonp(self):
  240. stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
  241. d = json.loads(stripped)
  242. self.assertEqual(d, [{"id": "532cb", "x": 3}])
  243. def test_uppercase_escape(self):
  244. self.assertEqual(uppercase_escape(''), '')
  245. self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
  246. def test_limit_length(self):
  247. self.assertEqual(limit_length(None, 12), None)
  248. self.assertEqual(limit_length('foo', 12), 'foo')
  249. self.assertTrue(
  250. limit_length('foo bar baz asd', 12).startswith('foo bar'))
  251. self.assertTrue('...' in limit_length('foo bar baz asd', 12))
  252. def test_escape_rfc3986(self):
  253. reserved = "!*'();:@&=+$,/?#[]"
  254. unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
  255. self.assertEqual(escape_rfc3986(reserved), reserved)
  256. self.assertEqual(escape_rfc3986(unreserved), unreserved)
  257. self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
  258. self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
  259. self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
  260. self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
  261. def test_escape_url(self):
  262. self.assertEqual(
  263. escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
  264. 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
  265. )
  266. self.assertEqual(
  267. escape_url('http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erklärt/Das-Erste/Video?documentId=22673108&bcastId=5290'),
  268. 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
  269. )
  270. self.assertEqual(
  271. escape_url('http://тест.рф/фрагмент'),
  272. 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
  273. )
  274. self.assertEqual(
  275. escape_url('http://тест.рф/абв?абв=абв#абв'),
  276. 'http://тест.рф/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
  277. )
  278. self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
  279. if __name__ == '__main__':
  280. unittest.main()