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 (
90 from youtube_dl
.compat
import (
92 compat_etree_fromstring
,
98 class TestUtil(unittest
.TestCase
):
99 def test_timeconvert(self
):
100 self
.assertTrue(timeconvert('') is None)
101 self
.assertTrue(timeconvert('bougrg') is None)
103 def test_sanitize_filename(self
):
104 self
.assertEqual(sanitize_filename('abc'), 'abc')
105 self
.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
107 self
.assertEqual(sanitize_filename('123'), '123')
109 self
.assertEqual('abc_de', sanitize_filename('abc/de'))
110 self
.assertFalse('/' in sanitize_filename('abc/de///'))
112 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
113 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
114 self
.assertEqual('yes no', sanitize_filename('yes? no'))
115 self
.assertEqual('this - that', sanitize_filename('this: that'))
117 self
.assertEqual(sanitize_filename('AT&T'), 'AT&T')
119 self
.assertEqual(sanitize_filename(aumlaut
), aumlaut
)
120 tests
= '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
121 self
.assertEqual(sanitize_filename(tests
), tests
)
124 sanitize_filename('New World record at 0:12:34'),
125 'New World record at 0_12_34')
127 self
.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
128 self
.assertEqual(sanitize_filename('--gasdgf', is_id
=True), '--gasdgf')
129 self
.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
130 self
.assertEqual(sanitize_filename('.gasdgf', is_id
=True), '.gasdgf')
134 for fbc
in forbidden
:
135 self
.assertTrue(fbc
not in sanitize_filename(fc
))
137 def test_sanitize_filename_restricted(self
):
138 self
.assertEqual(sanitize_filename('abc', restricted
=True), 'abc')
139 self
.assertEqual(sanitize_filename('abc_d-e', restricted
=True), 'abc_d-e')
141 self
.assertEqual(sanitize_filename('123', restricted
=True), '123')
143 self
.assertEqual('abc_de', sanitize_filename('abc/de', restricted
=True))
144 self
.assertFalse('/' in sanitize_filename('abc/de///', restricted
=True))
146 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted
=True))
147 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted
=True))
148 self
.assertEqual('yes_no', sanitize_filename('yes? no', restricted
=True))
149 self
.assertEqual('this_-_that', sanitize_filename('this: that', restricted
=True))
151 tests
= 'aäb\u4e2d\u56fd\u7684c'
152 self
.assertEqual(sanitize_filename(tests
, restricted
=True), 'aab_c')
153 self
.assertTrue(sanitize_filename('\xf6', restricted
=True) != '') # No empty filename
155 forbidden
= '"\0\\/&!: \'\t\n()[]{}$;`^,#'
157 for fbc
in forbidden
:
158 self
.assertTrue(fbc
not in sanitize_filename(fc
, restricted
=True))
160 # Handle a common case more neatly
161 self
.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted
=True), 'Song')
162 self
.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted
=True), 'Speech')
163 # .. but make sure the file name is never empty
164 self
.assertTrue(sanitize_filename('-', restricted
=True) != '')
165 self
.assertTrue(sanitize_filename(':', restricted
=True) != '')
167 self
.assertEqual(sanitize_filename(
168 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted
=True),
169 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYPssaaaaaaaeceeeeiiiionooooooooeuuuuuypy')
171 def test_sanitize_ids(self
):
172 self
.assertEqual(sanitize_filename('_n_cd26wFpw', is_id
=True), '_n_cd26wFpw')
173 self
.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id
=True), '_BD_eEpuzXw')
174 self
.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id
=True), 'N0Y__7-UOdI')
176 def test_sanitize_path(self
):
177 if sys
.platform
!= 'win32':
180 self
.assertEqual(sanitize_path('abc'), 'abc')
181 self
.assertEqual(sanitize_path('abc/def'), 'abc\\def')
182 self
.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
183 self
.assertEqual(sanitize_path('abc|def'), 'abc#def')
184 self
.assertEqual(sanitize_path('<>:"|?*'), '#######')
185 self
.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
186 self
.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
188 self
.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
189 self
.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
191 self
.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
192 self
.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
193 self
.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
194 self
.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
197 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
198 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
201 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
202 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
203 self
.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
204 self
.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
205 self
.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
207 self
.assertEqual(sanitize_path('../abc'), '..\\abc')
208 self
.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
209 self
.assertEqual(sanitize_path('./abc'), 'abc')
210 self
.assertEqual(sanitize_path('./../abc'), '..\\abc')
212 def test_prepend_extension(self
):
213 self
.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
214 self
.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
215 self
.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
216 self
.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
217 self
.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
218 self
.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
220 def test_replace_extension(self
):
221 self
.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
222 self
.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
223 self
.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
224 self
.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
225 self
.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
226 self
.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
228 def test_remove_start(self
):
229 self
.assertEqual(remove_start(None, 'A - '), None)
230 self
.assertEqual(remove_start('A - B', 'A - '), 'B')
231 self
.assertEqual(remove_start('B - A', 'A - '), 'B - A')
233 def test_remove_end(self
):
234 self
.assertEqual(remove_end(None, ' - B'), None)
235 self
.assertEqual(remove_end('A - B', ' - B'), 'A')
236 self
.assertEqual(remove_end('B - A', ' - B'), 'B - A')
238 def test_remove_quotes(self
):
239 self
.assertEqual(remove_quotes(None), None)
240 self
.assertEqual(remove_quotes('"'), '"')
241 self
.assertEqual(remove_quotes("'"), "'")
242 self
.assertEqual(remove_quotes(';'), ';')
243 self
.assertEqual(remove_quotes('";'), '";')
244 self
.assertEqual(remove_quotes('""'), '')
245 self
.assertEqual(remove_quotes('";"'), ';')
247 def test_ordered_set(self
):
248 self
.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
249 self
.assertEqual(orderedSet([]), [])
250 self
.assertEqual(orderedSet([1]), [1])
251 # keep the list ordered
252 self
.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
254 def test_unescape_html(self
):
255 self
.assertEqual(unescapeHTML('%20;'), '%20;')
256 self
.assertEqual(unescapeHTML('/'), '/')
257 self
.assertEqual(unescapeHTML('/'), '/')
258 self
.assertEqual(unescapeHTML('é'), 'é')
259 self
.assertEqual(unescapeHTML('�'), '�')
261 self
.assertEqual(unescapeHTML('.''), '.\'')
263 def test_date_from_str(self
):
264 self
.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
265 self
.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
266 self
.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
267 self
.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
268 self
.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
270 def test_daterange(self
):
271 _20century
= DateRange("19000101", "20000101")
272 self
.assertFalse("17890714" in _20century
)
273 _ac
= DateRange("00010101")
274 self
.assertTrue("19690721" in _ac
)
275 _firstmilenium
= DateRange(end
="10000101")
276 self
.assertTrue("07110427" in _firstmilenium
)
278 def test_unified_dates(self
):
279 self
.assertEqual(unified_strdate('December 21, 2010'), '20101221')
280 self
.assertEqual(unified_strdate('8/7/2009'), '20090708')
281 self
.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
282 self
.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
283 self
.assertEqual(unified_strdate('1968 12 10'), '19681210')
284 self
.assertEqual(unified_strdate('1968-12-10'), '19681210')
285 self
.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
287 unified_strdate('11/26/2014 11:30:00 AM PST', day_first
=False),
290 unified_strdate('2/2/2015 6:47:40 PM', day_first
=False),
292 self
.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
293 self
.assertEqual(unified_strdate('25-09-2014'), '20140925')
294 self
.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
295 self
.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
296 self
.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
298 def test_unified_timestamps(self
):
299 self
.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
300 self
.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
301 self
.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
302 self
.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
303 self
.assertEqual(unified_timestamp('1968 12 10'), -33436800)
304 self
.assertEqual(unified_timestamp('1968-12-10'), -33436800)
305 self
.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
307 unified_timestamp('11/26/2014 11:30:00 AM PST', day_first
=False),
310 unified_timestamp('2/2/2015 6:47:40 PM', day_first
=False),
312 self
.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
313 self
.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
314 self
.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
315 self
.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
316 self
.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
317 self
.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
319 def test_determine_ext(self
):
320 self
.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
321 self
.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
322 self
.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
323 self
.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
324 self
.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
326 def test_find_xpath_attr(self
):
334 doc
= compat_etree_fromstring(testxml
)
336 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n'), None)
337 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n', 'v'), None)
338 self
.assertEqual(find_xpath_attr(doc
, './/node', 'n'), None)
339 self
.assertEqual(find_xpath_attr(doc
, './/node', 'n', 'v'), None)
340 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x'), doc
[1])
341 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'a'), doc
[1])
342 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'b'), doc
[3])
343 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y'), doc
[2])
344 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'c'), doc
[2])
345 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'd'), doc
[3])
346 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', ''), doc
[4])
348 def test_xpath_with_ns(self
):
349 testxml
= '''<root xmlns:media="http://example.com/">
351 <media:author>The Author</media:author>
352 <url>http://server.com/download.mp3</url>
355 doc
= compat_etree_fromstring(testxml
)
356 find
= lambda p
: doc
.find(xpath_with_ns(p
, {'media': 'http://example.com/'}))
357 self
.assertTrue(find('media:song') is not None)
358 self
.assertEqual(find('media:song/media:author').text
, 'The Author')
359 self
.assertEqual(find('media:song/url').text
, 'http://server.com/download.mp3')
361 def test_xpath_element(self
):
362 doc
= xml
.etree
.ElementTree
.Element('root')
363 div
= xml
.etree
.ElementTree
.SubElement(doc
, 'div')
364 p
= xml
.etree
.ElementTree
.SubElement(div
, 'p')
366 self
.assertEqual(xpath_element(doc
, 'div/p'), p
)
367 self
.assertEqual(xpath_element(doc
, ['div/p']), p
)
368 self
.assertEqual(xpath_element(doc
, ['div/bar', 'div/p']), p
)
369 self
.assertEqual(xpath_element(doc
, 'div/bar', default
='default'), 'default')
370 self
.assertEqual(xpath_element(doc
, ['div/bar'], default
='default'), 'default')
371 self
.assertTrue(xpath_element(doc
, 'div/bar') is None)
372 self
.assertTrue(xpath_element(doc
, ['div/bar']) is None)
373 self
.assertTrue(xpath_element(doc
, ['div/bar'], 'div/baz') is None)
374 self
.assertRaises(ExtractorError
, xpath_element
, doc
, 'div/bar', fatal
=True)
375 self
.assertRaises(ExtractorError
, xpath_element
, doc
, ['div/bar'], fatal
=True)
376 self
.assertRaises(ExtractorError
, xpath_element
, doc
, ['div/bar', 'div/baz'], fatal
=True)
378 def test_xpath_text(self
):
384 doc
= compat_etree_fromstring(testxml
)
385 self
.assertEqual(xpath_text(doc
, 'div/p'), 'Foo')
386 self
.assertEqual(xpath_text(doc
, 'div/bar', default
='default'), 'default')
387 self
.assertTrue(xpath_text(doc
, 'div/bar') is None)
388 self
.assertRaises(ExtractorError
, xpath_text
, doc
, 'div/bar', fatal
=True)
390 def test_xpath_attr(self
):
396 doc
= compat_etree_fromstring(testxml
)
397 self
.assertEqual(xpath_attr(doc
, 'div/p', 'x'), 'a')
398 self
.assertEqual(xpath_attr(doc
, 'div/bar', 'x'), None)
399 self
.assertEqual(xpath_attr(doc
, 'div/p', 'y'), None)
400 self
.assertEqual(xpath_attr(doc
, 'div/bar', 'x', default
='default'), 'default')
401 self
.assertEqual(xpath_attr(doc
, 'div/p', 'y', default
='default'), 'default')
402 self
.assertRaises(ExtractorError
, xpath_attr
, doc
, 'div/bar', 'x', fatal
=True)
403 self
.assertRaises(ExtractorError
, xpath_attr
, doc
, 'div/p', 'y', fatal
=True)
405 def test_smuggle_url(self
):
406 data
= {"ö": "ö", "abc": [3]}
407 url
= 'https://foo.bar/baz?x=y#a'
408 smug_url
= smuggle_url(url
, data
)
409 unsmug_url
, unsmug_data
= unsmuggle_url(smug_url
)
410 self
.assertEqual(url
, unsmug_url
)
411 self
.assertEqual(data
, unsmug_data
)
413 res_url
, res_data
= unsmuggle_url(url
)
414 self
.assertEqual(res_url
, url
)
415 self
.assertEqual(res_data
, None)
417 smug_url
= smuggle_url(url
, {'a': 'b'})
418 smug_smug_url
= smuggle_url(smug_url
, {'c': 'd'})
419 res_url
, res_data
= unsmuggle_url(smug_smug_url
)
420 self
.assertEqual(res_url
, url
)
421 self
.assertEqual(res_data
, {'a': 'b', 'c': 'd'})
423 def test_shell_quote(self
):
424 args
= ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
425 self
.assertEqual(shell_quote(args
), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
427 def test_str_to_int(self
):
428 self
.assertEqual(str_to_int('123,456'), 123456)
429 self
.assertEqual(str_to_int('123.456'), 123456)
431 def test_url_basename(self
):
432 self
.assertEqual(url_basename('http://foo.de/'), '')
433 self
.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
434 self
.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
435 self
.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
436 self
.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
438 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
441 def test_base_url(self
):
442 self
.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
443 self
.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
444 self
.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
445 self
.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
446 self
.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
448 def test_parse_age_limit(self
):
449 self
.assertEqual(parse_age_limit(None), None)
450 self
.assertEqual(parse_age_limit(False), None)
451 self
.assertEqual(parse_age_limit('invalid'), None)
452 self
.assertEqual(parse_age_limit(0), 0)
453 self
.assertEqual(parse_age_limit(18), 18)
454 self
.assertEqual(parse_age_limit(21), 21)
455 self
.assertEqual(parse_age_limit(22), None)
456 self
.assertEqual(parse_age_limit('18'), 18)
457 self
.assertEqual(parse_age_limit('18+'), 18)
458 self
.assertEqual(parse_age_limit('PG-13'), 13)
459 self
.assertEqual(parse_age_limit('TV-14'), 14)
460 self
.assertEqual(parse_age_limit('TV-MA'), 17)
462 def test_parse_duration(self
):
463 self
.assertEqual(parse_duration(None), None)
464 self
.assertEqual(parse_duration(False), None)
465 self
.assertEqual(parse_duration('invalid'), None)
466 self
.assertEqual(parse_duration('1'), 1)
467 self
.assertEqual(parse_duration('1337:12'), 80232)
468 self
.assertEqual(parse_duration('9:12:43'), 33163)
469 self
.assertEqual(parse_duration('12:00'), 720)
470 self
.assertEqual(parse_duration('00:01:01'), 61)
471 self
.assertEqual(parse_duration('x:y'), None)
472 self
.assertEqual(parse_duration('3h11m53s'), 11513)
473 self
.assertEqual(parse_duration('3h 11m 53s'), 11513)
474 self
.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
475 self
.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
476 self
.assertEqual(parse_duration('62m45s'), 3765)
477 self
.assertEqual(parse_duration('6m59s'), 419)
478 self
.assertEqual(parse_duration('49s'), 49)
479 self
.assertEqual(parse_duration('0h0m0s'), 0)
480 self
.assertEqual(parse_duration('0m0s'), 0)
481 self
.assertEqual(parse_duration('0s'), 0)
482 self
.assertEqual(parse_duration('01:02:03.05'), 3723.05)
483 self
.assertEqual(parse_duration('T30M38S'), 1838)
484 self
.assertEqual(parse_duration('5 s'), 5)
485 self
.assertEqual(parse_duration('3 min'), 180)
486 self
.assertEqual(parse_duration('2.5 hours'), 9000)
487 self
.assertEqual(parse_duration('02:03:04'), 7384)
488 self
.assertEqual(parse_duration('01:02:03:04'), 93784)
489 self
.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
490 self
.assertEqual(parse_duration('87 Min.'), 5220)
491 self
.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
493 def test_fix_xml_ampersands(self
):
495 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
497 fix_xml_ampersands('"&x=y&wrong;&z=a'),
498 '"&x=y&wrong;&z=a')
500 fix_xml_ampersands('&'><"'),
501 '&'><"')
503 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
504 self
.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
506 def test_paged_list(self
):
507 def testPL(size
, pagesize
, sliceargs
, expected
):
508 def get_page(pagenum
):
509 firstid
= pagenum
* pagesize
510 upto
= min(size
, pagenum
* pagesize
+ pagesize
)
511 for i
in range(firstid
, upto
):
514 pl
= OnDemandPagedList(get_page
, pagesize
)
515 got
= pl
.getslice(*sliceargs
)
516 self
.assertEqual(got
, expected
)
518 iapl
= InAdvancePagedList(get_page
, size
// pagesize
+ 1, pagesize
)
519 got
= iapl
.getslice(*sliceargs
)
520 self
.assertEqual(got
, expected
)
522 testPL(5, 2, (), [0, 1, 2, 3, 4])
523 testPL(5, 2, (1,), [1, 2, 3, 4])
524 testPL(5, 2, (2,), [2, 3, 4])
525 testPL(5, 2, (4,), [4])
526 testPL(5, 2, (0, 3), [0, 1, 2])
527 testPL(5, 2, (1, 4), [1, 2, 3])
528 testPL(5, 2, (2, 99), [2, 3, 4])
529 testPL(5, 2, (20, 99), [])
531 def test_read_batch_urls(self
):
532 f
= io
.StringIO('''\xef\xbb\xbf foo
535 # More after this line\r
538 self
.assertEqual(read_batch_urls(f
), ['foo', 'bar', 'baz', 'bam'])
540 def test_urlencode_postdata(self
):
541 data
= urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
542 self
.assertTrue(isinstance(data
, bytes))
544 def test_update_url_query(self
):
546 return compat_parse_qs(compat_urlparse
.urlparse(url
).query
)
547 self
.assertEqual(query_dict(update_url_query(
548 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
549 query_dict('http://example.com/path?quality=HD&format=mp4'))
550 self
.assertEqual(query_dict(update_url_query(
551 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
552 query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
553 self
.assertEqual(query_dict(update_url_query(
554 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
555 query_dict('http://example.com/path?fields=id,formats,subtitles'))
556 self
.assertEqual(query_dict(update_url_query(
557 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
558 query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
559 self
.assertEqual(query_dict(update_url_query(
560 'http://example.com/path?manifest=f4m', {'manifest': []})),
561 query_dict('http://example.com/path'))
562 self
.assertEqual(query_dict(update_url_query(
563 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
564 query_dict('http://example.com/path?system=LINUX'))
565 self
.assertEqual(query_dict(update_url_query(
566 'http://example.com/path', {'fields': b
'id,formats,subtitles'})),
567 query_dict('http://example.com/path?fields=id,formats,subtitles'))
568 self
.assertEqual(query_dict(update_url_query(
569 'http://example.com/path', {'width': 1080, 'height': 720})),
570 query_dict('http://example.com/path?width=1080&height=720'))
571 self
.assertEqual(query_dict(update_url_query(
572 'http://example.com/path', {'bitrate': 5020.43})),
573 query_dict('http://example.com/path?bitrate=5020.43'))
574 self
.assertEqual(query_dict(update_url_query(
575 'http://example.com/path', {'test': '第二行тест'})),
576 query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
578 def test_dict_get(self
):
586 d
= FALSE_VALUES
.copy()
588 self
.assertEqual(dict_get(d
, 'a'), 42)
589 self
.assertEqual(dict_get(d
, 'b'), None)
590 self
.assertEqual(dict_get(d
, 'b', 42), 42)
591 self
.assertEqual(dict_get(d
, ('a', )), 42)
592 self
.assertEqual(dict_get(d
, ('b', 'a', )), 42)
593 self
.assertEqual(dict_get(d
, ('b', 'c', 'a', 'd', )), 42)
594 self
.assertEqual(dict_get(d
, ('b', 'c', )), None)
595 self
.assertEqual(dict_get(d
, ('b', 'c', ), 42), 42)
596 for key
, false_value
in FALSE_VALUES
.items():
597 self
.assertEqual(dict_get(d
, ('b', 'c', key
, )), None)
598 self
.assertEqual(dict_get(d
, ('b', 'c', key
, ), skip_false_values
=False), false_value
)
600 def test_encode_compat_str(self
):
601 self
.assertEqual(encode_compat_str(b
'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
602 self
.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
604 def test_parse_iso8601(self
):
605 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
606 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
607 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
608 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
609 self
.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
610 self
.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
612 def test_strip_jsonp(self
):
613 stripped
= strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
614 d
= json
.loads(stripped
)
615 self
.assertEqual(d
, [{"id": "532cb", "x": 3}])
617 stripped
= strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
618 d
= json
.loads(stripped
)
619 self
.assertEqual(d
, {'STATUS': 'OK'})
621 stripped
= strip_jsonp('ps.embedHandler({"status": "success"});')
622 d
= json
.loads(stripped
)
623 self
.assertEqual(d
, {'status': 'success'})
625 def test_uppercase_escape(self
):
626 self
.assertEqual(uppercase_escape('aä'), 'aä')
627 self
.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
629 def test_lowercase_escape(self
):
630 self
.assertEqual(lowercase_escape('aä'), 'aä')
631 self
.assertEqual(lowercase_escape('\\u0026'), '&')
633 def test_limit_length(self
):
634 self
.assertEqual(limit_length(None, 12), None)
635 self
.assertEqual(limit_length('foo', 12), 'foo')
637 limit_length('foo bar baz asd', 12).startswith('foo bar'))
638 self
.assertTrue('...' in limit_length('foo bar baz asd', 12))
640 def test_mimetype2ext(self
):
641 self
.assertEqual(mimetype2ext(None), None)
642 self
.assertEqual(mimetype2ext('video/x-flv'), 'flv')
643 self
.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
644 self
.assertEqual(mimetype2ext('text/vtt'), 'vtt')
645 self
.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
646 self
.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
648 def test_month_by_name(self
):
649 self
.assertEqual(month_by_name(None), None)
650 self
.assertEqual(month_by_name('December', 'en'), 12)
651 self
.assertEqual(month_by_name('décembre', 'fr'), 12)
652 self
.assertEqual(month_by_name('December'), 12)
653 self
.assertEqual(month_by_name('décembre'), None)
654 self
.assertEqual(month_by_name('Unknown', 'unknown'), None)
656 def test_parse_codecs(self
):
657 self
.assertEqual(parse_codecs(''), {})
658 self
.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
659 'vcodec': 'avc1.77.30',
660 'acodec': 'mp4a.40.2',
662 self
.assertEqual(parse_codecs('mp4a.40.2'), {
664 'acodec': 'mp4a.40.2',
666 self
.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
667 'vcodec': 'avc1.42001e',
668 'acodec': 'mp4a.40.5',
670 self
.assertEqual(parse_codecs('avc3.640028'), {
671 'vcodec': 'avc3.640028',
674 self
.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
679 def test_escape_rfc3986(self
):
680 reserved
= "!*'();:@&=+$,/?#[]"
681 unreserved
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
682 self
.assertEqual(escape_rfc3986(reserved
), reserved
)
683 self
.assertEqual(escape_rfc3986(unreserved
), unreserved
)
684 self
.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
685 self
.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
686 self
.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
687 self
.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
689 def test_escape_url(self
):
691 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
692 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
695 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'),
696 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
699 escape_url('http://тест.рф/фрагмент'),
700 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
703 escape_url('http://тест.рф/абв?абв=абв#абв'),
704 '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'
706 self
.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
708 def test_js_to_json_realworld(self
):
710 'clip':{'provider':'pseudo'}
712 self
.assertEqual(js_to_json(inp
), '''{
713 "clip":{"provider":"pseudo"}
715 json
.loads(js_to_json(inp
))
718 'playlist':[{'controls':{'all':null}}]
720 self
.assertEqual(js_to_json(inp
), '''{
721 "playlist":[{"controls":{"all":null}}]
724 inp
= '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
725 self
.assertEqual(js_to_json(inp
), '''"The CW's 'Crazy Ex-Girlfriend'"''')
727 inp
= '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
728 json_code
= js_to_json(inp
)
729 self
.assertEqual(json
.loads(json_code
), json
.loads(inp
))
732 0:{src:'skipped', type: 'application/dash+xml'},
733 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
735 self
.assertEqual(js_to_json(inp
), '''{
736 "0":{"src":"skipped", "type": "application/dash+xml"},
737 "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
740 inp
= '''{"foo":101}'''
741 self
.assertEqual(js_to_json(inp
), '''{"foo":101}''')
743 inp
= '''{"duration": "00:01:07"}'''
744 self
.assertEqual(js_to_json(inp
), '''{"duration": "00:01:07"}''')
746 def test_js_to_json_edgecases(self
):
747 on
= js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
748 self
.assertEqual(json
.loads(on
), {"abc_def": "1'\\2\\'3\"4"})
750 on
= js_to_json('{"abc": true}')
751 self
.assertEqual(json
.loads(on
), {'abc': True})
753 # Ignore JavaScript code as well
760 self
.assertEqual(d
['x'], 1)
761 self
.assertEqual(d
['y'], 'a')
763 on
= js_to_json('["abc", "def",]')
764 self
.assertEqual(json
.loads(on
), ['abc', 'def'])
766 on
= js_to_json('{"abc": "def",}')
767 self
.assertEqual(json
.loads(on
), {'abc': 'def'})
769 on
= js_to_json('{ 0: /* " \n */ ",]" , }')
770 self
.assertEqual(json
.loads(on
), {'0': ',]'})
772 on
= js_to_json(r
'["<p>x<\/p>"]')
773 self
.assertEqual(json
.loads(on
), ['<p>x</p>'])
775 on
= js_to_json(r
'["\xaa"]')
776 self
.assertEqual(json
.loads(on
), ['\u00aa'])
778 on
= js_to_json("['a\\\nb']")
779 self
.assertEqual(json
.loads(on
), ['ab'])
781 on
= js_to_json('{0xff:0xff}')
782 self
.assertEqual(json
.loads(on
), {'255': 255})
784 on
= js_to_json('{077:077}')
785 self
.assertEqual(json
.loads(on
), {'63': 63})
787 on
= js_to_json('{42:42}')
788 self
.assertEqual(json
.loads(on
), {'42': 42})
790 def test_extract_attributes(self
):
791 self
.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
792 self
.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
793 self
.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
794 self
.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
795 self
.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
796 self
.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
797 self
.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
798 self
.assertEqual(extract_attributes('<e x="&">'), {'x': '&'}) # XML
799 self
.assertEqual(extract_attributes('<e x=""">'), {'x': '"'})
800 self
.assertEqual(extract_attributes('<e x="£">'), {'x': '£'}) # HTML 3.2
801 self
.assertEqual(extract_attributes('<e x="λ">'), {'x': 'λ'}) # HTML 4.0
802 self
.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
803 self
.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
804 self
.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
805 self
.assertEqual(extract_attributes('<e x >'), {'x': None})
806 self
.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
807 self
.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
808 self
.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
809 self
.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
810 self
.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
811 self
.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
812 self
.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
813 self
.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
814 self
.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
815 self
.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
816 self
.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
817 self
.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
818 self
.assertEqual(extract_attributes('<e x="décomposé">'), {'x': 'décompose\u0301'})
819 # "Narrow" Python builds don't support unicode code points outside BMP.
822 supports_outside_bmp
= True
824 supports_outside_bmp
= False
825 if supports_outside_bmp
:
826 self
.assertEqual(extract_attributes('<e x="Smile 😀!">'), {'x': 'Smile \U0001f600!'})
828 def test_clean_html(self
):
829 self
.assertEqual(clean_html('a:\nb'), 'a: b')
830 self
.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
832 def test_intlist_to_bytes(self
):
834 intlist_to_bytes([0, 1, 127, 128, 255]),
835 b
'\x00\x01\x7f\x80\xff')
837 def test_args_to_str(self
):
839 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
840 'foo ba/r -baz \'2 be\' \'\''
843 def test_parse_filesize(self
):
844 self
.assertEqual(parse_filesize(None), None)
845 self
.assertEqual(parse_filesize(''), None)
846 self
.assertEqual(parse_filesize('91 B'), 91)
847 self
.assertEqual(parse_filesize('foobar'), None)
848 self
.assertEqual(parse_filesize('2 MiB'), 2097152)
849 self
.assertEqual(parse_filesize('5 GB'), 5000000000)
850 self
.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
851 self
.assertEqual(parse_filesize('1.2tb'), 1200000000000)
852 self
.assertEqual(parse_filesize('1,24 KB'), 1240)
853 self
.assertEqual(parse_filesize('1,24 kb'), 1240)
854 self
.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
856 def test_parse_count(self
):
857 self
.assertEqual(parse_count(None), None)
858 self
.assertEqual(parse_count(''), None)
859 self
.assertEqual(parse_count('0'), 0)
860 self
.assertEqual(parse_count('1000'), 1000)
861 self
.assertEqual(parse_count('1.000'), 1000)
862 self
.assertEqual(parse_count('1.1k'), 1100)
863 self
.assertEqual(parse_count('1.1kk'), 1100000)
864 self
.assertEqual(parse_count('1.1kk '), 1100000)
865 self
.assertEqual(parse_count('1.1kk views'), 1100000)
867 def test_version_tuple(self
):
868 self
.assertEqual(version_tuple('1'), (1,))
869 self
.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
870 self
.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
872 def test_detect_exe_version(self
):
873 self
.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
874 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
875 configuration: --prefix=/usr --extra-'''), '1.2.1')
876 self
.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
877 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
878 self
.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
879 Trying to open render node...
880 Success at /dev/dri/renderD128.
881 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
883 def test_age_restricted(self
):
884 self
.assertFalse(age_restricted(None, 10)) # unrestricted content
885 self
.assertFalse(age_restricted(1, None)) # unrestricted policy
886 self
.assertFalse(age_restricted(8, 10))
887 self
.assertTrue(age_restricted(18, 14))
888 self
.assertFalse(age_restricted(18, 18))
890 def test_is_html(self
):
891 self
.assertFalse(is_html(b
'\x49\x44\x43<html'))
892 self
.assertTrue(is_html(b
'<!DOCTYPE foo>\xaaa'))
893 self
.assertTrue(is_html( # UTF-8 with BOM
894 b
'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
895 self
.assertTrue(is_html( # UTF-16-LE
896 b
'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
898 self
.assertTrue(is_html( # UTF-16-BE
899 b
'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
901 self
.assertTrue(is_html( # UTF-32-BE
902 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'))
903 self
.assertTrue(is_html( # UTF-32-LE
904 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'))
906 def test_render_table(self
):
910 [[123, 4], [9999, 51]]),
915 def test_match_str(self
):
916 self
.assertRaises(ValueError, match_str
, 'xy>foobar', {})
917 self
.assertFalse(match_str('xy', {'x': 1200}))
918 self
.assertTrue(match_str('!xy', {'x': 1200}))
919 self
.assertTrue(match_str('x', {'x': 1200}))
920 self
.assertFalse(match_str('!x', {'x': 1200}))
921 self
.assertTrue(match_str('x', {'x': 0}))
922 self
.assertFalse(match_str('x>0', {'x': 0}))
923 self
.assertFalse(match_str('x>0', {}))
924 self
.assertTrue(match_str('x>?0', {}))
925 self
.assertTrue(match_str('x>1K', {'x': 1200}))
926 self
.assertFalse(match_str('x>2K', {'x': 1200}))
927 self
.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
928 self
.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
929 self
.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
930 self
.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
931 self
.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
932 self
.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
933 self
.assertFalse(match_str(
934 'like_count > 100 & dislike_count <? 50 & description',
935 {'like_count': 90, 'description': 'foo'}))
936 self
.assertTrue(match_str(
937 'like_count > 100 & dislike_count <? 50 & description',
938 {'like_count': 190, 'description': 'foo'}))
939 self
.assertFalse(match_str(
940 'like_count > 100 & dislike_count <? 50 & description',
941 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
942 self
.assertFalse(match_str(
943 'like_count > 100 & dislike_count <? 50 & description',
944 {'like_count': 190, 'dislike_count': 10}))
946 def test_parse_dfxp_time_expr(self
):
947 self
.assertEqual(parse_dfxp_time_expr(None), None)
948 self
.assertEqual(parse_dfxp_time_expr(''), None)
949 self
.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
950 self
.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
951 self
.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
952 self
.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
953 self
.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
955 def test_dfxp2srt(self
):
956 dfxp_data
= '''<?xml version="1.0" encoding="UTF-8"?>
957 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
960 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
961 <p begin="1" end="2">第二行<br/>♪♪</p>
962 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
963 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
964 <p begin="-1" end="-1">Ignore, two</p>
965 <p begin="3" dur="-1">Ignored, three</p>
970 00:00:00,000 --> 00:00:01,000
971 The following line contains Chinese characters and special symbols
974 00:00:01,000 --> 00:00:02,000
979 00:00:02,000 --> 00:00:03,000
984 self
.assertEqual(dfxp2srt(dfxp_data
), srt_data
)
986 dfxp_data_no_default_namespace
= '''<?xml version="1.0" encoding="UTF-8"?>
987 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
990 <p begin="0" end="1">The first line</p>
995 00:00:00,000 --> 00:00:01,000
999 self
.assertEqual(dfxp2srt(dfxp_data_no_default_namespace
), srt_data
)
1001 def test_cli_option(self
):
1002 self
.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
1003 self
.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
1004 self
.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
1005 self
.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
1007 def test_cli_valueless_option(self
):
1008 self
.assertEqual(cli_valueless_option(
1009 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
1010 self
.assertEqual(cli_valueless_option(
1011 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
1012 self
.assertEqual(cli_valueless_option(
1013 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
1014 self
.assertEqual(cli_valueless_option(
1015 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
1016 self
.assertEqual(cli_valueless_option(
1017 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
1018 self
.assertEqual(cli_valueless_option(
1019 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
1021 def test_cli_bool_option(self
):
1024 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
1025 ['--no-check-certificate', 'true'])
1028 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator
='='),
1029 ['--no-check-certificate=true'])
1032 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1033 ['--check-certificate', 'false'])
1036 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1037 ['--check-certificate=false'])
1040 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1041 ['--check-certificate', 'true'])
1044 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1045 ['--check-certificate=true'])
1047 def test_ohdave_rsa_encrypt(self
):
1048 N
= 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
1052 ohdave_rsa_encrypt(b
'aa111222', e
, N
),
1053 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
1055 def test_encode_base_n(self
):
1056 self
.assertEqual(encode_base_n(0, 30), '0')
1057 self
.assertEqual(encode_base_n(80, 30), '2k')
1059 custom_table
= '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
1060 self
.assertEqual(encode_base_n(0, 30, custom_table
), '9')
1061 self
.assertEqual(encode_base_n(80, 30, custom_table
), '7P')
1063 self
.assertRaises(ValueError, encode_base_n
, 0, 70)
1064 self
.assertRaises(ValueError, encode_base_n
, 0, 60, custom_table
)
1066 def test_urshift(self
):
1067 self
.assertEqual(urshift(3, 1), 1)
1068 self
.assertEqual(urshift(-3, 1), 2147483646)
1070 def test_get_element_by_class(self
):
1072 <span class="foo bar">nice</span>
1075 self
.assertEqual(get_element_by_class('foo', html
), 'nice')
1076 self
.assertEqual(get_element_by_class('no-such-class', html
), None)
1079 if __name__
== '__main__':