]> jfr.im git - yt-dlp.git/blob - test/test_utils.py
fix motherless
[yt-dlp.git] / test / test_utils.py
1 #!/usr/bin/env python3
2
3 # Allow direct execution
4 import os
5 import sys
6 import unittest
7 import warnings
8 import datetime as dt
9
10 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
12
13 import contextlib
14 import io
15 import itertools
16 import json
17 import subprocess
18 import xml.etree.ElementTree
19
20 from yt_dlp.compat import (
21 compat_etree_fromstring,
22 compat_HTMLParseError,
23 compat_os_name,
24 )
25 from yt_dlp.utils import (
26 Config,
27 DateRange,
28 ExtractorError,
29 InAdvancePagedList,
30 LazyList,
31 NO_DEFAULT,
32 OnDemandPagedList,
33 Popen,
34 age_restricted,
35 args_to_str,
36 base_url,
37 caesar,
38 clean_html,
39 clean_podcast_url,
40 cli_bool_option,
41 cli_option,
42 cli_valueless_option,
43 date_from_str,
44 datetime_from_str,
45 detect_exe_version,
46 determine_ext,
47 determine_file_encoding,
48 dfxp2srt,
49 encode_base_n,
50 encode_compat_str,
51 encodeFilename,
52 expand_path,
53 extract_attributes,
54 extract_basic_auth,
55 find_xpath_attr,
56 fix_xml_ampersands,
57 float_or_none,
58 format_bytes,
59 get_compatible_ext,
60 get_element_by_attribute,
61 get_element_by_class,
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,
70 int_or_none,
71 intlist_to_bytes,
72 iri_to_uri,
73 is_html,
74 js_to_json,
75 limit_length,
76 locked_file,
77 lowercase_escape,
78 match_str,
79 merge_dicts,
80 mimetype2ext,
81 month_by_name,
82 multipart_encode,
83 ohdave_rsa_encrypt,
84 orderedSet,
85 parse_age_limit,
86 parse_bitrate,
87 parse_codecs,
88 parse_count,
89 parse_dfxp_time_expr,
90 parse_duration,
91 parse_filesize,
92 parse_iso8601,
93 parse_qs,
94 parse_resolution,
95 pkcs1pad,
96 prepend_extension,
97 read_batch_urls,
98 remove_end,
99 remove_quotes,
100 remove_start,
101 render_table,
102 replace_extension,
103 rot47,
104 sanitize_filename,
105 sanitize_path,
106 sanitize_url,
107 shell_quote,
108 smuggle_url,
109 str_to_int,
110 strip_jsonp,
111 strip_or_none,
112 subtitles_filename,
113 timeconvert,
114 try_call,
115 unescapeHTML,
116 unified_strdate,
117 unified_timestamp,
118 unsmuggle_url,
119 update_url_query,
120 uppercase_escape,
121 url_basename,
122 url_or_none,
123 urlencode_postdata,
124 urljoin,
125 urshift,
126 variadic,
127 version_tuple,
128 xpath_attr,
129 xpath_element,
130 xpath_text,
131 xpath_with_ns,
132 )
133 from yt_dlp.utils._utils import _UnsafeExtensionError
134 from yt_dlp.utils.networking import (
135 HTTPHeaderDict,
136 escape_rfc3986,
137 normalize_url,
138 remove_dot_segments,
139 )
140
141
142 class TestUtil(unittest.TestCase):
143 def test_timeconvert(self):
144 self.assertTrue(timeconvert('') is None)
145 self.assertTrue(timeconvert('bougrg') is None)
146
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')
151
152 self.assertEqual(sanitize_filename('123'), '123')
153
154 self.assertEqual('abc⧸de', sanitize_filename('abc/de'))
155 self.assertFalse('/' in sanitize_filename('abc/de///'))
156
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))
161
162 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
163 aumlaut = 'ä'
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)
167
168 self.assertEqual(
169 sanitize_filename('New World record at 0:12:34'),
170 'New World record at 0_12_34')
171
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')
178
179 forbidden = '"\0\\/'
180 for fc in forbidden:
181 for fbc in forbidden:
182 self.assertTrue(fbc not in sanitize_filename(fc))
183
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')
187
188 self.assertEqual(sanitize_filename('123', restricted=True), '123')
189
190 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
191 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
192
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))
197
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
201
202 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
203 for fc in forbidden:
204 for fbc in forbidden:
205 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
206
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) != '')
213
214 self.assertEqual(sanitize_filename(
215 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
216 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYTHssaaaaaaaeceeeeiiiionooooooooeuuuuuythy')
217
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')
222
223 def test_sanitize_path(self):
224 if sys.platform != 'win32':
225 return
226
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')
234
235 self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
236 self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
237
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')
242
243 self.assertEqual(
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')
246
247 self.assertEqual(
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..#')
253
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')
258
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')
265
266 def test_expand_path(self):
267 def env(var):
268 return f'%{var}%' if sys.platform == 'win32' else f'${var}'
269
270 os.environ['yt_dlp_EXPATH_PATH'] = 'expanded'
271 self.assertEqual(expand_path(env('yt_dlp_EXPATH_PATH')), 'expanded')
272
273 old_home = os.environ.get('HOME')
274 test_str = R'C:\Documents and Settings\тест\Application Data'
275 try:
276 os.environ['HOME'] = test_str
277 self.assertEqual(expand_path(env('HOME')), os.getenv('HOME'))
278 self.assertEqual(expand_path('~'), os.getenv('HOME'))
279 self.assertEqual(
280 expand_path('~/{}'.format(env('yt_dlp_EXPATH_PATH'))),
281 '{}/expanded'.format(os.getenv('HOME')))
282 finally:
283 os.environ['HOME'] = old_home or ''
284
285 _uncommon_extensions = [
286 ('exe', 'abc.exe.ext'),
287 ('de', 'abc.de.ext'),
288 ('../.mp4', None),
289 ('..\\.mp4', None),
290 ]
291
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')
299
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)
305 if result:
306 self.assertEqual(prepend_extension('abc.ext', ext, 'ext'), result)
307 else:
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')
312
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')
320
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')
330
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')
335
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')
340
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')
345
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('";"'), ';')
354
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])
361
362 def test_unescape_html(self):
363 self.assertEqual(unescapeHTML('%20;'), '%20;')
364 self.assertEqual(unescapeHTML('&#x2F;'), '/')
365 self.assertEqual(unescapeHTML('&#47;'), '/')
366 self.assertEqual(unescapeHTML('&eacute;'), 'é')
367 self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
368 self.assertEqual(unescapeHTML('&a&quot;'), '&a"')
369 # HTML5 entities
370 self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
371
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'))
378
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'))
388
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)
396
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')
406 self.assertEqual(
407 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
408 '20141126')
409 self.assertEqual(
410 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
411 '20150202')
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')
422
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)
431 self.assertEqual(
432 unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
433 1417001400)
434 self.assertEqual(
435 unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
436 1422902860)
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
448 self.assertEqual(unified_timestamp('December 31 1969 20:00:01 EDT'), 1)
449 self.assertEqual(unified_timestamp('Wednesday 31 December 1969 18:01:26 MDT'), 86)
450 self.assertEqual(unified_timestamp('12/31/1969 20:01:18 EDT', False), 78)
451
452 def test_determine_ext(self):
453 self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
454 self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
455 self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
456 self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
457 self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
458 self.assertEqual(determine_ext('foobar', None), None)
459
460 def test_find_xpath_attr(self):
461 testxml = '''<root>
462 <node/>
463 <node x="a"/>
464 <node x="a" y="c" />
465 <node x="b" y="d" />
466 <node x="" />
467 </root>'''
468 doc = compat_etree_fromstring(testxml)
469
470 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
471 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
472 self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
473 self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
474 self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
475 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
476 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
477 self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
478 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
479 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
480 self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
481
482 def test_xpath_with_ns(self):
483 testxml = '''<root xmlns:media="http://example.com/">
484 <media:song>
485 <media:author>The Author</media:author>
486 <url>http://server.com/download.mp3</url>
487 </media:song>
488 </root>'''
489 doc = compat_etree_fromstring(testxml)
490 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
491 self.assertTrue(find('media:song') is not None)
492 self.assertEqual(find('media:song/media:author').text, 'The Author')
493 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
494
495 def test_xpath_element(self):
496 doc = xml.etree.ElementTree.Element('root')
497 div = xml.etree.ElementTree.SubElement(doc, 'div')
498 p = xml.etree.ElementTree.SubElement(div, 'p')
499 p.text = 'Foo'
500 self.assertEqual(xpath_element(doc, 'div/p'), p)
501 self.assertEqual(xpath_element(doc, ['div/p']), p)
502 self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
503 self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
504 self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
505 self.assertTrue(xpath_element(doc, 'div/bar') is None)
506 self.assertTrue(xpath_element(doc, ['div/bar']) is None)
507 self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
508 self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
509 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
510 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
511
512 def test_xpath_text(self):
513 testxml = '''<root>
514 <div>
515 <p>Foo</p>
516 </div>
517 </root>'''
518 doc = compat_etree_fromstring(testxml)
519 self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
520 self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
521 self.assertTrue(xpath_text(doc, 'div/bar') is None)
522 self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
523
524 def test_xpath_attr(self):
525 testxml = '''<root>
526 <div>
527 <p x="a">Foo</p>
528 </div>
529 </root>'''
530 doc = compat_etree_fromstring(testxml)
531 self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
532 self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
533 self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
534 self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
535 self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
536 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
537 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
538
539 def test_smuggle_url(self):
540 data = {'ö': 'ö', 'abc': [3]}
541 url = 'https://foo.bar/baz?x=y#a'
542 smug_url = smuggle_url(url, data)
543 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
544 self.assertEqual(url, unsmug_url)
545 self.assertEqual(data, unsmug_data)
546
547 res_url, res_data = unsmuggle_url(url)
548 self.assertEqual(res_url, url)
549 self.assertEqual(res_data, None)
550
551 smug_url = smuggle_url(url, {'a': 'b'})
552 smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
553 res_url, res_data = unsmuggle_url(smug_smug_url)
554 self.assertEqual(res_url, url)
555 self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
556
557 def test_shell_quote(self):
558 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
559 self.assertEqual(
560 shell_quote(args),
561 """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
562
563 def test_float_or_none(self):
564 self.assertEqual(float_or_none('42.42'), 42.42)
565 self.assertEqual(float_or_none('42'), 42.0)
566 self.assertEqual(float_or_none(''), None)
567 self.assertEqual(float_or_none(None), None)
568 self.assertEqual(float_or_none([]), None)
569 self.assertEqual(float_or_none(set()), None)
570
571 def test_int_or_none(self):
572 self.assertEqual(int_or_none('42'), 42)
573 self.assertEqual(int_or_none(''), None)
574 self.assertEqual(int_or_none(None), None)
575 self.assertEqual(int_or_none([]), None)
576 self.assertEqual(int_or_none(set()), None)
577
578 def test_str_to_int(self):
579 self.assertEqual(str_to_int('123,456'), 123456)
580 self.assertEqual(str_to_int('123.456'), 123456)
581 self.assertEqual(str_to_int(523), 523)
582 self.assertEqual(str_to_int('noninteger'), None)
583 self.assertEqual(str_to_int([]), None)
584
585 def test_url_basename(self):
586 self.assertEqual(url_basename('http://foo.de/'), '')
587 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
588 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
589 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
590 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
591 self.assertEqual(
592 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
593 'trailer.mp4')
594
595 def test_base_url(self):
596 self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
597 self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
598 self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
599 self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
600 self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
601 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/')
602
603 def test_urljoin(self):
604 self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
605 self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
606 self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
607 self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
608 self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
609 self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
610 self.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://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/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
613 self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
614 self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
615 self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
616 self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
617 self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
618 self.assertEqual(urljoin('http://foo.de/', None), None)
619 self.assertEqual(urljoin('http://foo.de/', ''), None)
620 self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
621 self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
622 self.assertEqual(urljoin('http://foo.de/a/b/c.txt', 'rtmp://foo.de'), 'rtmp://foo.de')
623 self.assertEqual(urljoin(None, 'rtmp://foo.de'), 'rtmp://foo.de')
624
625 def test_url_or_none(self):
626 self.assertEqual(url_or_none(None), None)
627 self.assertEqual(url_or_none(''), None)
628 self.assertEqual(url_or_none('foo'), None)
629 self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
630 self.assertEqual(url_or_none('https://foo.de'), 'https://foo.de')
631 self.assertEqual(url_or_none('http$://foo.de'), None)
632 self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
633 self.assertEqual(url_or_none('//foo.de'), '//foo.de')
634 self.assertEqual(url_or_none('s3://foo.de'), None)
635 self.assertEqual(url_or_none('rtmpte://foo.de'), 'rtmpte://foo.de')
636 self.assertEqual(url_or_none('mms://foo.de'), 'mms://foo.de')
637 self.assertEqual(url_or_none('rtspu://foo.de'), 'rtspu://foo.de')
638 self.assertEqual(url_or_none('ftps://foo.de'), 'ftps://foo.de')
639
640 def test_parse_age_limit(self):
641 self.assertEqual(parse_age_limit(None), None)
642 self.assertEqual(parse_age_limit(False), None)
643 self.assertEqual(parse_age_limit('invalid'), None)
644 self.assertEqual(parse_age_limit(0), 0)
645 self.assertEqual(parse_age_limit(18), 18)
646 self.assertEqual(parse_age_limit(21), 21)
647 self.assertEqual(parse_age_limit(22), None)
648 self.assertEqual(parse_age_limit('18'), 18)
649 self.assertEqual(parse_age_limit('18+'), 18)
650 self.assertEqual(parse_age_limit('PG-13'), 13)
651 self.assertEqual(parse_age_limit('TV-14'), 14)
652 self.assertEqual(parse_age_limit('TV-MA'), 17)
653 self.assertEqual(parse_age_limit('TV14'), 14)
654 self.assertEqual(parse_age_limit('TV_G'), 0)
655
656 def test_parse_duration(self):
657 self.assertEqual(parse_duration(None), None)
658 self.assertEqual(parse_duration(False), None)
659 self.assertEqual(parse_duration('invalid'), None)
660 self.assertEqual(parse_duration('1'), 1)
661 self.assertEqual(parse_duration('1337:12'), 80232)
662 self.assertEqual(parse_duration('9:12:43'), 33163)
663 self.assertEqual(parse_duration('12:00'), 720)
664 self.assertEqual(parse_duration('00:01:01'), 61)
665 self.assertEqual(parse_duration('x:y'), None)
666 self.assertEqual(parse_duration('3h11m53s'), 11513)
667 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
668 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
669 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 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('62m45s'), 3765)
673 self.assertEqual(parse_duration('6m59s'), 419)
674 self.assertEqual(parse_duration('49s'), 49)
675 self.assertEqual(parse_duration('0h0m0s'), 0)
676 self.assertEqual(parse_duration('0m0s'), 0)
677 self.assertEqual(parse_duration('0s'), 0)
678 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
679 self.assertEqual(parse_duration('T30M38S'), 1838)
680 self.assertEqual(parse_duration('5 s'), 5)
681 self.assertEqual(parse_duration('3 min'), 180)
682 self.assertEqual(parse_duration('2.5 hours'), 9000)
683 self.assertEqual(parse_duration('02:03:04'), 7384)
684 self.assertEqual(parse_duration('01:02:03:04'), 93784)
685 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
686 self.assertEqual(parse_duration('87 Min.'), 5220)
687 self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
688 self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
689 self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
690 self.assertEqual(parse_duration('01:02:03:050'), 3723.05)
691 self.assertEqual(parse_duration('103:050'), 103.05)
692 self.assertEqual(parse_duration('1HR 3MIN'), 3780)
693 self.assertEqual(parse_duration('2hrs 3mins'), 7380)
694
695 def test_fix_xml_ampersands(self):
696 self.assertEqual(
697 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
698 self.assertEqual(
699 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
700 '"&amp;x=y&amp;wrong;&amp;z=a')
701 self.assertEqual(
702 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
703 '&amp;&apos;&gt;&lt;&quot;')
704 self.assertEqual(
705 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
706 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
707
708 def test_paged_list(self):
709 def testPL(size, pagesize, sliceargs, expected):
710 def get_page(pagenum):
711 firstid = pagenum * pagesize
712 upto = min(size, pagenum * pagesize + pagesize)
713 yield from range(firstid, upto)
714
715 pl = OnDemandPagedList(get_page, pagesize)
716 got = pl.getslice(*sliceargs)
717 self.assertEqual(got, expected)
718
719 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
720 got = iapl.getslice(*sliceargs)
721 self.assertEqual(got, expected)
722
723 testPL(5, 2, (), [0, 1, 2, 3, 4])
724 testPL(5, 2, (1,), [1, 2, 3, 4])
725 testPL(5, 2, (2,), [2, 3, 4])
726 testPL(5, 2, (4,), [4])
727 testPL(5, 2, (0, 3), [0, 1, 2])
728 testPL(5, 2, (1, 4), [1, 2, 3])
729 testPL(5, 2, (2, 99), [2, 3, 4])
730 testPL(5, 2, (20, 99), [])
731
732 def test_read_batch_urls(self):
733 f = io.StringIO('''\xef\xbb\xbf foo
734 bar\r
735 baz
736 # More after this line\r
737 ; or after this
738 bam''')
739 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
740
741 def test_urlencode_postdata(self):
742 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
743 self.assertTrue(isinstance(data, bytes))
744
745 def test_update_url_query(self):
746 self.assertEqual(parse_qs(update_url_query(
747 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
748 parse_qs('http://example.com/path?quality=HD&format=mp4'))
749 self.assertEqual(parse_qs(update_url_query(
750 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
751 parse_qs('http://example.com/path?system=LINUX&system=WINDOWS'))
752 self.assertEqual(parse_qs(update_url_query(
753 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
754 parse_qs('http://example.com/path?fields=id,formats,subtitles'))
755 self.assertEqual(parse_qs(update_url_query(
756 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
757 parse_qs('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
758 self.assertEqual(parse_qs(update_url_query(
759 'http://example.com/path?manifest=f4m', {'manifest': []})),
760 parse_qs('http://example.com/path'))
761 self.assertEqual(parse_qs(update_url_query(
762 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
763 parse_qs('http://example.com/path?system=LINUX'))
764 self.assertEqual(parse_qs(update_url_query(
765 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
766 parse_qs('http://example.com/path?fields=id,formats,subtitles'))
767 self.assertEqual(parse_qs(update_url_query(
768 'http://example.com/path', {'width': 1080, 'height': 720})),
769 parse_qs('http://example.com/path?width=1080&height=720'))
770 self.assertEqual(parse_qs(update_url_query(
771 'http://example.com/path', {'bitrate': 5020.43})),
772 parse_qs('http://example.com/path?bitrate=5020.43'))
773 self.assertEqual(parse_qs(update_url_query(
774 'http://example.com/path', {'test': '第二行тест'})),
775 parse_qs('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
776
777 def test_multipart_encode(self):
778 self.assertEqual(
779 multipart_encode({b'field': b'value'}, boundary='AAAAAA')[0],
780 b'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
781 self.assertEqual(
782 multipart_encode({'欄位'.encode(): '值'.encode()}, boundary='AAAAAA')[0],
783 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')
784 self.assertRaises(
785 ValueError, multipart_encode, {b'field': b'value'}, boundary='value')
786
787 def test_merge_dicts(self):
788 self.assertEqual(merge_dicts({'a': 1}, {'b': 2}), {'a': 1, 'b': 2})
789 self.assertEqual(merge_dicts({'a': 1}, {'a': 2}), {'a': 1})
790 self.assertEqual(merge_dicts({'a': 1}, {'a': None}), {'a': 1})
791 self.assertEqual(merge_dicts({'a': 1}, {'a': ''}), {'a': 1})
792 self.assertEqual(merge_dicts({'a': 1}, {}), {'a': 1})
793 self.assertEqual(merge_dicts({'a': None}, {'a': 1}), {'a': 1})
794 self.assertEqual(merge_dicts({'a': ''}, {'a': 1}), {'a': ''})
795 self.assertEqual(merge_dicts({'a': ''}, {'a': 'abc'}), {'a': 'abc'})
796 self.assertEqual(merge_dicts({'a': None}, {'a': ''}, {'a': 'abc'}), {'a': 'abc'})
797
798 def test_encode_compat_str(self):
799 self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
800 self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
801
802 def test_parse_iso8601(self):
803 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
804 self.assertEqual(parse_iso8601('2014-03-23T23:04:26-07:00'), 1395641066)
805 self.assertEqual(parse_iso8601('2014-03-23T23:04:26', timezone=dt.timedelta(hours=-7)), 1395641066)
806 self.assertEqual(parse_iso8601('2014-03-23T23:04:26', timezone=NO_DEFAULT), None)
807 # default does not override timezone in date_str
808 self.assertEqual(parse_iso8601('2014-03-23T23:04:26-07:00', timezone=dt.timedelta(hours=-10)), 1395641066)
809 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
810 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
811 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
812 self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
813 self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
814
815 def test_strip_jsonp(self):
816 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
817 d = json.loads(stripped)
818 self.assertEqual(d, [{'id': '532cb', 'x': 3}])
819
820 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
821 d = json.loads(stripped)
822 self.assertEqual(d, {'STATUS': 'OK'})
823
824 stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
825 d = json.loads(stripped)
826 self.assertEqual(d, {'status': 'success'})
827
828 stripped = strip_jsonp('window.cb && window.cb({"status": "success"});')
829 d = json.loads(stripped)
830 self.assertEqual(d, {'status': 'success'})
831
832 stripped = strip_jsonp('window.cb && cb({"status": "success"});')
833 d = json.loads(stripped)
834 self.assertEqual(d, {'status': 'success'})
835
836 stripped = strip_jsonp('({"status": "success"});')
837 d = json.loads(stripped)
838 self.assertEqual(d, {'status': 'success'})
839
840 def test_strip_or_none(self):
841 self.assertEqual(strip_or_none(' abc'), 'abc')
842 self.assertEqual(strip_or_none('abc '), 'abc')
843 self.assertEqual(strip_or_none(' abc '), 'abc')
844 self.assertEqual(strip_or_none('\tabc\t'), 'abc')
845 self.assertEqual(strip_or_none('\n\tabc\n\t'), 'abc')
846 self.assertEqual(strip_or_none('abc'), 'abc')
847 self.assertEqual(strip_or_none(''), '')
848 self.assertEqual(strip_or_none(None), None)
849 self.assertEqual(strip_or_none(42), None)
850 self.assertEqual(strip_or_none([]), None)
851
852 def test_uppercase_escape(self):
853 self.assertEqual(uppercase_escape('aä'), 'aä')
854 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
855
856 def test_lowercase_escape(self):
857 self.assertEqual(lowercase_escape('aä'), 'aä')
858 self.assertEqual(lowercase_escape('\\u0026'), '&')
859
860 def test_limit_length(self):
861 self.assertEqual(limit_length(None, 12), None)
862 self.assertEqual(limit_length('foo', 12), 'foo')
863 self.assertTrue(
864 limit_length('foo bar baz asd', 12).startswith('foo bar'))
865 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
866
867 def test_mimetype2ext(self):
868 self.assertEqual(mimetype2ext(None), None)
869 self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
870 self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
871 self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
872 self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
873 self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
874 self.assertEqual(mimetype2ext('audio/x-wav'), 'wav')
875 self.assertEqual(mimetype2ext('audio/x-wav;codec=pcm'), 'wav')
876
877 def test_month_by_name(self):
878 self.assertEqual(month_by_name(None), None)
879 self.assertEqual(month_by_name('December', 'en'), 12)
880 self.assertEqual(month_by_name('décembre', 'fr'), 12)
881 self.assertEqual(month_by_name('December'), 12)
882 self.assertEqual(month_by_name('décembre'), None)
883 self.assertEqual(month_by_name('Unknown', 'unknown'), None)
884
885 def test_parse_codecs(self):
886 self.assertEqual(parse_codecs(''), {})
887 self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
888 'vcodec': 'avc1.77.30',
889 'acodec': 'mp4a.40.2',
890 'dynamic_range': None,
891 })
892 self.assertEqual(parse_codecs('mp4a.40.2'), {
893 'vcodec': 'none',
894 'acodec': 'mp4a.40.2',
895 'dynamic_range': None,
896 })
897 self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
898 'vcodec': 'avc1.42001e',
899 'acodec': 'mp4a.40.5',
900 'dynamic_range': None,
901 })
902 self.assertEqual(parse_codecs('avc3.640028'), {
903 'vcodec': 'avc3.640028',
904 'acodec': 'none',
905 'dynamic_range': None,
906 })
907 self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
908 'vcodec': 'h264',
909 'acodec': 'aac',
910 'dynamic_range': None,
911 })
912 self.assertEqual(parse_codecs('av01.0.05M.08'), {
913 'vcodec': 'av01.0.05M.08',
914 'acodec': 'none',
915 'dynamic_range': None,
916 })
917 self.assertEqual(parse_codecs('vp9.2'), {
918 'vcodec': 'vp9.2',
919 'acodec': 'none',
920 'dynamic_range': 'HDR10',
921 })
922 self.assertEqual(parse_codecs('av01.0.12M.10.0.110.09.16.09.0'), {
923 'vcodec': 'av01.0.12M.10.0.110.09.16.09.0',
924 'acodec': 'none',
925 'dynamic_range': 'HDR10',
926 })
927 self.assertEqual(parse_codecs('dvhe'), {
928 'vcodec': 'dvhe',
929 'acodec': 'none',
930 'dynamic_range': 'DV',
931 })
932 self.assertEqual(parse_codecs('theora, vorbis'), {
933 'vcodec': 'theora',
934 'acodec': 'vorbis',
935 'dynamic_range': None,
936 })
937 self.assertEqual(parse_codecs('unknownvcodec, unknownacodec'), {
938 'vcodec': 'unknownvcodec',
939 'acodec': 'unknownacodec',
940 })
941 self.assertEqual(parse_codecs('unknown'), {})
942
943 def test_escape_rfc3986(self):
944 reserved = "!*'();:@&=+$,/?#[]"
945 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
946 self.assertEqual(escape_rfc3986(reserved), reserved)
947 self.assertEqual(escape_rfc3986(unreserved), unreserved)
948 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
949 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
950 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
951 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
952
953 def test_normalize_url(self):
954 self.assertEqual(
955 normalize_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
956 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4',
957 )
958 self.assertEqual(
959 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'),
960 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290',
961 )
962 self.assertEqual(
963 normalize_url('http://тест.рф/фрагмент'),
964 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82',
965 )
966 self.assertEqual(
967 normalize_url('http://тест.рф/абв?абв=абв#абв'),
968 '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',
969 )
970 self.assertEqual(normalize_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
971
972 self.assertEqual(normalize_url('http://www.example.com/../a/b/../c/./d.html'), 'http://www.example.com/a/c/d.html')
973
974 def test_remove_dot_segments(self):
975 self.assertEqual(remove_dot_segments('/a/b/c/./../../g'), '/a/g')
976 self.assertEqual(remove_dot_segments('mid/content=5/../6'), 'mid/6')
977 self.assertEqual(remove_dot_segments('/ad/../cd'), '/cd')
978 self.assertEqual(remove_dot_segments('/ad/../cd/'), '/cd/')
979 self.assertEqual(remove_dot_segments('/..'), '/')
980 self.assertEqual(remove_dot_segments('/./'), '/')
981 self.assertEqual(remove_dot_segments('/./a'), '/a')
982 self.assertEqual(remove_dot_segments('/abc/./.././d/././e/.././f/./../../ghi'), '/ghi')
983 self.assertEqual(remove_dot_segments('/'), '/')
984 self.assertEqual(remove_dot_segments('/t'), '/t')
985 self.assertEqual(remove_dot_segments('t'), 't')
986 self.assertEqual(remove_dot_segments(''), '')
987 self.assertEqual(remove_dot_segments('/../a/b/c'), '/a/b/c')
988 self.assertEqual(remove_dot_segments('../a'), 'a')
989 self.assertEqual(remove_dot_segments('./a'), 'a')
990 self.assertEqual(remove_dot_segments('.'), '')
991 self.assertEqual(remove_dot_segments('////'), '////')
992
993 def test_js_to_json_vars_strings(self):
994 self.assertDictEqual(
995 json.loads(js_to_json(
996 '''{
997 'null': a,
998 'nullStr': b,
999 'true': c,
1000 'trueStr': d,
1001 'false': e,
1002 'falseStr': f,
1003 'unresolvedVar': g,
1004 }''',
1005 {
1006 'a': 'null',
1007 'b': '"null"',
1008 'c': 'true',
1009 'd': '"true"',
1010 'e': 'false',
1011 'f': '"false"',
1012 'g': 'var',
1013 },
1014 )),
1015 {
1016 'null': None,
1017 'nullStr': 'null',
1018 'true': True,
1019 'trueStr': 'true',
1020 'false': False,
1021 'falseStr': 'false',
1022 'unresolvedVar': 'var',
1023 },
1024 )
1025
1026 self.assertDictEqual(
1027 json.loads(js_to_json(
1028 '''{
1029 'int': a,
1030 'intStr': b,
1031 'float': c,
1032 'floatStr': d,
1033 }''',
1034 {
1035 'a': '123',
1036 'b': '"123"',
1037 'c': '1.23',
1038 'd': '"1.23"',
1039 },
1040 )),
1041 {
1042 'int': 123,
1043 'intStr': '123',
1044 'float': 1.23,
1045 'floatStr': '1.23',
1046 },
1047 )
1048
1049 self.assertDictEqual(
1050 json.loads(js_to_json(
1051 '''{
1052 'object': a,
1053 'objectStr': b,
1054 'array': c,
1055 'arrayStr': d,
1056 }''',
1057 {
1058 'a': '{}',
1059 'b': '"{}"',
1060 'c': '[]',
1061 'd': '"[]"',
1062 },
1063 )),
1064 {
1065 'object': {},
1066 'objectStr': '{}',
1067 'array': [],
1068 'arrayStr': '[]',
1069 },
1070 )
1071
1072 def test_js_to_json_realworld(self):
1073 inp = '''{
1074 'clip':{'provider':'pseudo'}
1075 }'''
1076 self.assertEqual(js_to_json(inp), '''{
1077 "clip":{"provider":"pseudo"}
1078 }''')
1079 json.loads(js_to_json(inp))
1080
1081 inp = '''{
1082 'playlist':[{'controls':{'all':null}}]
1083 }'''
1084 self.assertEqual(js_to_json(inp), '''{
1085 "playlist":[{"controls":{"all":null}}]
1086 }''')
1087
1088 inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
1089 self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
1090
1091 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
1092 json_code = js_to_json(inp)
1093 self.assertEqual(json.loads(json_code), json.loads(inp))
1094
1095 inp = '''{
1096 0:{src:'skipped', type: 'application/dash+xml'},
1097 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
1098 }'''
1099 self.assertEqual(js_to_json(inp), '''{
1100 "0":{"src":"skipped", "type": "application/dash+xml"},
1101 "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
1102 }''')
1103
1104 inp = '''{"foo":101}'''
1105 self.assertEqual(js_to_json(inp), '''{"foo":101}''')
1106
1107 inp = '''{"duration": "00:01:07"}'''
1108 self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
1109
1110 inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
1111 self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
1112
1113 def test_js_to_json_edgecases(self):
1114 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
1115 self.assertEqual(json.loads(on), {'abc_def': "1'\\2\\'3\"4"})
1116
1117 on = js_to_json('{"abc": true}')
1118 self.assertEqual(json.loads(on), {'abc': True})
1119
1120 # Ignore JavaScript code as well
1121 on = js_to_json('''{
1122 "x": 1,
1123 y: "a",
1124 z: some.code
1125 }''')
1126 d = json.loads(on)
1127 self.assertEqual(d['x'], 1)
1128 self.assertEqual(d['y'], 'a')
1129
1130 # Just drop ! prefix for now though this results in a wrong value
1131 on = js_to_json('''{
1132 a: !0,
1133 b: !1,
1134 c: !!0,
1135 d: !!42.42,
1136 e: !!![],
1137 f: !"abc",
1138 g: !"",
1139 !42: 42
1140 }''')
1141 self.assertEqual(json.loads(on), {
1142 'a': 0,
1143 'b': 1,
1144 'c': 0,
1145 'd': 42.42,
1146 'e': [],
1147 'f': 'abc',
1148 'g': '',
1149 '42': 42,
1150 })
1151
1152 on = js_to_json('["abc", "def",]')
1153 self.assertEqual(json.loads(on), ['abc', 'def'])
1154
1155 on = js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
1156 self.assertEqual(json.loads(on), ['abc', 'def'])
1157
1158 on = js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
1159 self.assertEqual(json.loads(on), ['abc', 'def'])
1160
1161 on = js_to_json('{"abc": "def",}')
1162 self.assertEqual(json.loads(on), {'abc': 'def'})
1163
1164 on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
1165 self.assertEqual(json.loads(on), {'abc': 'def'})
1166
1167 on = js_to_json('{ 0: /* " \n */ ",]" , }')
1168 self.assertEqual(json.loads(on), {'0': ',]'})
1169
1170 on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
1171 self.assertEqual(json.loads(on), {'0': ',]'})
1172
1173 on = js_to_json('{ 0: // comment\n1 }')
1174 self.assertEqual(json.loads(on), {'0': 1})
1175
1176 on = js_to_json(r'["<p>x<\/p>"]')
1177 self.assertEqual(json.loads(on), ['<p>x</p>'])
1178
1179 on = js_to_json(r'["\xaa"]')
1180 self.assertEqual(json.loads(on), ['\u00aa'])
1181
1182 on = js_to_json("['a\\\nb']")
1183 self.assertEqual(json.loads(on), ['ab'])
1184
1185 on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
1186 self.assertEqual(json.loads(on), ['ab'])
1187
1188 on = js_to_json('{0xff:0xff}')
1189 self.assertEqual(json.loads(on), {'255': 255})
1190
1191 on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
1192 self.assertEqual(json.loads(on), {'255': 255})
1193
1194 on = js_to_json('{077:077}')
1195 self.assertEqual(json.loads(on), {'63': 63})
1196
1197 on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
1198 self.assertEqual(json.loads(on), {'63': 63})
1199
1200 on = js_to_json('{42:42}')
1201 self.assertEqual(json.loads(on), {'42': 42})
1202
1203 on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
1204 self.assertEqual(json.loads(on), {'42': 42})
1205
1206 on = js_to_json('{42:4.2e1}')
1207 self.assertEqual(json.loads(on), {'42': 42.0})
1208
1209 on = js_to_json('{ "0x40": "0x40" }')
1210 self.assertEqual(json.loads(on), {'0x40': '0x40'})
1211
1212 on = js_to_json('{ "040": "040" }')
1213 self.assertEqual(json.loads(on), {'040': '040'})
1214
1215 on = js_to_json('[1,//{},\n2]')
1216 self.assertEqual(json.loads(on), [1, 2])
1217
1218 on = js_to_json(R'"\^\$\#"')
1219 self.assertEqual(json.loads(on), R'^$#', msg='Unnecessary escapes should be stripped')
1220
1221 on = js_to_json('\'"\\""\'')
1222 self.assertEqual(json.loads(on), '"""', msg='Unnecessary quote escape should be escaped')
1223
1224 on = js_to_json('[new Date("spam"), \'("eggs")\']')
1225 self.assertEqual(json.loads(on), ['spam', '("eggs")'], msg='Date regex should match a single string')
1226
1227 def test_js_to_json_malformed(self):
1228 self.assertEqual(js_to_json('42a1'), '42"a1"')
1229 self.assertEqual(js_to_json('42a-1'), '42"a"-1')
1230
1231 def test_js_to_json_template_literal(self):
1232 self.assertEqual(js_to_json('`Hello ${name}`', {'name': '"world"'}), '"Hello world"')
1233 self.assertEqual(js_to_json('`${name}${name}`', {'name': '"X"'}), '"XX"')
1234 self.assertEqual(js_to_json('`${name}${name}`', {'name': '5'}), '"55"')
1235 self.assertEqual(js_to_json('`${name}"${name}"`', {'name': '5'}), '"5\\"5\\""')
1236 self.assertEqual(js_to_json('`${name}`', {}), '"name"')
1237
1238 def test_js_to_json_common_constructors(self):
1239 self.assertEqual(json.loads(js_to_json('new Map([["a", 5]])')), {'a': 5})
1240 self.assertEqual(json.loads(js_to_json('Array(5, 10)')), [5, 10])
1241 self.assertEqual(json.loads(js_to_json('new Array(15,5)')), [15, 5])
1242 self.assertEqual(json.loads(js_to_json('new Map([Array(5, 10),new Array(15,5)])')), {'5': 10, '15': 5})
1243 self.assertEqual(json.loads(js_to_json('new Date("123")')), '123')
1244 self.assertEqual(json.loads(js_to_json('new Date(\'2023-10-19\')')), '2023-10-19')
1245
1246 def test_extract_attributes(self):
1247 self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
1248 self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
1249 self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
1250 self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
1251 self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
1252 self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
1253 self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
1254 self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
1255 self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
1256 self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
1257 self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
1258 self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
1259 self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
1260 self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
1261 self.assertEqual(extract_attributes('<e x >'), {'x': None})
1262 self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
1263 self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
1264 self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
1265 self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
1266 self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
1267 self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
1268 self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
1269 self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
1270 self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
1271 self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
1272 self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
1273 self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
1274 self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
1275 # "Narrow" Python builds don't support unicode code points outside BMP.
1276 try:
1277 chr(0x10000)
1278 supports_outside_bmp = True
1279 except ValueError:
1280 supports_outside_bmp = False
1281 if supports_outside_bmp:
1282 self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
1283 # Malformed HTML should not break attributes extraction on older Python
1284 self.assertEqual(extract_attributes('<mal"formed/>'), {})
1285
1286 def test_clean_html(self):
1287 self.assertEqual(clean_html('a:\nb'), 'a: b')
1288 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
1289 self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
1290
1291 def test_intlist_to_bytes(self):
1292 self.assertEqual(
1293 intlist_to_bytes([0, 1, 127, 128, 255]),
1294 b'\x00\x01\x7f\x80\xff')
1295
1296 def test_args_to_str(self):
1297 self.assertEqual(
1298 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
1299 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""',
1300 )
1301
1302 def test_parse_filesize(self):
1303 self.assertEqual(parse_filesize(None), None)
1304 self.assertEqual(parse_filesize(''), None)
1305 self.assertEqual(parse_filesize('91 B'), 91)
1306 self.assertEqual(parse_filesize('foobar'), None)
1307 self.assertEqual(parse_filesize('2 MiB'), 2097152)
1308 self.assertEqual(parse_filesize('5 GB'), 5000000000)
1309 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
1310 self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
1311 self.assertEqual(parse_filesize('1,24 KB'), 1240)
1312 self.assertEqual(parse_filesize('1,24 kb'), 1240)
1313 self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
1314
1315 def test_parse_count(self):
1316 self.assertEqual(parse_count(None), None)
1317 self.assertEqual(parse_count(''), None)
1318 self.assertEqual(parse_count('0'), 0)
1319 self.assertEqual(parse_count('1000'), 1000)
1320 self.assertEqual(parse_count('1.000'), 1000)
1321 self.assertEqual(parse_count('1.1k'), 1100)
1322 self.assertEqual(parse_count('1.1 k'), 1100)
1323 self.assertEqual(parse_count('1,1 k'), 1100)
1324 self.assertEqual(parse_count('1.1kk'), 1100000)
1325 self.assertEqual(parse_count('1.1kk '), 1100000)
1326 self.assertEqual(parse_count('1,1kk'), 1100000)
1327 self.assertEqual(parse_count('100 views'), 100)
1328 self.assertEqual(parse_count('1,100 views'), 1100)
1329 self.assertEqual(parse_count('1.1kk views'), 1100000)
1330 self.assertEqual(parse_count('10M views'), 10000000)
1331 self.assertEqual(parse_count('has 10M views'), 10000000)
1332
1333 def test_parse_resolution(self):
1334 self.assertEqual(parse_resolution(None), {})
1335 self.assertEqual(parse_resolution(''), {})
1336 self.assertEqual(parse_resolution(' 1920x1080'), {'width': 1920, 'height': 1080})
1337 self.assertEqual(parse_resolution('1920×1080 '), {'width': 1920, 'height': 1080})
1338 self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
1339 self.assertEqual(parse_resolution('720p'), {'height': 720})
1340 self.assertEqual(parse_resolution('4k'), {'height': 2160})
1341 self.assertEqual(parse_resolution('8K'), {'height': 4320})
1342 self.assertEqual(parse_resolution('pre_1920x1080_post'), {'width': 1920, 'height': 1080})
1343 self.assertEqual(parse_resolution('ep1x2'), {})
1344 self.assertEqual(parse_resolution('1920, 1080'), {'width': 1920, 'height': 1080})
1345
1346 def test_parse_bitrate(self):
1347 self.assertEqual(parse_bitrate(None), None)
1348 self.assertEqual(parse_bitrate(''), None)
1349 self.assertEqual(parse_bitrate('300kbps'), 300)
1350 self.assertEqual(parse_bitrate('1500kbps'), 1500)
1351 self.assertEqual(parse_bitrate('300 kbps'), 300)
1352
1353 def test_version_tuple(self):
1354 self.assertEqual(version_tuple('1'), (1,))
1355 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
1356 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
1357
1358 def test_detect_exe_version(self):
1359 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
1360 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
1361 configuration: --prefix=/usr --extra-'''), '1.2.1')
1362 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
1363 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
1364 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
1365 Trying to open render node...
1366 Success at /dev/dri/renderD128.
1367 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
1368
1369 def test_age_restricted(self):
1370 self.assertFalse(age_restricted(None, 10)) # unrestricted content
1371 self.assertFalse(age_restricted(1, None)) # unrestricted policy
1372 self.assertFalse(age_restricted(8, 10))
1373 self.assertTrue(age_restricted(18, 14))
1374 self.assertFalse(age_restricted(18, 18))
1375
1376 def test_is_html(self):
1377 self.assertFalse(is_html(b'\x49\x44\x43<html'))
1378 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
1379 self.assertTrue(is_html( # UTF-8 with BOM
1380 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
1381 self.assertTrue(is_html( # UTF-16-LE
1382 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00',
1383 ))
1384 self.assertTrue(is_html( # UTF-16-BE
1385 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4',
1386 ))
1387 self.assertTrue(is_html( # UTF-32-BE
1388 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'))
1389 self.assertTrue(is_html( # UTF-32-LE
1390 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'))
1391
1392 def test_render_table(self):
1393 self.assertEqual(
1394 render_table(
1395 ['a', 'empty', 'bcd'],
1396 [[123, '', 4], [9999, '', 51]]),
1397 'a empty bcd\n'
1398 '123 4\n'
1399 '9999 51')
1400
1401 self.assertEqual(
1402 render_table(
1403 ['a', 'empty', 'bcd'],
1404 [[123, '', 4], [9999, '', 51]],
1405 hide_empty=True),
1406 'a bcd\n'
1407 '123 4\n'
1408 '9999 51')
1409
1410 self.assertEqual(
1411 render_table(
1412 ['\ta', 'bcd'],
1413 [['1\t23', 4], ['\t9999', 51]]),
1414 ' a bcd\n'
1415 '1 23 4\n'
1416 '9999 51')
1417
1418 self.assertEqual(
1419 render_table(
1420 ['a', 'bcd'],
1421 [[123, 4], [9999, 51]],
1422 delim='-'),
1423 'a bcd\n'
1424 '--------\n'
1425 '123 4\n'
1426 '9999 51')
1427
1428 self.assertEqual(
1429 render_table(
1430 ['a', 'bcd'],
1431 [[123, 4], [9999, 51]],
1432 delim='-', extra_gap=2),
1433 'a bcd\n'
1434 '----------\n'
1435 '123 4\n'
1436 '9999 51')
1437
1438 def test_match_str(self):
1439 # Unary
1440 self.assertFalse(match_str('xy', {'x': 1200}))
1441 self.assertTrue(match_str('!xy', {'x': 1200}))
1442 self.assertTrue(match_str('x', {'x': 1200}))
1443 self.assertFalse(match_str('!x', {'x': 1200}))
1444 self.assertTrue(match_str('x', {'x': 0}))
1445 self.assertTrue(match_str('is_live', {'is_live': True}))
1446 self.assertFalse(match_str('is_live', {'is_live': False}))
1447 self.assertFalse(match_str('is_live', {'is_live': None}))
1448 self.assertFalse(match_str('is_live', {}))
1449 self.assertFalse(match_str('!is_live', {'is_live': True}))
1450 self.assertTrue(match_str('!is_live', {'is_live': False}))
1451 self.assertTrue(match_str('!is_live', {'is_live': None}))
1452 self.assertTrue(match_str('!is_live', {}))
1453 self.assertTrue(match_str('title', {'title': 'abc'}))
1454 self.assertTrue(match_str('title', {'title': ''}))
1455 self.assertFalse(match_str('!title', {'title': 'abc'}))
1456 self.assertFalse(match_str('!title', {'title': ''}))
1457
1458 # Numeric
1459 self.assertFalse(match_str('x>0', {'x': 0}))
1460 self.assertFalse(match_str('x>0', {}))
1461 self.assertTrue(match_str('x>?0', {}))
1462 self.assertTrue(match_str('x>1K', {'x': 1200}))
1463 self.assertFalse(match_str('x>2K', {'x': 1200}))
1464 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
1465 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
1466 self.assertTrue(match_str('x > 1:0:0', {'x': 3700}))
1467
1468 # String
1469 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
1470 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
1471 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
1472 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
1473 self.assertTrue(match_str('y^=foo', {'y': 'foobar42'}))
1474 self.assertFalse(match_str('y!^=foo', {'y': 'foobar42'}))
1475 self.assertFalse(match_str('y^=bar', {'y': 'foobar42'}))
1476 self.assertTrue(match_str('y!^=bar', {'y': 'foobar42'}))
1477 self.assertRaises(ValueError, match_str, 'x^=42', {'x': 42})
1478 self.assertTrue(match_str('y*=bar', {'y': 'foobar42'}))
1479 self.assertFalse(match_str('y!*=bar', {'y': 'foobar42'}))
1480 self.assertFalse(match_str('y*=baz', {'y': 'foobar42'}))
1481 self.assertTrue(match_str('y!*=baz', {'y': 'foobar42'}))
1482 self.assertTrue(match_str('y$=42', {'y': 'foobar42'}))
1483 self.assertFalse(match_str('y$=43', {'y': 'foobar42'}))
1484
1485 # And
1486 self.assertFalse(match_str(
1487 'like_count > 100 & dislike_count <? 50 & description',
1488 {'like_count': 90, 'description': 'foo'}))
1489 self.assertTrue(match_str(
1490 'like_count > 100 & dislike_count <? 50 & description',
1491 {'like_count': 190, 'description': 'foo'}))
1492 self.assertFalse(match_str(
1493 'like_count > 100 & dislike_count <? 50 & description',
1494 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
1495 self.assertFalse(match_str(
1496 'like_count > 100 & dislike_count <? 50 & description',
1497 {'like_count': 190, 'dislike_count': 10}))
1498
1499 # Regex
1500 self.assertTrue(match_str(r'x~=\bbar', {'x': 'foo bar'}))
1501 self.assertFalse(match_str(r'x~=\bbar.+', {'x': 'foo bar'}))
1502 self.assertFalse(match_str(r'x~=^FOO', {'x': 'foo bar'}))
1503 self.assertTrue(match_str(r'x~=(?i)^FOO', {'x': 'foo bar'}))
1504
1505 # Quotes
1506 self.assertTrue(match_str(r'x^="foo"', {'x': 'foo "bar"'}))
1507 self.assertFalse(match_str(r'x^="foo "', {'x': 'foo "bar"'}))
1508 self.assertFalse(match_str(r'x$="bar"', {'x': 'foo "bar"'}))
1509 self.assertTrue(match_str(r'x$=" \"bar\""', {'x': 'foo "bar"'}))
1510
1511 # Escaping &
1512 self.assertFalse(match_str(r'x=foo & bar', {'x': 'foo & bar'}))
1513 self.assertTrue(match_str(r'x=foo \& bar', {'x': 'foo & bar'}))
1514 self.assertTrue(match_str(r'x=foo \& bar & x^=foo', {'x': 'foo & bar'}))
1515 self.assertTrue(match_str(r'x="foo \& bar" & x^=foo', {'x': 'foo & bar'}))
1516
1517 # Example from docs
1518 self.assertTrue(match_str(
1519 r"!is_live & like_count>?100 & description~='(?i)\bcats \& dogs\b'",
1520 {'description': 'Raining Cats & Dogs'}))
1521
1522 # Incomplete
1523 self.assertFalse(match_str('id!=foo', {'id': 'foo'}, True))
1524 self.assertTrue(match_str('x', {'id': 'foo'}, True))
1525 self.assertTrue(match_str('!x', {'id': 'foo'}, True))
1526 self.assertFalse(match_str('x', {'id': 'foo'}, False))
1527
1528 def test_parse_dfxp_time_expr(self):
1529 self.assertEqual(parse_dfxp_time_expr(None), None)
1530 self.assertEqual(parse_dfxp_time_expr(''), None)
1531 self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
1532 self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
1533 self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
1534 self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
1535 self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
1536
1537 def test_dfxp2srt(self):
1538 dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
1539 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1540 <body>
1541 <div xml:lang="en">
1542 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
1543 <p begin="1" end="2">第二行<br/>♪♪</p>
1544 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
1545 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
1546 <p begin="-1" end="-1">Ignore, two</p>
1547 <p begin="3" dur="-1">Ignored, three</p>
1548 </div>
1549 </body>
1550 </tt>'''.encode()
1551 srt_data = '''1
1552 00:00:00,000 --> 00:00:01,000
1553 The following line contains Chinese characters and special symbols
1554
1555 2
1556 00:00:01,000 --> 00:00:02,000
1557 第二行
1558 ♪♪
1559
1560 3
1561 00:00:02,000 --> 00:00:03,000
1562 Third
1563 Line
1564
1565 '''
1566 self.assertEqual(dfxp2srt(dfxp_data), srt_data)
1567
1568 dfxp_data_no_default_namespace = b'''<?xml version="1.0" encoding="UTF-8"?>
1569 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1570 <body>
1571 <div xml:lang="en">
1572 <p begin="0" end="1">The first line</p>
1573 </div>
1574 </body>
1575 </tt>'''
1576 srt_data = '''1
1577 00:00:00,000 --> 00:00:01,000
1578 The first line
1579
1580 '''
1581 self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
1582
1583 dfxp_data_with_style = b'''<?xml version="1.0" encoding="utf-8"?>
1584 <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">
1585 <head>
1586 <styling>
1587 <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
1588 <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
1589 <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
1590 <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
1591 </styling>
1592 </head>
1593 <body tts:textAlign="center" style="s0">
1594 <div>
1595 <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
1596 <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>
1597 <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
1598 <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>
1599 </div>
1600 </body>
1601 </tt>'''
1602 srt_data = '''1
1603 00:00:02,080 --> 00:00:05,840
1604 <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
1605
1606 2
1607 00:00:02,080 --> 00:00:05,840
1608 <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
1609 </font>part 2</font></b>
1610
1611 3
1612 00:00:05,840 --> 00:00:09,560
1613 <u><font color="lime">line 3
1614 part 3</font></u>
1615
1616 4
1617 00:00:09,560 --> 00:00:12,360
1618 <i><u><font color="yellow"><font color="lime">inner
1619 </font>style</font></u></i>
1620
1621 '''
1622 self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
1623
1624 dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
1625 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1626 <body>
1627 <div xml:lang="en">
1628 <p begin="0" end="1">Line 1</p>
1629 <p begin="1" end="2">第二行</p>
1630 </div>
1631 </body>
1632 </tt>'''.encode('utf-16')
1633 srt_data = '''1
1634 00:00:00,000 --> 00:00:01,000
1635 Line 1
1636
1637 2
1638 00:00:01,000 --> 00:00:02,000
1639 第二行
1640
1641 '''
1642 self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
1643
1644 def test_cli_option(self):
1645 self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
1646 self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
1647 self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
1648 self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
1649
1650 def test_cli_valueless_option(self):
1651 self.assertEqual(cli_valueless_option(
1652 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
1653 self.assertEqual(cli_valueless_option(
1654 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
1655 self.assertEqual(cli_valueless_option(
1656 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
1657 self.assertEqual(cli_valueless_option(
1658 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
1659 self.assertEqual(cli_valueless_option(
1660 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
1661 self.assertEqual(cli_valueless_option(
1662 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
1663
1664 def test_cli_bool_option(self):
1665 self.assertEqual(
1666 cli_bool_option(
1667 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
1668 ['--no-check-certificate', 'true'])
1669 self.assertEqual(
1670 cli_bool_option(
1671 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
1672 ['--no-check-certificate=true'])
1673 self.assertEqual(
1674 cli_bool_option(
1675 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1676 ['--check-certificate', 'false'])
1677 self.assertEqual(
1678 cli_bool_option(
1679 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1680 ['--check-certificate=false'])
1681 self.assertEqual(
1682 cli_bool_option(
1683 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1684 ['--check-certificate', 'true'])
1685 self.assertEqual(
1686 cli_bool_option(
1687 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1688 ['--check-certificate=true'])
1689 self.assertEqual(
1690 cli_bool_option(
1691 {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1692 [])
1693
1694 def test_ohdave_rsa_encrypt(self):
1695 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
1696 e = 65537
1697
1698 self.assertEqual(
1699 ohdave_rsa_encrypt(b'aa111222', e, N),
1700 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
1701
1702 def test_pkcs1pad(self):
1703 data = [1, 2, 3]
1704 padded_data = pkcs1pad(data, 32)
1705 self.assertEqual(padded_data[:2], [0, 2])
1706 self.assertEqual(padded_data[28:], [0, 1, 2, 3])
1707
1708 self.assertRaises(ValueError, pkcs1pad, data, 8)
1709
1710 def test_encode_base_n(self):
1711 self.assertEqual(encode_base_n(0, 30), '0')
1712 self.assertEqual(encode_base_n(80, 30), '2k')
1713
1714 custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
1715 self.assertEqual(encode_base_n(0, 30, custom_table), '9')
1716 self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
1717
1718 self.assertRaises(ValueError, encode_base_n, 0, 70)
1719 self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
1720
1721 def test_caesar(self):
1722 self.assertEqual(caesar('ace', 'abcdef', 2), 'cea')
1723 self.assertEqual(caesar('cea', 'abcdef', -2), 'ace')
1724 self.assertEqual(caesar('ace', 'abcdef', -2), 'eac')
1725 self.assertEqual(caesar('eac', 'abcdef', 2), 'ace')
1726 self.assertEqual(caesar('ace', 'abcdef', 0), 'ace')
1727 self.assertEqual(caesar('xyz', 'abcdef', 2), 'xyz')
1728 self.assertEqual(caesar('abc', 'acegik', 2), 'ebg')
1729 self.assertEqual(caesar('ebg', 'acegik', -2), 'abc')
1730
1731 def test_rot47(self):
1732 self.assertEqual(rot47('yt-dlp'), r'JE\5=A')
1733 self.assertEqual(rot47('YT-DLP'), r'*%\s{!')
1734
1735 def test_urshift(self):
1736 self.assertEqual(urshift(3, 1), 1)
1737 self.assertEqual(urshift(-3, 1), 2147483646)
1738
1739 GET_ELEMENT_BY_CLASS_TEST_STRING = '''
1740 <span class="foo bar">nice</span>
1741 '''
1742
1743 def test_get_element_by_class(self):
1744 html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
1745
1746 self.assertEqual(get_element_by_class('foo', html), 'nice')
1747 self.assertEqual(get_element_by_class('no-such-class', html), None)
1748
1749 def test_get_element_html_by_class(self):
1750 html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
1751
1752 self.assertEqual(get_element_html_by_class('foo', html), html.strip())
1753 self.assertEqual(get_element_by_class('no-such-class', html), None)
1754
1755 GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING = '''
1756 <div itemprop="author" itemscope>foo</div>
1757 '''
1758
1759 def test_get_element_by_attribute(self):
1760 html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
1761
1762 self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
1763 self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
1764 self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
1765
1766 html = self.GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING
1767
1768 self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
1769
1770 def test_get_element_html_by_attribute(self):
1771 html = self.GET_ELEMENT_BY_CLASS_TEST_STRING
1772
1773 self.assertEqual(get_element_html_by_attribute('class', 'foo bar', html), html.strip())
1774 self.assertEqual(get_element_html_by_attribute('class', 'foo', html), None)
1775 self.assertEqual(get_element_html_by_attribute('class', 'no-such-foo', html), None)
1776
1777 html = self.GET_ELEMENT_BY_ATTRIBUTE_TEST_STRING
1778
1779 self.assertEqual(get_element_html_by_attribute('itemprop', 'author', html), html.strip())
1780
1781 GET_ELEMENTS_BY_CLASS_TEST_STRING = '''
1782 <span class="foo bar">nice</span><span class="foo bar">also nice</span>
1783 '''
1784 GET_ELEMENTS_BY_CLASS_RES = ['<span class="foo bar">nice</span>', '<span class="foo bar">also nice</span>']
1785
1786 def test_get_elements_by_class(self):
1787 html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
1788
1789 self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
1790 self.assertEqual(get_elements_by_class('no-such-class', html), [])
1791
1792 def test_get_elements_html_by_class(self):
1793 html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
1794
1795 self.assertEqual(get_elements_html_by_class('foo', html), self.GET_ELEMENTS_BY_CLASS_RES)
1796 self.assertEqual(get_elements_html_by_class('no-such-class', html), [])
1797
1798 def test_get_elements_by_attribute(self):
1799 html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
1800
1801 self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
1802 self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
1803 self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
1804
1805 def test_get_elements_html_by_attribute(self):
1806 html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
1807
1808 self.assertEqual(get_elements_html_by_attribute('class', 'foo bar', html), self.GET_ELEMENTS_BY_CLASS_RES)
1809 self.assertEqual(get_elements_html_by_attribute('class', 'foo', html), [])
1810 self.assertEqual(get_elements_html_by_attribute('class', 'no-such-foo', html), [])
1811
1812 def test_get_elements_text_and_html_by_attribute(self):
1813 html = self.GET_ELEMENTS_BY_CLASS_TEST_STRING
1814
1815 self.assertEqual(
1816 list(get_elements_text_and_html_by_attribute('class', 'foo bar', html)),
1817 list(zip(['nice', 'also nice'], self.GET_ELEMENTS_BY_CLASS_RES)))
1818 self.assertEqual(list(get_elements_text_and_html_by_attribute('class', 'foo', html)), [])
1819 self.assertEqual(list(get_elements_text_and_html_by_attribute('class', 'no-such-foo', html)), [])
1820
1821 self.assertEqual(list(get_elements_text_and_html_by_attribute(
1822 'class', 'foo', '<a class="foo">nice</a><span class="foo">nice</span>', tag='a')), [('nice', '<a class="foo">nice</a>')])
1823
1824 GET_ELEMENT_BY_TAG_TEST_STRING = '''
1825 random text lorem ipsum</p>
1826 <div>
1827 this should be returned
1828 <span>this should also be returned</span>
1829 <div>
1830 this should also be returned
1831 </div>
1832 closing tag above should not trick, so this should also be returned
1833 </div>
1834 but this text should not be returned
1835 '''
1836 GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML = GET_ELEMENT_BY_TAG_TEST_STRING.strip()[32:276]
1837 GET_ELEMENT_BY_TAG_RES_OUTERDIV_TEXT = GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML[5:-6]
1838 GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML = GET_ELEMENT_BY_TAG_TEST_STRING.strip()[78:119]
1839 GET_ELEMENT_BY_TAG_RES_INNERSPAN_TEXT = GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML[6:-7]
1840
1841 def test_get_element_text_and_html_by_tag(self):
1842 html = self.GET_ELEMENT_BY_TAG_TEST_STRING
1843
1844 self.assertEqual(
1845 get_element_text_and_html_by_tag('div', html),
1846 (self.GET_ELEMENT_BY_TAG_RES_OUTERDIV_TEXT, self.GET_ELEMENT_BY_TAG_RES_OUTERDIV_HTML))
1847 self.assertEqual(
1848 get_element_text_and_html_by_tag('span', html),
1849 (self.GET_ELEMENT_BY_TAG_RES_INNERSPAN_TEXT, self.GET_ELEMENT_BY_TAG_RES_INNERSPAN_HTML))
1850 self.assertRaises(compat_HTMLParseError, get_element_text_and_html_by_tag, 'article', html)
1851
1852 def test_iri_to_uri(self):
1853 self.assertEqual(
1854 iri_to_uri('https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b'),
1855 'https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b') # Same
1856 self.assertEqual(
1857 iri_to_uri('https://www.google.com/search?q=Käsesoßenrührlöffel'), # German for cheese sauce stirring spoon
1858 'https://www.google.com/search?q=K%C3%A4seso%C3%9Fenr%C3%BChrl%C3%B6ffel')
1859 self.assertEqual(
1860 iri_to_uri('https://www.google.com/search?q=lt<+gt>+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#'),
1861 'https://www.google.com/search?q=lt%3C+gt%3E+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#')
1862 self.assertEqual(
1863 iri_to_uri('http://правозащита38.рф/category/news/'),
1864 'http://xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
1865 self.assertEqual(
1866 iri_to_uri('http://www.правозащита38.рф/category/news/'),
1867 'http://www.xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
1868 self.assertEqual(
1869 iri_to_uri('https://i❤.ws/emojidomain/👍👏🤝💪'),
1870 'https://xn--i-7iq.ws/emojidomain/%F0%9F%91%8D%F0%9F%91%8F%F0%9F%A4%9D%F0%9F%92%AA')
1871 self.assertEqual(
1872 iri_to_uri('http://日本語.jp/'),
1873 'http://xn--wgv71a119e.jp/')
1874 self.assertEqual(
1875 iri_to_uri('http://导航.中国/'),
1876 'http://xn--fet810g.xn--fiqs8s/')
1877
1878 def test_clean_podcast_url(self):
1879 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')
1880 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')
1881 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')
1882 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')
1883
1884 def test_LazyList(self):
1885 it = list(range(10))
1886
1887 self.assertEqual(list(LazyList(it)), it)
1888 self.assertEqual(LazyList(it).exhaust(), it)
1889 self.assertEqual(LazyList(it)[5], it[5])
1890
1891 self.assertEqual(LazyList(it)[5:], it[5:])
1892 self.assertEqual(LazyList(it)[:5], it[:5])
1893 self.assertEqual(LazyList(it)[::2], it[::2])
1894 self.assertEqual(LazyList(it)[1::2], it[1::2])
1895 self.assertEqual(LazyList(it)[5::-1], it[5::-1])
1896 self.assertEqual(LazyList(it)[6:2:-2], it[6:2:-2])
1897 self.assertEqual(LazyList(it)[::-1], it[::-1])
1898
1899 self.assertTrue(LazyList(it))
1900 self.assertFalse(LazyList(range(0)))
1901 self.assertEqual(len(LazyList(it)), len(it))
1902 self.assertEqual(repr(LazyList(it)), repr(it))
1903 self.assertEqual(str(LazyList(it)), str(it))
1904
1905 self.assertEqual(list(LazyList(it, reverse=True)), it[::-1])
1906 self.assertEqual(list(reversed(LazyList(it))[::-1]), it)
1907 self.assertEqual(list(reversed(LazyList(it))[1:3:7]), it[::-1][1:3:7])
1908
1909 def test_LazyList_laziness(self):
1910
1911 def test(ll, idx, val, cache):
1912 self.assertEqual(ll[idx], val)
1913 self.assertEqual(ll._cache, list(cache))
1914
1915 ll = LazyList(range(10))
1916 test(ll, 0, 0, range(1))
1917 test(ll, 5, 5, range(6))
1918 test(ll, -3, 7, range(10))
1919
1920 ll = LazyList(range(10), reverse=True)
1921 test(ll, -1, 0, range(1))
1922 test(ll, 3, 6, range(10))
1923
1924 ll = LazyList(itertools.count())
1925 test(ll, 10, 10, range(11))
1926 ll = reversed(ll)
1927 test(ll, -15, 14, range(15))
1928
1929 def test_format_bytes(self):
1930 self.assertEqual(format_bytes(0), '0.00B')
1931 self.assertEqual(format_bytes(1000), '1000.00B')
1932 self.assertEqual(format_bytes(1024), '1.00KiB')
1933 self.assertEqual(format_bytes(1024**2), '1.00MiB')
1934 self.assertEqual(format_bytes(1024**3), '1.00GiB')
1935 self.assertEqual(format_bytes(1024**4), '1.00TiB')
1936 self.assertEqual(format_bytes(1024**5), '1.00PiB')
1937 self.assertEqual(format_bytes(1024**6), '1.00EiB')
1938 self.assertEqual(format_bytes(1024**7), '1.00ZiB')
1939 self.assertEqual(format_bytes(1024**8), '1.00YiB')
1940 self.assertEqual(format_bytes(1024**9), '1024.00YiB')
1941
1942 def test_hide_login_info(self):
1943 self.assertEqual(Config.hide_login_info(['-u', 'foo', '-p', 'bar']),
1944 ['-u', 'PRIVATE', '-p', 'PRIVATE'])
1945 self.assertEqual(Config.hide_login_info(['-u']), ['-u'])
1946 self.assertEqual(Config.hide_login_info(['-u', 'foo', '-u', 'bar']),
1947 ['-u', 'PRIVATE', '-u', 'PRIVATE'])
1948 self.assertEqual(Config.hide_login_info(['--username=foo']),
1949 ['--username=PRIVATE'])
1950
1951 def test_locked_file(self):
1952 TEXT = 'test_locked_file\n'
1953 FILE = 'test_locked_file.ytdl'
1954 MODES = 'war' # Order is important
1955
1956 try:
1957 for lock_mode in MODES:
1958 with locked_file(FILE, lock_mode, False) as f:
1959 if lock_mode == 'r':
1960 self.assertEqual(f.read(), TEXT * 2, 'Wrong file content')
1961 else:
1962 f.write(TEXT)
1963 for test_mode in MODES:
1964 testing_write = test_mode != 'r'
1965 try:
1966 with locked_file(FILE, test_mode, False):
1967 pass
1968 except (BlockingIOError, PermissionError):
1969 if not testing_write: # FIXME: blocked read access
1970 print(f'Known issue: Exclusive lock ({lock_mode}) blocks read access ({test_mode})')
1971 continue
1972 self.assertTrue(testing_write, f'{test_mode} is blocked by {lock_mode}')
1973 else:
1974 self.assertFalse(testing_write, f'{test_mode} is not blocked by {lock_mode}')
1975 finally:
1976 with contextlib.suppress(OSError):
1977 os.remove(FILE)
1978
1979 def test_determine_file_encoding(self):
1980 self.assertEqual(determine_file_encoding(b''), (None, 0))
1981 self.assertEqual(determine_file_encoding(b'--verbose -x --audio-format mkv\n'), (None, 0))
1982
1983 self.assertEqual(determine_file_encoding(b'\xef\xbb\xbf'), ('utf-8', 3))
1984 self.assertEqual(determine_file_encoding(b'\x00\x00\xfe\xff'), ('utf-32-be', 4))
1985 self.assertEqual(determine_file_encoding(b'\xff\xfe'), ('utf-16-le', 2))
1986
1987 self.assertEqual(determine_file_encoding(b'\xff\xfe# coding: utf-8\n--verbose'), ('utf-16-le', 2))
1988
1989 self.assertEqual(determine_file_encoding(b'# coding: utf-8\n--verbose'), ('utf-8', 0))
1990 self.assertEqual(determine_file_encoding(b'# coding: someencodinghere-12345\n--verbose'), ('someencodinghere-12345', 0))
1991
1992 self.assertEqual(determine_file_encoding(b'#coding:utf-8\n--verbose'), ('utf-8', 0))
1993 self.assertEqual(determine_file_encoding(b'# coding: utf-8 \r\n--verbose'), ('utf-8', 0))
1994
1995 self.assertEqual(determine_file_encoding('# coding: utf-32-be'.encode('utf-32-be')), ('utf-32-be', 0))
1996 self.assertEqual(determine_file_encoding('# coding: utf-16-le'.encode('utf-16-le')), ('utf-16-le', 0))
1997
1998 def test_get_compatible_ext(self):
1999 self.assertEqual(get_compatible_ext(
2000 vcodecs=[None], acodecs=[None, None], vexts=['mp4'], aexts=['m4a', 'm4a']), 'mkv')
2001 self.assertEqual(get_compatible_ext(
2002 vcodecs=[None], acodecs=[None], vexts=['flv'], aexts=['flv']), 'flv')
2003
2004 self.assertEqual(get_compatible_ext(
2005 vcodecs=[None], acodecs=[None], vexts=['mp4'], aexts=['m4a']), 'mp4')
2006 self.assertEqual(get_compatible_ext(
2007 vcodecs=[None], acodecs=[None], vexts=['mp4'], aexts=['webm']), 'mkv')
2008 self.assertEqual(get_compatible_ext(
2009 vcodecs=[None], acodecs=[None], vexts=['webm'], aexts=['m4a']), 'mkv')
2010 self.assertEqual(get_compatible_ext(
2011 vcodecs=[None], acodecs=[None], vexts=['webm'], aexts=['webm']), 'webm')
2012 self.assertEqual(get_compatible_ext(
2013 vcodecs=[None], acodecs=[None], vexts=['webm'], aexts=['weba']), 'webm')
2014
2015 self.assertEqual(get_compatible_ext(
2016 vcodecs=['h264'], acodecs=['mp4a'], vexts=['mov'], aexts=['m4a']), 'mp4')
2017 self.assertEqual(get_compatible_ext(
2018 vcodecs=['av01.0.12M.08'], acodecs=['opus'], vexts=['mp4'], aexts=['webm']), 'webm')
2019
2020 self.assertEqual(get_compatible_ext(
2021 vcodecs=['vp9'], acodecs=['opus'], vexts=['webm'], aexts=['webm'], preferences=['flv', 'mp4']), 'mp4')
2022 self.assertEqual(get_compatible_ext(
2023 vcodecs=['av1'], acodecs=['mp4a'], vexts=['webm'], aexts=['m4a'], preferences=('webm', 'mkv')), 'mkv')
2024
2025 def test_try_call(self):
2026 def total(*x, **kwargs):
2027 return sum(x) + sum(kwargs.values())
2028
2029 self.assertEqual(try_call(None), None,
2030 msg='not a fn should give None')
2031 self.assertEqual(try_call(lambda: 1), 1,
2032 msg='int fn with no expected_type should give int')
2033 self.assertEqual(try_call(lambda: 1, expected_type=int), 1,
2034 msg='int fn with expected_type int should give int')
2035 self.assertEqual(try_call(lambda: 1, expected_type=dict), None,
2036 msg='int fn with wrong expected_type should give None')
2037 self.assertEqual(try_call(total, args=(0, 1, 0), expected_type=int), 1,
2038 msg='fn should accept arglist')
2039 self.assertEqual(try_call(total, kwargs={'a': 0, 'b': 1, 'c': 0}, expected_type=int), 1,
2040 msg='fn should accept kwargs')
2041 self.assertEqual(try_call(lambda: 1, expected_type=dict), None,
2042 msg='int fn with no expected_type should give None')
2043 self.assertEqual(try_call(lambda x: {}, total, args=(42, ), expected_type=int), 42,
2044 msg='expect first int result with expected_type int')
2045
2046 def test_variadic(self):
2047 self.assertEqual(variadic(None), (None, ))
2048 self.assertEqual(variadic('spam'), ('spam', ))
2049 self.assertEqual(variadic('spam', allowed_types=dict), 'spam')
2050 with warnings.catch_warnings():
2051 warnings.simplefilter('ignore')
2052 self.assertEqual(variadic('spam', allowed_types=[dict]), 'spam')
2053
2054 def test_http_header_dict(self):
2055 headers = HTTPHeaderDict()
2056 headers['ytdl-test'] = b'0'
2057 self.assertEqual(list(headers.items()), [('Ytdl-Test', '0')])
2058 headers['ytdl-test'] = 1
2059 self.assertEqual(list(headers.items()), [('Ytdl-Test', '1')])
2060 headers['Ytdl-test'] = '2'
2061 self.assertEqual(list(headers.items()), [('Ytdl-Test', '2')])
2062 self.assertTrue('ytDl-Test' in headers)
2063 self.assertEqual(str(headers), str(dict(headers)))
2064 self.assertEqual(repr(headers), str(dict(headers)))
2065
2066 headers.update({'X-dlp': 'data'})
2067 self.assertEqual(set(headers.items()), {('Ytdl-Test', '2'), ('X-Dlp', 'data')})
2068 self.assertEqual(dict(headers), {'Ytdl-Test': '2', 'X-Dlp': 'data'})
2069 self.assertEqual(len(headers), 2)
2070 self.assertEqual(headers.copy(), headers)
2071 headers2 = HTTPHeaderDict({'X-dlp': 'data3'}, **headers, **{'X-dlp': 'data2'})
2072 self.assertEqual(set(headers2.items()), {('Ytdl-Test', '2'), ('X-Dlp', 'data2')})
2073 self.assertEqual(len(headers2), 2)
2074 headers2.clear()
2075 self.assertEqual(len(headers2), 0)
2076
2077 # ensure we prefer latter headers
2078 headers3 = HTTPHeaderDict({'Ytdl-TeSt': 1}, {'Ytdl-test': 2})
2079 self.assertEqual(set(headers3.items()), {('Ytdl-Test', '2')})
2080 del headers3['ytdl-tesT']
2081 self.assertEqual(dict(headers3), {})
2082
2083 headers4 = HTTPHeaderDict({'ytdl-test': 'data;'})
2084 self.assertEqual(set(headers4.items()), {('Ytdl-Test', 'data;')})
2085
2086 # common mistake: strip whitespace from values
2087 # https://github.com/yt-dlp/yt-dlp/issues/8729
2088 headers5 = HTTPHeaderDict({'ytdl-test': ' data; '})
2089 self.assertEqual(set(headers5.items()), {('Ytdl-Test', 'data;')})
2090
2091 def test_extract_basic_auth(self):
2092 assert extract_basic_auth('http://:foo.bar') == ('http://:foo.bar', None)
2093 assert extract_basic_auth('http://foo.bar') == ('http://foo.bar', None)
2094 assert extract_basic_auth('http://@foo.bar') == ('http://foo.bar', 'Basic Og==')
2095 assert extract_basic_auth('http://:pass@foo.bar') == ('http://foo.bar', 'Basic OnBhc3M=')
2096 assert extract_basic_auth('http://user:@foo.bar') == ('http://foo.bar', 'Basic dXNlcjo=')
2097 assert extract_basic_auth('http://user:pass@foo.bar') == ('http://foo.bar', 'Basic dXNlcjpwYXNz')
2098
2099 @unittest.skipUnless(compat_os_name == 'nt', 'Only relevant on Windows')
2100 def test_windows_escaping(self):
2101 tests = [
2102 'test"&',
2103 '%CMDCMDLINE:~-1%&',
2104 'a\nb',
2105 '"',
2106 '\\',
2107 '!',
2108 '^!',
2109 'a \\ b',
2110 'a \\" b',
2111 'a \\ b\\',
2112 # We replace \r with \n
2113 ('a\r\ra', 'a\n\na'),
2114 ]
2115
2116 def run_shell(args):
2117 stdout, stderr, error = Popen.run(
2118 args, text=True, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
2119 assert not stderr
2120 assert not error
2121 return stdout
2122
2123 for argument in tests:
2124 if isinstance(argument, str):
2125 expected = argument
2126 else:
2127 argument, expected = argument
2128
2129 args = [sys.executable, '-c', 'import sys; print(end=sys.argv[1])', argument, 'end']
2130 assert run_shell(args) == expected
2131 assert run_shell(shell_quote(args, shell=True)) == expected
2132
2133
2134 if __name__ == '__main__':
2135 unittest.main()