3 # Allow direct execution
10 sys
.path
.insert(0, os
.path
.dirname(os
.path
.dirname(os
.path
.abspath(__file__
))))
18 import xml
.etree
.ElementTree
20 from yt_dlp
.compat
import (
21 compat_etree_fromstring
,
22 compat_HTMLParseError
,
25 from yt_dlp
.utils
import (
47 determine_file_encoding
,
60 get_element_by_attribute
,
62 get_element_html_by_attribute
,
63 get_element_html_by_class
,
64 get_element_text_and_html_by_tag
,
65 get_elements_by_attribute
,
66 get_elements_by_class
,
67 get_elements_html_by_attribute
,
68 get_elements_html_by_class
,
69 get_elements_text_and_html_by_attribute
,
133 from yt_dlp
.utils
._utils
import _UnsafeExtensionError
134 from yt_dlp
.utils
.networking
import (
142 class TestUtil(unittest
.TestCase
):
143 def test_timeconvert(self
):
144 self
.assertTrue(timeconvert('') is None)
145 self
.assertTrue(timeconvert('bougrg') is None)
147 def test_sanitize_filename(self
):
148 self
.assertEqual(sanitize_filename(''), '')
149 self
.assertEqual(sanitize_filename('abc'), 'abc')
150 self
.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
152 self
.assertEqual(sanitize_filename('123'), '123')
154 self
.assertEqual('abc⧸de', sanitize_filename('abc/de'))
155 self
.assertFalse('/' in sanitize_filename('abc/de///'))
157 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', is_id
=False))
158 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', is_id
=False))
159 self
.assertEqual('yes no', sanitize_filename('yes? no', is_id
=False))
160 self
.assertEqual('this - that', sanitize_filename('this: that', is_id
=False))
162 self
.assertEqual(sanitize_filename('AT&T'), 'AT&T')
164 self
.assertEqual(sanitize_filename(aumlaut
), aumlaut
)
165 tests
= '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
166 self
.assertEqual(sanitize_filename(tests
), tests
)
169 sanitize_filename('New World record at 0:12:34'),
170 'New World record at 0_12_34')
172 self
.assertEqual(sanitize_filename('--gasdgf'), '--gasdgf')
173 self
.assertEqual(sanitize_filename('--gasdgf', is_id
=True), '--gasdgf')
174 self
.assertEqual(sanitize_filename('--gasdgf', is_id
=False), '_-gasdgf')
175 self
.assertEqual(sanitize_filename('.gasdgf'), '.gasdgf')
176 self
.assertEqual(sanitize_filename('.gasdgf', is_id
=True), '.gasdgf')
177 self
.assertEqual(sanitize_filename('.gasdgf', is_id
=False), 'gasdgf')
181 for fbc
in forbidden
:
182 self
.assertTrue(fbc
not in sanitize_filename(fc
))
184 def test_sanitize_filename_restricted(self
):
185 self
.assertEqual(sanitize_filename('abc', restricted
=True), 'abc')
186 self
.assertEqual(sanitize_filename('abc_d-e', restricted
=True), 'abc_d-e')
188 self
.assertEqual(sanitize_filename('123', restricted
=True), '123')
190 self
.assertEqual('abc_de', sanitize_filename('abc/de', restricted
=True))
191 self
.assertFalse('/' in sanitize_filename('abc/de///', restricted
=True))
193 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted
=True))
194 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted
=True))
195 self
.assertEqual('yes_no', sanitize_filename('yes? no', restricted
=True))
196 self
.assertEqual('this_-_that', sanitize_filename('this: that', restricted
=True))
198 tests
= 'aäb\u4e2d\u56fd\u7684c'
199 self
.assertEqual(sanitize_filename(tests
, restricted
=True), 'aab_c')
200 self
.assertTrue(sanitize_filename('\xf6', restricted
=True) != '') # No empty filename
202 forbidden
= '"\0\\/&!: \'\t\n()[]{}$;`^,#'
204 for fbc
in forbidden
:
205 self
.assertTrue(fbc
not in sanitize_filename(fc
, restricted
=True))
207 # Handle a common case more neatly
208 self
.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted
=True), 'Song')
209 self
.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted
=True), 'Speech')
210 # .. but make sure the file name is never empty
211 self
.assertTrue(sanitize_filename('-', restricted
=True) != '')
212 self
.assertTrue(sanitize_filename(':', restricted
=True) != '')
214 self
.assertEqual(sanitize_filename(
215 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted
=True),
216 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYTHssaaaaaaaeceeeeiiiionooooooooeuuuuuythy')
218 def test_sanitize_ids(self
):
219 self
.assertEqual(sanitize_filename('_n_cd26wFpw', is_id
=True), '_n_cd26wFpw')
220 self
.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id
=True), '_BD_eEpuzXw')
221 self
.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id
=True), 'N0Y__7-UOdI')
223 def test_sanitize_path(self
):
224 if sys
.platform
!= 'win32':
227 self
.assertEqual(sanitize_path('abc'), 'abc')
228 self
.assertEqual(sanitize_path('abc/def'), 'abc\\def')
229 self
.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
230 self
.assertEqual(sanitize_path('abc|def'), 'abc#def')
231 self
.assertEqual(sanitize_path('<>:"|?*'), '#######')
232 self
.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
233 self
.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
235 self
.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
236 self
.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
238 self
.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
239 self
.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
240 self
.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
241 self
.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
244 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
245 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
248 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
249 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
250 self
.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
251 self
.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
252 self
.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
254 self
.assertEqual(sanitize_path('../abc'), '..\\abc')
255 self
.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
256 self
.assertEqual(sanitize_path('./abc'), 'abc')
257 self
.assertEqual(sanitize_path('./../abc'), '..\\abc')
259 def test_sanitize_url(self
):
260 self
.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
261 self
.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
262 self
.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
263 self
.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
264 self
.assertEqual(sanitize_url('foo bar'), 'foo bar')
266 def test_expand_path(self
):
268 return f
'%{var}%' if sys
.platform
== 'win32' else f
'${var}'
270 os
.environ
['yt_dlp_EXPATH_PATH'] = 'expanded'
271 self
.assertEqual(expand_path(env('yt_dlp_EXPATH_PATH')), 'expanded')
273 old_home
= os
.environ
.get('HOME')
274 test_str
= R
'C:\Documents and Settings\тест\Application Data'
276 os
.environ
['HOME'] = test_str
277 self
.assertEqual(expand_path(env('HOME')), os
.getenv('HOME'))
278 self
.assertEqual(expand_path('~'), os
.getenv('HOME'))
280 expand_path('~/{}'.format(env('yt_dlp_EXPATH_PATH'))),
281 '{}/expanded'.format(os
.getenv('HOME')))
283 os
.environ
['HOME'] = old_home
or ''
285 _uncommon_extensions
= [
286 ('exe', 'abc.exe.ext'),
287 ('de', 'abc.de.ext'),
292 def test_prepend_extension(self
):
293 self
.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
294 self
.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
295 self
.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
296 self
.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
297 self
.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
298 self
.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
300 # Test uncommon extensions
301 self
.assertEqual(prepend_extension('abc.ext', 'bin'), 'abc.bin.ext')
302 for ext
, result
in self
._uncommon
_extensions
:
303 with self
.assertRaises(_UnsafeExtensionError
):
304 prepend_extension('abc', ext
)
306 self
.assertEqual(prepend_extension('abc.ext', ext
, 'ext'), result
)
308 with self
.assertRaises(_UnsafeExtensionError
):
309 prepend_extension('abc.ext', ext
, 'ext')
310 with self
.assertRaises(_UnsafeExtensionError
):
311 prepend_extension('abc.unexpected_ext', ext
, 'ext')
313 def test_replace_extension(self
):
314 self
.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
315 self
.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
316 self
.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
317 self
.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
318 self
.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
319 self
.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
321 # Test uncommon extensions
322 self
.assertEqual(replace_extension('abc.ext', 'bin'), 'abc.unknown_video')
323 for ext
, _
in self
._uncommon
_extensions
:
324 with self
.assertRaises(_UnsafeExtensionError
):
325 replace_extension('abc', ext
)
326 with self
.assertRaises(_UnsafeExtensionError
):
327 replace_extension('abc.ext', ext
, 'ext')
328 with self
.assertRaises(_UnsafeExtensionError
):
329 replace_extension('abc.unexpected_ext', ext
, 'ext')
331 def test_subtitles_filename(self
):
332 self
.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt'), 'abc.en.vtt')
333 self
.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt', 'ext'), 'abc.en.vtt')
334 self
.assertEqual(subtitles_filename('abc.unexpected_ext', 'en', 'vtt', 'ext'), 'abc.unexpected_ext.en.vtt')
336 def test_remove_start(self
):
337 self
.assertEqual(remove_start(None, 'A - '), None)
338 self
.assertEqual(remove_start('A - B', 'A - '), 'B')
339 self
.assertEqual(remove_start('B - A', 'A - '), 'B - A')
341 def test_remove_end(self
):
342 self
.assertEqual(remove_end(None, ' - B'), None)
343 self
.assertEqual(remove_end('A - B', ' - B'), 'A')
344 self
.assertEqual(remove_end('B - A', ' - B'), 'B - A')
346 def test_remove_quotes(self
):
347 self
.assertEqual(remove_quotes(None), None)
348 self
.assertEqual(remove_quotes('"'), '"')
349 self
.assertEqual(remove_quotes("'"), "'")
350 self
.assertEqual(remove_quotes(';'), ';')
351 self
.assertEqual(remove_quotes('";'), '";')
352 self
.assertEqual(remove_quotes('""'), '')
353 self
.assertEqual(remove_quotes('";"'), ';')
355 def test_ordered_set(self
):
356 self
.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
357 self
.assertEqual(orderedSet([]), [])
358 self
.assertEqual(orderedSet([1]), [1])
359 # keep the list ordered
360 self
.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
362 def test_unescape_html(self
):
363 self
.assertEqual(unescapeHTML('%20;'), '%20;')
364 self
.assertEqual(unescapeHTML('/'), '/')
365 self
.assertEqual(unescapeHTML('/'), '/')
366 self
.assertEqual(unescapeHTML('é'), 'é')
367 self
.assertEqual(unescapeHTML('�'), '�')
368 self
.assertEqual(unescapeHTML('&a"'), '&a"')
370 self
.assertEqual(unescapeHTML('.''), '.\'')
372 def test_date_from_str(self
):
373 self
.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
374 self
.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
375 self
.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
376 self
.assertEqual(date_from_str('20200229+365day'), date_from_str('20200229+1year'))
377 self
.assertEqual(date_from_str('20210131+28day'), date_from_str('20210131+1month'))
379 def test_datetime_from_str(self
):
380 self
.assertEqual(datetime_from_str('yesterday', precision
='day'), datetime_from_str('now-1day', precision
='auto'))
381 self
.assertEqual(datetime_from_str('now+7day', precision
='day'), datetime_from_str('now+1week', precision
='auto'))
382 self
.assertEqual(datetime_from_str('now+14day', precision
='day'), datetime_from_str('now+2week', precision
='auto'))
383 self
.assertEqual(datetime_from_str('20200229+365day', precision
='day'), datetime_from_str('20200229+1year', precision
='auto'))
384 self
.assertEqual(datetime_from_str('20210131+28day', precision
='day'), datetime_from_str('20210131+1month', precision
='auto'))
385 self
.assertEqual(datetime_from_str('20210131+59day', precision
='day'), datetime_from_str('20210131+2month', precision
='auto'))
386 self
.assertEqual(datetime_from_str('now+1day', precision
='hour'), datetime_from_str('now+24hours', precision
='auto'))
387 self
.assertEqual(datetime_from_str('now+23hours', precision
='hour'), datetime_from_str('now+23hours', precision
='auto'))
389 def test_daterange(self
):
390 _20century
= DateRange('19000101', '20000101')
391 self
.assertFalse('17890714' in _20century
)
392 _ac
= DateRange('00010101')
393 self
.assertTrue('19690721' in _ac
)
394 _firstmilenium
= DateRange(end
='10000101')
395 self
.assertTrue('07110427' in _firstmilenium
)
397 def test_unified_dates(self
):
398 self
.assertEqual(unified_strdate('December 21, 2010'), '20101221')
399 self
.assertEqual(unified_strdate('8/7/2009'), '20090708')
400 self
.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
401 self
.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
402 self
.assertEqual(unified_strdate('1968 12 10'), '19681210')
403 self
.assertEqual(unified_strdate('1968-12-10'), '19681210')
404 self
.assertEqual(unified_strdate('31-07-2022 20:00'), '20220731')
405 self
.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
407 unified_strdate('11/26/2014 11:30:00 AM PST', day_first
=False),
410 unified_strdate('2/2/2015 6:47:40 PM', day_first
=False),
412 self
.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
413 self
.assertEqual(unified_strdate('25-09-2014'), '20140925')
414 self
.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
415 self
.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
416 self
.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
417 self
.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
418 self
.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
419 self
.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
420 self
.assertEqual(unified_strdate('November 3rd, 2019'), '20191103')
421 self
.assertEqual(unified_strdate('October 23rd, 2005'), '20051023')
423 def test_unified_timestamps(self
):
424 self
.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
425 self
.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
426 self
.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
427 self
.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
428 self
.assertEqual(unified_timestamp('1968 12 10'), -33436800)
429 self
.assertEqual(unified_timestamp('1968-12-10'), -33436800)
430 self
.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
432 unified_timestamp('11/26/2014 11:30:00 AM PST', day_first
=False),
435 unified_timestamp('2/2/2015 6:47:40 PM', day_first
=False),
437 self
.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
438 self
.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
439 self
.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
440 self
.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
441 self
.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
442 self
.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
443 self
.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
444 self
.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
445 self
.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
446 self
.assertEqual(unified_timestamp('2018-03-14T08:32:43.1493874+00:00'), 1521016363)
447 self
.assertEqual(unified_timestamp('Sunday, 26 Nov 2006, 19:00'), 1164567600)
448 self
.assertEqual(unified_timestamp('wed, aug 16, 2008, 12:00pm'), 1218931200)
450 self
.assertEqual(unified_timestamp('December 31 1969 20:00:01 EDT'), 1)
451 self
.assertEqual(unified_timestamp('Wednesday 31 December 1969 18:01:26 MDT'), 86)
452 self
.assertEqual(unified_timestamp('12/31/1969 20:01:18 EDT', False), 78)
454 def test_determine_ext(self
):
455 self
.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
456 self
.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
457 self
.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
458 self
.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
459 self
.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
460 self
.assertEqual(determine_ext('foobar', None), None)
462 def test_find_xpath_attr(self
):
470 doc
= compat_etree_fromstring(testxml
)
472 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n'), None)
473 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n', 'v'), None)
474 self
.assertEqual(find_xpath_attr(doc
, './/node', 'n'), None)
475 self
.assertEqual(find_xpath_attr(doc
, './/node', 'n', 'v'), None)
476 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x'), doc
[1])
477 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'a'), doc
[1])
478 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'b'), doc
[3])
479 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y'), doc
[2])
480 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'c'), doc
[2])
481 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'd'), doc
[3])
482 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', ''), doc
[4])
484 def test_xpath_with_ns(self
):
485 testxml
= '''<root xmlns:media="http://example.com/">
487 <media:author>The Author</media:author>
488 <url>http://server.com/download.mp3</url>
491 doc
= compat_etree_fromstring(testxml
)
492 find
= lambda p
: doc
.find(xpath_with_ns(p
, {'media': 'http://example.com/'}))
493 self
.assertTrue(find('media:song') is not None)
494 self
.assertEqual(find('media:song/media:author').text
, 'The Author')
495 self
.assertEqual(find('media:song/url').text
, 'http://server.com/download.mp3')
497 def test_xpath_element(self
):
498 doc
= xml
.etree
.ElementTree
.Element('root')
499 div
= xml
.etree
.ElementTree
.SubElement(doc
, 'div')
500 p
= xml
.etree
.ElementTree
.SubElement(div
, 'p')
502 self
.assertEqual(xpath_element(doc
, 'div/p'), p
)
503 self
.assertEqual(xpath_element(doc
, ['div/p']), p
)
504 self
.assertEqual(xpath_element(doc
, ['div/bar', 'div/p']), p
)
505 self
.assertEqual(xpath_element(doc
, 'div/bar', default
='default'), 'default')
506 self
.assertEqual(xpath_element(doc
, ['div/bar'], default
='default'), 'default')
507 self
.assertTrue(xpath_element(doc
, 'div/bar') is None)
508 self
.assertTrue(xpath_element(doc
, ['div/bar']) is None)
509 self
.assertTrue(xpath_element(doc
, ['div/bar'], 'div/baz') is None)
510 self
.assertRaises(ExtractorError
, xpath_element
, doc
, 'div/bar', fatal
=True)
511 self
.assertRaises(ExtractorError
, xpath_element
, doc
, ['div/bar'], fatal
=True)
512 self
.assertRaises(ExtractorError
, xpath_element
, doc
, ['div/bar', 'div/baz'], fatal
=True)
514 def test_xpath_text(self
):
520 doc
= compat_etree_fromstring(testxml
)
521 self
.assertEqual(xpath_text(doc
, 'div/p'), 'Foo')
522 self
.assertEqual(xpath_text(doc
, 'div/bar', default
='default'), 'default')
523 self
.assertTrue(xpath_text(doc
, 'div/bar') is None)
524 self
.assertRaises(ExtractorError
, xpath_text
, doc
, 'div/bar', fatal
=True)
526 def test_xpath_attr(self
):
532 doc
= compat_etree_fromstring(testxml
)
533 self
.assertEqual(xpath_attr(doc
, 'div/p', 'x'), 'a')
534 self
.assertEqual(xpath_attr(doc
, 'div/bar', 'x'), None)
535 self
.assertEqual(xpath_attr(doc
, 'div/p', 'y'), None)
536 self
.assertEqual(xpath_attr(doc
, 'div/bar', 'x', default
='default'), 'default')
537 self
.assertEqual(xpath_attr(doc
, 'div/p', 'y', default
='default'), 'default')
538 self
.assertRaises(ExtractorError
, xpath_attr
, doc
, 'div/bar', 'x', fatal
=True)
539 self
.assertRaises(ExtractorError
, xpath_attr
, doc
, 'div/p', 'y', fatal
=True)
541 def test_smuggle_url(self
):
542 data
= {'ö': 'ö', 'abc': [3]}
543 url
= 'https://foo.bar/baz?x=y#a'
544 smug_url
= smuggle_url(url
, data
)
545 unsmug_url
, unsmug_data
= unsmuggle_url(smug_url
)
546 self
.assertEqual(url
, unsmug_url
)
547 self
.assertEqual(data
, unsmug_data
)
549 res_url
, res_data
= unsmuggle_url(url
)
550 self
.assertEqual(res_url
, url
)
551 self
.assertEqual(res_data
, None)
553 smug_url
= smuggle_url(url
, {'a': 'b'})
554 smug_smug_url
= smuggle_url(smug_url
, {'c': 'd'})
555 res_url
, res_data
= unsmuggle_url(smug_smug_url
)
556 self
.assertEqual(res_url
, url
)
557 self
.assertEqual(res_data
, {'a': 'b', 'c': 'd'})
559 def test_shell_quote(self
):
560 args
= ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
563 """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name
!= 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
565 def test_float_or_none(self
):
566 self
.assertEqual(float_or_none('42.42'), 42.42)
567 self
.assertEqual(float_or_none('42'), 42.0)
568 self
.assertEqual(float_or_none(''), None)
569 self
.assertEqual(float_or_none(None), None)
570 self
.assertEqual(float_or_none([]), None)
571 self
.assertEqual(float_or_none(set()), None)
573 def test_int_or_none(self
):
574 self
.assertEqual(int_or_none('42'), 42)
575 self
.assertEqual(int_or_none(''), None)
576 self
.assertEqual(int_or_none(None), None)
577 self
.assertEqual(int_or_none([]), None)
578 self
.assertEqual(int_or_none(set()), None)
580 def test_str_to_int(self
):
581 self
.assertEqual(str_to_int('123,456'), 123456)
582 self
.assertEqual(str_to_int('123.456'), 123456)
583 self
.assertEqual(str_to_int(523), 523)
584 self
.assertEqual(str_to_int('noninteger'), None)
585 self
.assertEqual(str_to_int([]), None)
587 def test_url_basename(self
):
588 self
.assertEqual(url_basename('http://foo.de/'), '')
589 self
.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
590 self
.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
591 self
.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
592 self
.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
594 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
597 def test_base_url(self
):
598 self
.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
599 self
.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
600 self
.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
601 self
.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
602 self
.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
603 self
.assertEqual(base_url('http://foo.de/bar/baz&x=z&w=y/x/c'), 'http://foo.de/bar/baz&x=z&w=y/x/')
605 def test_urljoin(self
):
606 self
.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
607 self
.assertEqual(urljoin(b
'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
608 self
.assertEqual(urljoin('http://foo.de/', b
'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
609 self
.assertEqual(urljoin(b
'http://foo.de/', b
'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
610 self
.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
611 self
.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
612 self
.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
613 self
.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
614 self
.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
615 self
.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
616 self
.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
617 self
.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
618 self
.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
619 self
.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
620 self
.assertEqual(urljoin('http://foo.de/', None), None)
621 self
.assertEqual(urljoin('http://foo.de/', ''), None)
622 self
.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
623 self
.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
624 self
.assertEqual(urljoin('http://foo.de/a/b/c.txt', 'rtmp://foo.de'), 'rtmp://foo.de')
625 self
.assertEqual(urljoin(None, 'rtmp://foo.de'), 'rtmp://foo.de')
627 def test_url_or_none(self
):
628 self
.assertEqual(url_or_none(None), None)
629 self
.assertEqual(url_or_none(''), None)
630 self
.assertEqual(url_or_none('foo'), None)
631 self
.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
632 self
.assertEqual(url_or_none('https://foo.de'), 'https://foo.de')
633 self
.assertEqual(url_or_none('http$://foo.de'), None)
634 self
.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
635 self
.assertEqual(url_or_none('//foo.de'), '//foo.de')
636 self
.assertEqual(url_or_none('s3://foo.de'), None)
637 self
.assertEqual(url_or_none('rtmpte://foo.de'), 'rtmpte://foo.de')
638 self
.assertEqual(url_or_none('mms://foo.de'), 'mms://foo.de')
639 self
.assertEqual(url_or_none('rtspu://foo.de'), 'rtspu://foo.de')
640 self
.assertEqual(url_or_none('ftps://foo.de'), 'ftps://foo.de')
642 def test_parse_age_limit(self
):
643 self
.assertEqual(parse_age_limit(None), None)
644 self
.assertEqual(parse_age_limit(False), None)
645 self
.assertEqual(parse_age_limit('invalid'), None)
646 self
.assertEqual(parse_age_limit(0), 0)
647 self
.assertEqual(parse_age_limit(18), 18)
648 self
.assertEqual(parse_age_limit(21), 21)
649 self
.assertEqual(parse_age_limit(22), None)
650 self
.assertEqual(parse_age_limit('18'), 18)
651 self
.assertEqual(parse_age_limit('18+'), 18)
652 self
.assertEqual(parse_age_limit('PG-13'), 13)
653 self
.assertEqual(parse_age_limit('TV-14'), 14)
654 self
.assertEqual(parse_age_limit('TV-MA'), 17)
655 self
.assertEqual(parse_age_limit('TV14'), 14)
656 self
.assertEqual(parse_age_limit('TV_G'), 0)
658 def test_parse_duration(self
):
659 self
.assertEqual(parse_duration(None), None)
660 self
.assertEqual(parse_duration(False), None)
661 self
.assertEqual(parse_duration('invalid'), None)
662 self
.assertEqual(parse_duration('1'), 1)
663 self
.assertEqual(parse_duration('1337:12'), 80232)
664 self
.assertEqual(parse_duration('9:12:43'), 33163)
665 self
.assertEqual(parse_duration('12:00'), 720)
666 self
.assertEqual(parse_duration('00:01:01'), 61)
667 self
.assertEqual(parse_duration('x:y'), None)
668 self
.assertEqual(parse_duration('3h11m53s'), 11513)
669 self
.assertEqual(parse_duration('3h 11m 53s'), 11513)
670 self
.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
671 self
.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
672 self
.assertEqual(parse_duration('3 hours, 11 minutes, 53 seconds'), 11513)
673 self
.assertEqual(parse_duration('3 hours, 11 mins, 53 secs'), 11513)
674 self
.assertEqual(parse_duration('62m45s'), 3765)
675 self
.assertEqual(parse_duration('6m59s'), 419)
676 self
.assertEqual(parse_duration('49s'), 49)
677 self
.assertEqual(parse_duration('0h0m0s'), 0)
678 self
.assertEqual(parse_duration('0m0s'), 0)
679 self
.assertEqual(parse_duration('0s'), 0)
680 self
.assertEqual(parse_duration('01:02:03.05'), 3723.05)
681 self
.assertEqual(parse_duration('T30M38S'), 1838)
682 self
.assertEqual(parse_duration('5 s'), 5)
683 self
.assertEqual(parse_duration('3 min'), 180)
684 self
.assertEqual(parse_duration('2.5 hours'), 9000)
685 self
.assertEqual(parse_duration('02:03:04'), 7384)
686 self
.assertEqual(parse_duration('01:02:03:04'), 93784)
687 self
.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
688 self
.assertEqual(parse_duration('87 Min.'), 5220)
689 self
.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
690 self
.assertEqual(parse_duration('PT00H03M30SZ'), 210)
691 self
.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
692 self
.assertEqual(parse_duration('01:02:03:050'), 3723.05)
693 self
.assertEqual(parse_duration('103:050'), 103.05)
694 self
.assertEqual(parse_duration('1HR 3MIN'), 3780)
695 self
.assertEqual(parse_duration('2hrs 3mins'), 7380)
697 def test_fix_xml_ampersands(self
):
699 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
701 fix_xml_ampersands('"&x=y&wrong;&z=a'),
702 '"&x=y&wrong;&z=a')
704 fix_xml_ampersands('&'><"'),
705 '&'><"')
707 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
708 self
.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
710 def test_paged_list(self
):
711 def testPL(size
, pagesize
, sliceargs
, expected
):
712 def get_page(pagenum
):
713 firstid
= pagenum
* pagesize
714 upto
= min(size
, pagenum
* pagesize
+ pagesize
)
715 yield from range(firstid
, upto
)
717 pl
= OnDemandPagedList(get_page
, pagesize
)
718 got
= pl
.getslice(*sliceargs
)
719 self
.assertEqual(got
, expected
)
721 iapl
= InAdvancePagedList(get_page
, size
// pagesize
+ 1, pagesize
)
722 got
= iapl
.getslice(*sliceargs
)
723 self
.assertEqual(got
, expected
)
725 testPL(5, 2, (), [0, 1, 2, 3, 4])
726 testPL(5, 2, (1,), [1, 2, 3, 4])
727 testPL(5, 2, (2,), [2, 3, 4])
728 testPL(5, 2, (4,), [4])
729 testPL(5, 2, (0, 3), [0, 1, 2])
730 testPL(5, 2, (1, 4), [1, 2, 3])
731 testPL(5, 2, (2, 99), [2, 3, 4])
732 testPL(5, 2, (20, 99), [])
734 def test_read_batch_urls(self
):
735 f
= io
.StringIO('''\xef\xbb\xbf foo
738 # More after this line\r
741 self
.assertEqual(read_batch_urls(f
), ['foo', 'bar', 'baz', 'bam'])
743 def test_urlencode_postdata(self
):
744 data
= urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
745 self
.assertTrue(isinstance(data
, bytes
))
747 def test_update_url_query(self
):
748 self
.assertEqual(parse_qs(update_url_query(
749 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
750 parse_qs('http://example.com/path?quality=HD&format=mp4'))
751 self
.assertEqual(parse_qs(update_url_query(
752 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
753 parse_qs('http://example.com/path?system=LINUX&system=WINDOWS'))
754 self
.assertEqual(parse_qs(update_url_query(
755 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
756 parse_qs('http://example.com/path?fields=id,formats,subtitles'))
757 self
.assertEqual(parse_qs(update_url_query(
758 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
759 parse_qs('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
760 self
.assertEqual(parse_qs(update_url_query(
761 'http://example.com/path?manifest=f4m', {'manifest': []})),
762 parse_qs('http://example.com/path'))
763 self
.assertEqual(parse_qs(update_url_query(
764 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
765 parse_qs('http://example.com/path?system=LINUX'))
766 self
.assertEqual(parse_qs(update_url_query(
767 'http://example.com/path', {'fields': b
'id,formats,subtitles'})),
768 parse_qs('http://example.com/path?fields=id,formats,subtitles'))
769 self
.assertEqual(parse_qs(update_url_query(
770 'http://example.com/path', {'width': 1080, 'height': 720})),
771 parse_qs('http://example.com/path?width=1080&height=720'))
772 self
.assertEqual(parse_qs(update_url_query(
773 'http://example.com/path', {'bitrate': 5020.43})),
774 parse_qs('http://example.com/path?bitrate=5020.43'))
775 self
.assertEqual(parse_qs(update_url_query(
776 'http://example.com/path', {'test': '第二行тест'})),
777 parse_qs('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
779 def test_multipart_encode(self
):
781 multipart_encode({b
'field': b
'value'}, boundary
='AAAAAA')[0],
782 b
'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
784 multipart_encode({'欄位'.encode(): '值'.encode()}, boundary
='AAAAAA')[0],
785 b
'--AAAAAA\r\nContent-Disposition: form-data; name="\xe6\xac\x84\xe4\xbd\x8d"\r\n\r\n\xe5\x80\xbc\r\n--AAAAAA--\r\n')
787 ValueError, multipart_encode
, {b
'field': b
'value'}, boundary
='value')
789 def test_merge_dicts(self
):
790 self
.assertEqual(merge_dicts({'a': 1}, {'b': 2}), {'a': 1, 'b': 2})
791 self
.assertEqual(merge_dicts({'a': 1}, {'a': 2}), {'a': 1})
792 self
.assertEqual(merge_dicts({'a': 1}, {'a': None}), {'a': 1})
793 self
.assertEqual(merge_dicts({'a': 1}, {'a': ''}), {'a': 1})
794 self
.assertEqual(merge_dicts({'a': 1}, {}), {'a': 1})
795 self
.assertEqual(merge_dicts({'a': None}, {'a': 1}), {'a': 1})
796 self
.assertEqual(merge_dicts({'a': ''}, {'a': 1}), {'a': ''})
797 self
.assertEqual(merge_dicts({'a': ''}, {'a': 'abc'}), {'a': 'abc'})
798 self
.assertEqual(merge_dicts({'a': None}, {'a': ''}, {'a': 'abc'}), {'a': 'abc'})
800 def test_encode_compat_str(self
):
801 self
.assertEqual(encode_compat_str(b
'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
802 self
.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
804 def test_parse_iso8601(self
):
805 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
806 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26-07:00'), 1395641066)
807 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26', timezone
=dt
.timedelta(hours
=-7)), 1395641066)
808 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26', timezone
=NO_DEFAULT
), None)
809 # default does not override timezone in date_str
810 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26-07:00', timezone
=dt
.timedelta(hours
=-10)), 1395641066)
811 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
812 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
813 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
814 self
.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
815 self
.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
817 def test_strip_jsonp(self
):
818 stripped
= strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
819 d
= json
.loads(stripped
)
820 self
.assertEqual(d
, [{'id': '532cb', 'x': 3}])
822 stripped
= strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
823 d
= json
.loads(stripped
)
824 self
.assertEqual(d
, {'STATUS': 'OK'})
826 stripped
= strip_jsonp('ps.embedHandler({"status": "success"});')
827 d
= json
.loads(stripped
)
828 self
.assertEqual(d
, {'status': 'success'})
830 stripped
= strip_jsonp('window.cb && window.cb({"status": "success"});')
831 d
= json
.loads(stripped
)
832 self
.assertEqual(d
, {'status': 'success'})
834 stripped
= strip_jsonp('window.cb && cb({"status": "success"});')
835 d
= json
.loads(stripped
)
836 self
.assertEqual(d
, {'status': 'success'})
838 stripped
= strip_jsonp('({"status": "success"});')
839 d
= json
.loads(stripped
)
840 self
.assertEqual(d
, {'status': 'success'})
842 def test_strip_or_none(self
):
843 self
.assertEqual(strip_or_none(' abc'), 'abc')
844 self
.assertEqual(strip_or_none('abc '), 'abc')
845 self
.assertEqual(strip_or_none(' abc '), 'abc')
846 self
.assertEqual(strip_or_none('\tabc\t'), 'abc')
847 self
.assertEqual(strip_or_none('\n\tabc\n\t'), 'abc')
848 self
.assertEqual(strip_or_none('abc'), 'abc')
849 self
.assertEqual(strip_or_none(''), '')
850 self
.assertEqual(strip_or_none(None), None)
851 self
.assertEqual(strip_or_none(42), None)
852 self
.assertEqual(strip_or_none([]), None)
854 def test_uppercase_escape(self
):
855 self
.assertEqual(uppercase_escape('aä'), 'aä')
856 self
.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
858 def test_lowercase_escape(self
):
859 self
.assertEqual(lowercase_escape('aä'), 'aä')
860 self
.assertEqual(lowercase_escape('\\u0026'), '&')
862 def test_limit_length(self
):
863 self
.assertEqual(limit_length(None, 12), None)
864 self
.assertEqual(limit_length('foo', 12), 'foo')
866 limit_length('foo bar baz asd', 12).startswith('foo bar'))
867 self
.assertTrue('...' in limit_length('foo bar baz asd', 12))
869 def test_mimetype2ext(self
):
870 self
.assertEqual(mimetype2ext(None), None)
871 self
.assertEqual(mimetype2ext('video/x-flv'), 'flv')
872 self
.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
873 self
.assertEqual(mimetype2ext('text/vtt'), 'vtt')
874 self
.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
875 self
.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
876 self
.assertEqual(mimetype2ext('audio/x-wav'), 'wav')
877 self
.assertEqual(mimetype2ext('audio/x-wav;codec=pcm'), 'wav')
879 def test_month_by_name(self
):
880 self
.assertEqual(month_by_name(None), None)
881 self
.assertEqual(month_by_name('December', 'en'), 12)
882 self
.assertEqual(month_by_name('décembre', 'fr'), 12)
883 self
.assertEqual(month_by_name('December'), 12)
884 self
.assertEqual(month_by_name('décembre'), None)
885 self
.assertEqual(month_by_name('Unknown', 'unknown'), None)
887 def test_parse_codecs(self
):
888 self
.assertEqual(parse_codecs(''), {})
889 self
.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
890 'vcodec': 'avc1.77.30',
891 'acodec': 'mp4a.40.2',
892 'dynamic_range': None,
894 self
.assertEqual(parse_codecs('mp4a.40.2'), {
896 'acodec': 'mp4a.40.2',
897 'dynamic_range': None,
899 self
.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
900 'vcodec': 'avc1.42001e',
901 'acodec': 'mp4a.40.5',
902 'dynamic_range': None,
904 self
.assertEqual(parse_codecs('avc3.640028'), {
905 'vcodec': 'avc3.640028',
907 'dynamic_range': None,
909 self
.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
912 'dynamic_range': None,
914 self
.assertEqual(parse_codecs('av01.0.05M.08'), {
915 'vcodec': 'av01.0.05M.08',
917 'dynamic_range': None,
919 self
.assertEqual(parse_codecs('vp9.2'), {
922 'dynamic_range': 'HDR10',
924 self
.assertEqual(parse_codecs('av01.0.12M.10.0.110.09.16.09.0'), {
925 'vcodec': 'av01.0.12M.10.0.110.09.16.09.0',
927 'dynamic_range': 'HDR10',
929 self
.assertEqual(parse_codecs('dvhe'), {
932 'dynamic_range': 'DV',
934 self
.assertEqual(parse_codecs('fLaC'), {
937 'dynamic_range': None,
939 self
.assertEqual(parse_codecs('theora, vorbis'), {
942 'dynamic_range': None,
944 self
.assertEqual(parse_codecs('unknownvcodec, unknownacodec'), {
945 'vcodec': 'unknownvcodec',
946 'acodec': 'unknownacodec',
948 self
.assertEqual(parse_codecs('unknown'), {})
950 def test_escape_rfc3986(self
):
951 reserved
= "!*'();:@&=+$,/?#[]"
952 unreserved
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
953 self
.assertEqual(escape_rfc3986(reserved
), reserved
)
954 self
.assertEqual(escape_rfc3986(unreserved
), unreserved
)
955 self
.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
956 self
.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
957 self
.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
958 self
.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
960 def test_normalize_url(self
):
962 normalize_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
963 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4',
966 normalize_url('http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erklärt/Das-Erste/Video?documentId=22673108&bcastId=5290'),
967 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290',
970 normalize_url('http://тест.рф/фрагмент'),
971 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82',
974 normalize_url('http://тест.рф/абв?абв=абв#абв'),
975 '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',
977 self
.assertEqual(normalize_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
979 self
.assertEqual(normalize_url('http://www.example.com/../a/b/../c/./d.html'), 'http://www.example.com/a/c/d.html')
981 def test_remove_dot_segments(self
):
982 self
.assertEqual(remove_dot_segments('/a/b/c/./../../g'), '/a/g')
983 self
.assertEqual(remove_dot_segments('mid/content=5/../6'), 'mid/6')
984 self
.assertEqual(remove_dot_segments('/ad/../cd'), '/cd')
985 self
.assertEqual(remove_dot_segments('/ad/../cd/'), '/cd/')
986 self
.assertEqual(remove_dot_segments('/..'), '/')
987 self
.assertEqual(remove_dot_segments('/./'), '/')
988 self
.assertEqual(remove_dot_segments('/./a'), '/a')
989 self
.assertEqual(remove_dot_segments('/abc/./.././d/././e/.././f/./../../ghi'), '/ghi')
990 self
.assertEqual(remove_dot_segments('/'), '/')
991 self
.assertEqual(remove_dot_segments('/t'), '/t')
992 self
.assertEqual(remove_dot_segments('t'), 't')
993 self
.assertEqual(remove_dot_segments(''), '')
994 self
.assertEqual(remove_dot_segments('/../a/b/c'), '/a/b/c')
995 self
.assertEqual(remove_dot_segments('../a'), 'a')
996 self
.assertEqual(remove_dot_segments('./a'), 'a')
997 self
.assertEqual(remove_dot_segments('.'), '')
998 self
.assertEqual(remove_dot_segments('////'), '////')
1000 def test_js_to_json_vars_strings(self
):
1001 self
.assertDictEqual(
1002 json
.loads(js_to_json(
1028 'falseStr': 'false',
1029 'unresolvedVar': 'var',
1033 self
.assertDictEqual(
1034 json
.loads(js_to_json(
1056 self
.assertDictEqual(
1057 json
.loads(js_to_json(
1079 def test_js_to_json_realworld(self
):
1081 'clip':{'provider':'pseudo'}
1083 self
.assertEqual(js_to_json(inp
), '''{
1084 "clip":{"provider":"pseudo"}
1086 json
.loads(js_to_json(inp
))
1089 'playlist':[{'controls':{'all':null}}]
1091 self
.assertEqual(js_to_json(inp
), '''{
1092 "playlist":[{"controls":{"all":null}}]
1095 inp
= '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
1096 self
.assertEqual(js_to_json(inp
), '''"The CW's 'Crazy Ex-Girlfriend'"''')
1098 inp
= '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
1099 json_code
= js_to_json(inp
)
1100 self
.assertEqual(json
.loads(json_code
), json
.loads(inp
))
1103 0:{src:'skipped', type: 'application/dash+xml'},
1104 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
1106 self
.assertEqual(js_to_json(inp
), '''{
1107 "0":{"src":"skipped", "type": "application/dash+xml"},
1108 "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
1111 inp
= '''{"foo":101}'''
1112 self
.assertEqual(js_to_json(inp
), '''{"foo":101}''')
1114 inp
= '''{"duration": "00:01:07"}'''
1115 self
.assertEqual(js_to_json(inp
), '''{"duration": "00:01:07"}''')
1117 inp
= '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
1118 self
.assertEqual(js_to_json(inp
), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
1120 def test_js_to_json_edgecases(self
):
1121 on
= js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
1122 self
.assertEqual(json
.loads(on
), {'abc_def': "1'\\2\\'3\"4"})
1124 on
= js_to_json('{"abc": true}')
1125 self
.assertEqual(json
.loads(on
), {'abc': True})
1127 # Ignore JavaScript code as well
1128 on
= js_to_json('''{
1134 self
.assertEqual(d
['x'], 1)
1135 self
.assertEqual(d
['y'], 'a')
1137 # Just drop ! prefix for now though this results in a wrong value
1138 on
= js_to_json('''{
1148 self
.assertEqual(json
.loads(on
), {
1159 on
= js_to_json('["abc", "def",]')
1160 self
.assertEqual(json
.loads(on
), ['abc', 'def'])
1162 on
= js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
1163 self
.assertEqual(json
.loads(on
), ['abc', 'def'])
1165 on
= js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
1166 self
.assertEqual(json
.loads(on
), ['abc', 'def'])
1168 on
= js_to_json('{"abc": "def",}')
1169 self
.assertEqual(json
.loads(on
), {'abc': 'def'})
1171 on
= js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
1172 self
.assertEqual(json
.loads(on
), {'abc': 'def'})
1174 on
= js_to_json('{ 0: /* " \n */ ",]" , }')
1175 self
.assertEqual(json
.loads(on
), {'0': ',]'})
1177 on
= js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
1178 self
.assertEqual(json
.loads(on
), {'0': ',]'})
1180 on
= js_to_json('{ 0: // comment\n1 }')
1181 self
.assertEqual(json
.loads(on
), {'0': 1})
1183 on
= js_to_json(r
'["<p>x<\/p>"]')
1184 self
.assertEqual(json
.loads(on
), ['<p>x</p>'])
1186 on
= js_to_json(r
'["\xaa"]')
1187 self
.assertEqual(json
.loads(on
), ['\u00aa'])
1189 on
= js_to_json("['a\\\nb']")
1190 self
.assertEqual(json
.loads(on
), ['ab'])
1192 on
= js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
1193 self
.assertEqual(json
.loads(on
), ['ab'])
1195 on
= js_to_json('{0xff:0xff}')
1196 self
.assertEqual(json
.loads(on
), {'255': 255})
1198 on
= js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
1199 self
.assertEqual(json
.loads(on
), {'255': 255})
1201 on
= js_to_json('{077:077}')
1202 self
.assertEqual(json
.loads(on
), {'63': 63})
1204 on
= js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
1205 self
.assertEqual(json
.loads(on
), {'63': 63})
1207 on
= js_to_json('{42:42}')
1208 self
.assertEqual(json
.loads(on
), {'42': 42})
1210 on
= js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
1211 self
.assertEqual(json
.loads(on
), {'42': 42})
1213 on
= js_to_json('{42:4.2e1}')
1214 self
.assertEqual(json
.loads(on
), {'42': 42.0})
1216 on
= js_to_json('{ "0x40": "0x40" }')
1217 self
.assertEqual(json
.loads(on
), {'0x40': '0x40'})
1219 on
= js_to_json('{ "040": "040" }')
1220 self
.assertEqual(json
.loads(on
), {'040': '040'})
1222 on
= js_to_json('[1,//{},\n2]')
1223 self
.assertEqual(json
.loads(on
), [1, 2])
1225 on
= js_to_json(R
'"\^\$\#"')
1226 self
.assertEqual(json
.loads(on
), R
'^$#', msg
='Unnecessary escapes should be stripped')
1228 on
= js_to_json('\'"\\""\'')
1229 self
.assertEqual(json
.loads(on
), '"""', msg
='Unnecessary quote escape should be escaped')
1231 on
= js_to_json('[new Date("spam"), \'("eggs")\']')
1232 self
.assertEqual(json
.loads(on
), ['spam', '("eggs")'], msg
='Date regex should match a single string')
1234 def test_js_to_json_malformed(self
):
1235 self
.assertEqual(js_to_json('42a1'), '42"a1"')
1236 self
.assertEqual(js_to_json('42a-1'), '42"a"-1')
1238 def test_js_to_json_template_literal(self
):
1239 self
.assertEqual(js_to_json('`Hello ${name}`', {'name': '"world"'}), '"Hello world"')
1240 self
.assertEqual(js_to_json('`${name}${name}`', {'name': '"X"'}), '"XX"')
1241 self
.assertEqual(js_to_json('`${name}${name}`', {'name': '5'}), '"55"')
1242 self
.assertEqual(js_to_json('`${name}"${name}"`', {'name': '5'}), '"5\\"5\\""')
1243 self
.assertEqual(js_to_json('`${name}`', {}), '"name"')
1245 def test_js_to_json_common_constructors(self
):
1246 self
.assertEqual(json
.loads(js_to_json('new Map([["a", 5]])')), {'a': 5})
1247 self
.assertEqual(json
.loads(js_to_json('Array(5, 10)')), [5, 10])
1248 self
.assertEqual(json
.loads(js_to_json('new Array(15,5)')), [15, 5])
1249 self
.assertEqual(json
.loads(js_to_json('new Map([Array(5, 10),new Array(15,5)])')), {'5': 10, '15': 5})
1250 self
.assertEqual(json
.loads(js_to_json('new Date("123")')), '123')
1251 self
.assertEqual(json
.loads(js_to_json('new Date(\'2023-10-19\')')), '2023-10-19')
1253 def test_extract_attributes(self
):
1254 self
.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
1255 self
.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
1256 self
.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
1257 self
.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
1258 self
.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
1259 self
.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
1260 self
.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
1261 self
.assertEqual(extract_attributes('<e x="&">'), {'x': '&'}) # XML
1262 self
.assertEqual(extract_attributes('<e x=""">'), {'x': '"'})
1263 self
.assertEqual(extract_attributes('<e x="£">'), {'x': '£'}) # HTML 3.2
1264 self
.assertEqual(extract_attributes('<e x="λ">'), {'x': 'λ'}) # HTML 4.0
1265 self
.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
1266 self
.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
1267 self
.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
1268 self
.assertEqual(extract_attributes('<e x >'), {'x': None})
1269 self
.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
1270 self
.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
1271 self
.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
1272 self
.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
1273 self
.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
1274 self
.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
1275 self
.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
1276 self
.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
1277 self
.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
1278 self
.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
1279 self
.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
1280 self
.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
1281 self
.assertEqual(extract_attributes('<e x="décomposé">'), {'x': 'décompose\u0301'})
1282 # "Narrow" Python builds don't support unicode code points outside BMP.
1285 supports_outside_bmp
= True
1287 supports_outside_bmp
= False
1288 if supports_outside_bmp
:
1289 self
.assertEqual(extract_attributes('<e x="Smile 😀!">'), {'x': 'Smile \U0001f600!'})
1290 # Malformed HTML should not break attributes extraction on older Python
1291 self
.assertEqual(extract_attributes('<mal"formed/>'), {})
1293 def test_clean_html(self
):
1294 self
.assertEqual(clean_html('a:\nb'), 'a: b')
1295 self
.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
1296 self
.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
1298 def test_intlist_to_bytes(self
):
1300 intlist_to_bytes([0, 1, 127, 128, 255]),
1301 b
'\x00\x01\x7f\x80\xff')
1303 def test_args_to_str(self
):
1305 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
1306 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name
!= 'nt' else 'foo ba/r -baz "2 be" ""',
1309 def test_parse_filesize(self
):
1310 self
.assertEqual(parse_filesize(None), None)
1311 self
.assertEqual(parse_filesize(''), None)
1312 self
.assertEqual(parse_filesize('91 B'), 91)
1313 self
.assertEqual(parse_filesize('foobar'), None)
1314 self
.assertEqual(parse_filesize('2 MiB'), 2097152)
1315 self
.assertEqual(parse_filesize('5 GB'), 5000000000)
1316 self
.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
1317 self
.assertEqual(parse_filesize('1.2tb'), 1200000000000)
1318 self
.assertEqual(parse_filesize('1,24 KB'), 1240)
1319 self
.assertEqual(parse_filesize('1,24 kb'), 1240)
1320 self
.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
1322 def test_parse_count(self
):
1323 self
.assertEqual(parse_count(None), None)
1324 self
.assertEqual(parse_count(''), None)
1325 self
.assertEqual(parse_count('0'), 0)
1326 self
.assertEqual(parse_count('1000'), 1000)
1327 self
.assertEqual(parse_count('1.000'), 1000)
1328 self
.assertEqual(parse_count('1.1k'), 1100)
1329 self
.assertEqual(parse_count('1.1 k'), 1100)
1330 self
.assertEqual(parse_count('1,1 k'), 1100)
1331 self
.assertEqual(parse_count('1.1kk'), 1100000)
1332 self
.assertEqual(parse_count('1.1kk '), 1100000)
1333 self
.assertEqual(parse_count('1,1kk'), 1100000)
1334 self
.assertEqual(parse_count('100 views'), 100)
1335 self
.assertEqual(parse_count('1,100 views'), 1100)
1336 self
.assertEqual(parse_count('1.1kk views'), 1100000)
1337 self
.assertEqual(parse_count('10M views'), 10000000)
1338 self
.assertEqual(parse_count('has 10M views'), 10000000)
1340 def test_parse_resolution(self
):
1341 self
.assertEqual(parse_resolution(None), {})
1342 self
.assertEqual(parse_resolution(''), {})
1343 self
.assertEqual(parse_resolution(' 1920x1080'), {'width': 1920, 'height': 1080})
1344 self
.assertEqual(parse_resolution('1920×1080 '), {'width': 1920, 'height': 1080})
1345 self
.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
1346 self
.assertEqual(parse_resolution('720p'), {'height': 720})
1347 self
.assertEqual(parse_resolution('4k'), {'height': 2160})
1348 self
.assertEqual(parse_resolution('8K'), {'height': 4320})
1349 self
.assertEqual(parse_resolution('pre_1920x1080_post'), {'width': 1920, 'height': 1080})
1350 self
.assertEqual(parse_resolution('ep1x2'), {})
1351 self
.assertEqual(parse_resolution('1920, 1080'), {'width': 1920, 'height': 1080})
1353 def test_parse_bitrate(self
):
1354 self
.assertEqual(parse_bitrate(None), None)
1355 self
.assertEqual(parse_bitrate(''), None)
1356 self
.assertEqual(parse_bitrate('300kbps'), 300)
1357 self
.assertEqual(parse_bitrate('1500kbps'), 1500)
1358 self
.assertEqual(parse_bitrate('300 kbps'), 300)
1360 def test_version_tuple(self
):
1361 self
.assertEqual(version_tuple('1'), (1,))
1362 self
.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
1363 self
.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
1365 def test_detect_exe_version(self
):
1366 self
.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
1367 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
1368 configuration: --prefix=/usr --extra-'''), '1.2.1')
1369 self
.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
1370 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
1371 self
.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
1372 Trying to open render node...
1373 Success at /dev/dri/renderD128.
1374 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
1376 def test_age_restricted(self
):
1377 self
.assertFalse(age_restricted(None, 10)) # unrestricted content
1378 self
.assertFalse(age_restricted(1, None)) # unrestricted policy
1379 self
.assertFalse(age_restricted(8, 10))
1380 self
.assertTrue(age_restricted(18, 14))
1381 self
.assertFalse(age_restricted(18, 18))
1383 def test_is_html(self
):
1384 self
.assertFalse(is_html(b
'\x49\x44\x43<html'))
1385 self
.assertTrue(is_html(b
'<!DOCTYPE foo>\xaaa'))
1386 self
.assertTrue(is_html( # UTF-8 with BOM
1387 b
'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
1388 self
.assertTrue(is_html( # UTF-16-LE
1389 b
'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00',
1391 self
.assertTrue(is_html( # UTF-16-BE
1392 b
'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4',
1394 self
.assertTrue(is_html( # UTF-32-BE
1395 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'))
1396 self
.assertTrue(is_html( # UTF-32-LE
1397 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'))
1399 def test_render_table(self
):
1402 ['a', 'empty', 'bcd'],
1403 [[123, '', 4], [9999, '', 51]]),
1410 ['a', 'empty', 'bcd'],
1411 [[123, '', 4], [9999, '', 51]],
1420 [['1\t23', 4], ['\t9999', 51]]),
1428 [[123, 4], [9999, 51]],
1438 [[123, 4], [9999, 51]],
1439 delim
='-', extra_gap
=2),
1445 def test_match_str(self
):
1447 self
.assertFalse(match_str('xy', {'x': 1200}))
1448 self
.assertTrue(match_str('!xy', {'x': 1200}))
1449 self
.assertTrue(match_str('x', {'x': 1200}))
1450 self
.assertFalse(match_str('!x', {'x': 1200}))
1451 self
.assertTrue(match_str('x', {'x': 0}))
1452 self
.assertTrue(match_str('is_live', {'is_live': True}))
1453 self
.assertFalse(match_str('is_live', {'is_live': False}))
1454 self
.assertFalse(match_str('is_live', {'is_live': None}))
1455 self
.assertFalse(match_str('is_live', {}))
1456 self
.assertFalse(match_str('!is_live', {'is_live': True}))
1457 self
.assertTrue(match_str('!is_live', {'is_live': False}))
1458 self
.assertTrue(match_str('!is_live', {'is_live': None}))
1459 self
.assertTrue(match_str('!is_live', {}))
1460 self
.assertTrue(match_str('title', {'title': 'abc'}))
1461 self
.assertTrue(match_str('title', {'title': ''}))
1462 self
.assertFalse(match_str('!title', {'title': 'abc'}))
1463 self
.assertFalse(match_str('!title', {'title': ''}))
1466 self
.assertFalse(match_str('x>0', {'x': 0}))
1467 self
.assertFalse(match_str('x>0', {}))
1468 self
.assertTrue(match_str('x>?0', {}))
1469 self
.assertTrue(match_str('x>1K', {'x': 1200}))
1470 self
.assertFalse(match_str('x>2K', {'x': 1200}))
1471 self
.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
1472 self
.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
1473 self
.assertTrue(match_str('x > 1:0:0', {'x': 3700}))
1476 self
.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
1477 self
.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
1478 self
.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
1479 self
.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
1480 self
.assertTrue(match_str('y^=foo', {'y': 'foobar42'}))
1481 self
.assertFalse(match_str('y!^=foo', {'y': 'foobar42'}))
1482 self
.assertFalse(match_str('y^=bar', {'y': 'foobar42'}))
1483 self
.assertTrue(match_str('y!^=bar', {'y': 'foobar42'}))
1484 self
.assertRaises(ValueError, match_str
, 'x^=42', {'x': 42})
1485 self
.assertTrue(match_str('y*=bar', {'y': 'foobar42'}))
1486 self
.assertFalse(match_str('y!*=bar', {'y': 'foobar42'}))
1487 self
.assertFalse(match_str('y*=baz', {'y': 'foobar42'}))
1488 self
.assertTrue(match_str('y!*=baz', {'y': 'foobar42'}))
1489 self
.assertTrue(match_str('y$=42', {'y': 'foobar42'}))
1490 self
.assertFalse(match_str('y$=43', {'y': 'foobar42'}))
1493 self
.assertFalse(match_str(
1494 'like_count > 100 & dislike_count <? 50 & description',
1495 {'like_count': 90, 'description': 'foo'}))
1496 self
.assertTrue(match_str(
1497 'like_count > 100 & dislike_count <? 50 & description',
1498 {'like_count': 190, 'description': 'foo'}))
1499 self
.assertFalse(match_str(
1500 'like_count > 100 & dislike_count <? 50 & description',
1501 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
1502 self
.assertFalse(match_str(
1503 'like_count > 100 & dislike_count <? 50 & description',
1504 {'like_count': 190, 'dislike_count': 10}))
1507 self
.assertTrue(match_str(r
'x~=\bbar', {'x': 'foo bar'}))
1508 self
.assertFalse(match_str(r
'x~=\bbar.+', {'x': 'foo bar'}))
1509 self
.assertFalse(match_str(r
'x~=^FOO', {'x': 'foo bar'}))
1510 self
.assertTrue(match_str(r
'x~=(?i)^FOO', {'x': 'foo bar'}))
1513 self
.assertTrue(match_str(r
'x^="foo"', {'x': 'foo "bar"'}))
1514 self
.assertFalse(match_str(r
'x^="foo "', {'x': 'foo "bar"'}))
1515 self
.assertFalse(match_str(r
'x$="bar"', {'x': 'foo "bar"'}))
1516 self
.assertTrue(match_str(r
'x$=" \"bar\""', {'x': 'foo "bar"'}))
1519 self
.assertFalse(match_str(r
'x=foo & bar', {'x': 'foo & bar'}))
1520 self
.assertTrue(match_str(r
'x=foo \& bar', {'x': 'foo & bar'}))
1521 self
.assertTrue(match_str(r
'x=foo \& bar & x^=foo', {'x': 'foo & bar'}))
1522 self
.assertTrue(match_str(r
'x="foo \& bar" & x^=foo', {'x': 'foo & bar'}))
1525 self
.assertTrue(match_str(
1526 r
"!is_live & like_count>?100 & description~='(?i)\bcats \& dogs\b'",
1527 {'description': 'Raining Cats & Dogs'}))
1530 self
.assertFalse(match_str('id!=foo', {'id': 'foo'}, True))
1531 self
.assertTrue(match_str('x', {'id': 'foo'}, True))
1532 self
.assertTrue(match_str('!x', {'id': 'foo'}, True))
1533 self
.assertFalse(match_str('x', {'id': 'foo'}, False))
1535 def test_parse_dfxp_time_expr(self
):
1536 self
.assertEqual(parse_dfxp_time_expr(None), None)
1537 self
.assertEqual(parse_dfxp_time_expr(''), None)
1538 self
.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
1539 self
.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
1540 self
.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
1541 self
.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
1542 self
.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
1544 def test_dfxp2srt(self
):
1545 dfxp_data
= '''<?xml version="1.0" encoding="UTF-8"?>
1546 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1549 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
1550 <p begin="1" end="2">第二行<br/>♪♪</p>
1551 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
1552 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
1553 <p begin="-1" end="-1">Ignore, two</p>
1554 <p begin="3" dur="-1">Ignored, three</p>
1559 00:00:00,000 --> 00:00:01,000
1560 The following line contains Chinese characters and special symbols
1563 00:00:01,000 --> 00:00:02,000
1568 00:00:02,000 --> 00:00:03,000
1573 self
.assertEqual(dfxp2srt(dfxp_data
), srt_data
)
1575 dfxp_data_no_default_namespace
= b
'''<?xml version="1.0" encoding="UTF-8"?>
1576 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1579 <p begin="0" end="1">The first line</p>
1584 00:00:00,000 --> 00:00:01,000
1588 self
.assertEqual(dfxp2srt(dfxp_data_no_default_namespace
), srt_data
)
1590 dfxp_data_with_style
= b
'''<?xml version="1.0" encoding="utf-8"?>
1591 <tt xmlns="http://www.w3.org/2006/10/ttaf1" xmlns:ttp="http://www.w3.org/2006/10/ttaf1#parameter" ttp:timeBase="media" xmlns:tts="http://www.w3.org/2006/10/ttaf1#style" xml:lang="en" xmlns:ttm="http://www.w3.org/2006/10/ttaf1#metadata">
1594 <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
1595 <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
1596 <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
1597 <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
1600 <body tts:textAlign="center" style="s0">
1602 <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
1603 <p style="s2" begin="00:00:02.08" id="p0" end="00:00:05.84"><span tts:color="lime">part 1<br /></span><span tts:color="cyan">part 2</span></p>
1604 <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
1605 <p style="s1" tts:textDecoration="underline" begin="00:00:09.56" id="p2" end="00:00:12.36"><span style="s2" tts:color="lime">inner<br /> </span>style</p>
1610 00:00:02,080 --> 00:00:05,840
1611 <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
1614 00:00:02,080 --> 00:00:05,840
1615 <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
1616 </font>part 2</font></b>
1619 00:00:05,840 --> 00:00:09,560
1620 <u><font color="lime">line 3
1624 00:00:09,560 --> 00:00:12,360
1625 <i><u><font color="yellow"><font color="lime">inner
1626 </font>style</font></u></i>
1629 self
.assertEqual(dfxp2srt(dfxp_data_with_style
), srt_data
)
1631 dfxp_data_non_utf8
= '''<?xml version="1.0" encoding="UTF-16"?>
1632 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1635 <p begin="0" end="1">Line 1</p>
1636 <p begin="1" end="2">第二行</p>
1639 </tt>'''.encode('utf-16')
1641 00:00:00,000 --> 00:00:01,000
1645 00:00:01,000 --> 00:00:02,000
1649 self
.assertEqual(dfxp2srt(dfxp_data_non_utf8
), srt_data
)
1651 def test_cli_option(self
):
1652 self
.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
1653 self
.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
1654 self
.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
1655 self
.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
1657 def test_cli_valueless_option(self
):
1658 self
.assertEqual(cli_valueless_option(
1659 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
1660 self
.assertEqual(cli_valueless_option(
1661 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
1662 self
.assertEqual(cli_valueless_option(
1663 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
1664 self
.assertEqual(cli_valueless_option(
1665 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
1666 self
.assertEqual(cli_valueless_option(
1667 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
1668 self
.assertEqual(cli_valueless_option(
1669 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
1671 def test_cli_bool_option(self
):
1674 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
1675 ['--no-check-certificate', 'true'])
1678 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator
='='),
1679 ['--no-check-certificate=true'])
1682 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1683 ['--check-certificate', 'false'])
1686 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1687 ['--check-certificate=false'])
1690 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1691 ['--check-certificate', 'true'])
1694 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1695 ['--check-certificate=true'])
1698 {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1701 def test_ohdave_rsa_encrypt(self
):
1702 N
= 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
1706 ohdave_rsa_encrypt(b
'aa111222', e
, N
),
1707 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
1709 def test_pkcs1pad(self
):
1711 padded_data
= pkcs1pad(data
, 32)
1712 self
.assertEqual(padded_data
[:2], [0, 2])
1713 self
.assertEqual(padded_data
[28:], [0, 1, 2, 3])
1715 self
.assertRaises(ValueError, pkcs1pad
, data
, 8)
1717 def test_encode_base_n(self
):
1718 self
.assertEqual(encode_base_n(0, 30), '0')
1719 self
.assertEqual(encode_base_n(80, 30), '2k')
1721 custom_table
= '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
1722 self
.assertEqual(encode_base_n(0, 30, custom_table
), '9')
1723 self
.assertEqual(encode_base_n(80, 30, custom_table
), '7P')
1725 self
.assertRaises(ValueError, encode_base_n
, 0, 70)
1726 self
.assertRaises(ValueError, encode_base_n
, 0, 60, custom_table
)
1728 def test_caesar(self
):
1729 self
.assertEqual(caesar('ace', 'abcdef', 2), 'cea')
1730 self
.assertEqual(caesar('cea', 'abcdef', -2), 'ace')
1731 self
.assertEqual(caesar('ace', 'abcdef', -2), 'eac')
1732 self
.assertEqual(caesar('eac', 'abcdef', 2), 'ace')
1733 self
.assertEqual(caesar('ace', 'abcdef', 0), 'ace')
1734 self
.assertEqual(caesar('xyz', 'abcdef', 2), 'xyz')
1735 self
.assertEqual(caesar('abc', 'acegik', 2), 'ebg')
1736 self
.assertEqual(caesar('ebg', 'acegik', -2), 'abc')
1738 def test_rot47(self
):
1739 self
.assertEqual(rot47('yt-dlp'), r
'JE\5=A')
1740 self
.assertEqual(rot47('YT-DLP'), r
'*%\s{!')
1742 def test_urshift(self
):
1743 self
.assertEqual(urshift(3, 1), 1)
1744 self
.assertEqual(urshift(-3, 1), 2147483646)
1746 GET_ELEMENT_BY_CLASS_TEST_STRING
= '''
1747 <span class="foo bar">nice</span>
1750 def test_get_element_by_class(self
):
1751 html
= self
.GET_ELEMENT_BY_CLASS_TEST_STRING
1753 self
.assertEqual(get_element_by_class('foo', html
), 'nice')
1754 self
.assertEqual(get_element_by_class('no-such-class', html
), None)
1756 def test_get_element_html_by_class(self
):
1757 html
= self
.GET_ELEMENT_BY_CLASS_TEST_STRING
1759 self
.assertEqual(get_element_html_by_class('foo', html
), html
.strip())
1760 self
.assertEqual(get_element_by_class('no-such-class', html
), None)
1762 GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING
= '''
1763 <div itemprop="author" itemscope>foo</div>
1766 def test_get_element_by_attribute(self
):
1767 html
= self
.GET_ELEMENT_BY_CLASS_TEST_STRING
1769 self
.assertEqual(get_element_by_attribute('class', 'foo bar', html
), 'nice')
1770 self
.assertEqual(get_element_by_attribute('class', 'foo', html
), None)
1771 self
.assertEqual(get_element_by_attribute('class', 'no-such-foo', html
), None)
1773 html
= self
.GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING
1775 self
.assertEqual(get_element_by_attribute('itemprop', 'author', html
), 'foo')
1777 def test_get_element_html_by_attribute(self
):
1778 html
= self
.GET_ELEMENT_BY_CLASS_TEST_STRING
1780 self
.assertEqual(get_element_html_by_attribute('class', 'foo bar', html
), html
.strip())
1781 self
.assertEqual(get_element_html_by_attribute('class', 'foo', html
), None)
1782 self
.assertEqual(get_element_html_by_attribute('class', 'no-such-foo', html
), None)
1784 html
= self
.GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING
1786 self
.assertEqual(get_element_html_by_attribute('itemprop', 'author', html
), html
.strip())
1788 GET_ELEMENTS_BY_CLASS_TEST_STRING
= '''
1789 <span class="foo bar">nice</span><span class="foo bar">also nice</span>
1791 GET_ELEMENTS_BY_CLASS_RES
= ['<span class="foo bar">nice</span>', '<span class="foo bar">also nice</span>']
1793 def test_get_elements_by_class(self
):
1794 html
= self
.GET_ELEMENTS_BY_CLASS_TEST_STRING
1796 self
.assertEqual(get_elements_by_class('foo', html
), ['nice', 'also nice'])
1797 self
.assertEqual(get_elements_by_class('no-such-class', html
), [])
1799 def test_get_elements_html_by_class(self
):
1800 html
= self
.GET_ELEMENTS_BY_CLASS_TEST_STRING
1802 self
.assertEqual(get_elements_html_by_class('foo', html
), self
.GET_ELEMENTS_BY_CLASS_RES
)
1803 self
.assertEqual(get_elements_html_by_class('no-such-class', html
), [])
1805 def test_get_elements_by_attribute(self
):
1806 html
= self
.GET_ELEMENTS_BY_CLASS_TEST_STRING
1808 self
.assertEqual(get_elements_by_attribute('class', 'foo bar', html
), ['nice', 'also nice'])
1809 self
.assertEqual(get_elements_by_attribute('class', 'foo', html
), [])
1810 self
.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html
), [])
1812 def test_get_elements_html_by_attribute(self
):
1813 html
= self
.GET_ELEMENTS_BY_CLASS_TEST_STRING
1815 self
.assertEqual(get_elements_html_by_attribute('class', 'foo bar', html
), self
.GET_ELEMENTS_BY_CLASS_RES
)
1816 self
.assertEqual(get_elements_html_by_attribute('class', 'foo', html
), [])
1817 self
.assertEqual(get_elements_html_by_attribute('class', 'no-such-foo', html
), [])
1819 def test_get_elements_text_and_html_by_attribute(self
):
1820 html
= self
.GET_ELEMENTS_BY_CLASS_TEST_STRING
1823 list(get_elements_text_and_html_by_attribute('class', 'foo bar', html
)),
1824 list(zip(['nice', 'also nice'], self
.GET_ELEMENTS_BY_CLASS_RES
)))
1825 self
.assertEqual(list(get_elements_text_and_html_by_attribute('class', 'foo', html
)), [])
1826 self
.assertEqual(list(get_elements_text_and_html_by_attribute('class', 'no-such-foo', html
)), [])
1828 self
.assertEqual(list(get_elements_text_and_html_by_attribute(
1829 'class', 'foo', '<a class="foo">nice</a><span class="foo">nice</span>', tag
='a')), [('nice', '<a class="foo">nice</a>')])
1831 GET_ELEMENT_BY_TAG_TEST_STRING
= '''
1832 random text lorem ipsum</p>
1834 this should be returned
1835 <span>this should also be returned</span>
1837 this should also be returned
1839 closing tag above should not trick, so this should also be returned
1841 but this text should not be returned
1843 GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML
= GET_ELEMENT_BY_TAG_TEST_STRING
.strip()[32:276]
1844 GET_ELEMENT_BY_TAG_RES_OUTERDIV_TEXT
= GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML
[5:-6]
1845 GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML
= GET_ELEMENT_BY_TAG_TEST_STRING
.strip()[78:119]
1846 GET_ELEMENT_BY_TAG_RES_INNERSPAN_TEXT
= GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML
[6:-7]
1848 def test_get_element_text_and_html_by_tag(self
):
1849 html
= self
.GET_ELEMENT_BY_TAG_TEST_STRING
1852 get_element_text_and_html_by_tag('div', html
),
1853 (self
.GET_ELEMENT_BY_TAG_RES_OUTERDIV_TEXT
, self
.GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML
))
1855 get_element_text_and_html_by_tag('span', html
),
1856 (self
.GET_ELEMENT_BY_TAG_RES_INNERSPAN_TEXT
, self
.GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML
))
1857 self
.assertRaises(compat_HTMLParseError
, get_element_text_and_html_by_tag
, 'article', html
)
1859 def test_iri_to_uri(self
):
1861 iri_to_uri('https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b'),
1862 'https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b') # Same
1864 iri_to_uri('https://www.google.com/search?q=Käsesoßenrührlöffel'), # German for cheese sauce stirring spoon
1865 'https://www.google.com/search?q=K%C3%A4seso%C3%9Fenr%C3%BChrl%C3%B6ffel')
1867 iri_to_uri('https://www.google.com/search?q=lt<+gt>+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#'),
1868 'https://www.google.com/search?q=lt%3C+gt%3E+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#')
1870 iri_to_uri('http://правозащита38.рф/category/news/'),
1871 'http://xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
1873 iri_to_uri('http://www.правозащита38.рф/category/news/'),
1874 'http://www.xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
1876 iri_to_uri('https://i❤.ws/emojidomain/👍👏🤝💪'),
1877 'https://xn--i-7iq.ws/emojidomain/%F0%9F%91%8D%F0%9F%91%8F%F0%9F%A4%9D%F0%9F%92%AA')
1879 iri_to_uri('http://日本語.jp/'),
1880 'http://xn--wgv71a119e.jp/')
1882 iri_to_uri('http://导航.中国/'),
1883 'http://xn--fet810g.xn--fiqs8s/')
1885 def test_clean_podcast_url(self
):
1886 self
.assertEqual(clean_podcast_url('https://www.podtrac.com/pts/redirect.mp3/chtbl.com/track/5899E/traffic.megaphone.fm/HSW7835899191.mp3'), 'https://traffic.megaphone.fm/HSW7835899191.mp3')
1887 self
.assertEqual(clean_podcast_url('https://play.podtrac.com/npr-344098539/edge1.pod.npr.org/anon.npr-podcasts/podcast/npr/waitwait/2020/10/20201003_waitwait_wwdtmpodcast201003-015621a5-f035-4eca-a9a1-7c118d90bc3c.mp3'), 'https://edge1.pod.npr.org/anon.npr-podcasts/podcast/npr/waitwait/2020/10/20201003_waitwait_wwdtmpodcast201003-015621a5-f035-4eca-a9a1-7c118d90bc3c.mp3')
1888 self
.assertEqual(clean_podcast_url('https://pdst.fm/e/2.gum.fm/chtbl.com/track/chrt.fm/track/34D33/pscrb.fm/rss/p/traffic.megaphone.fm/ITLLC7765286967.mp3?updated=1687282661'), 'https://traffic.megaphone.fm/ITLLC7765286967.mp3?updated=1687282661')
1889 self
.assertEqual(clean_podcast_url('https://pdst.fm/e/https://mgln.ai/e/441/www.buzzsprout.com/1121972/13019085-ep-252-the-deep-life-stack.mp3'), 'https://www.buzzsprout.com/1121972/13019085-ep-252-the-deep-life-stack.mp3')
1891 def test_LazyList(self
):
1892 it
= list(range(10))
1894 self
.assertEqual(list(LazyList(it
)), it
)
1895 self
.assertEqual(LazyList(it
).exhaust(), it
)
1896 self
.assertEqual(LazyList(it
)[5], it
[5])
1898 self
.assertEqual(LazyList(it
)[5:], it
[5:])
1899 self
.assertEqual(LazyList(it
)[:5], it
[:5])
1900 self
.assertEqual(LazyList(it
)[::2], it
[::2])
1901 self
.assertEqual(LazyList(it
)[1::2], it
[1::2])
1902 self
.assertEqual(LazyList(it
)[5::-1], it
[5::-1])
1903 self
.assertEqual(LazyList(it
)[6:2:-2], it
[6:2:-2])
1904 self
.assertEqual(LazyList(it
)[::-1], it
[::-1])
1906 self
.assertTrue(LazyList(it
))
1907 self
.assertFalse(LazyList(range(0)))
1908 self
.assertEqual(len(LazyList(it
)), len(it
))
1909 self
.assertEqual(repr(LazyList(it
)), repr(it
))
1910 self
.assertEqual(str(LazyList(it
)), str(it
))
1912 self
.assertEqual(list(LazyList(it
, reverse
=True)), it
[::-1])
1913 self
.assertEqual(list(reversed(LazyList(it
))[::-1]), it
)
1914 self
.assertEqual(list(reversed(LazyList(it
))[1:3:7]), it
[::-1][1:3:7])
1916 def test_LazyList_laziness(self
):
1918 def test(ll
, idx
, val
, cache
):
1919 self
.assertEqual(ll
[idx
], val
)
1920 self
.assertEqual(ll
._cache
, list(cache
))
1922 ll
= LazyList(range(10))
1923 test(ll
, 0, 0, range(1))
1924 test(ll
, 5, 5, range(6))
1925 test(ll
, -3, 7, range(10))
1927 ll
= LazyList(range(10), reverse
=True)
1928 test(ll
, -1, 0, range(1))
1929 test(ll
, 3, 6, range(10))
1931 ll
= LazyList(itertools
.count())
1932 test(ll
, 10, 10, range(11))
1934 test(ll
, -15, 14, range(15))
1936 def test_format_bytes(self
):
1937 self
.assertEqual(format_bytes(0), '0.00B')
1938 self
.assertEqual(format_bytes(1000), '1000.00B')
1939 self
.assertEqual(format_bytes(1024), '1.00KiB')
1940 self
.assertEqual(format_bytes(1024**2), '1.00MiB')
1941 self
.assertEqual(format_bytes(1024**3), '1.00GiB')
1942 self
.assertEqual(format_bytes(1024**4), '1.00TiB')
1943 self
.assertEqual(format_bytes(1024**5), '1.00PiB')
1944 self
.assertEqual(format_bytes(1024**6), '1.00EiB')
1945 self
.assertEqual(format_bytes(1024**7), '1.00ZiB')
1946 self
.assertEqual(format_bytes(1024**8), '1.00YiB')
1947 self
.assertEqual(format_bytes(1024**9), '1024.00YiB')
1949 def test_hide_login_info(self
):
1950 self
.assertEqual(Config
.hide_login_info(['-u', 'foo', '-p', 'bar']),
1951 ['-u', 'PRIVATE', '-p', 'PRIVATE'])
1952 self
.assertEqual(Config
.hide_login_info(['-u']), ['-u'])
1953 self
.assertEqual(Config
.hide_login_info(['-u', 'foo', '-u', 'bar']),
1954 ['-u', 'PRIVATE', '-u', 'PRIVATE'])
1955 self
.assertEqual(Config
.hide_login_info(['--username=foo']),
1956 ['--username=PRIVATE'])
1958 def test_locked_file(self
):
1959 TEXT
= 'test_locked_file\n'
1960 FILE
= 'test_locked_file.ytdl'
1961 MODES
= 'war' # Order is important
1964 for lock_mode
in MODES
:
1965 with
locked_file(FILE
, lock_mode
, False) as f
:
1966 if lock_mode
== 'r':
1967 self
.assertEqual(f
.read(), TEXT
* 2, 'Wrong file content')
1970 for test_mode
in MODES
:
1971 testing_write
= test_mode
!= 'r'
1973 with
locked_file(FILE
, test_mode
, False):
1975 except (BlockingIOError
, PermissionError
):
1976 if not testing_write
: # FIXME: blocked read access
1977 print(f
'Known issue: Exclusive lock ({lock_mode}) blocks read access ({test_mode})')
1979 self
.assertTrue(testing_write
, f
'{test_mode} is blocked by {lock_mode}')
1981 self
.assertFalse(testing_write
, f
'{test_mode} is not blocked by {lock_mode}')
1983 with contextlib
.suppress(OSError):
1986 def test_determine_file_encoding(self
):
1987 self
.assertEqual(determine_file_encoding(b
''), (None, 0))
1988 self
.assertEqual(determine_file_encoding(b
'--verbose -x --audio-format mkv\n'), (None, 0))
1990 self
.assertEqual(determine_file_encoding(b
'\xef\xbb\xbf'), ('utf-8', 3))
1991 self
.assertEqual(determine_file_encoding(b
'\x00\x00\xfe\xff'), ('utf-32-be', 4))
1992 self
.assertEqual(determine_file_encoding(b
'\xff\xfe'), ('utf-16-le', 2))
1994 self
.assertEqual(determine_file_encoding(b
'\xff\xfe# coding: utf-8\n--verbose'), ('utf-16-le', 2))
1996 self
.assertEqual(determine_file_encoding(b
'# coding: utf-8\n--verbose'), ('utf-8', 0))
1997 self
.assertEqual(determine_file_encoding(b
'# coding: someencodinghere-12345\n--verbose'), ('someencodinghere-12345', 0))
1999 self
.assertEqual(determine_file_encoding(b
'#coding:utf-8\n--verbose'), ('utf-8', 0))
2000 self
.assertEqual(determine_file_encoding(b
'# coding: utf-8 \r\n--verbose'), ('utf-8', 0))
2002 self
.assertEqual(determine_file_encoding('# coding: utf-32-be'.encode('utf-32-be')), ('utf-32-be', 0))
2003 self
.assertEqual(determine_file_encoding('# coding: utf-16-le'.encode('utf-16-le')), ('utf-16-le', 0))
2005 def test_get_compatible_ext(self
):
2006 self
.assertEqual(get_compatible_ext(
2007 vcodecs
=[None], acodecs
=[None, None], vexts
=['mp4'], aexts
=['m4a', 'm4a']), 'mkv')
2008 self
.assertEqual(get_compatible_ext(
2009 vcodecs
=[None], acodecs
=[None], vexts
=['flv'], aexts
=['flv']), 'flv')
2011 self
.assertEqual(get_compatible_ext(
2012 vcodecs
=[None], acodecs
=[None], vexts
=['mp4'], aexts
=['m4a']), 'mp4')
2013 self
.assertEqual(get_compatible_ext(
2014 vcodecs
=[None], acodecs
=[None], vexts
=['mp4'], aexts
=['webm']), 'mkv')
2015 self
.assertEqual(get_compatible_ext(
2016 vcodecs
=[None], acodecs
=[None], vexts
=['webm'], aexts
=['m4a']), 'mkv')
2017 self
.assertEqual(get_compatible_ext(
2018 vcodecs
=[None], acodecs
=[None], vexts
=['webm'], aexts
=['webm']), 'webm')
2019 self
.assertEqual(get_compatible_ext(
2020 vcodecs
=[None], acodecs
=[None], vexts
=['webm'], aexts
=['weba']), 'webm')
2022 self
.assertEqual(get_compatible_ext(
2023 vcodecs
=['h264'], acodecs
=['mp4a'], vexts
=['mov'], aexts
=['m4a']), 'mp4')
2024 self
.assertEqual(get_compatible_ext(
2025 vcodecs
=['av01.0.12M.08'], acodecs
=['opus'], vexts
=['mp4'], aexts
=['webm']), 'webm')
2027 self
.assertEqual(get_compatible_ext(
2028 vcodecs
=['vp9'], acodecs
=['opus'], vexts
=['webm'], aexts
=['webm'], preferences
=['flv', 'mp4']), 'mp4')
2029 self
.assertEqual(get_compatible_ext(
2030 vcodecs
=['av1'], acodecs
=['mp4a'], vexts
=['webm'], aexts
=['m4a'], preferences
=('webm', 'mkv')), 'mkv')
2032 def test_try_call(self
):
2033 def total(*x
, **kwargs
):
2034 return sum(x
) + sum(kwargs
.values())
2036 self
.assertEqual(try_call(None), None,
2037 msg
='not a fn should give None')
2038 self
.assertEqual(try_call(lambda: 1), 1,
2039 msg
='int fn with no expected_type should give int')
2040 self
.assertEqual(try_call(lambda: 1, expected_type
=int), 1,
2041 msg
='int fn with expected_type int should give int')
2042 self
.assertEqual(try_call(lambda: 1, expected_type
=dict), None,
2043 msg
='int fn with wrong expected_type should give None')
2044 self
.assertEqual(try_call(total
, args
=(0, 1, 0), expected_type
=int), 1,
2045 msg
='fn should accept arglist')
2046 self
.assertEqual(try_call(total
, kwargs
={'a': 0, 'b': 1, 'c': 0}, expected_type
=int), 1,
2047 msg
='fn should accept kwargs')
2048 self
.assertEqual(try_call(lambda: 1, expected_type
=dict), None,
2049 msg
='int fn with no expected_type should give None')
2050 self
.assertEqual(try_call(lambda x
: {}, total
, args
=(42, ), expected_type
=int), 42,
2051 msg
='expect first int result with expected_type int')
2053 def test_variadic(self
):
2054 self
.assertEqual(variadic(None), (None, ))
2055 self
.assertEqual(variadic('spam'), ('spam', ))
2056 self
.assertEqual(variadic('spam', allowed_types
=dict), 'spam')
2057 with warnings
.catch_warnings():
2058 warnings
.simplefilter('ignore')
2059 self
.assertEqual(variadic('spam', allowed_types
=[dict]), 'spam')
2061 def test_http_header_dict(self
):
2062 headers
= HTTPHeaderDict()
2063 headers
['ytdl-test'] = b
'0'
2064 self
.assertEqual(list(headers
.items()), [('Ytdl-Test', '0')])
2065 headers
['ytdl-test'] = 1
2066 self
.assertEqual(list(headers
.items()), [('Ytdl-Test', '1')])
2067 headers
['Ytdl-test'] = '2'
2068 self
.assertEqual(list(headers
.items()), [('Ytdl-Test', '2')])
2069 self
.assertTrue('ytDl-Test' in headers
)
2070 self
.assertEqual(str(headers
), str(dict(headers
)))
2071 self
.assertEqual(repr(headers
), str(dict(headers
)))
2073 headers
.update({'X-dlp': 'data'})
2074 self
.assertEqual(set(headers
.items()), {('Ytdl-Test', '2'), ('X-Dlp', 'data')})
2075 self
.assertEqual(dict(headers
), {'Ytdl-Test': '2', 'X-Dlp': 'data'})
2076 self
.assertEqual(len(headers
), 2)
2077 self
.assertEqual(headers
.copy(), headers
)
2078 headers2
= HTTPHeaderDict({'X-dlp': 'data3'}, **headers
, **{'X-dlp': 'data2'})
2079 self
.assertEqual(set(headers2
.items()), {('Ytdl-Test', '2'), ('X-Dlp', 'data2')})
2080 self
.assertEqual(len(headers2
), 2)
2082 self
.assertEqual(len(headers2
), 0)
2084 # ensure we prefer latter headers
2085 headers3
= HTTPHeaderDict({'Ytdl-TeSt': 1}, {'Ytdl-test': 2})
2086 self
.assertEqual(set(headers3
.items()), {('Ytdl-Test', '2')})
2087 del headers3
['ytdl-tesT']
2088 self
.assertEqual(dict(headers3
), {})
2090 headers4
= HTTPHeaderDict({'ytdl-test': 'data;'})
2091 self
.assertEqual(set(headers4
.items()), {('Ytdl-Test', 'data;')})
2093 # common mistake: strip whitespace from values
2094 # https://github.com/yt-dlp/yt-dlp/issues/8729
2095 headers5
= HTTPHeaderDict({'ytdl-test': ' data; '})
2096 self
.assertEqual(set(headers5
.items()), {('Ytdl-Test', 'data;')})
2098 def test_extract_basic_auth(self
):
2099 assert extract_basic_auth('http://:foo.bar') == ('http://:foo.bar', None)
2100 assert extract_basic_auth('http://foo.bar') == ('http://foo.bar', None)
2101 assert extract_basic_auth('http://@foo.bar') == ('http://foo.bar', 'Basic Og==')
2102 assert extract_basic_auth('http://:pass@foo.bar') == ('http://foo.bar', 'Basic OnBhc3M=')
2103 assert extract_basic_auth('http://user:@foo.bar') == ('http://foo.bar', 'Basic dXNlcjo=')
2104 assert extract_basic_auth('http://user:pass@foo.bar') == ('http://foo.bar', 'Basic dXNlcjpwYXNz')
2106 @unittest.skipUnless(compat_os_name
== 'nt', 'Only relevant on Windows')
2107 def test_windows_escaping(self
):
2110 '%CMDCMDLINE:~-1%&',
2119 # We replace \r with \n
2120 ('a\r\ra', 'a\n\na'),
2123 def run_shell(args
):
2124 stdout
, stderr
, error
= Popen
.run(
2125 args
, text
=True, shell
=True, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
)
2130 for argument
in tests
:
2131 if isinstance(argument
, str):
2134 argument
, expected
= argument
2136 args
= [sys
.executable
, '-c', 'import sys; print(end=sys.argv[1])', argument
, 'end']
2137 assert run_shell(args
) == expected
2138 assert run_shell(shell_quote(args
, shell
=True)) == expected
2141 if __name__
== '__main__':