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 (
57 url_sanitize_consecutive_slashes,
61 class TestUtil(unittest.TestCase):
62 def test_timeconvert(self):
63 self.assertTrue(timeconvert('') is None)
64 self.assertTrue(timeconvert('bougrg') is None)
66 def test_sanitize_filename(self):
67 self.assertEqual(sanitize_filename('abc'), 'abc')
68 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
70 self.assertEqual(sanitize_filename('123'), '123')
72 self.assertEqual('abc_de', sanitize_filename('abc/de'))
73 self.assertFalse('/' in sanitize_filename('abc/de///'))
75 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
76 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
77 self.assertEqual('yes no', sanitize_filename('yes? no'))
78 self.assertEqual('this - that', sanitize_filename('this: that'))
80 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
82 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
83 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
84 self.assertEqual(sanitize_filename(tests), tests)
87 sanitize_filename('New World record at 0:12:34'),
88 'New World record at 0_12_34')
90 self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
91 self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
92 self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
93 self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
98 self.assertTrue(fbc not in sanitize_filename(fc))
100 def test_sanitize_filename_restricted(self):
101 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
102 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
104 self.assertEqual(sanitize_filename('123', restricted=True), '123')
106 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
107 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
109 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
110 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
111 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
112 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
114 tests = 'a\xe4b\u4e2d\u56fd\u7684c'
115 self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
116 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
118 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
120 for fbc in forbidden:
121 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
123 # Handle a common case more neatly
124 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
125 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
126 # .. but make sure the file name is never empty
127 self.assertTrue(sanitize_filename('-', restricted=True) != '')
128 self.assertTrue(sanitize_filename(':', restricted=True) != '')
130 def test_sanitize_ids(self):
131 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
132 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
133 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
135 def test_ordered_set(self):
136 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
137 self.assertEqual(orderedSet([]), [])
138 self.assertEqual(orderedSet([1]), [1])
139 # keep the list ordered
140 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
142 def test_unescape_html(self):
143 self.assertEqual(unescapeHTML('%20;'), '%20;')
145 unescapeHTML('é'), 'é')
147 def test_daterange(self):
148 _20century = DateRange("19000101", "20000101")
149 self.assertFalse("17890714" in _20century)
150 _ac = DateRange("00010101")
151 self.assertTrue("19690721" in _ac)
152 _firstmilenium = DateRange(end="10000101")
153 self.assertTrue("07110427" in _firstmilenium)
155 def test_unified_dates(self):
156 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
157 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
158 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
159 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
160 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
161 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
162 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
164 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
167 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
170 def test_find_xpath_attr(self):
177 doc = xml.etree.ElementTree.fromstring(testxml)
179 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
180 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
181 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
183 def test_xpath_with_ns(self):
184 testxml = '''<root xmlns:media="http://example.com/">
186 <media:author>The Author</media:author>
187 <url>http://server.com/download.mp3</url>
190 doc = xml.etree.ElementTree.fromstring(testxml)
191 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
192 self.assertTrue(find('media:song') is not None)
193 self.assertEqual(find('media:song/media:author').text, 'The Author')
194 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
196 def test_smuggle_url(self):
197 data = {"ö": "ö", "abc": [3]}
198 url = 'https://foo.bar/baz?x=y#a'
199 smug_url = smuggle_url(url, data)
200 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
201 self.assertEqual(url, unsmug_url)
202 self.assertEqual(data, unsmug_data)
204 res_url, res_data = unsmuggle_url(url)
205 self.assertEqual(res_url, url)
206 self.assertEqual(res_data, None)
208 def test_shell_quote(self):
209 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
210 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
212 def test_str_to_int(self):
213 self.assertEqual(str_to_int('123,456'), 123456)
214 self.assertEqual(str_to_int('123.456'), 123456)
216 def test_url_basename(self):
217 self.assertEqual(url_basename('http://foo.de/'), '')
218 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
219 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
220 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
221 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
223 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
226 def test_parse_duration(self):
227 self.assertEqual(parse_duration(None), None)
228 self.assertEqual(parse_duration(False), None)
229 self.assertEqual(parse_duration('invalid'), None)
230 self.assertEqual(parse_duration('1'), 1)
231 self.assertEqual(parse_duration('1337:12'), 80232)
232 self.assertEqual(parse_duration('9:12:43'), 33163)
233 self.assertEqual(parse_duration('12:00'), 720)
234 self.assertEqual(parse_duration('00:01:01'), 61)
235 self.assertEqual(parse_duration('x:y'), None)
236 self.assertEqual(parse_duration('3h11m53s'), 11513)
237 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
238 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
239 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
240 self.assertEqual(parse_duration('62m45s'), 3765)
241 self.assertEqual(parse_duration('6m59s'), 419)
242 self.assertEqual(parse_duration('49s'), 49)
243 self.assertEqual(parse_duration('0h0m0s'), 0)
244 self.assertEqual(parse_duration('0m0s'), 0)
245 self.assertEqual(parse_duration('0s'), 0)
246 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
247 self.assertEqual(parse_duration('T30M38S'), 1838)
248 self.assertEqual(parse_duration('5 s'), 5)
249 self.assertEqual(parse_duration('3 min'), 180)
250 self.assertEqual(parse_duration('2.5 hours'), 9000)
251 self.assertEqual(parse_duration('02:03:04'), 7384)
252 self.assertEqual(parse_duration('01:02:03:04'), 93784)
253 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
255 def test_fix_xml_ampersands(self):
257 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
259 fix_xml_ampersands('"&x=y&wrong;&z=a'),
260 '"&x=y&wrong;&z=a')
262 fix_xml_ampersands('&'><"'),
263 '&'><"')
265 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
266 self.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
268 def test_paged_list(self):
269 def testPL(size, pagesize, sliceargs, expected):
270 def get_page(pagenum):
271 firstid = pagenum * pagesize
272 upto = min(size, pagenum * pagesize + pagesize)
273 for i in range(firstid, upto):
276 pl = OnDemandPagedList(get_page, pagesize)
277 got = pl.getslice(*sliceargs)
278 self.assertEqual(got, expected)
280 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
281 got = iapl.getslice(*sliceargs)
282 self.assertEqual(got, expected)
284 testPL(5, 2, (), [0, 1, 2, 3, 4])
285 testPL(5, 2, (1,), [1, 2, 3, 4])
286 testPL(5, 2, (2,), [2, 3, 4])
287 testPL(5, 2, (4,), [4])
288 testPL(5, 2, (0, 3), [0, 1, 2])
289 testPL(5, 2, (1, 4), [1, 2, 3])
290 testPL(5, 2, (2, 99), [2, 3, 4])
291 testPL(5, 2, (20, 99), [])
293 def test_struct_unpack(self):
294 self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
296 def test_read_batch_urls(self):
297 f = io.StringIO('''\xef\xbb\xbf foo
300 # More after this line\r
303 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
305 def test_urlencode_postdata(self):
306 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
307 self.assertTrue(isinstance(data, bytes))
309 def test_parse_iso8601(self):
310 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
311 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
312 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
313 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
315 def test_strip_jsonp(self):
316 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
317 d = json.loads(stripped)
318 self.assertEqual(d, [{"id": "532cb", "x": 3}])
320 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
321 d = json.loads(stripped)
322 self.assertEqual(d, {'STATUS': 'OK'})
324 def test_uppercase_escape(self):
325 self.assertEqual(uppercase_escape('aä'), 'aä')
326 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
328 def test_limit_length(self):
329 self.assertEqual(limit_length(None, 12), None)
330 self.assertEqual(limit_length('foo', 12), 'foo')
332 limit_length('foo bar baz asd', 12).startswith('foo bar'))
333 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
335 def test_escape_rfc3986(self):
336 reserved = "!*'();:@&=+$,/?#[]"
337 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
338 self.assertEqual(escape_rfc3986(reserved), reserved)
339 self.assertEqual(escape_rfc3986(unreserved), unreserved)
340 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
341 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
342 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
343 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
345 def test_escape_url(self):
347 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
348 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
351 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'),
352 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
355 escape_url('http://тест.рф/фрагмент'),
356 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
359 escape_url('http://тест.рф/абв?абв=абв#абв'),
360 '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'
362 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
364 def test_js_to_json_realworld(self):
366 'clip':{'provider':'pseudo'}
368 self.assertEqual(js_to_json(inp), '''{
369 "clip":{"provider":"pseudo"}
371 json.loads(js_to_json(inp))
374 'playlist':[{'controls':{'all':null}}]
376 self.assertEqual(js_to_json(inp), '''{
377 "playlist":[{"controls":{"all":null}}]
380 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
381 json_code = js_to_json(inp)
382 self.assertEqual(json.loads(json_code), json.loads(inp))
384 def test_js_to_json_edgecases(self):
385 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
386 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
388 on = js_to_json('{"abc": true}')
389 self.assertEqual(json.loads(on), {'abc': True})
391 # Ignore JavaScript code as well
398 self.assertEqual(d['x'], 1)
399 self.assertEqual(d['y'], 'a')
401 def test_clean_html(self):
402 self.assertEqual(clean_html('a:\nb'), 'a: b')
403 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
405 def test_intlist_to_bytes(self):
407 intlist_to_bytes([0, 1, 127, 128, 255]),
408 b'\x00\x01\x7f\x80\xff')
410 def test_args_to_str(self):
412 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
413 'foo ba/r -baz \'2 be\' \'\''
416 def test_parse_filesize(self):
417 self.assertEqual(parse_filesize(None), None)
418 self.assertEqual(parse_filesize(''), None)
419 self.assertEqual(parse_filesize('91 B'), 91)
420 self.assertEqual(parse_filesize('foobar'), None)
421 self.assertEqual(parse_filesize('2 MiB'), 2097152)
422 self.assertEqual(parse_filesize('5 GB'), 5000000000)
423 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
424 self.assertEqual(parse_filesize('1,24 KB'), 1240)
426 def test_version_tuple(self):
427 self.assertEqual(version_tuple('1'), (1,))
428 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
429 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
431 def test_detect_exe_version(self):
432 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
433 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
434 configuration: --prefix=/usr --extra-'''), '1.2.1')
435 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
436 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
437 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
438 Trying to open render node...
439 Success at /dev/dri/renderD128.
440 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
442 def test_age_restricted(self):
443 self.assertFalse(age_restricted(None, 10)) # unrestricted content
444 self.assertFalse(age_restricted(1, None)) # unrestricted policy
445 self.assertFalse(age_restricted(8, 10))
446 self.assertTrue(age_restricted(18, 14))
447 self.assertFalse(age_restricted(18, 18))
449 def test_is_html(self):
450 self.assertFalse(is_html(b'\x49\x44\x43<html'))
451 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
452 self.assertTrue(is_html( # UTF-8 with BOM
453 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
454 self.assertTrue(is_html( # UTF-16-LE
455 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
457 self.assertTrue(is_html( # UTF-16-BE
458 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
460 self.assertTrue(is_html( # UTF-32-BE
461 b'\x00\x00\xFE\xFF\x00\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4'))
462 self.assertTrue(is_html( # UTF-32-LE
463 b'\xFF\xFE\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4\x00\x00\x00'))
465 def test_render_table(self):
469 [[123, 4], [9999, 51]]),
474 def test_match_str(self):
475 self.assertRaises(ValueError, match_str, 'xy>foobar', {})
476 self.assertFalse(match_str('xy', {'x': 1200}))
477 self.assertTrue(match_str('!xy', {'x': 1200}))
478 self.assertTrue(match_str('x', {'x': 1200}))
479 self.assertFalse(match_str('!x', {'x': 1200}))
480 self.assertTrue(match_str('x', {'x': 0}))
481 self.assertFalse(match_str('x>0', {'x': 0}))
482 self.assertFalse(match_str('x>0', {}))
483 self.assertTrue(match_str('x>?0', {}))
484 self.assertTrue(match_str('x>1K', {'x': 1200}))
485 self.assertFalse(match_str('x>2K', {'x': 1200}))
486 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
487 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
488 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
489 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
490 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
491 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
492 self.assertFalse(match_str(
493 'like_count > 100 & dislike_count <? 50 & description',
494 {'like_count': 90, 'description': 'foo'}))
495 self.assertTrue(match_str(
496 'like_count > 100 & dislike_count <? 50 & description',
497 {'like_count': 190, 'description': 'foo'}))
498 self.assertFalse(match_str(
499 'like_count > 100 & dislike_count <? 50 & description',
500 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
501 self.assertFalse(match_str(
502 'like_count > 100 & dislike_count <? 50 & description',
503 {'like_count': 190, 'dislike_count': 10}))
505 def test_url_sanitize_consecutive_slashes(self):
506 self.assertEqual(url_sanitize_consecutive_slashes(
507 'http://hostname/foo//bar/filename.html'),
508 'http://hostname/foo/bar/filename.html')
509 self.assertEqual(url_sanitize_consecutive_slashes(
510 'http://hostname//foo/bar/filename.html'),
511 'http://hostname/foo/bar/filename.html')
512 self.assertEqual(url_sanitize_consecutive_slashes(
513 'http://hostname//'), 'http://hostname/')
514 self.assertEqual(url_sanitize_consecutive_slashes(
515 'http://hostname/foo/bar/filename.html'),
516 'http://hostname/foo/bar/filename.html')
517 self.assertEqual(url_sanitize_consecutive_slashes(
518 'http://hostname/'), 'http://hostname/')
521 if __name__ == '__main__':