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 (
56 class TestUtil(unittest
.TestCase
):
57 def test_timeconvert(self
):
58 self
.assertTrue(timeconvert('') is None)
59 self
.assertTrue(timeconvert('bougrg') is None)
61 def test_sanitize_filename(self
):
62 self
.assertEqual(sanitize_filename('abc'), 'abc')
63 self
.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
65 self
.assertEqual(sanitize_filename('123'), '123')
67 self
.assertEqual('abc_de', sanitize_filename('abc/de'))
68 self
.assertFalse('/' in sanitize_filename('abc/de///'))
70 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
71 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
72 self
.assertEqual('yes no', sanitize_filename('yes? no'))
73 self
.assertEqual('this - that', sanitize_filename('this: that'))
75 self
.assertEqual(sanitize_filename('AT&T'), 'AT&T')
77 self
.assertEqual(sanitize_filename(aumlaut
), aumlaut
)
78 tests
= '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
79 self
.assertEqual(sanitize_filename(tests
), tests
)
84 self
.assertTrue(fbc
not in sanitize_filename(fc
))
86 def test_sanitize_filename_restricted(self
):
87 self
.assertEqual(sanitize_filename('abc', restricted
=True), 'abc')
88 self
.assertEqual(sanitize_filename('abc_d-e', restricted
=True), 'abc_d-e')
90 self
.assertEqual(sanitize_filename('123', restricted
=True), '123')
92 self
.assertEqual('abc_de', sanitize_filename('abc/de', restricted
=True))
93 self
.assertFalse('/' in sanitize_filename('abc/de///', restricted
=True))
95 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted
=True))
96 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted
=True))
97 self
.assertEqual('yes_no', sanitize_filename('yes? no', restricted
=True))
98 self
.assertEqual('this_-_that', sanitize_filename('this: that', restricted
=True))
100 tests
= 'a\xe4b\u4e2d\u56fd\u7684c'
101 self
.assertEqual(sanitize_filename(tests
, restricted
=True), 'a_b_c')
102 self
.assertTrue(sanitize_filename('\xf6', restricted
=True) != '') # No empty filename
104 forbidden
= '"\0\\/&!: \'\t\n()[]{}$;`^,#'
106 for fbc
in forbidden
:
107 self
.assertTrue(fbc
not in sanitize_filename(fc
, restricted
=True))
109 # Handle a common case more neatly
110 self
.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted
=True), 'Song')
111 self
.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted
=True), 'Speech')
112 # .. but make sure the file name is never empty
113 self
.assertTrue(sanitize_filename('-', restricted
=True) != '')
114 self
.assertTrue(sanitize_filename(':', restricted
=True) != '')
116 def test_sanitize_ids(self
):
117 self
.assertEqual(sanitize_filename('_n_cd26wFpw', is_id
=True), '_n_cd26wFpw')
118 self
.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id
=True), '_BD_eEpuzXw')
119 self
.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id
=True), 'N0Y__7-UOdI')
121 def test_ordered_set(self
):
122 self
.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
123 self
.assertEqual(orderedSet([]), [])
124 self
.assertEqual(orderedSet([1]), [1])
125 # keep the list ordered
126 self
.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
128 def test_unescape_html(self
):
129 self
.assertEqual(unescapeHTML('%20;'), '%20;')
131 unescapeHTML('é'), 'é')
133 def test_daterange(self
):
134 _20century
= DateRange("19000101", "20000101")
135 self
.assertFalse("17890714" in _20century
)
136 _ac
= DateRange("00010101")
137 self
.assertTrue("19690721" in _ac
)
138 _firstmilenium
= DateRange(end
="10000101")
139 self
.assertTrue("07110427" in _firstmilenium
)
141 def test_unified_dates(self
):
142 self
.assertEqual(unified_strdate('December 21, 2010'), '20101221')
143 self
.assertEqual(unified_strdate('8/7/2009'), '20090708')
144 self
.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
145 self
.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
146 self
.assertEqual(unified_strdate('1968-12-10'), '19681210')
147 self
.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
149 unified_strdate('11/26/2014 11:30:00 AM PST', day_first
=False),
152 def test_find_xpath_attr(self
):
159 doc
= xml
.etree
.ElementTree
.fromstring(testxml
)
161 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n', 'v'), None)
162 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'a'), doc
[1])
163 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'c'), doc
[2])
165 def test_xpath_with_ns(self
):
166 testxml
= '''<root xmlns:media="http://example.com/">
168 <media:author>The Author</media:author>
169 <url>http://server.com/download.mp3</url>
172 doc
= xml
.etree
.ElementTree
.fromstring(testxml
)
173 find
= lambda p
: doc
.find(xpath_with_ns(p
, {'media': 'http://example.com/'}
))
174 self
.assertTrue(find('media:song') is not None)
175 self
.assertEqual(find('media:song/media:author').text
, 'The Author')
176 self
.assertEqual(find('media:song/url').text
, 'http://server.com/download.mp3')
178 def test_smuggle_url(self
):
179 data
= {"ö": "ö", "abc": [3]}
180 url
= 'https://foo.bar/baz?x=y#a'
181 smug_url
= smuggle_url(url
, data
)
182 unsmug_url
, unsmug_data
= unsmuggle_url(smug_url
)
183 self
.assertEqual(url
, unsmug_url
)
184 self
.assertEqual(data
, unsmug_data
)
186 res_url
, res_data
= unsmuggle_url(url
)
187 self
.assertEqual(res_url
, url
)
188 self
.assertEqual(res_data
, None)
190 def test_shell_quote(self
):
191 args
= ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
192 self
.assertEqual(shell_quote(args
), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
194 def test_str_to_int(self
):
195 self
.assertEqual(str_to_int('123,456'), 123456)
196 self
.assertEqual(str_to_int('123.456'), 123456)
198 def test_url_basename(self
):
199 self
.assertEqual(url_basename('http://foo.de/'), '')
200 self
.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
201 self
.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
202 self
.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
203 self
.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
205 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
208 def test_parse_duration(self
):
209 self
.assertEqual(parse_duration(None), None)
210 self
.assertEqual(parse_duration('1'), 1)
211 self
.assertEqual(parse_duration('1337:12'), 80232)
212 self
.assertEqual(parse_duration('9:12:43'), 33163)
213 self
.assertEqual(parse_duration('12:00'), 720)
214 self
.assertEqual(parse_duration('00:01:01'), 61)
215 self
.assertEqual(parse_duration('x:y'), None)
216 self
.assertEqual(parse_duration('3h11m53s'), 11513)
217 self
.assertEqual(parse_duration('3h 11m 53s'), 11513)
218 self
.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
219 self
.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
220 self
.assertEqual(parse_duration('62m45s'), 3765)
221 self
.assertEqual(parse_duration('6m59s'), 419)
222 self
.assertEqual(parse_duration('49s'), 49)
223 self
.assertEqual(parse_duration('0h0m0s'), 0)
224 self
.assertEqual(parse_duration('0m0s'), 0)
225 self
.assertEqual(parse_duration('0s'), 0)
226 self
.assertEqual(parse_duration('01:02:03.05'), 3723.05)
227 self
.assertEqual(parse_duration('T30M38S'), 1838)
228 self
.assertEqual(parse_duration('5 s'), 5)
229 self
.assertEqual(parse_duration('3 min'), 180)
230 self
.assertEqual(parse_duration('2.5 hours'), 9000)
232 def test_fix_xml_ampersands(self
):
234 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
236 fix_xml_ampersands('"&x=y&wrong;&z=a'),
237 '"&x=y&wrong;&z=a')
239 fix_xml_ampersands('&'><"'),
240 '&'><"')
242 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
243 self
.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
245 def test_paged_list(self
):
246 def testPL(size
, pagesize
, sliceargs
, expected
):
247 def get_page(pagenum
):
248 firstid
= pagenum
* pagesize
249 upto
= min(size
, pagenum
* pagesize
+ pagesize
)
250 for i
in range(firstid
, upto
):
253 pl
= OnDemandPagedList(get_page
, pagesize
)
254 got
= pl
.getslice(*sliceargs
)
255 self
.assertEqual(got
, expected
)
257 iapl
= InAdvancePagedList(get_page
, size
// pagesize
+ 1, pagesize
)
258 got
= iapl
.getslice(*sliceargs
)
259 self
.assertEqual(got
, expected
)
261 testPL(5, 2, (), [0, 1, 2, 3, 4])
262 testPL(5, 2, (1,), [1, 2, 3, 4])
263 testPL(5, 2, (2,), [2, 3, 4])
264 testPL(5, 2, (4,), [4])
265 testPL(5, 2, (0, 3), [0, 1, 2])
266 testPL(5, 2, (1, 4), [1, 2, 3])
267 testPL(5, 2, (2, 99), [2, 3, 4])
268 testPL(5, 2, (20, 99), [])
270 def test_struct_unpack(self
):
271 self
.assertEqual(struct_unpack('!B', b
'\x00'), (0,))
273 def test_read_batch_urls(self
):
274 f
= io
.StringIO('''\xef\xbb\xbf foo
277 # More after this line\r
280 self
.assertEqual(read_batch_urls(f
), ['foo', 'bar', 'baz', 'bam'])
282 def test_urlencode_postdata(self
):
283 data
= urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'}
)
284 self
.assertTrue(isinstance(data
, bytes))
286 def test_parse_iso8601(self
):
287 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
288 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
289 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
290 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
292 def test_strip_jsonp(self
):
293 stripped
= strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
294 d
= json
.loads(stripped
)
295 self
.assertEqual(d
, [{"id": "532cb", "x": 3}
])
297 stripped
= strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
298 d
= json
.loads(stripped
)
299 self
.assertEqual(d
, {'STATUS': 'OK'}
)
301 def test_uppercase_escape(self
):
302 self
.assertEqual(uppercase_escape('aä'), 'aä')
303 self
.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
305 def test_limit_length(self
):
306 self
.assertEqual(limit_length(None, 12), None)
307 self
.assertEqual(limit_length('foo', 12), 'foo')
309 limit_length('foo bar baz asd', 12).startswith('foo bar'))
310 self
.assertTrue('...' in limit_length('foo bar baz asd', 12))
312 def test_escape_rfc3986(self
):
313 reserved
= "!*'();:@&=+$,/?#[]"
314 unreserved
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
315 self
.assertEqual(escape_rfc3986(reserved
), reserved
)
316 self
.assertEqual(escape_rfc3986(unreserved
), unreserved
)
317 self
.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
318 self
.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
319 self
.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
320 self
.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
322 def test_escape_url(self
):
324 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
325 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
328 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'),
329 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
332 escape_url('http://тест.рф/фрагмент'),
333 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
336 escape_url('http://тест.рф/абв?абв=абв#абв'),
337 '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'
339 self
.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
341 def test_js_to_json_realworld(self
):
343 'clip':{'provider':'pseudo'}
345 self
.assertEqual(js_to_json(inp
), '''{
346 "clip":{"provider":"pseudo"}
348 json
.loads(js_to_json(inp
))
351 'playlist':[{'controls':{'all':null}}]
353 self
.assertEqual(js_to_json(inp
), '''{
354 "playlist":[{"controls":{"all":null}}]
357 def test_js_to_json_edgecases(self
):
358 on
= js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
359 self
.assertEqual(json
.loads(on
), {"abc_def": "1'\\2\\'3\"4"}
)
361 on
= js_to_json('{"abc": true}')
362 self
.assertEqual(json
.loads(on
), {'abc': True}
)
364 def test_clean_html(self
):
365 self
.assertEqual(clean_html('a:\nb'), 'a: b')
366 self
.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
368 def test_intlist_to_bytes(self
):
370 intlist_to_bytes([0, 1, 127, 128, 255]),
371 b
'\x00\x01\x7f\x80\xff')
373 def test_args_to_str(self
):
375 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
376 'foo ba/r -baz \'2 be\' \'\''
379 def test_parse_filesize(self
):
380 self
.assertEqual(parse_filesize(None), None)
381 self
.assertEqual(parse_filesize(''), None)
382 self
.assertEqual(parse_filesize('91 B'), 91)
383 self
.assertEqual(parse_filesize('foobar'), None)
384 self
.assertEqual(parse_filesize('2 MiB'), 2097152)
385 self
.assertEqual(parse_filesize('5 GB'), 5000000000)
386 self
.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
387 self
.assertEqual(parse_filesize('1,24 KB'), 1240)
389 def test_version_tuple(self
):
390 self
.assertEqual(version_tuple('1'), (1,))
391 self
.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
392 self
.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
394 def test_detect_exe_version(self
):
395 self
.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
396 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
397 configuration: --prefix=/usr --extra-'''), '1.2.1')
398 self
.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
399 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
400 self
.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
401 Trying to open render node...
402 Success at /dev/dri/renderD128.
403 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
405 if __name__
== '__main__':