4 from __future__ import unicode_literals
6 # Allow direct execution
10 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
13 # Various small unit tests
16 import xml.etree.ElementTree
18 from youtube_dl.utils import (
48 get_filesystem_encoding,
54 class TestUtil(unittest.TestCase):
55 def test_timeconvert(self):
56 self.assertTrue(timeconvert('') is None)
57 self.assertTrue(timeconvert('bougrg') is None)
59 def test_sanitize_filename(self):
60 self.assertEqual(sanitize_filename('abc'), 'abc')
61 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
63 self.assertEqual(sanitize_filename('123'), '123')
65 self.assertEqual('abc_de', sanitize_filename('abc/de'))
66 self.assertFalse('/' in sanitize_filename('abc/de///'))
68 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
69 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
70 self.assertEqual('yes no', sanitize_filename('yes? no'))
71 self.assertEqual('this - that', sanitize_filename('this: that'))
73 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
75 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
76 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
77 self.assertEqual(sanitize_filename(tests), tests)
82 self.assertTrue(fbc not in sanitize_filename(fc))
84 def test_sanitize_filename_restricted(self):
85 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
86 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
88 self.assertEqual(sanitize_filename('123', restricted=True), '123')
90 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
91 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
93 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
94 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
95 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
96 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
98 tests = 'a\xe4b\u4e2d\u56fd\u7684c'
99 self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
100 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
102 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
104 for fbc in forbidden:
105 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
107 # Handle a common case more neatly
108 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
109 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
110 # .. but make sure the file name is never empty
111 self.assertTrue(sanitize_filename('-', restricted=True) != '')
112 self.assertTrue(sanitize_filename(':', restricted=True) != '')
114 def test_sanitize_ids(self):
115 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
116 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
117 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
119 def test_ordered_set(self):
120 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
121 self.assertEqual(orderedSet([]), [])
122 self.assertEqual(orderedSet([1]), [1])
123 #keep the list ordered
124 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
126 def test_unescape_html(self):
127 self.assertEqual(unescapeHTML('%20;'), '%20;')
129 unescapeHTML('é'), 'é')
131 def test_daterange(self):
132 _20century = DateRange("19000101","20000101")
133 self.assertFalse("17890714" in _20century)
134 _ac = DateRange("00010101")
135 self.assertTrue("19690721" in _ac)
136 _firstmilenium = DateRange(end="10000101")
137 self.assertTrue("07110427" in _firstmilenium)
139 def test_unified_dates(self):
140 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
141 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
142 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
143 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
144 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
145 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
147 def test_find_xpath_attr(self):
154 doc = xml.etree.ElementTree.fromstring(testxml)
156 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
157 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
158 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
160 def test_meta_parser(self):
163 <meta name="description" content="foo & bar">
164 <meta content='Plato' name='author'/>
167 get_meta = lambda name: get_meta_content(name, testhtml)
168 self.assertEqual(get_meta('description'), 'foo & bar')
169 self.assertEqual(get_meta('author'), 'Plato')
171 def test_xpath_with_ns(self):
172 testxml = '''<root xmlns:media="http://example.com/">
174 <media:author>The Author</media:author>
175 <url>http://server.com/download.mp3</url>
178 doc = xml.etree.ElementTree.fromstring(testxml)
179 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
180 self.assertTrue(find('media:song') is not None)
181 self.assertEqual(find('media:song/media:author').text, 'The Author')
182 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
184 def test_smuggle_url(self):
185 data = {u"ö": u"ö", u"abc": [3]}
186 url = 'https://foo.bar/baz?x=y#a'
187 smug_url = smuggle_url(url, data)
188 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
189 self.assertEqual(url, unsmug_url)
190 self.assertEqual(data, unsmug_data)
192 res_url, res_data = unsmuggle_url(url)
193 self.assertEqual(res_url, url)
194 self.assertEqual(res_data, None)
196 def test_shell_quote(self):
197 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
198 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
200 def test_str_to_int(self):
201 self.assertEqual(str_to_int('123,456'), 123456)
202 self.assertEqual(str_to_int('123.456'), 123456)
204 def test_url_basename(self):
205 self.assertEqual(url_basename('http://foo.de/'), '')
206 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
207 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
208 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
209 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
211 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
214 def test_parse_duration(self):
215 self.assertEqual(parse_duration(None), None)
216 self.assertEqual(parse_duration('1'), 1)
217 self.assertEqual(parse_duration('1337:12'), 80232)
218 self.assertEqual(parse_duration('9:12:43'), 33163)
219 self.assertEqual(parse_duration('12:00'), 720)
220 self.assertEqual(parse_duration('00:01:01'), 61)
221 self.assertEqual(parse_duration('x:y'), None)
222 self.assertEqual(parse_duration('3h11m53s'), 11513)
223 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
224 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
225 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
226 self.assertEqual(parse_duration('62m45s'), 3765)
227 self.assertEqual(parse_duration('6m59s'), 419)
228 self.assertEqual(parse_duration('49s'), 49)
229 self.assertEqual(parse_duration('0h0m0s'), 0)
230 self.assertEqual(parse_duration('0m0s'), 0)
231 self.assertEqual(parse_duration('0s'), 0)
232 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
234 def test_fix_xml_ampersands(self):
236 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
238 fix_xml_ampersands('"&x=y&wrong;&z=a'),
239 '"&x=y&wrong;&z=a')
241 fix_xml_ampersands('&'><"'),
242 '&'><"')
244 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
245 self.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
247 def test_paged_list(self):
248 def testPL(size, pagesize, sliceargs, expected):
249 def get_page(pagenum):
250 firstid = pagenum * pagesize
251 upto = min(size, pagenum * pagesize + pagesize)
252 for i in range(firstid, upto):
255 pl = OnDemandPagedList(get_page, pagesize)
256 got = pl.getslice(*sliceargs)
257 self.assertEqual(got, expected)
259 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
260 got = iapl.getslice(*sliceargs)
261 self.assertEqual(got, expected)
263 testPL(5, 2, (), [0, 1, 2, 3, 4])
264 testPL(5, 2, (1,), [1, 2, 3, 4])
265 testPL(5, 2, (2,), [2, 3, 4])
266 testPL(5, 2, (4,), [4])
267 testPL(5, 2, (0, 3), [0, 1, 2])
268 testPL(5, 2, (1, 4), [1, 2, 3])
269 testPL(5, 2, (2, 99), [2, 3, 4])
270 testPL(5, 2, (20, 99), [])
272 def test_struct_unpack(self):
273 self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
275 def test_read_batch_urls(self):
276 f = io.StringIO('''\xef\xbb\xbf foo
279 # More after this line\r
282 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
284 def test_urlencode_postdata(self):
285 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
286 self.assertTrue(isinstance(data, bytes))
288 def test_parse_iso8601(self):
289 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
290 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
291 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
293 def test_strip_jsonp(self):
294 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
295 d = json.loads(stripped)
296 self.assertEqual(d, [{"id": "532cb", "x": 3}])
298 def test_uppercase_escape(self):
299 self.assertEqual(uppercase_escape('aä'), 'aä')
300 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
302 def test_limit_length(self):
303 self.assertEqual(limit_length(None, 12), None)
304 self.assertEqual(limit_length('foo', 12), 'foo')
306 limit_length('foo bar baz asd', 12).startswith('foo bar'))
307 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
309 def test_escape_rfc3986(self):
310 reserved = "!*'();:@&=+$,/?#[]"
311 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
312 self.assertEqual(escape_rfc3986(reserved), reserved)
313 self.assertEqual(escape_rfc3986(unreserved), unreserved)
314 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
315 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
316 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
317 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
319 def test_escape_url(self):
321 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
322 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
325 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'),
326 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
329 escape_url('http://тест.рф/фрагмент'),
330 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
333 escape_url('http://тест.рф/абв?абв=абв#абв'),
334 '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'
336 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
338 def test_js_to_json_realworld(self):
340 'clip':{'provider':'pseudo'}
342 self.assertEqual(js_to_json(inp), '''{
343 "clip":{"provider":"pseudo"}
345 json.loads(js_to_json(inp))
348 'playlist':[{'controls':{'all':null}}]
350 self.assertEqual(js_to_json(inp), '''{
351 "playlist":[{"controls":{"all":null}}]
354 def test_js_to_json_edgecases(self):
355 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
356 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
358 on = js_to_json('{"abc": true}')
359 self.assertEqual(json.loads(on), {'abc': True})
361 def test_compat_getenv(self):
363 os.environ['YOUTUBE-DL-TEST'] = (test_str if sys.version_info >= (3, 0)
364 else test_str.encode(get_filesystem_encoding()))
365 self.assertEqual(compat_getenv('YOUTUBE-DL-TEST'), test_str)
367 def test_compat_expanduser(self):
368 test_str = 'C:\Documents and Settings\тест\Application Data'
369 os.environ['HOME'] = (test_str if sys.version_info >= (3, 0)
370 else test_str.encode(get_filesystem_encoding()))
371 self.assertEqual(compat_expanduser('~'), test_str)
373 if __name__ == '__main__':