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 (
76 from youtube_dl
.compat
import (
77 compat_etree_fromstring
,
81 class TestUtil(unittest
.TestCase
):
82 def test_timeconvert(self
):
83 self
.assertTrue(timeconvert('') is None)
84 self
.assertTrue(timeconvert('bougrg') is None)
86 def test_sanitize_filename(self
):
87 self
.assertEqual(sanitize_filename('abc'), 'abc')
88 self
.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
90 self
.assertEqual(sanitize_filename('123'), '123')
92 self
.assertEqual('abc_de', sanitize_filename('abc/de'))
93 self
.assertFalse('/' in sanitize_filename('abc/de///'))
95 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
96 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
97 self
.assertEqual('yes no', sanitize_filename('yes? no'))
98 self
.assertEqual('this - that', sanitize_filename('this: that'))
100 self
.assertEqual(sanitize_filename('AT&T'), 'AT&T')
102 self
.assertEqual(sanitize_filename(aumlaut
), aumlaut
)
103 tests
= '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
104 self
.assertEqual(sanitize_filename(tests
), tests
)
107 sanitize_filename('New World record at 0:12:34'),
108 'New World record at 0_12_34')
110 self
.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
111 self
.assertEqual(sanitize_filename('--gasdgf', is_id
=True), '--gasdgf')
112 self
.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
113 self
.assertEqual(sanitize_filename('.gasdgf', is_id
=True), '.gasdgf')
117 for fbc
in forbidden
:
118 self
.assertTrue(fbc
not in sanitize_filename(fc
))
120 def test_sanitize_filename_restricted(self
):
121 self
.assertEqual(sanitize_filename('abc', restricted
=True), 'abc')
122 self
.assertEqual(sanitize_filename('abc_d-e', restricted
=True), 'abc_d-e')
124 self
.assertEqual(sanitize_filename('123', restricted
=True), '123')
126 self
.assertEqual('abc_de', sanitize_filename('abc/de', restricted
=True))
127 self
.assertFalse('/' in sanitize_filename('abc/de///', restricted
=True))
129 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted
=True))
130 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted
=True))
131 self
.assertEqual('yes_no', sanitize_filename('yes? no', restricted
=True))
132 self
.assertEqual('this_-_that', sanitize_filename('this: that', restricted
=True))
134 tests
= 'a\xe4b\u4e2d\u56fd\u7684c'
135 self
.assertEqual(sanitize_filename(tests
, restricted
=True), 'a_b_c')
136 self
.assertTrue(sanitize_filename('\xf6', restricted
=True) != '') # No empty filename
138 forbidden
= '"\0\\/&!: \'\t\n()[]{}$;`^,#'
140 for fbc
in forbidden
:
141 self
.assertTrue(fbc
not in sanitize_filename(fc
, restricted
=True))
143 # Handle a common case more neatly
144 self
.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted
=True), 'Song')
145 self
.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted
=True), 'Speech')
146 # .. but make sure the file name is never empty
147 self
.assertTrue(sanitize_filename('-', restricted
=True) != '')
148 self
.assertTrue(sanitize_filename(':', restricted
=True) != '')
150 def test_sanitize_ids(self
):
151 self
.assertEqual(sanitize_filename('_n_cd26wFpw', is_id
=True), '_n_cd26wFpw')
152 self
.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id
=True), '_BD_eEpuzXw')
153 self
.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id
=True), 'N0Y__7-UOdI')
155 def test_sanitize_path(self
):
156 if sys
.platform
!= 'win32':
159 self
.assertEqual(sanitize_path('abc'), 'abc')
160 self
.assertEqual(sanitize_path('abc/def'), 'abc\\def')
161 self
.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
162 self
.assertEqual(sanitize_path('abc|def'), 'abc#def')
163 self
.assertEqual(sanitize_path('<>:"|?*'), '#######')
164 self
.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
165 self
.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
167 self
.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
168 self
.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
170 self
.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
171 self
.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
172 self
.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
173 self
.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
176 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
177 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
180 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
181 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
182 self
.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
183 self
.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
184 self
.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
186 self
.assertEqual(sanitize_path('../abc'), '..\\abc')
187 self
.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
188 self
.assertEqual(sanitize_path('./abc'), 'abc')
189 self
.assertEqual(sanitize_path('./../abc'), '..\\abc')
191 def test_prepend_extension(self
):
192 self
.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
193 self
.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
194 self
.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
195 self
.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
196 self
.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
197 self
.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
199 def test_replace_extension(self
):
200 self
.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
201 self
.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
202 self
.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
203 self
.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
204 self
.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
205 self
.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
207 def test_remove_quotes(self
):
208 self
.assertEqual(remove_quotes(None), None)
209 self
.assertEqual(remove_quotes('"'), '"')
210 self
.assertEqual(remove_quotes("'"), "'")
211 self
.assertEqual(remove_quotes(';'), ';')
212 self
.assertEqual(remove_quotes('";'), '";')
213 self
.assertEqual(remove_quotes('""'), '')
214 self
.assertEqual(remove_quotes('";"'), ';')
216 def test_ordered_set(self
):
217 self
.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
218 self
.assertEqual(orderedSet([]), [])
219 self
.assertEqual(orderedSet([1]), [1])
220 # keep the list ordered
221 self
.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
223 def test_unescape_html(self
):
224 self
.assertEqual(unescapeHTML('%20;'), '%20;')
225 self
.assertEqual(unescapeHTML('/'), '/')
226 self
.assertEqual(unescapeHTML('/'), '/')
227 self
.assertEqual(unescapeHTML('é'), 'é')
228 self
.assertEqual(unescapeHTML('�'), '�')
230 def test_daterange(self
):
231 _20century
= DateRange("19000101", "20000101")
232 self
.assertFalse("17890714" in _20century
)
233 _ac
= DateRange("00010101")
234 self
.assertTrue("19690721" in _ac
)
235 _firstmilenium
= DateRange(end
="10000101")
236 self
.assertTrue("07110427" in _firstmilenium
)
238 def test_unified_dates(self
):
239 self
.assertEqual(unified_strdate('December 21, 2010'), '20101221')
240 self
.assertEqual(unified_strdate('8/7/2009'), '20090708')
241 self
.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
242 self
.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
243 self
.assertEqual(unified_strdate('1968 12 10'), '19681210')
244 self
.assertEqual(unified_strdate('1968-12-10'), '19681210')
245 self
.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
247 unified_strdate('11/26/2014 11:30:00 AM PST', day_first
=False),
250 unified_strdate('2/2/2015 6:47:40 PM', day_first
=False),
252 self
.assertEqual(unified_strdate('25-09-2014'), '20140925')
253 self
.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
255 def test_determine_ext(self
):
256 self
.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
257 self
.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
258 self
.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
259 self
.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
260 self
.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
262 def test_find_xpath_attr(self
):
270 doc
= compat_etree_fromstring(testxml
)
272 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n'), None)
273 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n', 'v'), None)
274 self
.assertEqual(find_xpath_attr(doc
, './/node', 'n'), None)
275 self
.assertEqual(find_xpath_attr(doc
, './/node', 'n', 'v'), None)
276 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x'), doc
[1])
277 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'a'), doc
[1])
278 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'b'), doc
[3])
279 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y'), doc
[2])
280 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'c'), doc
[2])
281 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'd'), doc
[3])
282 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', ''), doc
[4])
284 def test_xpath_with_ns(self
):
285 testxml
= '''<root xmlns:media="http://example.com/">
287 <media:author>The Author</media:author>
288 <url>http://server.com/download.mp3</url>
291 doc
= compat_etree_fromstring(testxml
)
292 find
= lambda p
: doc
.find(xpath_with_ns(p
, {'media': 'http://example.com/'}))
293 self
.assertTrue(find('media:song') is not None)
294 self
.assertEqual(find('media:song/media:author').text
, 'The Author')
295 self
.assertEqual(find('media:song/url').text
, 'http://server.com/download.mp3')
297 def test_xpath_element(self
):
298 doc
= xml
.etree
.ElementTree
.Element('root')
299 div
= xml
.etree
.ElementTree
.SubElement(doc
, 'div')
300 p
= xml
.etree
.ElementTree
.SubElement(div
, 'p')
302 self
.assertEqual(xpath_element(doc
, 'div/p'), p
)
303 self
.assertEqual(xpath_element(doc
, ['div/p']), p
)
304 self
.assertEqual(xpath_element(doc
, ['div/bar', 'div/p']), p
)
305 self
.assertEqual(xpath_element(doc
, 'div/bar', default
='default'), 'default')
306 self
.assertEqual(xpath_element(doc
, ['div/bar'], default
='default'), 'default')
307 self
.assertTrue(xpath_element(doc
, 'div/bar') is None)
308 self
.assertTrue(xpath_element(doc
, ['div/bar']) is None)
309 self
.assertTrue(xpath_element(doc
, ['div/bar'], 'div/baz') is None)
310 self
.assertRaises(ExtractorError
, xpath_element
, doc
, 'div/bar', fatal
=True)
311 self
.assertRaises(ExtractorError
, xpath_element
, doc
, ['div/bar'], fatal
=True)
312 self
.assertRaises(ExtractorError
, xpath_element
, doc
, ['div/bar', 'div/baz'], fatal
=True)
314 def test_xpath_text(self
):
320 doc
= compat_etree_fromstring(testxml
)
321 self
.assertEqual(xpath_text(doc
, 'div/p'), 'Foo')
322 self
.assertEqual(xpath_text(doc
, 'div/bar', default
='default'), 'default')
323 self
.assertTrue(xpath_text(doc
, 'div/bar') is None)
324 self
.assertRaises(ExtractorError
, xpath_text
, doc
, 'div/bar', fatal
=True)
326 def test_xpath_attr(self
):
332 doc
= compat_etree_fromstring(testxml
)
333 self
.assertEqual(xpath_attr(doc
, 'div/p', 'x'), 'a')
334 self
.assertEqual(xpath_attr(doc
, 'div/bar', 'x'), None)
335 self
.assertEqual(xpath_attr(doc
, 'div/p', 'y'), None)
336 self
.assertEqual(xpath_attr(doc
, 'div/bar', 'x', default
='default'), 'default')
337 self
.assertEqual(xpath_attr(doc
, 'div/p', 'y', default
='default'), 'default')
338 self
.assertRaises(ExtractorError
, xpath_attr
, doc
, 'div/bar', 'x', fatal
=True)
339 self
.assertRaises(ExtractorError
, xpath_attr
, doc
, 'div/p', 'y', fatal
=True)
341 def test_smuggle_url(self
):
342 data
= {"ö": "ö", "abc": [3]}
343 url
= 'https://foo.bar/baz?x=y#a'
344 smug_url
= smuggle_url(url
, data
)
345 unsmug_url
, unsmug_data
= unsmuggle_url(smug_url
)
346 self
.assertEqual(url
, unsmug_url
)
347 self
.assertEqual(data
, unsmug_data
)
349 res_url
, res_data
= unsmuggle_url(url
)
350 self
.assertEqual(res_url
, url
)
351 self
.assertEqual(res_data
, None)
353 def test_shell_quote(self
):
354 args
= ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
355 self
.assertEqual(shell_quote(args
), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
357 def test_str_to_int(self
):
358 self
.assertEqual(str_to_int('123,456'), 123456)
359 self
.assertEqual(str_to_int('123.456'), 123456)
361 def test_url_basename(self
):
362 self
.assertEqual(url_basename('http://foo.de/'), '')
363 self
.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
364 self
.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
365 self
.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
366 self
.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
368 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
371 def test_parse_duration(self
):
372 self
.assertEqual(parse_duration(None), None)
373 self
.assertEqual(parse_duration(False), None)
374 self
.assertEqual(parse_duration('invalid'), None)
375 self
.assertEqual(parse_duration('1'), 1)
376 self
.assertEqual(parse_duration('1337:12'), 80232)
377 self
.assertEqual(parse_duration('9:12:43'), 33163)
378 self
.assertEqual(parse_duration('12:00'), 720)
379 self
.assertEqual(parse_duration('00:01:01'), 61)
380 self
.assertEqual(parse_duration('x:y'), None)
381 self
.assertEqual(parse_duration('3h11m53s'), 11513)
382 self
.assertEqual(parse_duration('3h 11m 53s'), 11513)
383 self
.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
384 self
.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
385 self
.assertEqual(parse_duration('62m45s'), 3765)
386 self
.assertEqual(parse_duration('6m59s'), 419)
387 self
.assertEqual(parse_duration('49s'), 49)
388 self
.assertEqual(parse_duration('0h0m0s'), 0)
389 self
.assertEqual(parse_duration('0m0s'), 0)
390 self
.assertEqual(parse_duration('0s'), 0)
391 self
.assertEqual(parse_duration('01:02:03.05'), 3723.05)
392 self
.assertEqual(parse_duration('T30M38S'), 1838)
393 self
.assertEqual(parse_duration('5 s'), 5)
394 self
.assertEqual(parse_duration('3 min'), 180)
395 self
.assertEqual(parse_duration('2.5 hours'), 9000)
396 self
.assertEqual(parse_duration('02:03:04'), 7384)
397 self
.assertEqual(parse_duration('01:02:03:04'), 93784)
398 self
.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
399 self
.assertEqual(parse_duration('87 Min.'), 5220)
401 def test_fix_xml_ampersands(self
):
403 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
405 fix_xml_ampersands('"&x=y&wrong;&z=a'),
406 '"&x=y&wrong;&z=a')
408 fix_xml_ampersands('&'><"'),
409 '&'><"')
411 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
412 self
.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
414 def test_paged_list(self
):
415 def testPL(size
, pagesize
, sliceargs
, expected
):
416 def get_page(pagenum
):
417 firstid
= pagenum
* pagesize
418 upto
= min(size
, pagenum
* pagesize
+ pagesize
)
419 for i
in range(firstid
, upto
):
422 pl
= OnDemandPagedList(get_page
, pagesize
)
423 got
= pl
.getslice(*sliceargs
)
424 self
.assertEqual(got
, expected
)
426 iapl
= InAdvancePagedList(get_page
, size
// pagesize
+ 1, pagesize
)
427 got
= iapl
.getslice(*sliceargs
)
428 self
.assertEqual(got
, expected
)
430 testPL(5, 2, (), [0, 1, 2, 3, 4])
431 testPL(5, 2, (1,), [1, 2, 3, 4])
432 testPL(5, 2, (2,), [2, 3, 4])
433 testPL(5, 2, (4,), [4])
434 testPL(5, 2, (0, 3), [0, 1, 2])
435 testPL(5, 2, (1, 4), [1, 2, 3])
436 testPL(5, 2, (2, 99), [2, 3, 4])
437 testPL(5, 2, (20, 99), [])
439 def test_struct_unpack(self
):
440 self
.assertEqual(struct_unpack('!B', b
'\x00'), (0,))
442 def test_read_batch_urls(self
):
443 f
= io
.StringIO('''\xef\xbb\xbf foo
446 # More after this line\r
449 self
.assertEqual(read_batch_urls(f
), ['foo', 'bar', 'baz', 'bam'])
451 def test_urlencode_postdata(self
):
452 data
= urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
453 self
.assertTrue(isinstance(data
, bytes))
455 def test_dict_get(self
):
463 d
= FALSE_VALUES
.copy()
465 self
.assertEqual(dict_get(d
, 'a'), 42)
466 self
.assertEqual(dict_get(d
, 'b'), None)
467 self
.assertEqual(dict_get(d
, 'b', 42), 42)
468 self
.assertEqual(dict_get(d
, ('a', )), 42)
469 self
.assertEqual(dict_get(d
, ('b', 'a', )), 42)
470 self
.assertEqual(dict_get(d
, ('b', 'c', 'a', 'd', )), 42)
471 self
.assertEqual(dict_get(d
, ('b', 'c', )), None)
472 self
.assertEqual(dict_get(d
, ('b', 'c', ), 42), 42)
473 for key
, false_value
in FALSE_VALUES
.items():
474 self
.assertEqual(dict_get(d
, ('b', 'c', key
, )), None)
475 self
.assertEqual(dict_get(d
, ('b', 'c', key
, ), skip_false_values
=False), false_value
)
477 def test_encode_compat_str(self
):
478 self
.assertEqual(encode_compat_str(b
'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
479 self
.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
481 def test_parse_iso8601(self
):
482 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
483 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
484 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
485 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
486 self
.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
487 self
.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
489 def test_strip_jsonp(self
):
490 stripped
= strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
491 d
= json
.loads(stripped
)
492 self
.assertEqual(d
, [{"id": "532cb", "x": 3}])
494 stripped
= strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
495 d
= json
.loads(stripped
)
496 self
.assertEqual(d
, {'STATUS': 'OK'})
498 stripped
= strip_jsonp('ps.embedHandler({"status": "success"});')
499 d
= json
.loads(stripped
)
500 self
.assertEqual(d
, {'status': 'success'})
502 def test_uppercase_escape(self
):
503 self
.assertEqual(uppercase_escape('aä'), 'aä')
504 self
.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
506 def test_lowercase_escape(self
):
507 self
.assertEqual(lowercase_escape('aä'), 'aä')
508 self
.assertEqual(lowercase_escape('\\u0026'), '&')
510 def test_limit_length(self
):
511 self
.assertEqual(limit_length(None, 12), None)
512 self
.assertEqual(limit_length('foo', 12), 'foo')
514 limit_length('foo bar baz asd', 12).startswith('foo bar'))
515 self
.assertTrue('...' in limit_length('foo bar baz asd', 12))
517 def test_escape_rfc3986(self
):
518 reserved
= "!*'();:@&=+$,/?#[]"
519 unreserved
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
520 self
.assertEqual(escape_rfc3986(reserved
), reserved
)
521 self
.assertEqual(escape_rfc3986(unreserved
), unreserved
)
522 self
.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
523 self
.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
524 self
.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
525 self
.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
527 def test_escape_url(self
):
529 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
530 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
533 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'),
534 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
537 escape_url('http://тест.рф/фрагмент'),
538 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
541 escape_url('http://тест.рф/абв?абв=абв#абв'),
542 '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'
544 self
.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
546 def test_js_to_json_realworld(self
):
548 'clip':{'provider':'pseudo'}
550 self
.assertEqual(js_to_json(inp
), '''{
551 "clip":{"provider":"pseudo"}
553 json
.loads(js_to_json(inp
))
556 'playlist':[{'controls':{'all':null}}]
558 self
.assertEqual(js_to_json(inp
), '''{
559 "playlist":[{"controls":{"all":null}}]
562 inp
= '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
563 self
.assertEqual(js_to_json(inp
), '''"The CW's 'Crazy Ex-Girlfriend'"''')
565 inp
= '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
566 json_code
= js_to_json(inp
)
567 self
.assertEqual(json
.loads(json_code
), json
.loads(inp
))
569 def test_js_to_json_edgecases(self
):
570 on
= js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
571 self
.assertEqual(json
.loads(on
), {"abc_def": "1'\\2\\'3\"4"})
573 on
= js_to_json('{"abc": true}')
574 self
.assertEqual(json
.loads(on
), {'abc': True})
576 # Ignore JavaScript code as well
583 self
.assertEqual(d
['x'], 1)
584 self
.assertEqual(d
['y'], 'a')
586 on
= js_to_json('["abc", "def",]')
587 self
.assertEqual(json
.loads(on
), ['abc', 'def'])
589 on
= js_to_json('{"abc": "def",}')
590 self
.assertEqual(json
.loads(on
), {'abc': 'def'})
592 def test_clean_html(self
):
593 self
.assertEqual(clean_html('a:\nb'), 'a: b')
594 self
.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
596 def test_intlist_to_bytes(self
):
598 intlist_to_bytes([0, 1, 127, 128, 255]),
599 b
'\x00\x01\x7f\x80\xff')
601 def test_args_to_str(self
):
603 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
604 'foo ba/r -baz \'2 be\' \'\''
607 def test_parse_filesize(self
):
608 self
.assertEqual(parse_filesize(None), None)
609 self
.assertEqual(parse_filesize(''), None)
610 self
.assertEqual(parse_filesize('91 B'), 91)
611 self
.assertEqual(parse_filesize('foobar'), None)
612 self
.assertEqual(parse_filesize('2 MiB'), 2097152)
613 self
.assertEqual(parse_filesize('5 GB'), 5000000000)
614 self
.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
615 self
.assertEqual(parse_filesize('1,24 KB'), 1240)
617 def test_version_tuple(self
):
618 self
.assertEqual(version_tuple('1'), (1,))
619 self
.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
620 self
.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
622 def test_detect_exe_version(self
):
623 self
.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
624 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
625 configuration: --prefix=/usr --extra-'''), '1.2.1')
626 self
.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
627 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
628 self
.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
629 Trying to open render node...
630 Success at /dev/dri/renderD128.
631 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
633 def test_age_restricted(self
):
634 self
.assertFalse(age_restricted(None, 10)) # unrestricted content
635 self
.assertFalse(age_restricted(1, None)) # unrestricted policy
636 self
.assertFalse(age_restricted(8, 10))
637 self
.assertTrue(age_restricted(18, 14))
638 self
.assertFalse(age_restricted(18, 18))
640 def test_is_html(self
):
641 self
.assertFalse(is_html(b
'\x49\x44\x43<html'))
642 self
.assertTrue(is_html(b
'<!DOCTYPE foo>\xaaa'))
643 self
.assertTrue(is_html( # UTF-8 with BOM
644 b
'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
645 self
.assertTrue(is_html( # UTF-16-LE
646 b
'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
648 self
.assertTrue(is_html( # UTF-16-BE
649 b
'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
651 self
.assertTrue(is_html( # UTF-32-BE
652 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'))
653 self
.assertTrue(is_html( # UTF-32-LE
654 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'))
656 def test_render_table(self
):
660 [[123, 4], [9999, 51]]),
665 def test_match_str(self
):
666 self
.assertRaises(ValueError, match_str
, 'xy>foobar', {})
667 self
.assertFalse(match_str('xy', {'x': 1200}))
668 self
.assertTrue(match_str('!xy', {'x': 1200}))
669 self
.assertTrue(match_str('x', {'x': 1200}))
670 self
.assertFalse(match_str('!x', {'x': 1200}))
671 self
.assertTrue(match_str('x', {'x': 0}))
672 self
.assertFalse(match_str('x>0', {'x': 0}))
673 self
.assertFalse(match_str('x>0', {}))
674 self
.assertTrue(match_str('x>?0', {}))
675 self
.assertTrue(match_str('x>1K', {'x': 1200}))
676 self
.assertFalse(match_str('x>2K', {'x': 1200}))
677 self
.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
678 self
.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
679 self
.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
680 self
.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
681 self
.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
682 self
.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
683 self
.assertFalse(match_str(
684 'like_count > 100 & dislike_count <? 50 & description',
685 {'like_count': 90, 'description': 'foo'}))
686 self
.assertTrue(match_str(
687 'like_count > 100 & dislike_count <? 50 & description',
688 {'like_count': 190, 'description': 'foo'}))
689 self
.assertFalse(match_str(
690 'like_count > 100 & dislike_count <? 50 & description',
691 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
692 self
.assertFalse(match_str(
693 'like_count > 100 & dislike_count <? 50 & description',
694 {'like_count': 190, 'dislike_count': 10}))
696 def test_parse_dfxp_time_expr(self
):
697 self
.assertEqual(parse_dfxp_time_expr(None), None)
698 self
.assertEqual(parse_dfxp_time_expr(''), None)
699 self
.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
700 self
.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
701 self
.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
702 self
.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
703 self
.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
705 def test_dfxp2srt(self
):
706 dfxp_data
= '''<?xml version="1.0" encoding="UTF-8"?>
707 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
710 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
711 <p begin="1" end="2">第二行<br/>♪♪</p>
712 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
713 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
714 <p begin="-1" end="-1">Ignore, two</p>
715 <p begin="3" dur="-1">Ignored, three</p>
720 00:00:00,000 --> 00:00:01,000
721 The following line contains Chinese characters and special symbols
724 00:00:01,000 --> 00:00:02,000
729 00:00:02,000 --> 00:00:03,000
734 self
.assertEqual(dfxp2srt(dfxp_data
), srt_data
)
736 dfxp_data_no_default_namespace
= '''<?xml version="1.0" encoding="UTF-8"?>
737 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
740 <p begin="0" end="1">The first line</p>
745 00:00:00,000 --> 00:00:01,000
749 self
.assertEqual(dfxp2srt(dfxp_data_no_default_namespace
), srt_data
)
751 def test_cli_option(self
):
752 self
.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
753 self
.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
754 self
.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
756 def test_cli_valueless_option(self
):
757 self
.assertEqual(cli_valueless_option(
758 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
759 self
.assertEqual(cli_valueless_option(
760 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
761 self
.assertEqual(cli_valueless_option(
762 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
763 self
.assertEqual(cli_valueless_option(
764 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
765 self
.assertEqual(cli_valueless_option(
766 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
767 self
.assertEqual(cli_valueless_option(
768 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
770 def test_cli_bool_option(self
):
773 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
774 ['--no-check-certificate', 'true'])
777 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator
='='),
778 ['--no-check-certificate=true'])
781 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
782 ['--check-certificate', 'false'])
785 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
786 ['--check-certificate=false'])
789 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
790 ['--check-certificate', 'true'])
793 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
794 ['--check-certificate=true'])
796 def test_ohdave_rsa_encrypt(self
):
797 N
= 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
801 ohdave_rsa_encrypt(b
'aa111222', e
, N
),
802 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
804 if __name__
== '__main__':