]>
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 (
59 class TestUtil(unittest
.TestCase
):
60 def test_timeconvert(self
):
61 self
.assertTrue(timeconvert('') is None)
62 self
.assertTrue(timeconvert('bougrg') is None)
64 def test_sanitize_filename(self
):
65 self
.assertEqual(sanitize_filename('abc'), 'abc')
66 self
.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
68 self
.assertEqual(sanitize_filename('123'), '123')
70 self
.assertEqual('abc_de', sanitize_filename('abc/de'))
71 self
.assertFalse('/' in sanitize_filename('abc/de///'))
73 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
74 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
75 self
.assertEqual('yes no', sanitize_filename('yes? no'))
76 self
.assertEqual('this - that', sanitize_filename('this: that'))
78 self
.assertEqual(sanitize_filename('AT&T'), 'AT&T')
80 self
.assertEqual(sanitize_filename(aumlaut
), aumlaut
)
81 tests
= '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
82 self
.assertEqual(sanitize_filename(tests
), tests
)
85 sanitize_filename('New World record at 0:12:34'),
86 'New World record at 0_12_34')
91 self
.assertTrue(fbc
not in sanitize_filename(fc
))
93 def test_sanitize_filename_restricted(self
):
94 self
.assertEqual(sanitize_filename('abc', restricted
=True), 'abc')
95 self
.assertEqual(sanitize_filename('abc_d-e', restricted
=True), 'abc_d-e')
97 self
.assertEqual(sanitize_filename('123', restricted
=True), '123')
99 self
.assertEqual('abc_de', sanitize_filename('abc/de', restricted
=True))
100 self
.assertFalse('/' in sanitize_filename('abc/de///', restricted
=True))
102 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted
=True))
103 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted
=True))
104 self
.assertEqual('yes_no', sanitize_filename('yes? no', restricted
=True))
105 self
.assertEqual('this_-_that', sanitize_filename('this: that', restricted
=True))
107 tests
= 'a\xe4b\u4e2d\u56fd\u7684c'
108 self
.assertEqual(sanitize_filename(tests
, restricted
=True), 'a_b_c')
109 self
.assertTrue(sanitize_filename('\xf6', restricted
=True) != '') # No empty filename
111 forbidden
= '"\0\\/&!: \'\t\n()[]{}$;`^,#'
113 for fbc
in forbidden
:
114 self
.assertTrue(fbc
not in sanitize_filename(fc
, restricted
=True))
116 # Handle a common case more neatly
117 self
.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted
=True), 'Song')
118 self
.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted
=True), 'Speech')
119 # .. but make sure the file name is never empty
120 self
.assertTrue(sanitize_filename('-', restricted
=True) != '')
121 self
.assertTrue(sanitize_filename(':', restricted
=True) != '')
123 def test_sanitize_ids(self
):
124 self
.assertEqual(sanitize_filename('_n_cd26wFpw', is_id
=True), '_n_cd26wFpw')
125 self
.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id
=True), '_BD_eEpuzXw')
126 self
.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id
=True), 'N0Y__7-UOdI')
128 def test_ordered_set(self
):
129 self
.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
130 self
.assertEqual(orderedSet([]), [])
131 self
.assertEqual(orderedSet([1]), [1])
132 # keep the list ordered
133 self
.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
135 def test_unescape_html(self
):
136 self
.assertEqual(unescapeHTML('%20;'), '%20;')
138 unescapeHTML('é'), 'é')
140 def test_daterange(self
):
141 _20century
= DateRange("19000101", "20000101")
142 self
.assertFalse("17890714" in _20century
)
143 _ac
= DateRange("00010101")
144 self
.assertTrue("19690721" in _ac
)
145 _firstmilenium
= DateRange(end
="10000101")
146 self
.assertTrue("07110427" in _firstmilenium
)
148 def test_unified_dates(self
):
149 self
.assertEqual(unified_strdate('December 21, 2010'), '20101221')
150 self
.assertEqual(unified_strdate('8/7/2009'), '20090708')
151 self
.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
152 self
.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
153 self
.assertEqual(unified_strdate('1968 12 10'), '19681210')
154 self
.assertEqual(unified_strdate('1968-12-10'), '19681210')
155 self
.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
157 unified_strdate('11/26/2014 11:30:00 AM PST', day_first
=False),
160 unified_strdate('2/2/2015 6:47:40 PM', day_first
=False),
163 def test_find_xpath_attr(self
):
170 doc
= xml
.etree
.ElementTree
.fromstring(testxml
)
172 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n', 'v'), None)
173 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'a'), doc
[1])
174 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'c'), doc
[2])
176 def test_xpath_with_ns(self
):
177 testxml
= '''<root xmlns:media="http://example.com/">
179 <media:author>The Author</media:author>
180 <url>http://server.com/download.mp3</url>
183 doc
= xml
.etree
.ElementTree
.fromstring(testxml
)
184 find
= lambda p
: doc
.find(xpath_with_ns(p
, {'media': 'http://example.com/'}))
185 self
.assertTrue(find('media:song') is not None)
186 self
.assertEqual(find('media:song/media:author').text
, 'The Author')
187 self
.assertEqual(find('media:song/url').text
, 'http://server.com/download.mp3')
189 def test_smuggle_url(self
):
190 data
= {"ö": "ö", "abc": [3]}
191 url
= 'https://foo.bar/baz?x=y#a'
192 smug_url
= smuggle_url(url
, data
)
193 unsmug_url
, unsmug_data
= unsmuggle_url(smug_url
)
194 self
.assertEqual(url
, unsmug_url
)
195 self
.assertEqual(data
, unsmug_data
)
197 res_url
, res_data
= unsmuggle_url(url
)
198 self
.assertEqual(res_url
, url
)
199 self
.assertEqual(res_data
, None)
201 def test_shell_quote(self
):
202 args
= ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
203 self
.assertEqual(shell_quote(args
), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
205 def test_str_to_int(self
):
206 self
.assertEqual(str_to_int('123,456'), 123456)
207 self
.assertEqual(str_to_int('123.456'), 123456)
209 def test_url_basename(self
):
210 self
.assertEqual(url_basename('http://foo.de/'), '')
211 self
.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
212 self
.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
213 self
.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
214 self
.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
216 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
219 def test_parse_duration(self
):
220 self
.assertEqual(parse_duration(None), None)
221 self
.assertEqual(parse_duration(False), None)
222 self
.assertEqual(parse_duration('invalid'), None)
223 self
.assertEqual(parse_duration('1'), 1)
224 self
.assertEqual(parse_duration('1337:12'), 80232)
225 self
.assertEqual(parse_duration('9:12:43'), 33163)
226 self
.assertEqual(parse_duration('12:00'), 720)
227 self
.assertEqual(parse_duration('00:01:01'), 61)
228 self
.assertEqual(parse_duration('x:y'), None)
229 self
.assertEqual(parse_duration('3h11m53s'), 11513)
230 self
.assertEqual(parse_duration('3h 11m 53s'), 11513)
231 self
.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
232 self
.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
233 self
.assertEqual(parse_duration('62m45s'), 3765)
234 self
.assertEqual(parse_duration('6m59s'), 419)
235 self
.assertEqual(parse_duration('49s'), 49)
236 self
.assertEqual(parse_duration('0h0m0s'), 0)
237 self
.assertEqual(parse_duration('0m0s'), 0)
238 self
.assertEqual(parse_duration('0s'), 0)
239 self
.assertEqual(parse_duration('01:02:03.05'), 3723.05)
240 self
.assertEqual(parse_duration('T30M38S'), 1838)
241 self
.assertEqual(parse_duration('5 s'), 5)
242 self
.assertEqual(parse_duration('3 min'), 180)
243 self
.assertEqual(parse_duration('2.5 hours'), 9000)
244 self
.assertEqual(parse_duration('02:03:04'), 7384)
245 self
.assertEqual(parse_duration('01:02:03:04'), 93784)
247 def test_fix_xml_ampersands(self
):
249 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
251 fix_xml_ampersands('"&x=y&wrong;&z=a'),
252 '"&x=y&wrong;&z=a')
254 fix_xml_ampersands('&'><"'),
255 '&'><"')
257 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
258 self
.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
260 def test_paged_list(self
):
261 def testPL(size
, pagesize
, sliceargs
, expected
):
262 def get_page(pagenum
):
263 firstid
= pagenum
* pagesize
264 upto
= min(size
, pagenum
* pagesize
+ pagesize
)
265 for i
in range(firstid
, upto
):
268 pl
= OnDemandPagedList(get_page
, pagesize
)
269 got
= pl
.getslice(*sliceargs
)
270 self
.assertEqual(got
, expected
)
272 iapl
= InAdvancePagedList(get_page
, size
// pagesize
+ 1, pagesize
)
273 got
= iapl
.getslice(*sliceargs
)
274 self
.assertEqual(got
, expected
)
276 testPL(5, 2, (), [0, 1, 2, 3, 4])
277 testPL(5, 2, (1,), [1, 2, 3, 4])
278 testPL(5, 2, (2,), [2, 3, 4])
279 testPL(5, 2, (4,), [4])
280 testPL(5, 2, (0, 3), [0, 1, 2])
281 testPL(5, 2, (1, 4), [1, 2, 3])
282 testPL(5, 2, (2, 99), [2, 3, 4])
283 testPL(5, 2, (20, 99), [])
285 def test_struct_unpack(self
):
286 self
.assertEqual(struct_unpack('!B', b
'\x00'), (0,))
288 def test_read_batch_urls(self
):
289 f
= io
.StringIO('''\xef\xbb\xbf foo
292 # More after this line\r
295 self
.assertEqual(read_batch_urls(f
), ['foo', 'bar', 'baz', 'bam'])
297 def test_urlencode_postdata(self
):
298 data
= urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
299 self
.assertTrue(isinstance(data
, bytes))
301 def test_parse_iso8601(self
):
302 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
303 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
304 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
305 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
307 def test_strip_jsonp(self
):
308 stripped
= strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
309 d
= json
.loads(stripped
)
310 self
.assertEqual(d
, [{"id": "532cb", "x": 3}])
312 stripped
= strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
313 d
= json
.loads(stripped
)
314 self
.assertEqual(d
, {'STATUS': 'OK'})
316 def test_uppercase_escape(self
):
317 self
.assertEqual(uppercase_escape('aä'), 'aä')
318 self
.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
320 def test_limit_length(self
):
321 self
.assertEqual(limit_length(None, 12), None)
322 self
.assertEqual(limit_length('foo', 12), 'foo')
324 limit_length('foo bar baz asd', 12).startswith('foo bar'))
325 self
.assertTrue('...' in limit_length('foo bar baz asd', 12))
327 def test_escape_rfc3986(self
):
328 reserved
= "!*'();:@&=+$,/?#[]"
329 unreserved
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
330 self
.assertEqual(escape_rfc3986(reserved
), reserved
)
331 self
.assertEqual(escape_rfc3986(unreserved
), unreserved
)
332 self
.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
333 self
.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
334 self
.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
335 self
.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
337 def test_escape_url(self
):
339 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
340 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
343 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'),
344 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
347 escape_url('http://тест.рф/фрагмент'),
348 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
351 escape_url('http://тест.рф/абв?абв=абв#абв'),
352 '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'
354 self
.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
356 def test_js_to_json_realworld(self
):
358 'clip':{'provider':'pseudo'}
360 self
.assertEqual(js_to_json(inp
), '''{
361 "clip":{"provider":"pseudo"}
363 json
.loads(js_to_json(inp
))
366 'playlist':[{'controls':{'all':null}}]
368 self
.assertEqual(js_to_json(inp
), '''{
369 "playlist":[{"controls":{"all":null}}]
372 def test_js_to_json_edgecases(self
):
373 on
= js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
374 self
.assertEqual(json
.loads(on
), {"abc_def": "1'\\2\\'3\"4"})
376 on
= js_to_json('{"abc": true}')
377 self
.assertEqual(json
.loads(on
), {'abc': True})
379 # Ignore JavaScript code as well
386 self
.assertEqual(d
['x'], 1)
387 self
.assertEqual(d
['y'], 'a')
389 def test_clean_html(self
):
390 self
.assertEqual(clean_html('a:\nb'), 'a: b')
391 self
.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
393 def test_intlist_to_bytes(self
):
395 intlist_to_bytes([0, 1, 127, 128, 255]),
396 b
'\x00\x01\x7f\x80\xff')
398 def test_args_to_str(self
):
400 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
401 'foo ba/r -baz \'2 be\' \'\''
404 def test_parse_filesize(self
):
405 self
.assertEqual(parse_filesize(None), None)
406 self
.assertEqual(parse_filesize(''), None)
407 self
.assertEqual(parse_filesize('91 B'), 91)
408 self
.assertEqual(parse_filesize('foobar'), None)
409 self
.assertEqual(parse_filesize('2 MiB'), 2097152)
410 self
.assertEqual(parse_filesize('5 GB'), 5000000000)
411 self
.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
412 self
.assertEqual(parse_filesize('1,24 KB'), 1240)
414 def test_version_tuple(self
):
415 self
.assertEqual(version_tuple('1'), (1,))
416 self
.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
417 self
.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
419 def test_detect_exe_version(self
):
420 self
.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
421 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
422 configuration: --prefix=/usr --extra-'''), '1.2.1')
423 self
.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
424 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
425 self
.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
426 Trying to open render node...
427 Success at /dev/dri/renderD128.
428 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
430 def test_age_restricted(self
):
431 self
.assertFalse(age_restricted(None, 10)) # unrestricted content
432 self
.assertFalse(age_restricted(1, None)) # unrestricted policy
433 self
.assertFalse(age_restricted(8, 10))
434 self
.assertTrue(age_restricted(18, 14))
435 self
.assertFalse(age_restricted(18, 18))
437 def test_is_html(self
):
438 self
.assertFalse(is_html(b
'\x49\x44\x43<html'))
439 self
.assertTrue(is_html(b
'<!DOCTYPE foo>\xaaa'))
440 self
.assertTrue(is_html( # UTF-8 with BOM
441 b
'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
442 self
.assertTrue(is_html( # UTF-16-LE
443 b
'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
445 self
.assertTrue(is_html( # UTF-16-BE
446 b
'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
448 self
.assertTrue(is_html( # UTF-32-BE
449 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'))
450 self
.assertTrue(is_html( # UTF-32-LE
451 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'))
453 def test_render_table(self
):
457 [[123, 4], [9999, 51]]),
463 if __name__
== '__main__':