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 (
71 from youtube_dl
.compat
import (
72 compat_etree_fromstring
,
76 class TestUtil(unittest
.TestCase
):
77 def test_timeconvert(self
):
78 self
.assertTrue(timeconvert('') is None)
79 self
.assertTrue(timeconvert('bougrg') is None)
81 def test_sanitize_filename(self
):
82 self
.assertEqual(sanitize_filename('abc'), 'abc')
83 self
.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
85 self
.assertEqual(sanitize_filename('123'), '123')
87 self
.assertEqual('abc_de', sanitize_filename('abc/de'))
88 self
.assertFalse('/' in sanitize_filename('abc/de///'))
90 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
91 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
92 self
.assertEqual('yes no', sanitize_filename('yes? no'))
93 self
.assertEqual('this - that', sanitize_filename('this: that'))
95 self
.assertEqual(sanitize_filename('AT&T'), 'AT&T')
97 self
.assertEqual(sanitize_filename(aumlaut
), aumlaut
)
98 tests
= '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
99 self
.assertEqual(sanitize_filename(tests
), tests
)
102 sanitize_filename('New World record at 0:12:34'),
103 'New World record at 0_12_34')
105 self
.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
106 self
.assertEqual(sanitize_filename('--gasdgf', is_id
=True), '--gasdgf')
107 self
.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
108 self
.assertEqual(sanitize_filename('.gasdgf', is_id
=True), '.gasdgf')
112 for fbc
in forbidden
:
113 self
.assertTrue(fbc
not in sanitize_filename(fc
))
115 def test_sanitize_filename_restricted(self
):
116 self
.assertEqual(sanitize_filename('abc', restricted
=True), 'abc')
117 self
.assertEqual(sanitize_filename('abc_d-e', restricted
=True), 'abc_d-e')
119 self
.assertEqual(sanitize_filename('123', restricted
=True), '123')
121 self
.assertEqual('abc_de', sanitize_filename('abc/de', restricted
=True))
122 self
.assertFalse('/' in sanitize_filename('abc/de///', restricted
=True))
124 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted
=True))
125 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted
=True))
126 self
.assertEqual('yes_no', sanitize_filename('yes? no', restricted
=True))
127 self
.assertEqual('this_-_that', sanitize_filename('this: that', restricted
=True))
129 tests
= 'a\xe4b\u4e2d\u56fd\u7684c'
130 self
.assertEqual(sanitize_filename(tests
, restricted
=True), 'a_b_c')
131 self
.assertTrue(sanitize_filename('\xf6', restricted
=True) != '') # No empty filename
133 forbidden
= '"\0\\/&!: \'\t\n()[]{}$;`^,#'
135 for fbc
in forbidden
:
136 self
.assertTrue(fbc
not in sanitize_filename(fc
, restricted
=True))
138 # Handle a common case more neatly
139 self
.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted
=True), 'Song')
140 self
.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted
=True), 'Speech')
141 # .. but make sure the file name is never empty
142 self
.assertTrue(sanitize_filename('-', restricted
=True) != '')
143 self
.assertTrue(sanitize_filename(':', restricted
=True) != '')
145 def test_sanitize_ids(self
):
146 self
.assertEqual(sanitize_filename('_n_cd26wFpw', is_id
=True), '_n_cd26wFpw')
147 self
.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id
=True), '_BD_eEpuzXw')
148 self
.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id
=True), 'N0Y__7-UOdI')
150 def test_sanitize_path(self
):
151 if sys
.platform
!= 'win32':
154 self
.assertEqual(sanitize_path('abc'), 'abc')
155 self
.assertEqual(sanitize_path('abc/def'), 'abc\\def')
156 self
.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
157 self
.assertEqual(sanitize_path('abc|def'), 'abc#def')
158 self
.assertEqual(sanitize_path('<>:"|?*'), '#######')
159 self
.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
160 self
.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
162 self
.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
163 self
.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
165 self
.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
166 self
.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
167 self
.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
168 self
.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
171 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
172 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
175 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
176 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
177 self
.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
178 self
.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
179 self
.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
181 self
.assertEqual(sanitize_path('../abc'), '..\\abc')
182 self
.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
183 self
.assertEqual(sanitize_path('./abc'), 'abc')
184 self
.assertEqual(sanitize_path('./../abc'), '..\\abc')
186 def test_prepend_extension(self
):
187 self
.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
188 self
.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
189 self
.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
190 self
.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
191 self
.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
192 self
.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
194 def test_replace_extension(self
):
195 self
.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
196 self
.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
197 self
.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
198 self
.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
199 self
.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
200 self
.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
202 def test_ordered_set(self
):
203 self
.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
204 self
.assertEqual(orderedSet([]), [])
205 self
.assertEqual(orderedSet([1]), [1])
206 # keep the list ordered
207 self
.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
209 def test_unescape_html(self
):
210 self
.assertEqual(unescapeHTML('%20;'), '%20;')
211 self
.assertEqual(unescapeHTML('/'), '/')
212 self
.assertEqual(unescapeHTML('/'), '/')
214 unescapeHTML('é'), 'é')
216 def test_daterange(self
):
217 _20century
= DateRange("19000101", "20000101")
218 self
.assertFalse("17890714" in _20century
)
219 _ac
= DateRange("00010101")
220 self
.assertTrue("19690721" in _ac
)
221 _firstmilenium
= DateRange(end
="10000101")
222 self
.assertTrue("07110427" in _firstmilenium
)
224 def test_unified_dates(self
):
225 self
.assertEqual(unified_strdate('December 21, 2010'), '20101221')
226 self
.assertEqual(unified_strdate('8/7/2009'), '20090708')
227 self
.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
228 self
.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
229 self
.assertEqual(unified_strdate('1968 12 10'), '19681210')
230 self
.assertEqual(unified_strdate('1968-12-10'), '19681210')
231 self
.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
233 unified_strdate('11/26/2014 11:30:00 AM PST', day_first
=False),
236 unified_strdate('2/2/2015 6:47:40 PM', day_first
=False),
238 self
.assertEqual(unified_strdate('25-09-2014'), '20140925')
240 def test_find_xpath_attr(self
):
248 doc
= compat_etree_fromstring(testxml
)
250 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n'), None)
251 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n', 'v'), None)
252 self
.assertEqual(find_xpath_attr(doc
, './/node', 'n'), None)
253 self
.assertEqual(find_xpath_attr(doc
, './/node', 'n', 'v'), None)
254 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x'), doc
[1])
255 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'a'), doc
[1])
256 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'b'), doc
[3])
257 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y'), doc
[2])
258 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'c'), doc
[2])
259 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'd'), doc
[3])
260 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', ''), doc
[4])
262 def test_xpath_with_ns(self
):
263 testxml
= '''<root xmlns:media="http://example.com/">
265 <media:author>The Author</media:author>
266 <url>http://server.com/download.mp3</url>
269 doc
= compat_etree_fromstring(testxml
)
270 find
= lambda p
: doc
.find(xpath_with_ns(p
, {'media': 'http://example.com/'}
))
271 self
.assertTrue(find('media:song') is not None)
272 self
.assertEqual(find('media:song/media:author').text
, 'The Author')
273 self
.assertEqual(find('media:song/url').text
, 'http://server.com/download.mp3')
275 def test_xpath_element(self
):
276 doc
= xml
.etree
.ElementTree
.Element('root')
277 div
= xml
.etree
.ElementTree
.SubElement(doc
, 'div')
278 p
= xml
.etree
.ElementTree
.SubElement(div
, 'p')
280 self
.assertEqual(xpath_element(doc
, 'div/p'), p
)
281 self
.assertEqual(xpath_element(doc
, ['div/p']), p
)
282 self
.assertEqual(xpath_element(doc
, ['div/bar', 'div/p']), p
)
283 self
.assertEqual(xpath_element(doc
, 'div/bar', default
='default'), 'default')
284 self
.assertEqual(xpath_element(doc
, ['div/bar'], default
='default'), 'default')
285 self
.assertTrue(xpath_element(doc
, 'div/bar') is None)
286 self
.assertTrue(xpath_element(doc
, ['div/bar']) is None)
287 self
.assertTrue(xpath_element(doc
, ['div/bar'], 'div/baz') is None)
288 self
.assertRaises(ExtractorError
, xpath_element
, doc
, 'div/bar', fatal
=True)
289 self
.assertRaises(ExtractorError
, xpath_element
, doc
, ['div/bar'], fatal
=True)
290 self
.assertRaises(ExtractorError
, xpath_element
, doc
, ['div/bar', 'div/baz'], fatal
=True)
292 def test_xpath_text(self
):
298 doc
= compat_etree_fromstring(testxml
)
299 self
.assertEqual(xpath_text(doc
, 'div/p'), 'Foo')
300 self
.assertEqual(xpath_text(doc
, 'div/bar', default
='default'), 'default')
301 self
.assertTrue(xpath_text(doc
, 'div/bar') is None)
302 self
.assertRaises(ExtractorError
, xpath_text
, doc
, 'div/bar', fatal
=True)
304 def test_xpath_attr(self
):
310 doc
= compat_etree_fromstring(testxml
)
311 self
.assertEqual(xpath_attr(doc
, 'div/p', 'x'), 'a')
312 self
.assertEqual(xpath_attr(doc
, 'div/bar', 'x'), None)
313 self
.assertEqual(xpath_attr(doc
, 'div/p', 'y'), None)
314 self
.assertEqual(xpath_attr(doc
, 'div/bar', 'x', default
='default'), 'default')
315 self
.assertEqual(xpath_attr(doc
, 'div/p', 'y', default
='default'), 'default')
316 self
.assertRaises(ExtractorError
, xpath_attr
, doc
, 'div/bar', 'x', fatal
=True)
317 self
.assertRaises(ExtractorError
, xpath_attr
, doc
, 'div/p', 'y', fatal
=True)
319 def test_smuggle_url(self
):
320 data
= {"ö": "ö", "abc": [3]}
321 url
= 'https://foo.bar/baz?x=y#a'
322 smug_url
= smuggle_url(url
, data
)
323 unsmug_url
, unsmug_data
= unsmuggle_url(smug_url
)
324 self
.assertEqual(url
, unsmug_url
)
325 self
.assertEqual(data
, unsmug_data
)
327 res_url
, res_data
= unsmuggle_url(url
)
328 self
.assertEqual(res_url
, url
)
329 self
.assertEqual(res_data
, None)
331 def test_shell_quote(self
):
332 args
= ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
333 self
.assertEqual(shell_quote(args
), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
335 def test_str_to_int(self
):
336 self
.assertEqual(str_to_int('123,456'), 123456)
337 self
.assertEqual(str_to_int('123.456'), 123456)
339 def test_url_basename(self
):
340 self
.assertEqual(url_basename('http://foo.de/'), '')
341 self
.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
342 self
.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
343 self
.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
344 self
.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
346 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
349 def test_parse_duration(self
):
350 self
.assertEqual(parse_duration(None), None)
351 self
.assertEqual(parse_duration(False), None)
352 self
.assertEqual(parse_duration('invalid'), None)
353 self
.assertEqual(parse_duration('1'), 1)
354 self
.assertEqual(parse_duration('1337:12'), 80232)
355 self
.assertEqual(parse_duration('9:12:43'), 33163)
356 self
.assertEqual(parse_duration('12:00'), 720)
357 self
.assertEqual(parse_duration('00:01:01'), 61)
358 self
.assertEqual(parse_duration('x:y'), None)
359 self
.assertEqual(parse_duration('3h11m53s'), 11513)
360 self
.assertEqual(parse_duration('3h 11m 53s'), 11513)
361 self
.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
362 self
.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
363 self
.assertEqual(parse_duration('62m45s'), 3765)
364 self
.assertEqual(parse_duration('6m59s'), 419)
365 self
.assertEqual(parse_duration('49s'), 49)
366 self
.assertEqual(parse_duration('0h0m0s'), 0)
367 self
.assertEqual(parse_duration('0m0s'), 0)
368 self
.assertEqual(parse_duration('0s'), 0)
369 self
.assertEqual(parse_duration('01:02:03.05'), 3723.05)
370 self
.assertEqual(parse_duration('T30M38S'), 1838)
371 self
.assertEqual(parse_duration('5 s'), 5)
372 self
.assertEqual(parse_duration('3 min'), 180)
373 self
.assertEqual(parse_duration('2.5 hours'), 9000)
374 self
.assertEqual(parse_duration('02:03:04'), 7384)
375 self
.assertEqual(parse_duration('01:02:03:04'), 93784)
376 self
.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
377 self
.assertEqual(parse_duration('87 Min.'), 5220)
379 def test_fix_xml_ampersands(self
):
381 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
383 fix_xml_ampersands('"&x=y&wrong;&z=a'),
384 '"&x=y&wrong;&z=a')
386 fix_xml_ampersands('&'><"'),
387 '&'><"')
389 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
390 self
.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
392 def test_paged_list(self
):
393 def testPL(size
, pagesize
, sliceargs
, expected
):
394 def get_page(pagenum
):
395 firstid
= pagenum
* pagesize
396 upto
= min(size
, pagenum
* pagesize
+ pagesize
)
397 for i
in range(firstid
, upto
):
400 pl
= OnDemandPagedList(get_page
, pagesize
)
401 got
= pl
.getslice(*sliceargs
)
402 self
.assertEqual(got
, expected
)
404 iapl
= InAdvancePagedList(get_page
, size
// pagesize
+ 1, pagesize
)
405 got
= iapl
.getslice(*sliceargs
)
406 self
.assertEqual(got
, expected
)
408 testPL(5, 2, (), [0, 1, 2, 3, 4])
409 testPL(5, 2, (1,), [1, 2, 3, 4])
410 testPL(5, 2, (2,), [2, 3, 4])
411 testPL(5, 2, (4,), [4])
412 testPL(5, 2, (0, 3), [0, 1, 2])
413 testPL(5, 2, (1, 4), [1, 2, 3])
414 testPL(5, 2, (2, 99), [2, 3, 4])
415 testPL(5, 2, (20, 99), [])
417 def test_struct_unpack(self
):
418 self
.assertEqual(struct_unpack('!B', b
'\x00'), (0,))
420 def test_read_batch_urls(self
):
421 f
= io
.StringIO('''\xef\xbb\xbf foo
424 # More after this line\r
427 self
.assertEqual(read_batch_urls(f
), ['foo', 'bar', 'baz', 'bam'])
429 def test_urlencode_postdata(self
):
430 data
= urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'}
)
431 self
.assertTrue(isinstance(data
, bytes))
433 def test_parse_iso8601(self
):
434 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
435 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
436 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
437 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
438 self
.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
439 self
.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
441 def test_strip_jsonp(self
):
442 stripped
= strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
443 d
= json
.loads(stripped
)
444 self
.assertEqual(d
, [{"id": "532cb", "x": 3}
])
446 stripped
= strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
447 d
= json
.loads(stripped
)
448 self
.assertEqual(d
, {'STATUS': 'OK'}
)
450 def test_uppercase_escape(self
):
451 self
.assertEqual(uppercase_escape('aä'), 'aä')
452 self
.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
454 def test_lowercase_escape(self
):
455 self
.assertEqual(lowercase_escape('aä'), 'aä')
456 self
.assertEqual(lowercase_escape('\\u0026'), '&')
458 def test_limit_length(self
):
459 self
.assertEqual(limit_length(None, 12), None)
460 self
.assertEqual(limit_length('foo', 12), 'foo')
462 limit_length('foo bar baz asd', 12).startswith('foo bar'))
463 self
.assertTrue('...' in limit_length('foo bar baz asd', 12))
465 def test_escape_rfc3986(self
):
466 reserved
= "!*'();:@&=+$,/?#[]"
467 unreserved
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
468 self
.assertEqual(escape_rfc3986(reserved
), reserved
)
469 self
.assertEqual(escape_rfc3986(unreserved
), unreserved
)
470 self
.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
471 self
.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
472 self
.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
473 self
.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
475 def test_escape_url(self
):
477 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
478 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
481 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'),
482 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
485 escape_url('http://тест.рф/фрагмент'),
486 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
489 escape_url('http://тест.рф/абв?абв=абв#абв'),
490 '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'
492 self
.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
494 def test_js_to_json_realworld(self
):
496 'clip':{'provider':'pseudo'}
498 self
.assertEqual(js_to_json(inp
), '''{
499 "clip":{"provider":"pseudo"}
501 json
.loads(js_to_json(inp
))
504 'playlist':[{'controls':{'all':null}}]
506 self
.assertEqual(js_to_json(inp
), '''{
507 "playlist":[{"controls":{"all":null}}]
510 inp
= '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
511 self
.assertEqual(js_to_json(inp
), '''"The CW's 'Crazy Ex-Girlfriend'"''')
513 inp
= '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
514 json_code
= js_to_json(inp
)
515 self
.assertEqual(json
.loads(json_code
), json
.loads(inp
))
517 def test_js_to_json_edgecases(self
):
518 on
= js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
519 self
.assertEqual(json
.loads(on
), {"abc_def": "1'\\2\\'3\"4"}
)
521 on
= js_to_json('{"abc": true}')
522 self
.assertEqual(json
.loads(on
), {'abc': True}
)
524 # Ignore JavaScript code as well
531 self
.assertEqual(d
['x'], 1)
532 self
.assertEqual(d
['y'], 'a')
534 on
= js_to_json('["abc", "def",]')
535 self
.assertEqual(json
.loads(on
), ['abc', 'def'])
537 on
= js_to_json('{"abc": "def",}')
538 self
.assertEqual(json
.loads(on
), {'abc': 'def'}
)
540 def test_clean_html(self
):
541 self
.assertEqual(clean_html('a:\nb'), 'a: b')
542 self
.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
544 def test_intlist_to_bytes(self
):
546 intlist_to_bytes([0, 1, 127, 128, 255]),
547 b
'\x00\x01\x7f\x80\xff')
549 def test_args_to_str(self
):
551 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
552 'foo ba/r -baz \'2 be\' \'\''
555 def test_parse_filesize(self
):
556 self
.assertEqual(parse_filesize(None), None)
557 self
.assertEqual(parse_filesize(''), None)
558 self
.assertEqual(parse_filesize('91 B'), 91)
559 self
.assertEqual(parse_filesize('foobar'), None)
560 self
.assertEqual(parse_filesize('2 MiB'), 2097152)
561 self
.assertEqual(parse_filesize('5 GB'), 5000000000)
562 self
.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
563 self
.assertEqual(parse_filesize('1,24 KB'), 1240)
565 def test_version_tuple(self
):
566 self
.assertEqual(version_tuple('1'), (1,))
567 self
.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
568 self
.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
570 def test_detect_exe_version(self
):
571 self
.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
572 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
573 configuration: --prefix=/usr --extra-'''), '1.2.1')
574 self
.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
575 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
576 self
.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
577 Trying to open render node...
578 Success at /dev/dri/renderD128.
579 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
581 def test_age_restricted(self
):
582 self
.assertFalse(age_restricted(None, 10)) # unrestricted content
583 self
.assertFalse(age_restricted(1, None)) # unrestricted policy
584 self
.assertFalse(age_restricted(8, 10))
585 self
.assertTrue(age_restricted(18, 14))
586 self
.assertFalse(age_restricted(18, 18))
588 def test_is_html(self
):
589 self
.assertFalse(is_html(b
'\x49\x44\x43<html'))
590 self
.assertTrue(is_html(b
'<!DOCTYPE foo>\xaaa'))
591 self
.assertTrue(is_html( # UTF-8 with BOM
592 b
'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
593 self
.assertTrue(is_html( # UTF-16-LE
594 b
'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
596 self
.assertTrue(is_html( # UTF-16-BE
597 b
'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
599 self
.assertTrue(is_html( # UTF-32-BE
600 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'))
601 self
.assertTrue(is_html( # UTF-32-LE
602 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'))
604 def test_render_table(self
):
608 [[123, 4], [9999, 51]]),
613 def test_match_str(self
):
614 self
.assertRaises(ValueError, match_str
, 'xy>foobar', {})
615 self
.assertFalse(match_str('xy', {'x': 1200}
))
616 self
.assertTrue(match_str('!xy', {'x': 1200}
))
617 self
.assertTrue(match_str('x', {'x': 1200}
))
618 self
.assertFalse(match_str('!x', {'x': 1200}
))
619 self
.assertTrue(match_str('x', {'x': 0}
))
620 self
.assertFalse(match_str('x>0', {'x': 0}
))
621 self
.assertFalse(match_str('x>0', {}))
622 self
.assertTrue(match_str('x>?0', {}))
623 self
.assertTrue(match_str('x>1K', {'x': 1200}
))
624 self
.assertFalse(match_str('x>2K', {'x': 1200}
))
625 self
.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}
))
626 self
.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}
))
627 self
.assertFalse(match_str('y=a212', {'y': 'foobar42'}
))
628 self
.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}
))
629 self
.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}
))
630 self
.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}
))
631 self
.assertFalse(match_str(
632 'like_count > 100 & dislike_count <? 50 & description',
633 {'like_count': 90, 'description': 'foo'}
))
634 self
.assertTrue(match_str(
635 'like_count > 100 & dislike_count <? 50 & description',
636 {'like_count': 190, 'description': 'foo'}
))
637 self
.assertFalse(match_str(
638 'like_count > 100 & dislike_count <? 50 & description',
639 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}
))
640 self
.assertFalse(match_str(
641 'like_count > 100 & dislike_count <? 50 & description',
642 {'like_count': 190, 'dislike_count': 10}
))
644 def test_parse_dfxp_time_expr(self
):
645 self
.assertEqual(parse_dfxp_time_expr(None), 0.0)
646 self
.assertEqual(parse_dfxp_time_expr(''), 0.0)
647 self
.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
648 self
.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
649 self
.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
650 self
.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
652 def test_dfxp2srt(self
):
653 dfxp_data
= '''<?xml version="1.0" encoding="UTF-8"?>
654 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
657 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
658 <p begin="1" end="2">第二行<br/>♪♪</p>
659 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
664 00:00:00,000 --> 00:00:01,000
665 The following line contains Chinese characters and special symbols
668 00:00:01,000 --> 00:00:02,000
673 00:00:02,000 --> 00:00:03,000
678 self
.assertEqual(dfxp2srt(dfxp_data
), srt_data
)
680 dfxp_data_no_default_namespace
= '''<?xml version="1.0" encoding="UTF-8"?>
681 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
684 <p begin="0" end="1">The first line</p>
689 00:00:00,000 --> 00:00:01,000
693 self
.assertEqual(dfxp2srt(dfxp_data_no_default_namespace
), srt_data
)
695 def test_cli_option(self
):
696 self
.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}
, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
697 self
.assertEqual(cli_option({'proxy': None}
, '--proxy', 'proxy'), [])
698 self
.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
700 def test_cli_valueless_option(self
):
701 self
.assertEqual(cli_valueless_option(
702 {'downloader': 'external'}
, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
703 self
.assertEqual(cli_valueless_option(
704 {'downloader': 'internal'}
, '--external-downloader', 'downloader', 'external'), [])
705 self
.assertEqual(cli_valueless_option(
706 {'nocheckcertificate': True}
, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
707 self
.assertEqual(cli_valueless_option(
708 {'nocheckcertificate': False}
, '--no-check-certificate', 'nocheckcertificate'), [])
709 self
.assertEqual(cli_valueless_option(
710 {'checkcertificate': True}
, '--no-check-certificate', 'checkcertificate', False), [])
711 self
.assertEqual(cli_valueless_option(
712 {'checkcertificate': False}
, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
714 def test_cli_bool_option(self
):
717 {'nocheckcertificate': True}
, '--no-check-certificate', 'nocheckcertificate'),
718 ['--no-check-certificate', 'true'])
721 {'nocheckcertificate': True}
, '--no-check-certificate', 'nocheckcertificate', separator
='='),
722 ['--no-check-certificate=true'])
725 {'nocheckcertificate': True}
, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
726 ['--check-certificate', 'false'])
729 {'nocheckcertificate': True}
, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
730 ['--check-certificate=false'])
733 {'nocheckcertificate': False}
, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
734 ['--check-certificate', 'true'])
737 {'nocheckcertificate': False}
, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
738 ['--check-certificate=true'])
741 if __name__
== '__main__':