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 (
80 from youtube_dl.compat import (
82 compat_etree_fromstring,
88 class TestUtil(unittest.TestCase):
89 def test_timeconvert(self):
90 self.assertTrue(timeconvert('') is None)
91 self.assertTrue(timeconvert('bougrg') is None)
93 def test_sanitize_filename(self):
94 self.assertEqual(sanitize_filename('abc'), 'abc')
95 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
97 self.assertEqual(sanitize_filename('123'), '123')
99 self.assertEqual('abc_de', sanitize_filename('abc/de'))
100 self.assertFalse('/' in sanitize_filename('abc/de///'))
102 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
103 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
104 self.assertEqual('yes no', sanitize_filename('yes? no'))
105 self.assertEqual('this - that', sanitize_filename('this: that'))
107 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
109 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
110 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
111 self.assertEqual(sanitize_filename(tests), tests)
114 sanitize_filename('New World record at 0:12:34'),
115 'New World record at 0_12_34')
117 self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
118 self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
119 self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
120 self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
124 for fbc in forbidden:
125 self.assertTrue(fbc not in sanitize_filename(fc))
127 def test_sanitize_filename_restricted(self):
128 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
129 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
131 self.assertEqual(sanitize_filename('123', restricted=True), '123')
133 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
134 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
136 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
137 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
138 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
139 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
141 tests = 'a\xe4b\u4e2d\u56fd\u7684c'
142 self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
143 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
145 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
147 for fbc in forbidden:
148 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
150 # Handle a common case more neatly
151 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
152 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
153 # .. but make sure the file name is never empty
154 self.assertTrue(sanitize_filename('-', restricted=True) != '')
155 self.assertTrue(sanitize_filename(':', restricted=True) != '')
157 def test_sanitize_ids(self):
158 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
159 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
160 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
162 def test_sanitize_path(self):
163 if sys.platform != 'win32':
166 self.assertEqual(sanitize_path('abc'), 'abc')
167 self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
168 self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
169 self.assertEqual(sanitize_path('abc|def'), 'abc#def')
170 self.assertEqual(sanitize_path('<>:"|?*'), '#######')
171 self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
172 self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
174 self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
175 self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
177 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
178 self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
179 self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
180 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
183 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
184 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
187 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
188 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
189 self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
190 self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
191 self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
193 self.assertEqual(sanitize_path('../abc'), '..\\abc')
194 self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
195 self.assertEqual(sanitize_path('./abc'), 'abc')
196 self.assertEqual(sanitize_path('./../abc'), '..\\abc')
198 def test_prepend_extension(self):
199 self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
200 self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
201 self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
202 self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
203 self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
204 self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
206 def test_replace_extension(self):
207 self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
208 self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
209 self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
210 self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
211 self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
212 self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
214 def test_remove_quotes(self):
215 self.assertEqual(remove_quotes(None), None)
216 self.assertEqual(remove_quotes('"'), '"')
217 self.assertEqual(remove_quotes("'"), "'")
218 self.assertEqual(remove_quotes(';'), ';')
219 self.assertEqual(remove_quotes('";'), '";')
220 self.assertEqual(remove_quotes('""'), '')
221 self.assertEqual(remove_quotes('";"'), ';')
223 def test_ordered_set(self):
224 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
225 self.assertEqual(orderedSet([]), [])
226 self.assertEqual(orderedSet([1]), [1])
227 # keep the list ordered
228 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
230 def test_unescape_html(self):
231 self.assertEqual(unescapeHTML('%20;'), '%20;')
232 self.assertEqual(unescapeHTML('/'), '/')
233 self.assertEqual(unescapeHTML('/'), '/')
234 self.assertEqual(unescapeHTML('é'), 'é')
235 self.assertEqual(unescapeHTML('�'), '�')
237 def test_daterange(self):
238 _20century = DateRange("19000101", "20000101")
239 self.assertFalse("17890714" in _20century)
240 _ac = DateRange("00010101")
241 self.assertTrue("19690721" in _ac)
242 _firstmilenium = DateRange(end="10000101")
243 self.assertTrue("07110427" in _firstmilenium)
245 def test_unified_dates(self):
246 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
247 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
248 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
249 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
250 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
251 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
252 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
254 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
257 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
259 self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
260 self.assertEqual(unified_strdate('25-09-2014'), '20140925')
261 self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
263 def test_determine_ext(self):
264 self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
265 self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
266 self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
267 self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
268 self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
270 def test_find_xpath_attr(self):
278 doc = compat_etree_fromstring(testxml)
280 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
281 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
282 self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
283 self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
284 self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
285 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
286 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
287 self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
288 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
289 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
290 self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
292 def test_xpath_with_ns(self):
293 testxml = '''<root xmlns:media="http://example.com/">
295 <media:author>The Author</media:author>
296 <url>http://server.com/download.mp3</url>
299 doc = compat_etree_fromstring(testxml)
300 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
301 self.assertTrue(find('media:song') is not None)
302 self.assertEqual(find('media:song/media:author').text, 'The Author')
303 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
305 def test_xpath_element(self):
306 doc = xml.etree.ElementTree.Element('root')
307 div = xml.etree.ElementTree.SubElement(doc, 'div')
308 p = xml.etree.ElementTree.SubElement(div, 'p')
310 self.assertEqual(xpath_element(doc, 'div/p'), p)
311 self.assertEqual(xpath_element(doc, ['div/p']), p)
312 self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
313 self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
314 self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
315 self.assertTrue(xpath_element(doc, 'div/bar') is None)
316 self.assertTrue(xpath_element(doc, ['div/bar']) is None)
317 self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
318 self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
319 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
320 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
322 def test_xpath_text(self):
328 doc = compat_etree_fromstring(testxml)
329 self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
330 self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
331 self.assertTrue(xpath_text(doc, 'div/bar') is None)
332 self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
334 def test_xpath_attr(self):
340 doc = compat_etree_fromstring(testxml)
341 self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
342 self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
343 self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
344 self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
345 self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
346 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
347 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
349 def test_smuggle_url(self):
350 data = {"ö": "ö", "abc": [3]}
351 url = 'https://foo.bar/baz?x=y#a'
352 smug_url = smuggle_url(url, data)
353 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
354 self.assertEqual(url, unsmug_url)
355 self.assertEqual(data, unsmug_data)
357 res_url, res_data = unsmuggle_url(url)
358 self.assertEqual(res_url, url)
359 self.assertEqual(res_data, None)
361 def test_shell_quote(self):
362 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
363 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
365 def test_str_to_int(self):
366 self.assertEqual(str_to_int('123,456'), 123456)
367 self.assertEqual(str_to_int('123.456'), 123456)
369 def test_url_basename(self):
370 self.assertEqual(url_basename('http://foo.de/'), '')
371 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
372 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
373 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
374 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
376 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
379 def test_parse_duration(self):
380 self.assertEqual(parse_duration(None), None)
381 self.assertEqual(parse_duration(False), None)
382 self.assertEqual(parse_duration('invalid'), None)
383 self.assertEqual(parse_duration('1'), 1)
384 self.assertEqual(parse_duration('1337:12'), 80232)
385 self.assertEqual(parse_duration('9:12:43'), 33163)
386 self.assertEqual(parse_duration('12:00'), 720)
387 self.assertEqual(parse_duration('00:01:01'), 61)
388 self.assertEqual(parse_duration('x:y'), None)
389 self.assertEqual(parse_duration('3h11m53s'), 11513)
390 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
391 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
392 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
393 self.assertEqual(parse_duration('62m45s'), 3765)
394 self.assertEqual(parse_duration('6m59s'), 419)
395 self.assertEqual(parse_duration('49s'), 49)
396 self.assertEqual(parse_duration('0h0m0s'), 0)
397 self.assertEqual(parse_duration('0m0s'), 0)
398 self.assertEqual(parse_duration('0s'), 0)
399 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
400 self.assertEqual(parse_duration('T30M38S'), 1838)
401 self.assertEqual(parse_duration('5 s'), 5)
402 self.assertEqual(parse_duration('3 min'), 180)
403 self.assertEqual(parse_duration('2.5 hours'), 9000)
404 self.assertEqual(parse_duration('02:03:04'), 7384)
405 self.assertEqual(parse_duration('01:02:03:04'), 93784)
406 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
407 self.assertEqual(parse_duration('87 Min.'), 5220)
409 def test_fix_xml_ampersands(self):
411 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
413 fix_xml_ampersands('"&x=y&wrong;&z=a'),
414 '"&x=y&wrong;&z=a')
416 fix_xml_ampersands('&'><"'),
417 '&'><"')
419 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
420 self.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
422 def test_paged_list(self):
423 def testPL(size, pagesize, sliceargs, expected):
424 def get_page(pagenum):
425 firstid = pagenum * pagesize
426 upto = min(size, pagenum * pagesize + pagesize)
427 for i in range(firstid, upto):
430 pl = OnDemandPagedList(get_page, pagesize)
431 got = pl.getslice(*sliceargs)
432 self.assertEqual(got, expected)
434 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
435 got = iapl.getslice(*sliceargs)
436 self.assertEqual(got, expected)
438 testPL(5, 2, (), [0, 1, 2, 3, 4])
439 testPL(5, 2, (1,), [1, 2, 3, 4])
440 testPL(5, 2, (2,), [2, 3, 4])
441 testPL(5, 2, (4,), [4])
442 testPL(5, 2, (0, 3), [0, 1, 2])
443 testPL(5, 2, (1, 4), [1, 2, 3])
444 testPL(5, 2, (2, 99), [2, 3, 4])
445 testPL(5, 2, (20, 99), [])
447 def test_struct_unpack(self):
448 self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
450 def test_read_batch_urls(self):
451 f = io.StringIO('''\xef\xbb\xbf foo
454 # More after this line\r
457 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
459 def test_urlencode_postdata(self):
460 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
461 self.assertTrue(isinstance(data, bytes))
463 def test_update_url_query(self):
465 return compat_parse_qs(compat_urlparse.urlparse(url).query)
466 self.assertEqual(query_dict(update_url_query(
467 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
468 query_dict('http://example.com/path?quality=HD&format=mp4'))
469 self.assertEqual(query_dict(update_url_query(
470 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
471 query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
472 self.assertEqual(query_dict(update_url_query(
473 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
474 query_dict('http://example.com/path?fields=id,formats,subtitles'))
475 self.assertEqual(query_dict(update_url_query(
476 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
477 query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
478 self.assertEqual(query_dict(update_url_query(
479 'http://example.com/path?manifest=f4m', {'manifest': []})),
480 query_dict('http://example.com/path'))
481 self.assertEqual(query_dict(update_url_query(
482 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
483 query_dict('http://example.com/path?system=LINUX'))
484 self.assertEqual(query_dict(update_url_query(
485 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
486 query_dict('http://example.com/path?fields=id,formats,subtitles'))
487 self.assertEqual(query_dict(update_url_query(
488 'http://example.com/path', {'width': 1080, 'height': 720})),
489 query_dict('http://example.com/path?width=1080&height=720'))
490 self.assertEqual(query_dict(update_url_query(
491 'http://example.com/path', {'bitrate': 5020.43})),
492 query_dict('http://example.com/path?bitrate=5020.43'))
493 self.assertEqual(query_dict(update_url_query(
494 'http://example.com/path', {'test': '第二行тест'})),
495 query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
497 def test_dict_get(self):
505 d = FALSE_VALUES.copy()
507 self.assertEqual(dict_get(d, 'a'), 42)
508 self.assertEqual(dict_get(d, 'b'), None)
509 self.assertEqual(dict_get(d, 'b', 42), 42)
510 self.assertEqual(dict_get(d, ('a', )), 42)
511 self.assertEqual(dict_get(d, ('b', 'a', )), 42)
512 self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
513 self.assertEqual(dict_get(d, ('b', 'c', )), None)
514 self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
515 for key, false_value in FALSE_VALUES.items():
516 self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
517 self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
519 def test_encode_compat_str(self):
520 self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
521 self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
523 def test_parse_iso8601(self):
524 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
525 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
526 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
527 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
528 self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
529 self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
531 def test_strip_jsonp(self):
532 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
533 d = json.loads(stripped)
534 self.assertEqual(d, [{"id": "532cb", "x": 3}])
536 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
537 d = json.loads(stripped)
538 self.assertEqual(d, {'STATUS': 'OK'})
540 stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
541 d = json.loads(stripped)
542 self.assertEqual(d, {'status': 'success'})
544 def test_uppercase_escape(self):
545 self.assertEqual(uppercase_escape('aä'), 'aä')
546 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
548 def test_lowercase_escape(self):
549 self.assertEqual(lowercase_escape('aä'), 'aä')
550 self.assertEqual(lowercase_escape('\\u0026'), '&')
552 def test_limit_length(self):
553 self.assertEqual(limit_length(None, 12), None)
554 self.assertEqual(limit_length('foo', 12), 'foo')
556 limit_length('foo bar baz asd', 12).startswith('foo bar'))
557 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
559 def test_escape_rfc3986(self):
560 reserved = "!*'();:@&=+$,/?#[]"
561 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
562 self.assertEqual(escape_rfc3986(reserved), reserved)
563 self.assertEqual(escape_rfc3986(unreserved), unreserved)
564 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
565 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
566 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
567 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
569 def test_escape_url(self):
571 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
572 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
575 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'),
576 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
579 escape_url('http://тест.рф/фрагмент'),
580 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
583 escape_url('http://тест.рф/абв?абв=абв#абв'),
584 'http://xn--e1aybc.xn--p1ai/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
586 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
588 def test_js_to_json_realworld(self):
590 'clip':{'provider':'pseudo'}
592 self.assertEqual(js_to_json(inp), '''{
593 "clip":{"provider":"pseudo"}
595 json.loads(js_to_json(inp))
598 'playlist':[{'controls':{'all':null}}]
600 self.assertEqual(js_to_json(inp), '''{
601 "playlist":[{"controls":{"all":null}}]
604 inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
605 self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
607 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
608 json_code = js_to_json(inp)
609 self.assertEqual(json.loads(json_code), json.loads(inp))
611 def test_js_to_json_edgecases(self):
612 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
613 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
615 on = js_to_json('{"abc": true}')
616 self.assertEqual(json.loads(on), {'abc': True})
618 # Ignore JavaScript code as well
625 self.assertEqual(d['x'], 1)
626 self.assertEqual(d['y'], 'a')
628 on = js_to_json('["abc", "def",]')
629 self.assertEqual(json.loads(on), ['abc', 'def'])
631 on = js_to_json('{"abc": "def",}')
632 self.assertEqual(json.loads(on), {'abc': 'def'})
634 def test_extract_attributes(self):
635 self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
636 self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
637 self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
638 self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
639 self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
640 self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
641 self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
642 self.assertEqual(extract_attributes('<e x="&">'), {'x': '&'}) # XML
643 self.assertEqual(extract_attributes('<e x=""">'), {'x': '"'})
644 self.assertEqual(extract_attributes('<e x="£">'), {'x': '£'}) # HTML 3.2
645 self.assertEqual(extract_attributes('<e x="λ">'), {'x': 'λ'}) # HTML 4.0
646 self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
647 self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
648 self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
649 self.assertEqual(extract_attributes('<e x >'), {'x': None})
650 self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
651 self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
652 self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
653 self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
654 self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
655 self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
656 self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
657 self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
658 self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
659 self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
660 self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
661 self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
662 self.assertEqual(extract_attributes('<e x="décomposé">'), {'x': 'décompose\u0301'})
663 # "Narrow" Python builds don't support unicode code points outside BMP.
666 supports_outside_bmp = True
668 supports_outside_bmp = False
669 if supports_outside_bmp:
670 self.assertEqual(extract_attributes('<e x="Smile 😀!">'), {'x': 'Smile \U0001f600!'})
672 def test_clean_html(self):
673 self.assertEqual(clean_html('a:\nb'), 'a: b')
674 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
676 def test_intlist_to_bytes(self):
678 intlist_to_bytes([0, 1, 127, 128, 255]),
679 b'\x00\x01\x7f\x80\xff')
681 def test_args_to_str(self):
683 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
684 'foo ba/r -baz \'2 be\' \'\''
687 def test_parse_filesize(self):
688 self.assertEqual(parse_filesize(None), None)
689 self.assertEqual(parse_filesize(''), None)
690 self.assertEqual(parse_filesize('91 B'), 91)
691 self.assertEqual(parse_filesize('foobar'), None)
692 self.assertEqual(parse_filesize('2 MiB'), 2097152)
693 self.assertEqual(parse_filesize('5 GB'), 5000000000)
694 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
695 self.assertEqual(parse_filesize('1,24 KB'), 1240)
697 def test_parse_count(self):
698 self.assertEqual(parse_count(None), None)
699 self.assertEqual(parse_count(''), None)
700 self.assertEqual(parse_count('0'), 0)
701 self.assertEqual(parse_count('1000'), 1000)
702 self.assertEqual(parse_count('1.000'), 1000)
703 self.assertEqual(parse_count('1.1k'), 1100)
704 self.assertEqual(parse_count('1.1kk'), 1100000)
705 self.assertEqual(parse_count('1.1kk '), 1100000)
706 self.assertEqual(parse_count('1.1kk views'), 1100000)
708 def test_version_tuple(self):
709 self.assertEqual(version_tuple('1'), (1,))
710 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
711 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
713 def test_detect_exe_version(self):
714 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
715 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
716 configuration: --prefix=/usr --extra-'''), '1.2.1')
717 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
718 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
719 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
720 Trying to open render node...
721 Success at /dev/dri/renderD128.
722 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
724 def test_age_restricted(self):
725 self.assertFalse(age_restricted(None, 10)) # unrestricted content
726 self.assertFalse(age_restricted(1, None)) # unrestricted policy
727 self.assertFalse(age_restricted(8, 10))
728 self.assertTrue(age_restricted(18, 14))
729 self.assertFalse(age_restricted(18, 18))
731 def test_is_html(self):
732 self.assertFalse(is_html(b'\x49\x44\x43<html'))
733 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
734 self.assertTrue(is_html( # UTF-8 with BOM
735 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
736 self.assertTrue(is_html( # UTF-16-LE
737 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
739 self.assertTrue(is_html( # UTF-16-BE
740 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
742 self.assertTrue(is_html( # UTF-32-BE
743 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'))
744 self.assertTrue(is_html( # UTF-32-LE
745 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'))
747 def test_render_table(self):
751 [[123, 4], [9999, 51]]),
756 def test_match_str(self):
757 self.assertRaises(ValueError, match_str, 'xy>foobar', {})
758 self.assertFalse(match_str('xy', {'x': 1200}))
759 self.assertTrue(match_str('!xy', {'x': 1200}))
760 self.assertTrue(match_str('x', {'x': 1200}))
761 self.assertFalse(match_str('!x', {'x': 1200}))
762 self.assertTrue(match_str('x', {'x': 0}))
763 self.assertFalse(match_str('x>0', {'x': 0}))
764 self.assertFalse(match_str('x>0', {}))
765 self.assertTrue(match_str('x>?0', {}))
766 self.assertTrue(match_str('x>1K', {'x': 1200}))
767 self.assertFalse(match_str('x>2K', {'x': 1200}))
768 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
769 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
770 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
771 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
772 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
773 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
774 self.assertFalse(match_str(
775 'like_count > 100 & dislike_count <? 50 & description',
776 {'like_count': 90, 'description': 'foo'}))
777 self.assertTrue(match_str(
778 'like_count > 100 & dislike_count <? 50 & description',
779 {'like_count': 190, 'description': 'foo'}))
780 self.assertFalse(match_str(
781 'like_count > 100 & dislike_count <? 50 & description',
782 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
783 self.assertFalse(match_str(
784 'like_count > 100 & dislike_count <? 50 & description',
785 {'like_count': 190, 'dislike_count': 10}))
787 def test_parse_dfxp_time_expr(self):
788 self.assertEqual(parse_dfxp_time_expr(None), None)
789 self.assertEqual(parse_dfxp_time_expr(''), None)
790 self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
791 self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
792 self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
793 self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
794 self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
796 def test_dfxp2srt(self):
797 dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
798 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
801 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
802 <p begin="1" end="2">第二行<br/>♪♪</p>
803 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
804 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
805 <p begin="-1" end="-1">Ignore, two</p>
806 <p begin="3" dur="-1">Ignored, three</p>
811 00:00:00,000 --> 00:00:01,000
812 The following line contains Chinese characters and special symbols
815 00:00:01,000 --> 00:00:02,000
820 00:00:02,000 --> 00:00:03,000
825 self.assertEqual(dfxp2srt(dfxp_data), srt_data)
827 dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
828 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
831 <p begin="0" end="1">The first line</p>
836 00:00:00,000 --> 00:00:01,000
840 self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
842 def test_cli_option(self):
843 self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
844 self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
845 self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
847 def test_cli_valueless_option(self):
848 self.assertEqual(cli_valueless_option(
849 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
850 self.assertEqual(cli_valueless_option(
851 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
852 self.assertEqual(cli_valueless_option(
853 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
854 self.assertEqual(cli_valueless_option(
855 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
856 self.assertEqual(cli_valueless_option(
857 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
858 self.assertEqual(cli_valueless_option(
859 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
861 def test_cli_bool_option(self):
864 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
865 ['--no-check-certificate', 'true'])
868 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
869 ['--no-check-certificate=true'])
872 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
873 ['--check-certificate', 'false'])
876 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
877 ['--check-certificate=false'])
880 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
881 ['--check-certificate', 'true'])
884 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
885 ['--check-certificate=true'])
887 def test_ohdave_rsa_encrypt(self):
888 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
892 ohdave_rsa_encrypt(b'aa111222', e, N),
893 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
895 def test_encode_base_n(self):
896 self.assertEqual(encode_base_n(0, 30), '0')
897 self.assertEqual(encode_base_n(80, 30), '2k')
899 custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
900 self.assertEqual(encode_base_n(0, 30, custom_table), '9')
901 self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
903 self.assertRaises(ValueError, encode_base_n, 0, 70)
904 self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
906 if __name__ == '__main__':