]> jfr.im git - yt-dlp.git/blame - test/test_utils.py
[cleanup] Point all shebang to `python3` (#372)
[yt-dlp.git] / test / test_utils.py
CommitLineData
cc52de43 1#!/usr/bin/env python3
9d4660ca 2# coding: utf-8
e387eb5a 3
4e408e47
PH
4from __future__ import unicode_literals
5
44a5f171
PH
6# Allow direct execution
7import os
dae7c920 8import sys
44fb3454 9import unittest
44a5f171 10sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
44fb3454 11
44a5f171
PH
12
13# Various small unit tests
62e609ab 14import io
fac55558 15import json
44a5f171 16import xml.etree.ElementTree
dae7c920 17
7a5c1cfe 18from yt_dlp.utils import (
05900629 19 age_restricted,
cae97f65 20 args_to_str,
5eb6bdce 21 encode_base_n,
1ced2221 22 caesar,
e4bdb37e 23 clean_html,
00dd0cd5 24 clean_podcast_url,
eb9c3edd 25 date_from_str,
9e62f283 26 datetime_from_str,
a921f407 27 DateRange,
cae97f65 28 detect_exe_version,
5035536e 29 determine_ext,
cbecc9b9 30 dict_get,
6b77d52b 31 encode_compat_str,
29eb5174 32 encodeFilename,
cae97f65
PH
33 escape_rfc3986,
34 escape_url,
8bb56eee 35 extract_attributes,
5379a2d4 36 ExtractorError,
a921f407 37 find_xpath_attr,
5aafe895 38 fix_xml_ampersands,
5e1271c5 39 float_or_none,
84c237fb 40 get_element_by_class,
2af12ad9
TC
41 get_element_by_attribute,
42 get_elements_by_class,
43 get_elements_by_attribute,
9c44d242 44 InAdvancePagedList,
5e1271c5 45 int_or_none,
cae97f65 46 intlist_to_bytes,
61ca9a80 47 is_html,
cae97f65
PH
48 js_to_json,
49 limit_length,
6cc62232 50 merge_dicts,
6562d34a 51 mimetype2ext,
f6717dec 52 month_by_name,
0c265486 53 multipart_encode,
5bc880b9 54 ohdave_rsa_encrypt,
cae97f65
PH
55 OnDemandPagedList,
56 orderedSet,
a8795327 57 parse_age_limit,
608d11f5 58 parse_duration,
cae97f65 59 parse_filesize,
fb47597b 60 parse_count,
cae97f65 61 parse_iso8601,
b871d7e9 62 parse_resolution,
0dc41787 63 parse_bitrate,
f48409c7 64 pkcs1pad,
62e609ab 65 read_batch_urls,
29eb5174 66 sanitize_filename,
a2aaf4db 67 sanitize_path,
befa4708 68 sanitize_url,
5435dcf9 69 sanitized_Request,
51098426 70 expand_path,
a4bcaad7 71 prepend_extension,
b3ed15b7 72 replace_extension,
46bc9b7d
S
73 remove_start,
74 remove_end,
31b2051e 75 remove_quotes,
1ced2221 76 rot47,
a6a173c2 77 shell_quote,
29eb5174 78 smuggle_url,
f53c966a 79 str_to_int,
cae97f65 80 strip_jsonp,
53cd37ba 81 strip_or_none,
824fa511 82 subtitles_filename,
29eb5174
PH
83 timeconvert,
84 unescapeHTML,
85 unified_strdate,
46f59e89 86 unified_timestamp,
29eb5174 87 unsmuggle_url,
cae97f65 88 uppercase_escape,
0fe2ff78 89 lowercase_escape,
29eb5174 90 url_basename,
af03000a 91 url_or_none,
02dc0a36 92 base_url,
e34c3361 93 urljoin,
b74fa8cd 94 urlencode_postdata,
1143535d 95 urshift,
fb640d0a 96 update_url_query,
5f9b8394 97 version_tuple,
cae97f65 98 xpath_with_ns,
87f70ab3 99 xpath_element,
5379a2d4 100 xpath_text,
87f70ab3 101 xpath_attr,
cfb56d1a 102 render_table,
347de493 103 match_str,
bf6427d2
YCH
104 parse_dfxp_time_expr,
105 dfxp2srt,
f7126449
S
106 cli_option,
107 cli_valueless_option,
108 cli_bool_option,
4f3c5e06 109 parse_codecs,
732044af 110 iri_to_uri,
a921f407 111)
7a5c1cfe 112from yt_dlp.compat import (
8bb56eee 113 compat_chr,
36e6f62c 114 compat_etree_fromstring,
51098426 115 compat_getenv,
dee2ff1d 116 compat_os_name,
51098426 117 compat_setenv,
fb640d0a 118 compat_urlparse,
119 compat_parse_qs,
36e6f62c 120)
44fb3454 121
627dcfff 122
44fb3454 123class TestUtil(unittest.TestCase):
59ae15a5
PH
124 def test_timeconvert(self):
125 self.assertTrue(timeconvert('') is None)
126 self.assertTrue(timeconvert('bougrg') is None)
127
128 def test_sanitize_filename(self):
129 self.assertEqual(sanitize_filename('abc'), 'abc')
130 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
131
132 self.assertEqual(sanitize_filename('123'), '123')
133
134 self.assertEqual('abc_de', sanitize_filename('abc/de'))
135 self.assertFalse('/' in sanitize_filename('abc/de///'))
136
137 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
138 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
139 self.assertEqual('yes no', sanitize_filename('yes? no'))
140 self.assertEqual('this - that', sanitize_filename('this: that'))
141
142 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
4e408e47 143 aumlaut = 'ä'
59ae15a5 144 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
4e408e47 145 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
59ae15a5
PH
146 self.assertEqual(sanitize_filename(tests), tests)
147
2aeb06d6
PH
148 self.assertEqual(
149 sanitize_filename('New World record at 0:12:34'),
150 'New World record at 0_12_34')
a7440261 151
5a42414b
PH
152 self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
153 self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
a7440261
PH
154 self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
155 self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
2aeb06d6 156
59ae15a5
PH
157 forbidden = '"\0\\/'
158 for fc in forbidden:
159 for fbc in forbidden:
160 self.assertTrue(fbc not in sanitize_filename(fc))
161
162 def test_sanitize_filename_restricted(self):
163 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
164 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
165
166 self.assertEqual(sanitize_filename('123', restricted=True), '123')
167
168 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
169 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
170
171 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
172 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
173 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
174 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
175
79a2e94e
AT
176 tests = 'aäb\u4e2d\u56fd\u7684c'
177 self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
4e408e47 178 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
59ae15a5 179
627dcfff 180 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
59ae15a5
PH
181 for fc in forbidden:
182 for fbc in forbidden:
183 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
184
185 # Handle a common case more neatly
4e408e47
PH
186 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
187 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
59ae15a5
PH
188 # .. but make sure the file name is never empty
189 self.assertTrue(sanitize_filename('-', restricted=True) != '')
190 self.assertTrue(sanitize_filename(':', restricted=True) != '')
191
79a2e94e 192 self.assertEqual(sanitize_filename(
b96f007e 193 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
fd35d8cd 194 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYTHssaaaaaaaeceeeeiiiionooooooooeuuuuuythy')
79a2e94e 195
796173d0 196 def test_sanitize_ids(self):
314d506b
PH
197 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
198 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
199 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
796173d0 200
a2aaf4db
S
201 def test_sanitize_path(self):
202 if sys.platform != 'win32':
203 return
204
205 self.assertEqual(sanitize_path('abc'), 'abc')
206 self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
207 self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
208 self.assertEqual(sanitize_path('abc|def'), 'abc#def')
209 self.assertEqual(sanitize_path('<>:"|?*'), '#######')
210 self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
211 self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
212
213 self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
214 self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
215
216 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
217 self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
218 self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
219 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
220
f18ef2d1
S
221 self.assertEqual(
222 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
223 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
224
225 self.assertEqual(
226 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
227 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
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
2ebfeaca
S
232 self.assertEqual(sanitize_path('../abc'), '..\\abc')
233 self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
234 self.assertEqual(sanitize_path('./abc'), 'abc')
235 self.assertEqual(sanitize_path('./../abc'), '..\\abc')
236
befa4708
S
237 def test_sanitize_url(self):
238 self.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
239 self.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
240 self.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
241 self.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
bc6b9bcd 242 self.assertEqual(sanitize_url('foo bar'), 'foo bar')
befa4708 243
5435dcf9
HH
244 def test_extract_basic_auth(self):
245 auth_header = lambda url: sanitized_Request(url).get_header('Authorization')
246 self.assertFalse(auth_header('http://foo.bar'))
247 self.assertFalse(auth_header('http://:foo.bar'))
248 self.assertEqual(auth_header('http://@foo.bar'), 'Basic Og==')
249 self.assertEqual(auth_header('http://:pass@foo.bar'), 'Basic OnBhc3M=')
250 self.assertEqual(auth_header('http://user:@foo.bar'), 'Basic dXNlcjo=')
251 self.assertEqual(auth_header('http://user:pass@foo.bar'), 'Basic dXNlcjpwYXNz')
252
51098426 253 def test_expand_path(self):
41c5e60d
S
254 def env(var):
255 return '%{0}%'.format(var) if sys.platform == 'win32' else '${0}'.format(var)
256
7a5c1cfe
P
257 compat_setenv('yt_dlp_EXPATH_PATH', 'expanded')
258 self.assertEqual(expand_path(env('yt_dlp_EXPATH_PATH')), 'expanded')
a426ef6d 259 self.assertEqual(expand_path(env('HOME')), compat_getenv('HOME'))
51098426 260 self.assertEqual(expand_path('~'), compat_getenv('HOME'))
41c5e60d 261 self.assertEqual(
7a5c1cfe 262 expand_path('~/%s' % env('yt_dlp_EXPATH_PATH')),
41c5e60d 263 '%s/expanded' % compat_getenv('HOME'))
51098426 264
a4bcaad7
S
265 def test_prepend_extension(self):
266 self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
267 self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
268 self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
269 self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
270 self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
271 self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
272
b3ed15b7
S
273 def test_replace_extension(self):
274 self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
275 self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
276 self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
277 self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
278 self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
279 self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
280
824fa511
S
281 def test_subtitles_filename(self):
282 self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt'), 'abc.en.vtt')
283 self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt', 'ext'), 'abc.en.vtt')
284 self.assertEqual(subtitles_filename('abc.unexpected_ext', 'en', 'vtt', 'ext'), 'abc.unexpected_ext.en.vtt')
285
46bc9b7d
S
286 def test_remove_start(self):
287 self.assertEqual(remove_start(None, 'A - '), None)
288 self.assertEqual(remove_start('A - B', 'A - '), 'B')
289 self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
290
291 def test_remove_end(self):
292 self.assertEqual(remove_end(None, ' - B'), None)
293 self.assertEqual(remove_end('A - B', ' - B'), 'A')
294 self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
295
31b2051e
S
296 def test_remove_quotes(self):
297 self.assertEqual(remove_quotes(None), None)
298 self.assertEqual(remove_quotes('"'), '"')
299 self.assertEqual(remove_quotes("'"), "'")
300 self.assertEqual(remove_quotes(';'), ';')
301 self.assertEqual(remove_quotes('";'), '";')
302 self.assertEqual(remove_quotes('""'), '')
303 self.assertEqual(remove_quotes('";"'), ';')
304
59ae15a5 305 def test_ordered_set(self):
627dcfff 306 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
59ae15a5
PH
307 self.assertEqual(orderedSet([]), [])
308 self.assertEqual(orderedSet([1]), [1])
5f6a1245 309 # keep the list ordered
627dcfff 310 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
59ae15a5
PH
311
312 def test_unescape_html(self):
4e408e47 313 self.assertEqual(unescapeHTML('%20;'), '%20;')
91757b0f
NJ
314 self.assertEqual(unescapeHTML('&#x2F;'), '/')
315 self.assertEqual(unescapeHTML('&#47;'), '/')
7aefc49c
S
316 self.assertEqual(unescapeHTML('&eacute;'), 'é')
317 self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
95f3f7c2 318 self.assertEqual(unescapeHTML('&a&quot;'), '&a"')
55b2f099
YCH
319 # HTML5 entities
320 self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
5f6a1245 321
eb9c3edd
JMF
322 def test_date_from_str(self):
323 self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
324 self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
325 self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
9e62f283 326 self.assertEqual(date_from_str('20200229+365day'), date_from_str('20200229+1year'))
327 self.assertEqual(date_from_str('20210131+28day'), date_from_str('20210131+1month'))
328
329 def test_datetime_from_str(self):
330 self.assertEqual(datetime_from_str('yesterday', precision='day'), datetime_from_str('now-1day', precision='auto'))
331 self.assertEqual(datetime_from_str('now+7day', precision='day'), datetime_from_str('now+1week', precision='auto'))
332 self.assertEqual(datetime_from_str('now+14day', precision='day'), datetime_from_str('now+2week', precision='auto'))
333 self.assertEqual(datetime_from_str('20200229+365day', precision='day'), datetime_from_str('20200229+1year', precision='auto'))
334 self.assertEqual(datetime_from_str('20210131+28day', precision='day'), datetime_from_str('20210131+1month', precision='auto'))
335 self.assertEqual(datetime_from_str('20210131+59day', precision='day'), datetime_from_str('20210131+2month', precision='auto'))
336 self.assertEqual(datetime_from_str('now+1day', precision='hour'), datetime_from_str('now+24hours', precision='auto'))
337 self.assertEqual(datetime_from_str('now+23hours', precision='hour'), datetime_from_str('now+23hours', precision='auto'))
eb9c3edd 338
bd558525 339 def test_daterange(self):
5f6a1245 340 _20century = DateRange("19000101", "20000101")
bd558525
JMF
341 self.assertFalse("17890714" in _20century)
342 _ac = DateRange("00010101")
343 self.assertTrue("19690721" in _ac)
344 _firstmilenium = DateRange(end="10000101")
345 self.assertTrue("07110427" in _firstmilenium)
37254abc 346
bf50b038
JMF
347 def test_unified_dates(self):
348 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
349 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
350 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
351 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
a69801e2 352 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
026fcc04 353 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
99b67fec 354 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
42bdd9d0
PH
355 self.assertEqual(
356 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
357 '20141126')
9bb8e0a3
PH
358 self.assertEqual(
359 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
360 '20150202')
f160785c 361 self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
8cf70de4 362 self.assertEqual(unified_strdate('25-09-2014'), '20140925')
46f59e89 363 self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
6a750402 364 self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
c6eed6b8 365 self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
cb655f34
S
366 self.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
367 self.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
368 self.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
9d30c213
I
369 self.assertEqual(unified_strdate('November 3rd, 2019'), '20191103')
370 self.assertEqual(unified_strdate('October 23rd, 2005'), '20051023')
dae7c920 371
46f59e89
S
372 def test_unified_timestamps(self):
373 self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
374 self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
375 self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
376 self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
377 self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
378 self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
379 self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
380 self.assertEqual(
381 unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
382 1417001400)
383 self.assertEqual(
384 unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
385 1422902860)
386 self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
387 self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
388 self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
389 self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
7dc2a74e 390 self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
c6eed6b8 391 self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
deef3195 392 self.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
2ae2ffda 393 self.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
b555ae9b 394 self.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
f226880c 395 self.assertEqual(unified_timestamp('2018-03-14T08:32:43.1493874+00:00'), 1521016363)
46f59e89 396
5035536e
S
397 def test_determine_ext(self):
398 self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
399 self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
9cb9a5df
S
400 self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
401 self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
402 self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
85750f89 403 self.assertEqual(determine_ext('foobar', None), None)
5035536e 404
59ae56fa 405 def test_find_xpath_attr(self):
4e408e47 406 testxml = '''<root>
59ae56fa
PH
407 <node/>
408 <node x="a"/>
409 <node x="a" y="c" />
410 <node x="b" y="d" />
ee114368 411 <node x="" />
59ae56fa 412 </root>'''
36e6f62c 413 doc = compat_etree_fromstring(testxml)
59ae56fa 414
ee114368 415 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
59ae56fa 416 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
ee114368
S
417 self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
418 self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
419 self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
59ae56fa 420 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
ee114368
S
421 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
422 self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
59ae56fa 423 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
ee114368
S
424 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
425 self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
59ae56fa 426
d7e66d39 427 def test_xpath_with_ns(self):
4e408e47 428 testxml = '''<root xmlns:media="http://example.com/">
d7e66d39
JMF
429 <media:song>
430 <media:author>The Author</media:author>
431 <url>http://server.com/download.mp3</url>
432 </media:song>
433 </root>'''
36e6f62c 434 doc = compat_etree_fromstring(testxml)
d7e66d39
JMF
435 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
436 self.assertTrue(find('media:song') is not None)
4e408e47
PH
437 self.assertEqual(find('media:song/media:author').text, 'The Author')
438 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
d7e66d39 439
87f70ab3
S
440 def test_xpath_element(self):
441 doc = xml.etree.ElementTree.Element('root')
442 div = xml.etree.ElementTree.SubElement(doc, 'div')
443 p = xml.etree.ElementTree.SubElement(div, 'p')
444 p.text = 'Foo'
445 self.assertEqual(xpath_element(doc, 'div/p'), p)
578c0745
S
446 self.assertEqual(xpath_element(doc, ['div/p']), p)
447 self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
87f70ab3 448 self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
578c0745 449 self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
87f70ab3 450 self.assertTrue(xpath_element(doc, 'div/bar') is None)
578c0745
S
451 self.assertTrue(xpath_element(doc, ['div/bar']) is None)
452 self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
87f70ab3 453 self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
578c0745
S
454 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
455 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
87f70ab3 456
5379a2d4
JMF
457 def test_xpath_text(self):
458 testxml = '''<root>
459 <div>
460 <p>Foo</p>
461 </div>
462 </root>'''
36e6f62c 463 doc = compat_etree_fromstring(testxml)
5379a2d4 464 self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
87f70ab3 465 self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
5379a2d4
JMF
466 self.assertTrue(xpath_text(doc, 'div/bar') is None)
467 self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
468
87f70ab3
S
469 def test_xpath_attr(self):
470 testxml = '''<root>
471 <div>
472 <p x="a">Foo</p>
473 </div>
474 </root>'''
36e6f62c 475 doc = compat_etree_fromstring(testxml)
87f70ab3
S
476 self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
477 self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
478 self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
479 self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
480 self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
481 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
482 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
483
9d4660ca 484 def test_smuggle_url(self):
e075a44a 485 data = {"ö": "ö", "abc": [3]}
9d4660ca
PH
486 url = 'https://foo.bar/baz?x=y#a'
487 smug_url = smuggle_url(url, data)
488 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
489 self.assertEqual(url, unsmug_url)
490 self.assertEqual(data, unsmug_data)
491
492 res_url, res_data = unsmuggle_url(url)
493 self.assertEqual(res_url, url)
494 self.assertEqual(res_data, None)
495
dfaa86b7
RA
496 smug_url = smuggle_url(url, {'a': 'b'})
497 smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
498 res_url, res_data = unsmuggle_url(smug_smug_url)
499 self.assertEqual(res_url, url)
500 self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
501
a6a173c2 502 def test_shell_quote(self):
4e408e47 503 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
dee2ff1d
S
504 self.assertEqual(
505 shell_quote(args),
506 """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
a6a173c2 507
5e1271c5
S
508 def test_float_or_none(self):
509 self.assertEqual(float_or_none('42.42'), 42.42)
510 self.assertEqual(float_or_none('42'), 42.0)
511 self.assertEqual(float_or_none(''), None)
512 self.assertEqual(float_or_none(None), None)
513 self.assertEqual(float_or_none([]), None)
514 self.assertEqual(float_or_none(set()), None)
515
516 def test_int_or_none(self):
517 self.assertEqual(int_or_none('42'), 42)
518 self.assertEqual(int_or_none(''), None)
519 self.assertEqual(int_or_none(None), None)
520 self.assertEqual(int_or_none([]), None)
521 self.assertEqual(int_or_none(set()), None)
522
f53c966a
JMF
523 def test_str_to_int(self):
524 self.assertEqual(str_to_int('123,456'), 123456)
525 self.assertEqual(str_to_int('123.456'), 123456)
348c6bf1 526 self.assertEqual(str_to_int(523), 523)
42db58ec
S
527 # Python 3 has no long
528 if sys.version_info < (3, 0):
529 eval('self.assertEqual(str_to_int(123456L), 123456)')
530 self.assertEqual(str_to_int('noninteger'), None)
531 self.assertEqual(str_to_int([]), None)
f53c966a 532
29eb5174 533 def test_url_basename(self):
4e408e47
PH
534 self.assertEqual(url_basename('http://foo.de/'), '')
535 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
536 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
537 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
538 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
d6c7a367 539 self.assertEqual(
4e408e47
PH
540 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
541 'trailer.mp4')
9d4660ca 542
02dc0a36
S
543 def test_base_url(self):
544 self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
545 self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
546 self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
547 self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
548 self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
549
e34c3361
S
550 def test_urljoin(self):
551 self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
4b5de77b
S
552 self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
553 self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
554 self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
b0c65c67 555 self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//foo.de/a/b/c.txt')
e34c3361
S
556 self.assertEqual(urljoin('http://foo.de/', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
557 self.assertEqual(urljoin('http://foo.de', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
558 self.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
559 self.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
b0c65c67 560 self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
e34c3361 561 self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
b0c65c67 562 self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
e34c3361
S
563 self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
564 self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
565 self.assertEqual(urljoin('http://foo.de/', None), None)
566 self.assertEqual(urljoin('http://foo.de/', ''), None)
567 self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
7fe15920 568 self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
fad4ceb5
S
569 self.assertEqual(urljoin('http://foo.de/a/b/c.txt', 'rtmp://foo.de'), 'rtmp://foo.de')
570 self.assertEqual(urljoin(None, 'rtmp://foo.de'), 'rtmp://foo.de')
e34c3361 571
af03000a
S
572 def test_url_or_none(self):
573 self.assertEqual(url_or_none(None), None)
574 self.assertEqual(url_or_none(''), None)
575 self.assertEqual(url_or_none('foo'), None)
576 self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
577 self.assertEqual(url_or_none('https://foo.de'), 'https://foo.de')
578 self.assertEqual(url_or_none('http$://foo.de'), None)
579 self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
580 self.assertEqual(url_or_none('//foo.de'), '//foo.de')
29f7c58a 581 self.assertEqual(url_or_none('s3://foo.de'), None)
582 self.assertEqual(url_or_none('rtmpte://foo.de'), 'rtmpte://foo.de')
583 self.assertEqual(url_or_none('mms://foo.de'), 'mms://foo.de')
584 self.assertEqual(url_or_none('rtspu://foo.de'), 'rtspu://foo.de')
585 self.assertEqual(url_or_none('ftps://foo.de'), 'ftps://foo.de')
af03000a 586
a8795327
S
587 def test_parse_age_limit(self):
588 self.assertEqual(parse_age_limit(None), None)
589 self.assertEqual(parse_age_limit(False), None)
590 self.assertEqual(parse_age_limit('invalid'), None)
591 self.assertEqual(parse_age_limit(0), 0)
592 self.assertEqual(parse_age_limit(18), 18)
593 self.assertEqual(parse_age_limit(21), 21)
594 self.assertEqual(parse_age_limit(22), None)
595 self.assertEqual(parse_age_limit('18'), 18)
596 self.assertEqual(parse_age_limit('18+'), 18)
597 self.assertEqual(parse_age_limit('PG-13'), 13)
598 self.assertEqual(parse_age_limit('TV-14'), 14)
599 self.assertEqual(parse_age_limit('TV-MA'), 17)
3bb3ff38
RA
600 self.assertEqual(parse_age_limit('TV14'), 14)
601 self.assertEqual(parse_age_limit('TV_G'), 0)
a8795327 602
608d11f5
PH
603 def test_parse_duration(self):
604 self.assertEqual(parse_duration(None), None)
a5fb718c
S
605 self.assertEqual(parse_duration(False), None)
606 self.assertEqual(parse_duration('invalid'), None)
608d11f5
PH
607 self.assertEqual(parse_duration('1'), 1)
608 self.assertEqual(parse_duration('1337:12'), 80232)
609 self.assertEqual(parse_duration('9:12:43'), 33163)
2db806b4
S
610 self.assertEqual(parse_duration('12:00'), 720)
611 self.assertEqual(parse_duration('00:01:01'), 61)
608d11f5 612 self.assertEqual(parse_duration('x:y'), None)
2db806b4 613 self.assertEqual(parse_duration('3h11m53s'), 11513)
ca7b3246
S
614 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
615 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
616 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
2db806b4
S
617 self.assertEqual(parse_duration('62m45s'), 3765)
618 self.assertEqual(parse_duration('6m59s'), 419)
619 self.assertEqual(parse_duration('49s'), 49)
620 self.assertEqual(parse_duration('0h0m0s'), 0)
621 self.assertEqual(parse_duration('0m0s'), 0)
622 self.assertEqual(parse_duration('0s'), 0)
7adcbe75 623 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
6a68bb57 624 self.assertEqual(parse_duration('T30M38S'), 1838)
e8df5cee
PH
625 self.assertEqual(parse_duration('5 s'), 5)
626 self.assertEqual(parse_duration('3 min'), 180)
627 self.assertEqual(parse_duration('2.5 hours'), 9000)
8f4b58d7
PH
628 self.assertEqual(parse_duration('02:03:04'), 7384)
629 self.assertEqual(parse_duration('01:02:03:04'), 93784)
3e675fab 630 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
9c29bc69 631 self.assertEqual(parse_duration('87 Min.'), 5220)
acaff495 632 self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
15846398 633 self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
056653bb 634 self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
608d11f5 635
5aafe895
PH
636 def test_fix_xml_ampersands(self):
637 self.assertEqual(
638 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
639 self.assertEqual(
640 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
641 '"&amp;x=y&amp;wrong;&amp;z=a')
642 self.assertEqual(
643 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
644 '&amp;&apos;&gt;&lt;&quot;')
645 self.assertEqual(
646 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
647 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
648
b7ab0590
PH
649 def test_paged_list(self):
650 def testPL(size, pagesize, sliceargs, expected):
651 def get_page(pagenum):
652 firstid = pagenum * pagesize
653 upto = min(size, pagenum * pagesize + pagesize)
654 for i in range(firstid, upto):
655 yield i
656
9c44d242 657 pl = OnDemandPagedList(get_page, pagesize)
b7ab0590
PH
658 got = pl.getslice(*sliceargs)
659 self.assertEqual(got, expected)
660
9c44d242
PH
661 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
662 got = iapl.getslice(*sliceargs)
663 self.assertEqual(got, expected)
664
b7ab0590
PH
665 testPL(5, 2, (), [0, 1, 2, 3, 4])
666 testPL(5, 2, (1,), [1, 2, 3, 4])
667 testPL(5, 2, (2,), [2, 3, 4])
668 testPL(5, 2, (4,), [4])
669 testPL(5, 2, (0, 3), [0, 1, 2])
670 testPL(5, 2, (1, 4), [1, 2, 3])
671 testPL(5, 2, (2, 99), [2, 3, 4])
672 testPL(5, 2, (20, 99), [])
673
62e609ab 674 def test_read_batch_urls(self):
4e408e47 675 f = io.StringIO('''\xef\xbb\xbf foo
62e609ab
PH
676 bar\r
677 baz
678 # More after this line\r
679 ; or after this
680 bam''')
4e408e47 681 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
62e609ab 682
b74fa8cd
JMF
683 def test_urlencode_postdata(self):
684 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
685 self.assertTrue(isinstance(data, bytes))
686
fb640d0a 687 def test_update_url_query(self):
688 def query_dict(url):
689 return compat_parse_qs(compat_urlparse.urlparse(url).query)
690 self.assertEqual(query_dict(update_url_query(
691 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
692 query_dict('http://example.com/path?quality=HD&format=mp4'))
693 self.assertEqual(query_dict(update_url_query(
694 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
695 query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
696 self.assertEqual(query_dict(update_url_query(
697 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
698 query_dict('http://example.com/path?fields=id,formats,subtitles'))
699 self.assertEqual(query_dict(update_url_query(
700 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
701 query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
702 self.assertEqual(query_dict(update_url_query(
703 'http://example.com/path?manifest=f4m', {'manifest': []})),
704 query_dict('http://example.com/path'))
705 self.assertEqual(query_dict(update_url_query(
706 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
707 query_dict('http://example.com/path?system=LINUX'))
708 self.assertEqual(query_dict(update_url_query(
709 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
710 query_dict('http://example.com/path?fields=id,formats,subtitles'))
3201a67f 711 self.assertEqual(query_dict(update_url_query(
712 'http://example.com/path', {'width': 1080, 'height': 720})),
713 query_dict('http://example.com/path?width=1080&height=720'))
714 self.assertEqual(query_dict(update_url_query(
715 'http://example.com/path', {'bitrate': 5020.43})),
716 query_dict('http://example.com/path?bitrate=5020.43'))
717 self.assertEqual(query_dict(update_url_query(
718 'http://example.com/path', {'test': '第二行тест'})),
719 query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
fb640d0a 720
0c265486
YCH
721 def test_multipart_encode(self):
722 self.assertEqual(
723 multipart_encode({b'field': b'value'}, boundary='AAAAAA')[0],
724 b'--AAAAAA\r\nContent-Disposition: form-data; name="field"\r\n\r\nvalue\r\n--AAAAAA--\r\n')
725 self.assertEqual(
726 multipart_encode({'欄位'.encode('utf-8'): '值'.encode('utf-8')}, boundary='AAAAAA')[0],
727 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')
728 self.assertRaises(
729 ValueError, multipart_encode, {b'field': b'value'}, boundary='value')
730
cbecc9b9 731 def test_dict_get(self):
86296ad2
S
732 FALSE_VALUES = {
733 'none': None,
734 'false': False,
735 'zero': 0,
736 'empty_string': '',
737 'empty_list': [],
cbecc9b9 738 }
86296ad2
S
739 d = FALSE_VALUES.copy()
740 d['a'] = 42
cbecc9b9
S
741 self.assertEqual(dict_get(d, 'a'), 42)
742 self.assertEqual(dict_get(d, 'b'), None)
743 self.assertEqual(dict_get(d, 'b', 42), 42)
744 self.assertEqual(dict_get(d, ('a', )), 42)
745 self.assertEqual(dict_get(d, ('b', 'a', )), 42)
746 self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
747 self.assertEqual(dict_get(d, ('b', 'c', )), None)
748 self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
86296ad2
S
749 for key, false_value in FALSE_VALUES.items():
750 self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
751 self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
cbecc9b9 752
6cc62232
S
753 def test_merge_dicts(self):
754 self.assertEqual(merge_dicts({'a': 1}, {'b': 2}), {'a': 1, 'b': 2})
755 self.assertEqual(merge_dicts({'a': 1}, {'a': 2}), {'a': 1})
756 self.assertEqual(merge_dicts({'a': 1}, {'a': None}), {'a': 1})
757 self.assertEqual(merge_dicts({'a': 1}, {'a': ''}), {'a': 1})
758 self.assertEqual(merge_dicts({'a': 1}, {}), {'a': 1})
759 self.assertEqual(merge_dicts({'a': None}, {'a': 1}), {'a': 1})
760 self.assertEqual(merge_dicts({'a': ''}, {'a': 1}), {'a': ''})
761 self.assertEqual(merge_dicts({'a': ''}, {'a': 'abc'}), {'a': 'abc'})
762 self.assertEqual(merge_dicts({'a': None}, {'a': ''}, {'a': 'abc'}), {'a': 'abc'})
763
6b77d52b
S
764 def test_encode_compat_str(self):
765 self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
766 self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
767
912b38b4
PH
768 def test_parse_iso8601(self):
769 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
770 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
771 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
6ad4013d 772 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
52c3a6e4
S
773 self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
774 self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
912b38b4 775
fac55558
PH
776 def test_strip_jsonp(self):
777 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
778 d = json.loads(stripped)
779 self.assertEqual(d, [{"id": "532cb", "x": 3}])
780
609a61e3
PH
781 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
782 d = json.loads(stripped)
783 self.assertEqual(d, {'STATUS': 'OK'})
784
8411229b
S
785 stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
786 d = json.loads(stripped)
787 self.assertEqual(d, {'status': 'success'})
788
5552c9eb
YCH
789 stripped = strip_jsonp('window.cb && window.cb({"status": "success"});')
790 d = json.loads(stripped)
791 self.assertEqual(d, {'status': 'success'})
792
793 stripped = strip_jsonp('window.cb && cb({"status": "success"});')
794 d = json.loads(stripped)
795 self.assertEqual(d, {'status': 'success'})
e9c671d5
S
796
797 stripped = strip_jsonp('({"status": "success"});')
798 d = json.loads(stripped)
799 self.assertEqual(d, {'status': 'success'})
5552c9eb 800
53cd37ba
S
801 def test_strip_or_none(self):
802 self.assertEqual(strip_or_none(' abc'), 'abc')
803 self.assertEqual(strip_or_none('abc '), 'abc')
804 self.assertEqual(strip_or_none(' abc '), 'abc')
805 self.assertEqual(strip_or_none('\tabc\t'), 'abc')
806 self.assertEqual(strip_or_none('\n\tabc\n\t'), 'abc')
807 self.assertEqual(strip_or_none('abc'), 'abc')
808 self.assertEqual(strip_or_none(''), '')
809 self.assertEqual(strip_or_none(None), None)
810 self.assertEqual(strip_or_none(42), None)
811 self.assertEqual(strip_or_none([]), None)
812
173a7026 813 def test_uppercase_escape(self):
4e408e47
PH
814 self.assertEqual(uppercase_escape('aä'), 'aä')
815 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
fac55558 816
0fe2ff78
YCH
817 def test_lowercase_escape(self):
818 self.assertEqual(lowercase_escape('aä'), 'aä')
819 self.assertEqual(lowercase_escape('\\u0026'), '&')
820
a020a0dc
PH
821 def test_limit_length(self):
822 self.assertEqual(limit_length(None, 12), None)
823 self.assertEqual(limit_length('foo', 12), 'foo')
824 self.assertTrue(
825 limit_length('foo bar baz asd', 12).startswith('foo bar'))
826 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
827
6562d34a
S
828 def test_mimetype2ext(self):
829 self.assertEqual(mimetype2ext(None), None)
830 self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
831 self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
832 self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
833 self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
834 self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
39e7107d
U
835 self.assertEqual(mimetype2ext('audio/x-wav'), 'wav')
836 self.assertEqual(mimetype2ext('audio/x-wav;codec=pcm'), 'wav')
6562d34a 837
f6717dec
S
838 def test_month_by_name(self):
839 self.assertEqual(month_by_name(None), None)
840 self.assertEqual(month_by_name('December', 'en'), 12)
3e4185c3 841 self.assertEqual(month_by_name('décembre', 'fr'), 12)
f6717dec 842 self.assertEqual(month_by_name('December'), 12)
3e4185c3 843 self.assertEqual(month_by_name('décembre'), None)
f6717dec
S
844 self.assertEqual(month_by_name('Unknown', 'unknown'), None)
845
4f3c5e06 846 def test_parse_codecs(self):
847 self.assertEqual(parse_codecs(''), {})
848 self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
849 'vcodec': 'avc1.77.30',
850 'acodec': 'mp4a.40.2',
851 })
852 self.assertEqual(parse_codecs('mp4a.40.2'), {
853 'vcodec': 'none',
854 'acodec': 'mp4a.40.2',
855 })
856 self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
857 'vcodec': 'avc1.42001e',
858 'acodec': 'mp4a.40.5',
859 })
860 self.assertEqual(parse_codecs('avc3.640028'), {
861 'vcodec': 'avc3.640028',
862 'acodec': 'none',
863 })
864 self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
865 'vcodec': 'h264',
866 'acodec': 'aac',
867 })
25d110be
S
868 self.assertEqual(parse_codecs('av01.0.05M.08'), {
869 'vcodec': 'av01.0.05M.08',
870 'acodec': 'none',
871 })
28cc2241
S
872 self.assertEqual(parse_codecs('theora, vorbis'), {
873 'vcodec': 'theora',
874 'acodec': 'vorbis',
875 })
876 self.assertEqual(parse_codecs('unknownvcodec, unknownacodec'), {
877 'vcodec': 'unknownvcodec',
878 'acodec': 'unknownacodec',
879 })
880 self.assertEqual(parse_codecs('unknown'), {})
4f3c5e06 881
d05cfe06
S
882 def test_escape_rfc3986(self):
883 reserved = "!*'();:@&=+$,/?#[]"
884 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
885 self.assertEqual(escape_rfc3986(reserved), reserved)
886 self.assertEqual(escape_rfc3986(unreserved), unreserved)
887 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
888 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
889 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
890 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
891
892 def test_escape_url(self):
893 self.assertEqual(
894 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
895 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
896 )
897 self.assertEqual(
898 escape_url('http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erklärt/Das-Erste/Video?documentId=22673108&bcastId=5290'),
899 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
900 )
901 self.assertEqual(
902 escape_url('http://тест.рф/фрагмент'),
2d60465e 903 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
d05cfe06
S
904 )
905 self.assertEqual(
906 escape_url('http://тест.рф/абв?абв=абв#абв'),
81f36eba 907 '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'
d05cfe06
S
908 )
909 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
910
e7b6d122 911 def test_js_to_json_realworld(self):
410f3e73 912 inp = '''{
e7b6d122 913 'clip':{'provider':'pseudo'}
410f3e73
PH
914 }'''
915 self.assertEqual(js_to_json(inp), '''{
e7b6d122 916 "clip":{"provider":"pseudo"}
410f3e73
PH
917 }''')
918 json.loads(js_to_json(inp))
919
e7b6d122
PH
920 inp = '''{
921 'playlist':[{'controls':{'all':null}}]
922 }'''
923 self.assertEqual(js_to_json(inp), '''{
924 "playlist":[{"controls":{"all":null}}]
925 }''')
926
d01949dc
S
927 inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
928 self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
929
d305dd73
PH
930 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
931 json_code = js_to_json(inp)
932 self.assertEqual(json.loads(json_code), json.loads(inp))
933
89ac4a19
S
934 inp = '''{
935 0:{src:'skipped', type: 'application/dash+xml'},
936 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
937 }'''
938 self.assertEqual(js_to_json(inp), '''{
939 "0":{"src":"skipped", "type": "application/dash+xml"},
940 "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
941 }''')
942
47212f7b
YCH
943 inp = '''{"foo":101}'''
944 self.assertEqual(js_to_json(inp), '''{"foo":101}''')
945
e4659b45
YCH
946 inp = '''{"duration": "00:01:07"}'''
947 self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
948
c384d537
MF
949 inp = '''{segments: [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}'''
950 self.assertEqual(js_to_json(inp), '''{"segments": [{"offset":-3.885780586188048e-16,"duration":39.75000000000001}]}''')
951
e7b6d122
PH
952 def test_js_to_json_edgecases(self):
953 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
954 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
955
956 on = js_to_json('{"abc": true}')
957 self.assertEqual(json.loads(on), {'abc': True})
958
8f4b58d7
PH
959 # Ignore JavaScript code as well
960 on = js_to_json('''{
961 "x": 1,
962 y: "a",
963 z: some.code
964 }''')
965 d = json.loads(on)
966 self.assertEqual(d['x'], 1)
967 self.assertEqual(d['y'], 'a')
968
8bdd16b4 969 # Just drop ! prefix for now though this results in a wrong value
970 on = js_to_json('''{
971 a: !0,
972 b: !1,
973 c: !!0,
974 d: !!42.42,
975 e: !!![],
976 f: !"abc",
977 g: !"",
978 !42: 42
979 }''')
980 self.assertEqual(json.loads(on), {
981 'a': 0,
982 'b': 1,
983 'c': 0,
984 'd': 42.42,
985 'e': [],
986 'f': "abc",
987 'g': "",
988 '42': 42
989 })
990
ba9e68f4
S
991 on = js_to_json('["abc", "def",]')
992 self.assertEqual(json.loads(on), ['abc', 'def'])
993
4195096e
S
994 on = js_to_json('[/*comment\n*/"abc"/*comment\n*/,/*comment\n*/"def",/*comment\n*/]')
995 self.assertEqual(json.loads(on), ['abc', 'def'])
996
997 on = js_to_json('[//comment\n"abc" //comment\n,//comment\n"def",//comment\n]')
998 self.assertEqual(json.loads(on), ['abc', 'def'])
999
ba9e68f4
S
1000 on = js_to_json('{"abc": "def",}')
1001 self.assertEqual(json.loads(on), {'abc': 'def'})
1002
4195096e
S
1003 on = js_to_json('{/*comment\n*/"abc"/*comment\n*/:/*comment\n*/"def"/*comment\n*/,/*comment\n*/}')
1004 self.assertEqual(json.loads(on), {'abc': 'def'})
1005
bd1e4844 1006 on = js_to_json('{ 0: /* " \n */ ",]" , }')
1007 self.assertEqual(json.loads(on), {'0': ',]'})
1008
4195096e
S
1009 on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
1010 self.assertEqual(json.loads(on), {'0': ',]'})
1011
b3ee552e
1012 on = js_to_json('{ 0: // comment\n1 }')
1013 self.assertEqual(json.loads(on), {'0': 1})
1014
bd1e4844 1015 on = js_to_json(r'["<p>x<\/p>"]')
1016 self.assertEqual(json.loads(on), ['<p>x</p>'])
1017
1018 on = js_to_json(r'["\xaa"]')
1019 self.assertEqual(json.loads(on), ['\u00aa'])
1020
1021 on = js_to_json("['a\\\nb']")
1022 self.assertEqual(json.loads(on), ['ab'])
1023
4195096e
S
1024 on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
1025 self.assertEqual(json.loads(on), ['ab'])
1026
89ac4a19
S
1027 on = js_to_json('{0xff:0xff}')
1028 self.assertEqual(json.loads(on), {'255': 255})
1029
4195096e
S
1030 on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
1031 self.assertEqual(json.loads(on), {'255': 255})
1032
89ac4a19
S
1033 on = js_to_json('{077:077}')
1034 self.assertEqual(json.loads(on), {'63': 63})
1035
4195096e
S
1036 on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
1037 self.assertEqual(json.loads(on), {'63': 63})
1038
89ac4a19
S
1039 on = js_to_json('{42:42}')
1040 self.assertEqual(json.loads(on), {'42': 42})
1041
4195096e
S
1042 on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
1043 self.assertEqual(json.loads(on), {'42': 42})
1044
c384d537
MF
1045 on = js_to_json('{42:4.2e1}')
1046 self.assertEqual(json.loads(on), {'42': 42.0})
1047
8bdd16b4 1048 on = js_to_json('{ "0x40": "0x40" }')
1049 self.assertEqual(json.loads(on), {'0x40': '0x40'})
1050
1051 on = js_to_json('{ "040": "040" }')
1052 self.assertEqual(json.loads(on), {'040': '040'})
1053
c707b1d8
S
1054 def test_js_to_json_malformed(self):
1055 self.assertEqual(js_to_json('42a1'), '42"a1"')
1056 self.assertEqual(js_to_json('42a-1'), '42"a"-1')
1057
8bb56eee
BF
1058 def test_extract_attributes(self):
1059 self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
1060 self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
1061 self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
1062 self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
1063 self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
1064 self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
1065 self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
1066 self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
1067 self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
c5229f39
S
1068 self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
1069 self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
8bb56eee
BF
1070 self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
1071 self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
1072 self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
1073 self.assertEqual(extract_attributes('<e x >'), {'x': None})
1074 self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
1075 self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
1076 self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
1077 self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
1078 self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
1079 self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
1080 self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
c5229f39 1081 self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
8bb56eee
BF
1082 self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
1083 self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
1084 self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
1085 self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
1086 self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
1087 # "Narrow" Python builds don't support unicode code points outside BMP.
1088 try:
1089 compat_chr(0x10000)
1090 supports_outside_bmp = True
1091 except ValueError:
1092 supports_outside_bmp = False
1093 if supports_outside_bmp:
1094 self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
b4a3d461
S
1095 # Malformed HTML should not break attributes extraction on older Python
1096 self.assertEqual(extract_attributes('<mal"formed/>'), {})
8bb56eee 1097
e4bdb37e
PH
1098 def test_clean_html(self):
1099 self.assertEqual(clean_html('a:\nb'), 'a: b')
1100 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
9222d945 1101 self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
e4bdb37e 1102
4c0924bb
PH
1103 def test_intlist_to_bytes(self):
1104 self.assertEqual(
1105 intlist_to_bytes([0, 1, 127, 128, 255]),
1106 b'\x00\x01\x7f\x80\xff')
1107
7d4111ed
PH
1108 def test_args_to_str(self):
1109 self.assertEqual(
1110 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
dee2ff1d 1111 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""'
7d4111ed
PH
1112 )
1113
be64b5b0
PH
1114 def test_parse_filesize(self):
1115 self.assertEqual(parse_filesize(None), None)
1116 self.assertEqual(parse_filesize(''), None)
1117 self.assertEqual(parse_filesize('91 B'), 91)
1118 self.assertEqual(parse_filesize('foobar'), None)
1119 self.assertEqual(parse_filesize('2 MiB'), 2097152)
1120 self.assertEqual(parse_filesize('5 GB'), 5000000000)
1121 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
13585d76 1122 self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
4349c07d 1123 self.assertEqual(parse_filesize('1,24 KB'), 1240)
13585d76 1124 self.assertEqual(parse_filesize('1,24 kb'), 1240)
70852b47 1125 self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
be64b5b0 1126
fb47597b
S
1127 def test_parse_count(self):
1128 self.assertEqual(parse_count(None), None)
1129 self.assertEqual(parse_count(''), None)
1130 self.assertEqual(parse_count('0'), 0)
1131 self.assertEqual(parse_count('1000'), 1000)
1132 self.assertEqual(parse_count('1.000'), 1000)
1133 self.assertEqual(parse_count('1.1k'), 1100)
1134 self.assertEqual(parse_count('1.1kk'), 1100000)
782b1b5b
JMF
1135 self.assertEqual(parse_count('1.1kk '), 1100000)
1136 self.assertEqual(parse_count('1.1kk views'), 1100000)
fb47597b 1137
b871d7e9
S
1138 def test_parse_resolution(self):
1139 self.assertEqual(parse_resolution(None), {})
1140 self.assertEqual(parse_resolution(''), {})
1141 self.assertEqual(parse_resolution('1920x1080'), {'width': 1920, 'height': 1080})
1142 self.assertEqual(parse_resolution('1920×1080'), {'width': 1920, 'height': 1080})
1143 self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
1144 self.assertEqual(parse_resolution('720p'), {'height': 720})
1145 self.assertEqual(parse_resolution('4k'), {'height': 2160})
1146 self.assertEqual(parse_resolution('8K'), {'height': 4320})
1147
0dc41787
S
1148 def test_parse_bitrate(self):
1149 self.assertEqual(parse_bitrate(None), None)
1150 self.assertEqual(parse_bitrate(''), None)
1151 self.assertEqual(parse_bitrate('300kbps'), 300)
1152 self.assertEqual(parse_bitrate('1500kbps'), 1500)
1153 self.assertEqual(parse_bitrate('300 kbps'), 300)
1154
5f9b8394
PH
1155 def test_version_tuple(self):
1156 self.assertEqual(version_tuple('1'), (1,))
1157 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
47d7c642 1158 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
5f9b8394 1159
cae97f65
PH
1160 def test_detect_exe_version(self):
1161 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
1162built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
1163configuration: --prefix=/usr --extra-'''), '1.2.1')
1164 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
1165built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
1166 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
1167Trying to open render node...
1168Success at /dev/dri/renderD128.
1169ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
1170
05900629
PH
1171 def test_age_restricted(self):
1172 self.assertFalse(age_restricted(None, 10)) # unrestricted content
1173 self.assertFalse(age_restricted(1, None)) # unrestricted policy
1174 self.assertFalse(age_restricted(8, 10))
1175 self.assertTrue(age_restricted(18, 14))
1176 self.assertFalse(age_restricted(18, 18))
1177
61ca9a80
PH
1178 def test_is_html(self):
1179 self.assertFalse(is_html(b'\x49\x44\x43<html'))
1180 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
1181 self.assertTrue(is_html( # UTF-8 with BOM
1182 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
1183 self.assertTrue(is_html( # UTF-16-LE
1184 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
1185 ))
1186 self.assertTrue(is_html( # UTF-16-BE
1187 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
1188 ))
1189 self.assertTrue(is_html( # UTF-32-BE
1190 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'))
1191 self.assertTrue(is_html( # UTF-32-LE
1192 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'))
1193
cfb56d1a
PH
1194 def test_render_table(self):
1195 self.assertEqual(
1196 render_table(
1197 ['a', 'bcd'],
1198 [[123, 4], [9999, 51]]),
1199 'a bcd\n'
1200 '123 4\n'
1201 '9999 51')
1202
347de493
PH
1203 def test_match_str(self):
1204 self.assertRaises(ValueError, match_str, 'xy>foobar', {})
1205 self.assertFalse(match_str('xy', {'x': 1200}))
1206 self.assertTrue(match_str('!xy', {'x': 1200}))
1207 self.assertTrue(match_str('x', {'x': 1200}))
1208 self.assertFalse(match_str('!x', {'x': 1200}))
1209 self.assertTrue(match_str('x', {'x': 0}))
1210 self.assertFalse(match_str('x>0', {'x': 0}))
1211 self.assertFalse(match_str('x>0', {}))
1212 self.assertTrue(match_str('x>?0', {}))
1213 self.assertTrue(match_str('x>1K', {'x': 1200}))
1214 self.assertFalse(match_str('x>2K', {'x': 1200}))
1215 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
1216 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
1217 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
1218 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
1219 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
1220 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
1221 self.assertFalse(match_str(
1222 'like_count > 100 & dislike_count <? 50 & description',
1223 {'like_count': 90, 'description': 'foo'}))
1224 self.assertTrue(match_str(
1225 'like_count > 100 & dislike_count <? 50 & description',
1226 {'like_count': 190, 'description': 'foo'}))
1227 self.assertFalse(match_str(
1228 'like_count > 100 & dislike_count <? 50 & description',
1229 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
1230 self.assertFalse(match_str(
1231 'like_count > 100 & dislike_count <? 50 & description',
1232 {'like_count': 190, 'dislike_count': 10}))
1cc47c66
S
1233 self.assertTrue(match_str('is_live', {'is_live': True}))
1234 self.assertFalse(match_str('is_live', {'is_live': False}))
1235 self.assertFalse(match_str('is_live', {'is_live': None}))
1236 self.assertFalse(match_str('is_live', {}))
1237 self.assertFalse(match_str('!is_live', {'is_live': True}))
1238 self.assertTrue(match_str('!is_live', {'is_live': False}))
1239 self.assertTrue(match_str('!is_live', {'is_live': None}))
1240 self.assertTrue(match_str('!is_live', {}))
1241 self.assertTrue(match_str('title', {'title': 'abc'}))
1242 self.assertTrue(match_str('title', {'title': ''}))
1243 self.assertFalse(match_str('!title', {'title': 'abc'}))
1244 self.assertFalse(match_str('!title', {'title': ''}))
347de493 1245
bf6427d2 1246 def test_parse_dfxp_time_expr(self):
d631d5f9
YCH
1247 self.assertEqual(parse_dfxp_time_expr(None), None)
1248 self.assertEqual(parse_dfxp_time_expr(''), None)
bf6427d2
YCH
1249 self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
1250 self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
1251 self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
1252 self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
db2fe38b 1253 self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
bf6427d2
YCH
1254
1255 def test_dfxp2srt(self):
1256 dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
1257 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1258 <body>
1259 <div xml:lang="en">
1260 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
1261 <p begin="1" end="2">第二行<br/>♪♪</p>
7dff0363 1262 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
d631d5f9
YCH
1263 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
1264 <p begin="-1" end="-1">Ignore, two</p>
1265 <p begin="3" dur="-1">Ignored, three</p>
bf6427d2
YCH
1266 </div>
1267 </body>
3869028f 1268 </tt>'''.encode('utf-8')
bf6427d2
YCH
1269 srt_data = '''1
127000:00:00,000 --> 00:00:01,000
1271The following line contains Chinese characters and special symbols
1272
12732
127400:00:01,000 --> 00:00:02,000
1275第二行
1276♪♪
1277
12783
127900:00:02,000 --> 00:00:03,000
1280Third
1281Line
1282
1283'''
1284 self.assertEqual(dfxp2srt(dfxp_data), srt_data)
1285
1b0427e6
YCH
1286 dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
1287 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1288 <body>
1289 <div xml:lang="en">
1290 <p begin="0" end="1">The first line</p>
1291 </div>
1292 </body>
3869028f 1293 </tt>'''.encode('utf-8')
1b0427e6
YCH
1294 srt_data = '''1
129500:00:00,000 --> 00:00:01,000
1296The first line
1297
1298'''
1299 self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
1300
5b995f71
RA
1301 dfxp_data_with_style = '''<?xml version="1.0" encoding="utf-8"?>
1302<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">
1303 <head>
1304 <styling>
1305 <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
1306 <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
1307 <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
1308 <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
1309 </styling>
1310 </head>
1311 <body tts:textAlign="center" style="s0">
1312 <div>
1313 <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
1314 <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>
1315 <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
1316 <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>
1317 </div>
1318 </body>
3869028f 1319</tt>'''.encode('utf-8')
5b995f71
RA
1320 srt_data = '''1
132100:00:02,080 --> 00:00:05,839
1322<font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
1323
13242
132500:00:02,080 --> 00:00:05,839
1326<b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
1327</font>part 2</font></b>
1328
13293
133000:00:05,839 --> 00:00:09,560
1331<u><font color="lime">line 3
1332part 3</font></u>
1333
13344
133500:00:09,560 --> 00:00:12,359
1336<i><u><font color="yellow"><font color="lime">inner
1337 </font>style</font></u></i>
1338
1339'''
1340 self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
1341
3869028f
YCH
1342 dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
1343 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1344 <body>
1345 <div xml:lang="en">
1346 <p begin="0" end="1">Line 1</p>
1347 <p begin="1" end="2">第二行</p>
1348 </div>
1349 </body>
1350 </tt>'''.encode('utf-16')
1351 srt_data = '''1
135200:00:00,000 --> 00:00:01,000
1353Line 1
1354
13552
135600:00:01,000 --> 00:00:02,000
1357第二行
1358
1359'''
1360 self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
1361
f7126449
S
1362 def test_cli_option(self):
1363 self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
1364 self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
1365 self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
5f2c2b79 1366 self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
f7126449
S
1367
1368 def test_cli_valueless_option(self):
1369 self.assertEqual(cli_valueless_option(
1370 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
1371 self.assertEqual(cli_valueless_option(
1372 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
1373 self.assertEqual(cli_valueless_option(
1374 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
1375 self.assertEqual(cli_valueless_option(
1376 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
1377 self.assertEqual(cli_valueless_option(
1378 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
1379 self.assertEqual(cli_valueless_option(
1380 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
1381
1382 def test_cli_bool_option(self):
1383 self.assertEqual(
1384 cli_bool_option(
1385 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
1386 ['--no-check-certificate', 'true'])
1387 self.assertEqual(
1388 cli_bool_option(
1389 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
1390 ['--no-check-certificate=true'])
1391 self.assertEqual(
1392 cli_bool_option(
1393 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1394 ['--check-certificate', 'false'])
1395 self.assertEqual(
1396 cli_bool_option(
1397 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1398 ['--check-certificate=false'])
1399 self.assertEqual(
1400 cli_bool_option(
1401 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1402 ['--check-certificate', 'true'])
1403 self.assertEqual(
1404 cli_bool_option(
1405 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1406 ['--check-certificate=true'])
5b232f46
S
1407 self.assertEqual(
1408 cli_bool_option(
1409 {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1410 [])
f7126449 1411
5bc880b9
YCH
1412 def test_ohdave_rsa_encrypt(self):
1413 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
1414 e = 65537
1415
1416 self.assertEqual(
1417 ohdave_rsa_encrypt(b'aa111222', e, N),
1418 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
cfb56d1a 1419
f48409c7
YCH
1420 def test_pkcs1pad(self):
1421 data = [1, 2, 3]
1422 padded_data = pkcs1pad(data, 32)
1423 self.assertEqual(padded_data[:2], [0, 2])
1424 self.assertEqual(padded_data[28:], [0, 1, 2, 3])
1425
1426 self.assertRaises(ValueError, pkcs1pad, data, 8)
1427
5eb6bdce
YCH
1428 def test_encode_base_n(self):
1429 self.assertEqual(encode_base_n(0, 30), '0')
1430 self.assertEqual(encode_base_n(80, 30), '2k')
1431
1432 custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
1433 self.assertEqual(encode_base_n(0, 30, custom_table), '9')
1434 self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
1435
1436 self.assertRaises(ValueError, encode_base_n, 0, 70)
1437 self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
1438
1ced2221
S
1439 def test_caesar(self):
1440 self.assertEqual(caesar('ace', 'abcdef', 2), 'cea')
1441 self.assertEqual(caesar('cea', 'abcdef', -2), 'ace')
1442 self.assertEqual(caesar('ace', 'abcdef', -2), 'eac')
1443 self.assertEqual(caesar('eac', 'abcdef', 2), 'ace')
1444 self.assertEqual(caesar('ace', 'abcdef', 0), 'ace')
1445 self.assertEqual(caesar('xyz', 'abcdef', 2), 'xyz')
1446 self.assertEqual(caesar('abc', 'acegik', 2), 'ebg')
1447 self.assertEqual(caesar('ebg', 'acegik', -2), 'abc')
1448
1449 def test_rot47(self):
7a5c1cfe
P
1450 self.assertEqual(rot47('yt-dlp'), r'JE\5=A')
1451 self.assertEqual(rot47('YT-DLP'), r'*%\s{!')
1ced2221 1452
1143535d
YCH
1453 def test_urshift(self):
1454 self.assertEqual(urshift(3, 1), 1)
1455 self.assertEqual(urshift(-3, 1), 2147483646)
1456
84c237fb
YCH
1457 def test_get_element_by_class(self):
1458 html = '''
1459 <span class="foo bar">nice</span>
1460 '''
1461
1462 self.assertEqual(get_element_by_class('foo', html), 'nice')
1463 self.assertEqual(get_element_by_class('no-such-class', html), None)
1464
2af12ad9
TC
1465 def test_get_element_by_attribute(self):
1466 html = '''
1467 <span class="foo bar">nice</span>
1468 '''
1469
1470 self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
1471 self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
1472 self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
1473
609ff8ca
YCH
1474 html = '''
1475 <div itemprop="author" itemscope>foo</div>
1476 '''
1477
1478 self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
1479
2af12ad9
TC
1480 def test_get_elements_by_class(self):
1481 html = '''
1482 <span class="foo bar">nice</span><span class="foo bar">also nice</span>
1483 '''
1484
1485 self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
1486 self.assertEqual(get_elements_by_class('no-such-class', html), [])
1487
1488 def test_get_elements_by_attribute(self):
1489 html = '''
1490 <span class="foo bar">nice</span><span class="foo bar">also nice</span>
1491 '''
1492
1493 self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
1494 self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
1495 self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
1496
732044af 1497 def test_iri_to_uri(self):
1498 self.assertEqual(
1499 iri_to_uri('https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b'),
1500 'https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b') # Same
1501 self.assertEqual(
1502 iri_to_uri('https://www.google.com/search?q=Käsesoßenrührlöffel'), # German for cheese sauce stirring spoon
1503 'https://www.google.com/search?q=K%C3%A4seso%C3%9Fenr%C3%BChrl%C3%B6ffel')
1504 self.assertEqual(
1505 iri_to_uri('https://www.google.com/search?q=lt<+gt>+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#'),
1506 'https://www.google.com/search?q=lt%3C+gt%3E+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#')
1507 self.assertEqual(
1508 iri_to_uri('http://правозащита38.рф/category/news/'),
1509 'http://xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
1510 self.assertEqual(
1511 iri_to_uri('http://www.правозащита38.рф/category/news/'),
1512 'http://www.xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
1513 self.assertEqual(
1514 iri_to_uri('https://i❤.ws/emojidomain/👍👏🤝💪'),
1515 'https://xn--i-7iq.ws/emojidomain/%F0%9F%91%8D%F0%9F%91%8F%F0%9F%A4%9D%F0%9F%92%AA')
1516 self.assertEqual(
1517 iri_to_uri('http://日本語.jp/'),
1518 'http://xn--wgv71a119e.jp/')
1519 self.assertEqual(
1520 iri_to_uri('http://导航.中国/'),
1521 'http://xn--fet810g.xn--fiqs8s/')
1522
00dd0cd5 1523 def test_clean_podcast_url(self):
1524 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')
1525 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')
1526
582be358 1527
dae7c920 1528if __name__ == '__main__':
59ae15a5 1529 unittest.main()