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