]> jfr.im git - yt-dlp.git/blob - test/test_utils.py
[utils] Allow duration strings in filter
[yt-dlp.git] / test / test_utils.py
1 #!/usr/bin/env python3
2 # coding: utf-8
3
4 from __future__ import unicode_literals
5
6 # Allow direct execution
7 import os
8 import sys
9 import unittest
10 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
12
13 # Various small unit tests
14 import io
15 import itertools
16 import json
17 import xml.etree.ElementTree
18
19 from yt_dlp.utils import (
20 age_restricted,
21 args_to_str,
22 encode_base_n,
23 caesar,
24 clean_html,
25 clean_podcast_url,
26 date_from_str,
27 datetime_from_str,
28 DateRange,
29 detect_exe_version,
30 determine_ext,
31 dict_get,
32 encode_compat_str,
33 encodeFilename,
34 escape_rfc3986,
35 escape_url,
36 extract_attributes,
37 ExtractorError,
38 find_xpath_attr,
39 fix_xml_ampersands,
40 float_or_none,
41 get_element_by_class,
42 get_element_by_attribute,
43 get_elements_by_class,
44 get_elements_by_attribute,
45 InAdvancePagedList,
46 int_or_none,
47 intlist_to_bytes,
48 is_html,
49 js_to_json,
50 limit_length,
51 merge_dicts,
52 mimetype2ext,
53 month_by_name,
54 multipart_encode,
55 ohdave_rsa_encrypt,
56 OnDemandPagedList,
57 orderedSet,
58 parse_age_limit,
59 parse_duration,
60 parse_filesize,
61 parse_count,
62 parse_iso8601,
63 parse_resolution,
64 parse_bitrate,
65 parse_qs,
66 pkcs1pad,
67 read_batch_urls,
68 sanitize_filename,
69 sanitize_path,
70 sanitize_url,
71 sanitized_Request,
72 expand_path,
73 prepend_extension,
74 replace_extension,
75 remove_start,
76 remove_end,
77 remove_quotes,
78 rot47,
79 shell_quote,
80 smuggle_url,
81 str_to_int,
82 strip_jsonp,
83 strip_or_none,
84 subtitles_filename,
85 timeconvert,
86 unescapeHTML,
87 unified_strdate,
88 unified_timestamp,
89 unsmuggle_url,
90 uppercase_escape,
91 lowercase_escape,
92 url_basename,
93 url_or_none,
94 base_url,
95 urljoin,
96 urlencode_postdata,
97 urshift,
98 update_url_query,
99 version_tuple,
100 xpath_with_ns,
101 xpath_element,
102 xpath_text,
103 xpath_attr,
104 render_table,
105 match_str,
106 parse_dfxp_time_expr,
107 dfxp2srt,
108 cli_option,
109 cli_valueless_option,
110 cli_bool_option,
111 parse_codecs,
112 iri_to_uri,
113 LazyList,
114 )
115 from yt_dlp.compat import (
116 compat_chr,
117 compat_etree_fromstring,
118 compat_getenv,
119 compat_os_name,
120 compat_setenv,
121 )
122
123
124 class TestUtil(unittest.TestCase):
125 def test_timeconvert(self):
126 self.assertTrue(timeconvert('') is None)
127 self.assertTrue(timeconvert('bougrg') is None)
128
129 def test_sanitize_filename(self):
130 self.assertEqual(sanitize_filename(''), '')
131 self.assertEqual(sanitize_filename('abc'), 'abc')
132 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
133
134 self.assertEqual(sanitize_filename('123'), '123')
135
136 self.assertEqual('abc_de', sanitize_filename('abc/de'))
137 self.assertFalse('/' in sanitize_filename('abc/de///'))
138
139 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
140 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
141 self.assertEqual('yes no', sanitize_filename('yes? no'))
142 self.assertEqual('this - that', sanitize_filename('this: that'))
143
144 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
145 aumlaut = 'ä'
146 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
147 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
148 self.assertEqual(sanitize_filename(tests), tests)
149
150 self.assertEqual(
151 sanitize_filename('New World record at 0:12:34'),
152 'New World record at 0_12_34')
153
154 self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
155 self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
156 self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
157 self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
158
159 forbidden = '"\0\\/'
160 for fc in forbidden:
161 for fbc in forbidden:
162 self.assertTrue(fbc not in sanitize_filename(fc))
163
164 def test_sanitize_filename_restricted(self):
165 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
166 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
167
168 self.assertEqual(sanitize_filename('123', restricted=True), '123')
169
170 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
171 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
172
173 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
174 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
175 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
176 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
177
178 tests = 'aäb\u4e2d\u56fd\u7684c'
179 self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
180 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
181
182 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
183 for fc in forbidden:
184 for fbc in forbidden:
185 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
186
187 # Handle a common case more neatly
188 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
189 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
190 # .. but make sure the file name is never empty
191 self.assertTrue(sanitize_filename('-', restricted=True) != '')
192 self.assertTrue(sanitize_filename(':', restricted=True) != '')
193
194 self.assertEqual(sanitize_filename(
195 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
196 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYTHssaaaaaaaeceeeeiiiionooooooooeuuuuuythy')
197
198 def test_sanitize_ids(self):
199 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
200 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
201 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
202
203 def test_sanitize_path(self):
204 if sys.platform != 'win32':
205 return
206
207 self.assertEqual(sanitize_path('abc'), 'abc')
208 self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
209 self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
210 self.assertEqual(sanitize_path('abc|def'), 'abc#def')
211 self.assertEqual(sanitize_path('<>:"|?*'), '#######')
212 self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
213 self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
214
215 self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
216 self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
217
218 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
219 self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
220 self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
221 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
222
223 self.assertEqual(
224 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
225 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
226
227 self.assertEqual(
228 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
229 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
230 self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
231 self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
232 self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
233
234 self.assertEqual(sanitize_path('../abc'), '..\\abc')
235 self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
236 self.assertEqual(sanitize_path('./abc'), 'abc')
237 self.assertEqual(sanitize_path('./../abc'), '..\\abc')
238
239 def test_sanitize_url(self):
240 self.assertEqual(sanitize_url('//foo.bar'), 'http://foo.bar')
241 self.assertEqual(sanitize_url('httpss://foo.bar'), 'https://foo.bar')
242 self.assertEqual(sanitize_url('rmtps://foo.bar'), 'rtmps://foo.bar')
243 self.assertEqual(sanitize_url('https://foo.bar'), 'https://foo.bar')
244 self.assertEqual(sanitize_url('foo bar'), 'foo bar')
245
246 def test_extract_basic_auth(self):
247 auth_header = lambda url: sanitized_Request(url).get_header('Authorization')
248 self.assertFalse(auth_header('http://foo.bar'))
249 self.assertFalse(auth_header('http://:foo.bar'))
250 self.assertEqual(auth_header('http://@foo.bar'), 'Basic Og==')
251 self.assertEqual(auth_header('http://:pass@foo.bar'), 'Basic OnBhc3M=')
252 self.assertEqual(auth_header('http://user:@foo.bar'), 'Basic dXNlcjo=')
253 self.assertEqual(auth_header('http://user:pass@foo.bar'), 'Basic dXNlcjpwYXNz')
254
255 def test_expand_path(self):
256 def env(var):
257 return '%{0}%'.format(var) if sys.platform == 'win32' else '${0}'.format(var)
258
259 compat_setenv('yt_dlp_EXPATH_PATH', 'expanded')
260 self.assertEqual(expand_path(env('yt_dlp_EXPATH_PATH')), 'expanded')
261 self.assertEqual(expand_path(env('HOME')), compat_getenv('HOME'))
262 self.assertEqual(expand_path('~'), compat_getenv('HOME'))
263 self.assertEqual(
264 expand_path('~/%s' % env('yt_dlp_EXPATH_PATH')),
265 '%s/expanded' % compat_getenv('HOME'))
266
267 def test_prepend_extension(self):
268 self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
269 self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
270 self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
271 self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
272 self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
273 self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
274
275 def test_replace_extension(self):
276 self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
277 self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
278 self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
279 self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
280 self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
281 self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
282
283 def test_subtitles_filename(self):
284 self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt'), 'abc.en.vtt')
285 self.assertEqual(subtitles_filename('abc.ext', 'en', 'vtt', 'ext'), 'abc.en.vtt')
286 self.assertEqual(subtitles_filename('abc.unexpected_ext', 'en', 'vtt', 'ext'), 'abc.unexpected_ext.en.vtt')
287
288 def test_remove_start(self):
289 self.assertEqual(remove_start(None, 'A - '), None)
290 self.assertEqual(remove_start('A - B', 'A - '), 'B')
291 self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
292
293 def test_remove_end(self):
294 self.assertEqual(remove_end(None, ' - B'), None)
295 self.assertEqual(remove_end('A - B', ' - B'), 'A')
296 self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
297
298 def test_remove_quotes(self):
299 self.assertEqual(remove_quotes(None), None)
300 self.assertEqual(remove_quotes('"'), '"')
301 self.assertEqual(remove_quotes("'"), "'")
302 self.assertEqual(remove_quotes(';'), ';')
303 self.assertEqual(remove_quotes('";'), '";')
304 self.assertEqual(remove_quotes('""'), '')
305 self.assertEqual(remove_quotes('";"'), ';')
306
307 def test_ordered_set(self):
308 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
309 self.assertEqual(orderedSet([]), [])
310 self.assertEqual(orderedSet([1]), [1])
311 # keep the list ordered
312 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
313
314 def test_unescape_html(self):
315 self.assertEqual(unescapeHTML('%20;'), '%20;')
316 self.assertEqual(unescapeHTML('&#x2F;'), '/')
317 self.assertEqual(unescapeHTML('&#47;'), '/')
318 self.assertEqual(unescapeHTML('&eacute;'), 'é')
319 self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
320 self.assertEqual(unescapeHTML('&a&quot;'), '&a"')
321 # HTML5 entities
322 self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
323
324 def test_date_from_str(self):
325 self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
326 self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
327 self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
328 self.assertEqual(date_from_str('20200229+365day'), date_from_str('20200229+1year'))
329 self.assertEqual(date_from_str('20210131+28day'), date_from_str('20210131+1month'))
330
331 def test_datetime_from_str(self):
332 self.assertEqual(datetime_from_str('yesterday', precision='day'), datetime_from_str('now-1day', precision='auto'))
333 self.assertEqual(datetime_from_str('now+7day', precision='day'), datetime_from_str('now+1week', precision='auto'))
334 self.assertEqual(datetime_from_str('now+14day', precision='day'), datetime_from_str('now+2week', precision='auto'))
335 self.assertEqual(datetime_from_str('20200229+365day', precision='day'), datetime_from_str('20200229+1year', precision='auto'))
336 self.assertEqual(datetime_from_str('20210131+28day', precision='day'), datetime_from_str('20210131+1month', precision='auto'))
337 self.assertEqual(datetime_from_str('20210131+59day', precision='day'), datetime_from_str('20210131+2month', precision='auto'))
338 self.assertEqual(datetime_from_str('now+1day', precision='hour'), datetime_from_str('now+24hours', precision='auto'))
339 self.assertEqual(datetime_from_str('now+23hours', precision='hour'), datetime_from_str('now+23hours', precision='auto'))
340
341 def test_daterange(self):
342 _20century = DateRange("19000101", "20000101")
343 self.assertFalse("17890714" in _20century)
344 _ac = DateRange("00010101")
345 self.assertTrue("19690721" in _ac)
346 _firstmilenium = DateRange(end="10000101")
347 self.assertTrue("07110427" in _firstmilenium)
348
349 def test_unified_dates(self):
350 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
351 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
352 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
353 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
354 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
355 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
356 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
357 self.assertEqual(
358 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
359 '20141126')
360 self.assertEqual(
361 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
362 '20150202')
363 self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
364 self.assertEqual(unified_strdate('25-09-2014'), '20140925')
365 self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
366 self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
367 self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
368 self.assertEqual(unified_strdate('July 15th, 2013'), '20130715')
369 self.assertEqual(unified_strdate('September 1st, 2013'), '20130901')
370 self.assertEqual(unified_strdate('Sep 2nd, 2013'), '20130902')
371 self.assertEqual(unified_strdate('November 3rd, 2019'), '20191103')
372 self.assertEqual(unified_strdate('October 23rd, 2005'), '20051023')
373
374 def test_unified_timestamps(self):
375 self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
376 self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
377 self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
378 self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
379 self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
380 self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
381 self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
382 self.assertEqual(
383 unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
384 1417001400)
385 self.assertEqual(
386 unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
387 1422902860)
388 self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
389 self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
390 self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
391 self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
392 self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
393 self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
394 self.assertEqual(unified_timestamp('2017-03-30T17:52:41Q'), 1490896361)
395 self.assertEqual(unified_timestamp('Sep 11, 2013 | 5:49 AM'), 1378878540)
396 self.assertEqual(unified_timestamp('December 15, 2017 at 7:49 am'), 1513324140)
397 self.assertEqual(unified_timestamp('2018-03-14T08:32:43.1493874+00:00'), 1521016363)
398
399 def test_determine_ext(self):
400 self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
401 self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
402 self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
403 self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
404 self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
405 self.assertEqual(determine_ext('foobar', None), None)
406
407 def test_find_xpath_attr(self):
408 testxml = '''<root>
409 <node/>
410 <node x="a"/>
411 <node x="a" y="c" />
412 <node x="b" y="d" />
413 <node x="" />
414 </root>'''
415 doc = compat_etree_fromstring(testxml)
416
417 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
418 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
419 self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
420 self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
421 self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
422 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
423 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
424 self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
425 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
426 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
427 self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
428
429 def test_xpath_with_ns(self):
430 testxml = '''<root xmlns:media="http://example.com/">
431 <media:song>
432 <media:author>The Author</media:author>
433 <url>http://server.com/download.mp3</url>
434 </media:song>
435 </root>'''
436 doc = compat_etree_fromstring(testxml)
437 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
438 self.assertTrue(find('media:song') is not None)
439 self.assertEqual(find('media:song/media:author').text, 'The Author')
440 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
441
442 def test_xpath_element(self):
443 doc = xml.etree.ElementTree.Element('root')
444 div = xml.etree.ElementTree.SubElement(doc, 'div')
445 p = xml.etree.ElementTree.SubElement(div, 'p')
446 p.text = 'Foo'
447 self.assertEqual(xpath_element(doc, 'div/p'), p)
448 self.assertEqual(xpath_element(doc, ['div/p']), p)
449 self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
450 self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
451 self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
452 self.assertTrue(xpath_element(doc, 'div/bar') is None)
453 self.assertTrue(xpath_element(doc, ['div/bar']) is None)
454 self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
455 self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
456 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
457 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
458
459 def test_xpath_text(self):
460 testxml = '''<root>
461 <div>
462 <p>Foo</p>
463 </div>
464 </root>'''
465 doc = compat_etree_fromstring(testxml)
466 self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
467 self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
468 self.assertTrue(xpath_text(doc, 'div/bar') is None)
469 self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
470
471 def test_xpath_attr(self):
472 testxml = '''<root>
473 <div>
474 <p x="a">Foo</p>
475 </div>
476 </root>'''
477 doc = compat_etree_fromstring(testxml)
478 self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
479 self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
480 self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
481 self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
482 self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
483 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
484 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
485
486 def test_smuggle_url(self):
487 data = {"ö": "ö", "abc": [3]}
488 url = 'https://foo.bar/baz?x=y#a'
489 smug_url = smuggle_url(url, data)
490 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
491 self.assertEqual(url, unsmug_url)
492 self.assertEqual(data, unsmug_data)
493
494 res_url, res_data = unsmuggle_url(url)
495 self.assertEqual(res_url, url)
496 self.assertEqual(res_data, None)
497
498 smug_url = smuggle_url(url, {'a': 'b'})
499 smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
500 res_url, res_data = unsmuggle_url(smug_smug_url)
501 self.assertEqual(res_url, url)
502 self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
503
504 def test_shell_quote(self):
505 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
506 self.assertEqual(
507 shell_quote(args),
508 """ffmpeg -i 'ñ€ß'"'"'.mp4'""" if compat_os_name != 'nt' else '''ffmpeg -i "ñ€ß'.mp4"''')
509
510 def test_float_or_none(self):
511 self.assertEqual(float_or_none('42.42'), 42.42)
512 self.assertEqual(float_or_none('42'), 42.0)
513 self.assertEqual(float_or_none(''), None)
514 self.assertEqual(float_or_none(None), None)
515 self.assertEqual(float_or_none([]), None)
516 self.assertEqual(float_or_none(set()), None)
517
518 def test_int_or_none(self):
519 self.assertEqual(int_or_none('42'), 42)
520 self.assertEqual(int_or_none(''), None)
521 self.assertEqual(int_or_none(None), None)
522 self.assertEqual(int_or_none([]), None)
523 self.assertEqual(int_or_none(set()), None)
524
525 def test_str_to_int(self):
526 self.assertEqual(str_to_int('123,456'), 123456)
527 self.assertEqual(str_to_int('123.456'), 123456)
528 self.assertEqual(str_to_int(523), 523)
529 # Python 3 has no long
530 if sys.version_info < (3, 0):
531 eval('self.assertEqual(str_to_int(123456L), 123456)')
532 self.assertEqual(str_to_int('noninteger'), None)
533 self.assertEqual(str_to_int([]), None)
534
535 def test_url_basename(self):
536 self.assertEqual(url_basename('http://foo.de/'), '')
537 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
538 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
539 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
540 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
541 self.assertEqual(
542 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
543 'trailer.mp4')
544
545 def test_base_url(self):
546 self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
547 self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
548 self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
549 self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
550 self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
551
552 def test_urljoin(self):
553 self.assertEqual(urljoin('http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
554 self.assertEqual(urljoin(b'http://foo.de/', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
555 self.assertEqual(urljoin('http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
556 self.assertEqual(urljoin(b'http://foo.de/', b'/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
557 self.assertEqual(urljoin('//foo.de/', '/a/b/c.txt'), '//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', '/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
560 self.assertEqual(urljoin('http://foo.de', 'a/b/c.txt'), 'http://foo.de/a/b/c.txt')
561 self.assertEqual(urljoin('http://foo.de/', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
562 self.assertEqual(urljoin('http://foo.de/', '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
563 self.assertEqual(urljoin(None, 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
564 self.assertEqual(urljoin(None, '//foo.de/a/b/c.txt'), '//foo.de/a/b/c.txt')
565 self.assertEqual(urljoin('', 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
566 self.assertEqual(urljoin(['foobar'], 'http://foo.de/a/b/c.txt'), 'http://foo.de/a/b/c.txt')
567 self.assertEqual(urljoin('http://foo.de/', None), None)
568 self.assertEqual(urljoin('http://foo.de/', ''), None)
569 self.assertEqual(urljoin('http://foo.de/', ['foobar']), None)
570 self.assertEqual(urljoin('http://foo.de/a/b/c.txt', '.././../d.txt'), 'http://foo.de/d.txt')
571 self.assertEqual(urljoin('http://foo.de/a/b/c.txt', 'rtmp://foo.de'), 'rtmp://foo.de')
572 self.assertEqual(urljoin(None, 'rtmp://foo.de'), 'rtmp://foo.de')
573
574 def test_url_or_none(self):
575 self.assertEqual(url_or_none(None), None)
576 self.assertEqual(url_or_none(''), None)
577 self.assertEqual(url_or_none('foo'), None)
578 self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
579 self.assertEqual(url_or_none('https://foo.de'), 'https://foo.de')
580 self.assertEqual(url_or_none('http$://foo.de'), None)
581 self.assertEqual(url_or_none('http://foo.de'), 'http://foo.de')
582 self.assertEqual(url_or_none('//foo.de'), '//foo.de')
583 self.assertEqual(url_or_none('s3://foo.de'), None)
584 self.assertEqual(url_or_none('rtmpte://foo.de'), 'rtmpte://foo.de')
585 self.assertEqual(url_or_none('mms://foo.de'), 'mms://foo.de')
586 self.assertEqual(url_or_none('rtspu://foo.de'), 'rtspu://foo.de')
587 self.assertEqual(url_or_none('ftps://foo.de'), 'ftps://foo.de')
588
589 def test_parse_age_limit(self):
590 self.assertEqual(parse_age_limit(None), None)
591 self.assertEqual(parse_age_limit(False), None)
592 self.assertEqual(parse_age_limit('invalid'), None)
593 self.assertEqual(parse_age_limit(0), 0)
594 self.assertEqual(parse_age_limit(18), 18)
595 self.assertEqual(parse_age_limit(21), 21)
596 self.assertEqual(parse_age_limit(22), None)
597 self.assertEqual(parse_age_limit('18'), 18)
598 self.assertEqual(parse_age_limit('18+'), 18)
599 self.assertEqual(parse_age_limit('PG-13'), 13)
600 self.assertEqual(parse_age_limit('TV-14'), 14)
601 self.assertEqual(parse_age_limit('TV-MA'), 17)
602 self.assertEqual(parse_age_limit('TV14'), 14)
603 self.assertEqual(parse_age_limit('TV_G'), 0)
604
605 def test_parse_duration(self):
606 self.assertEqual(parse_duration(None), None)
607 self.assertEqual(parse_duration(False), None)
608 self.assertEqual(parse_duration('invalid'), None)
609 self.assertEqual(parse_duration('1'), 1)
610 self.assertEqual(parse_duration('1337:12'), 80232)
611 self.assertEqual(parse_duration('9:12:43'), 33163)
612 self.assertEqual(parse_duration('12:00'), 720)
613 self.assertEqual(parse_duration('00:01:01'), 61)
614 self.assertEqual(parse_duration('x:y'), None)
615 self.assertEqual(parse_duration('3h11m53s'), 11513)
616 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
617 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
618 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
619 self.assertEqual(parse_duration('62m45s'), 3765)
620 self.assertEqual(parse_duration('6m59s'), 419)
621 self.assertEqual(parse_duration('49s'), 49)
622 self.assertEqual(parse_duration('0h0m0s'), 0)
623 self.assertEqual(parse_duration('0m0s'), 0)
624 self.assertEqual(parse_duration('0s'), 0)
625 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
626 self.assertEqual(parse_duration('T30M38S'), 1838)
627 self.assertEqual(parse_duration('5 s'), 5)
628 self.assertEqual(parse_duration('3 min'), 180)
629 self.assertEqual(parse_duration('2.5 hours'), 9000)
630 self.assertEqual(parse_duration('02:03:04'), 7384)
631 self.assertEqual(parse_duration('01:02:03:04'), 93784)
632 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
633 self.assertEqual(parse_duration('87 Min.'), 5220)
634 self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
635 self.assertEqual(parse_duration('PT00H03M30SZ'), 210)
636 self.assertEqual(parse_duration('P0Y0M0DT0H4M20.880S'), 260.88)
637
638 def test_fix_xml_ampersands(self):
639 self.assertEqual(
640 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
641 self.assertEqual(
642 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
643 '"&amp;x=y&amp;wrong;&amp;z=a')
644 self.assertEqual(
645 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
646 '&amp;&apos;&gt;&lt;&quot;')
647 self.assertEqual(
648 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
649 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
650
651 def test_paged_list(self):
652 def testPL(size, pagesize, sliceargs, expected):
653 def get_page(pagenum):
654 firstid = pagenum * pagesize
655 upto = min(size, pagenum * pagesize + pagesize)
656 for i in range(firstid, upto):
657 yield i
658
659 pl = OnDemandPagedList(get_page, pagesize)
660 got = pl.getslice(*sliceargs)
661 self.assertEqual(got, expected)
662
663 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
664 got = iapl.getslice(*sliceargs)
665 self.assertEqual(got, expected)
666
667 testPL(5, 2, (), [0, 1, 2, 3, 4])
668 testPL(5, 2, (1,), [1, 2, 3, 4])
669 testPL(5, 2, (2,), [2, 3, 4])
670 testPL(5, 2, (4,), [4])
671 testPL(5, 2, (0, 3), [0, 1, 2])
672 testPL(5, 2, (1, 4), [1, 2, 3])
673 testPL(5, 2, (2, 99), [2, 3, 4])
674 testPL(5, 2, (20, 99), [])
675
676 def test_read_batch_urls(self):
677 f = io.StringIO('''\xef\xbb\xbf foo
678 bar\r
679 baz
680 # More after this line\r
681 ; or after this
682 bam''')
683 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
684
685 def test_urlencode_postdata(self):
686 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
687 self.assertTrue(isinstance(data, bytes))
688
689 def test_update_url_query(self):
690 self.assertEqual(parse_qs(update_url_query(
691 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
692 parse_qs('http://example.com/path?quality=HD&format=mp4'))
693 self.assertEqual(parse_qs(update_url_query(
694 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
695 parse_qs('http://example.com/path?system=LINUX&system=WINDOWS'))
696 self.assertEqual(parse_qs(update_url_query(
697 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
698 parse_qs('http://example.com/path?fields=id,formats,subtitles'))
699 self.assertEqual(parse_qs(update_url_query(
700 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
701 parse_qs('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
702 self.assertEqual(parse_qs(update_url_query(
703 'http://example.com/path?manifest=f4m', {'manifest': []})),
704 parse_qs('http://example.com/path'))
705 self.assertEqual(parse_qs(update_url_query(
706 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
707 parse_qs('http://example.com/path?system=LINUX'))
708 self.assertEqual(parse_qs(update_url_query(
709 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
710 parse_qs('http://example.com/path?fields=id,formats,subtitles'))
711 self.assertEqual(parse_qs(update_url_query(
712 'http://example.com/path', {'width': 1080, 'height': 720})),
713 parse_qs('http://example.com/path?width=1080&height=720'))
714 self.assertEqual(parse_qs(update_url_query(
715 'http://example.com/path', {'bitrate': 5020.43})),
716 parse_qs('http://example.com/path?bitrate=5020.43'))
717 self.assertEqual(parse_qs(update_url_query(
718 'http://example.com/path', {'test': '第二行тест'})),
719 parse_qs('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
720
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
731 def test_dict_get(self):
732 FALSE_VALUES = {
733 'none': None,
734 'false': False,
735 'zero': 0,
736 'empty_string': '',
737 'empty_list': [],
738 }
739 d = FALSE_VALUES.copy()
740 d['a'] = 42
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)
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)
752
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
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
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)
772 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
773 self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
774 self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
775
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
781 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
782 d = json.loads(stripped)
783 self.assertEqual(d, {'STATUS': 'OK'})
784
785 stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
786 d = json.loads(stripped)
787 self.assertEqual(d, {'status': 'success'})
788
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'})
796
797 stripped = strip_jsonp('({"status": "success"});')
798 d = json.loads(stripped)
799 self.assertEqual(d, {'status': 'success'})
800
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
813 def test_uppercase_escape(self):
814 self.assertEqual(uppercase_escape('aä'), 'aä')
815 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
816
817 def test_lowercase_escape(self):
818 self.assertEqual(lowercase_escape('aä'), 'aä')
819 self.assertEqual(lowercase_escape('\\u0026'), '&')
820
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
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')
835 self.assertEqual(mimetype2ext('audio/x-wav'), 'wav')
836 self.assertEqual(mimetype2ext('audio/x-wav;codec=pcm'), 'wav')
837
838 def test_month_by_name(self):
839 self.assertEqual(month_by_name(None), None)
840 self.assertEqual(month_by_name('December', 'en'), 12)
841 self.assertEqual(month_by_name('décembre', 'fr'), 12)
842 self.assertEqual(month_by_name('December'), 12)
843 self.assertEqual(month_by_name('décembre'), None)
844 self.assertEqual(month_by_name('Unknown', 'unknown'), None)
845
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 })
868 self.assertEqual(parse_codecs('av01.0.05M.08'), {
869 'vcodec': 'av01.0.05M.08',
870 'acodec': 'none',
871 })
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'), {})
881
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://тест.рф/фрагмент'),
903 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
904 )
905 self.assertEqual(
906 escape_url('http://тест.рф/абв?абв=абв#абв'),
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'
908 )
909 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
910
911 def test_js_to_json_realworld(self):
912 inp = '''{
913 'clip':{'provider':'pseudo'}
914 }'''
915 self.assertEqual(js_to_json(inp), '''{
916 "clip":{"provider":"pseudo"}
917 }''')
918 json.loads(js_to_json(inp))
919
920 inp = '''{
921 'playlist':[{'controls':{'all':null}}]
922 }'''
923 self.assertEqual(js_to_json(inp), '''{
924 "playlist":[{"controls":{"all":null}}]
925 }''')
926
927 inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
928 self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
929
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
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
943 inp = '''{"foo":101}'''
944 self.assertEqual(js_to_json(inp), '''{"foo":101}''')
945
946 inp = '''{"duration": "00:01:07"}'''
947 self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
948
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
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
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
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
991 on = js_to_json('["abc", "def",]')
992 self.assertEqual(json.loads(on), ['abc', 'def'])
993
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
1000 on = js_to_json('{"abc": "def",}')
1001 self.assertEqual(json.loads(on), {'abc': 'def'})
1002
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
1006 on = js_to_json('{ 0: /* " \n */ ",]" , }')
1007 self.assertEqual(json.loads(on), {'0': ',]'})
1008
1009 on = js_to_json('{ /*comment\n*/0/*comment\n*/: /* " \n */ ",]" , }')
1010 self.assertEqual(json.loads(on), {'0': ',]'})
1011
1012 on = js_to_json('{ 0: // comment\n1 }')
1013 self.assertEqual(json.loads(on), {'0': 1})
1014
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
1024 on = js_to_json("/*comment\n*/[/*comment\n*/'a\\\nb'/*comment\n*/]/*comment\n*/")
1025 self.assertEqual(json.loads(on), ['ab'])
1026
1027 on = js_to_json('{0xff:0xff}')
1028 self.assertEqual(json.loads(on), {'255': 255})
1029
1030 on = js_to_json('{/*comment\n*/0xff/*comment\n*/:/*comment\n*/0xff/*comment\n*/}')
1031 self.assertEqual(json.loads(on), {'255': 255})
1032
1033 on = js_to_json('{077:077}')
1034 self.assertEqual(json.loads(on), {'63': 63})
1035
1036 on = js_to_json('{/*comment\n*/077/*comment\n*/:/*comment\n*/077/*comment\n*/}')
1037 self.assertEqual(json.loads(on), {'63': 63})
1038
1039 on = js_to_json('{42:42}')
1040 self.assertEqual(json.loads(on), {'42': 42})
1041
1042 on = js_to_json('{/*comment\n*/42/*comment\n*/:/*comment\n*/42/*comment\n*/}')
1043 self.assertEqual(json.loads(on), {'42': 42})
1044
1045 on = js_to_json('{42:4.2e1}')
1046 self.assertEqual(json.loads(on), {'42': 42.0})
1047
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
1054 on = js_to_json('[1,//{},\n2]')
1055 self.assertEqual(json.loads(on), [1, 2])
1056
1057 def test_js_to_json_malformed(self):
1058 self.assertEqual(js_to_json('42a1'), '42"a1"')
1059 self.assertEqual(js_to_json('42a-1'), '42"a"-1')
1060
1061 def test_extract_attributes(self):
1062 self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
1063 self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
1064 self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
1065 self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
1066 self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
1067 self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
1068 self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
1069 self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
1070 self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
1071 self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
1072 self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
1073 self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
1074 self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
1075 self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
1076 self.assertEqual(extract_attributes('<e x >'), {'x': None})
1077 self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
1078 self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
1079 self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
1080 self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
1081 self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
1082 self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
1083 self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
1084 self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
1085 self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
1086 self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
1087 self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
1088 self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
1089 self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
1090 # "Narrow" Python builds don't support unicode code points outside BMP.
1091 try:
1092 compat_chr(0x10000)
1093 supports_outside_bmp = True
1094 except ValueError:
1095 supports_outside_bmp = False
1096 if supports_outside_bmp:
1097 self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
1098 # Malformed HTML should not break attributes extraction on older Python
1099 self.assertEqual(extract_attributes('<mal"formed/>'), {})
1100
1101 def test_clean_html(self):
1102 self.assertEqual(clean_html('a:\nb'), 'a: b')
1103 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
1104 self.assertEqual(clean_html('a<br>\xa0b'), 'a\nb')
1105
1106 def test_intlist_to_bytes(self):
1107 self.assertEqual(
1108 intlist_to_bytes([0, 1, 127, 128, 255]),
1109 b'\x00\x01\x7f\x80\xff')
1110
1111 def test_args_to_str(self):
1112 self.assertEqual(
1113 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
1114 'foo ba/r -baz \'2 be\' \'\'' if compat_os_name != 'nt' else 'foo ba/r -baz "2 be" ""'
1115 )
1116
1117 def test_parse_filesize(self):
1118 self.assertEqual(parse_filesize(None), None)
1119 self.assertEqual(parse_filesize(''), None)
1120 self.assertEqual(parse_filesize('91 B'), 91)
1121 self.assertEqual(parse_filesize('foobar'), None)
1122 self.assertEqual(parse_filesize('2 MiB'), 2097152)
1123 self.assertEqual(parse_filesize('5 GB'), 5000000000)
1124 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
1125 self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
1126 self.assertEqual(parse_filesize('1,24 KB'), 1240)
1127 self.assertEqual(parse_filesize('1,24 kb'), 1240)
1128 self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
1129
1130 def test_parse_count(self):
1131 self.assertEqual(parse_count(None), None)
1132 self.assertEqual(parse_count(''), None)
1133 self.assertEqual(parse_count('0'), 0)
1134 self.assertEqual(parse_count('1000'), 1000)
1135 self.assertEqual(parse_count('1.000'), 1000)
1136 self.assertEqual(parse_count('1.1k'), 1100)
1137 self.assertEqual(parse_count('1.1kk'), 1100000)
1138 self.assertEqual(parse_count('1.1kk '), 1100000)
1139 self.assertEqual(parse_count('1.1kk views'), 1100000)
1140
1141 def test_parse_resolution(self):
1142 self.assertEqual(parse_resolution(None), {})
1143 self.assertEqual(parse_resolution(''), {})
1144 self.assertEqual(parse_resolution('1920x1080'), {'width': 1920, 'height': 1080})
1145 self.assertEqual(parse_resolution('1920×1080'), {'width': 1920, 'height': 1080})
1146 self.assertEqual(parse_resolution('1920 x 1080'), {'width': 1920, 'height': 1080})
1147 self.assertEqual(parse_resolution('720p'), {'height': 720})
1148 self.assertEqual(parse_resolution('4k'), {'height': 2160})
1149 self.assertEqual(parse_resolution('8K'), {'height': 4320})
1150
1151 def test_parse_bitrate(self):
1152 self.assertEqual(parse_bitrate(None), None)
1153 self.assertEqual(parse_bitrate(''), None)
1154 self.assertEqual(parse_bitrate('300kbps'), 300)
1155 self.assertEqual(parse_bitrate('1500kbps'), 1500)
1156 self.assertEqual(parse_bitrate('300 kbps'), 300)
1157
1158 def test_version_tuple(self):
1159 self.assertEqual(version_tuple('1'), (1,))
1160 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
1161 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
1162
1163 def test_detect_exe_version(self):
1164 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
1165 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
1166 configuration: --prefix=/usr --extra-'''), '1.2.1')
1167 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
1168 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
1169 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
1170 Trying to open render node...
1171 Success at /dev/dri/renderD128.
1172 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
1173
1174 def test_age_restricted(self):
1175 self.assertFalse(age_restricted(None, 10)) # unrestricted content
1176 self.assertFalse(age_restricted(1, None)) # unrestricted policy
1177 self.assertFalse(age_restricted(8, 10))
1178 self.assertTrue(age_restricted(18, 14))
1179 self.assertFalse(age_restricted(18, 18))
1180
1181 def test_is_html(self):
1182 self.assertFalse(is_html(b'\x49\x44\x43<html'))
1183 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
1184 self.assertTrue(is_html( # UTF-8 with BOM
1185 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
1186 self.assertTrue(is_html( # UTF-16-LE
1187 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
1188 ))
1189 self.assertTrue(is_html( # UTF-16-BE
1190 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
1191 ))
1192 self.assertTrue(is_html( # UTF-32-BE
1193 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'))
1194 self.assertTrue(is_html( # UTF-32-LE
1195 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'))
1196
1197 def test_render_table(self):
1198 self.assertEqual(
1199 render_table(
1200 ['a', 'bcd'],
1201 [[123, 4], [9999, 51]]),
1202 'a bcd\n'
1203 '123 4\n'
1204 '9999 51')
1205
1206 def test_match_str(self):
1207 # Unary
1208 self.assertFalse(match_str('xy', {'x': 1200}))
1209 self.assertTrue(match_str('!xy', {'x': 1200}))
1210 self.assertTrue(match_str('x', {'x': 1200}))
1211 self.assertFalse(match_str('!x', {'x': 1200}))
1212 self.assertTrue(match_str('x', {'x': 0}))
1213 self.assertTrue(match_str('is_live', {'is_live': True}))
1214 self.assertFalse(match_str('is_live', {'is_live': False}))
1215 self.assertFalse(match_str('is_live', {'is_live': None}))
1216 self.assertFalse(match_str('is_live', {}))
1217 self.assertFalse(match_str('!is_live', {'is_live': True}))
1218 self.assertTrue(match_str('!is_live', {'is_live': False}))
1219 self.assertTrue(match_str('!is_live', {'is_live': None}))
1220 self.assertTrue(match_str('!is_live', {}))
1221 self.assertTrue(match_str('title', {'title': 'abc'}))
1222 self.assertTrue(match_str('title', {'title': ''}))
1223 self.assertFalse(match_str('!title', {'title': 'abc'}))
1224 self.assertFalse(match_str('!title', {'title': ''}))
1225
1226 # Numeric
1227 self.assertFalse(match_str('x>0', {'x': 0}))
1228 self.assertFalse(match_str('x>0', {}))
1229 self.assertTrue(match_str('x>?0', {}))
1230 self.assertTrue(match_str('x>1K', {'x': 1200}))
1231 self.assertFalse(match_str('x>2K', {'x': 1200}))
1232 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
1233 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
1234 self.assertTrue(match_str('x > 1:0:0', {'x': 3700}))
1235
1236 # String
1237 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
1238 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
1239 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
1240 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
1241 self.assertTrue(match_str('y^=foo', {'y': 'foobar42'}))
1242 self.assertFalse(match_str('y!^=foo', {'y': 'foobar42'}))
1243 self.assertFalse(match_str('y^=bar', {'y': 'foobar42'}))
1244 self.assertTrue(match_str('y!^=bar', {'y': 'foobar42'}))
1245 self.assertRaises(ValueError, match_str, 'x^=42', {'x': 42})
1246 self.assertTrue(match_str('y*=bar', {'y': 'foobar42'}))
1247 self.assertFalse(match_str('y!*=bar', {'y': 'foobar42'}))
1248 self.assertFalse(match_str('y*=baz', {'y': 'foobar42'}))
1249 self.assertTrue(match_str('y!*=baz', {'y': 'foobar42'}))
1250 self.assertTrue(match_str('y$=42', {'y': 'foobar42'}))
1251 self.assertFalse(match_str('y$=43', {'y': 'foobar42'}))
1252
1253 # And
1254 self.assertFalse(match_str(
1255 'like_count > 100 & dislike_count <? 50 & description',
1256 {'like_count': 90, 'description': 'foo'}))
1257 self.assertTrue(match_str(
1258 'like_count > 100 & dislike_count <? 50 & description',
1259 {'like_count': 190, 'description': 'foo'}))
1260 self.assertFalse(match_str(
1261 'like_count > 100 & dislike_count <? 50 & description',
1262 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
1263 self.assertFalse(match_str(
1264 'like_count > 100 & dislike_count <? 50 & description',
1265 {'like_count': 190, 'dislike_count': 10}))
1266
1267 # Regex
1268 self.assertTrue(match_str(r'x~=\bbar', {'x': 'foo bar'}))
1269 self.assertFalse(match_str(r'x~=\bbar.+', {'x': 'foo bar'}))
1270 self.assertFalse(match_str(r'x~=^FOO', {'x': 'foo bar'}))
1271 self.assertTrue(match_str(r'x~=(?i)^FOO', {'x': 'foo bar'}))
1272
1273 # Quotes
1274 self.assertTrue(match_str(r'x^="foo"', {'x': 'foo "bar"'}))
1275 self.assertFalse(match_str(r'x^="foo "', {'x': 'foo "bar"'}))
1276 self.assertFalse(match_str(r'x$="bar"', {'x': 'foo "bar"'}))
1277 self.assertTrue(match_str(r'x$=" \"bar\""', {'x': 'foo "bar"'}))
1278
1279 # Escaping &
1280 self.assertFalse(match_str(r'x=foo & bar', {'x': 'foo & bar'}))
1281 self.assertTrue(match_str(r'x=foo \& bar', {'x': 'foo & bar'}))
1282 self.assertTrue(match_str(r'x=foo \& bar & x^=foo', {'x': 'foo & bar'}))
1283 self.assertTrue(match_str(r'x="foo \& bar" & x^=foo', {'x': 'foo & bar'}))
1284
1285 # Example from docs
1286 self.assertTrue(match_str(
1287 r"!is_live & like_count>?100 & description~='(?i)\bcats \& dogs\b'",
1288 {'description': 'Raining Cats & Dogs'}))
1289
1290 # Incomplete
1291 self.assertFalse(match_str('id!=foo', {'id': 'foo'}, True))
1292 self.assertTrue(match_str('x', {'id': 'foo'}, True))
1293 self.assertTrue(match_str('!x', {'id': 'foo'}, True))
1294 self.assertFalse(match_str('x', {'id': 'foo'}, False))
1295
1296 def test_parse_dfxp_time_expr(self):
1297 self.assertEqual(parse_dfxp_time_expr(None), None)
1298 self.assertEqual(parse_dfxp_time_expr(''), None)
1299 self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
1300 self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
1301 self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
1302 self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
1303 self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
1304
1305 def test_dfxp2srt(self):
1306 dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
1307 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1308 <body>
1309 <div xml:lang="en">
1310 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
1311 <p begin="1" end="2">第二行<br/>♪♪</p>
1312 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
1313 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
1314 <p begin="-1" end="-1">Ignore, two</p>
1315 <p begin="3" dur="-1">Ignored, three</p>
1316 </div>
1317 </body>
1318 </tt>'''.encode('utf-8')
1319 srt_data = '''1
1320 00:00:00,000 --> 00:00:01,000
1321 The following line contains Chinese characters and special symbols
1322
1323 2
1324 00:00:01,000 --> 00:00:02,000
1325 第二行
1326 ♪♪
1327
1328 3
1329 00:00:02,000 --> 00:00:03,000
1330 Third
1331 Line
1332
1333 '''
1334 self.assertEqual(dfxp2srt(dfxp_data), srt_data)
1335
1336 dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
1337 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1338 <body>
1339 <div xml:lang="en">
1340 <p begin="0" end="1">The first line</p>
1341 </div>
1342 </body>
1343 </tt>'''.encode('utf-8')
1344 srt_data = '''1
1345 00:00:00,000 --> 00:00:01,000
1346 The first line
1347
1348 '''
1349 self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
1350
1351 dfxp_data_with_style = '''<?xml version="1.0" encoding="utf-8"?>
1352 <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">
1353 <head>
1354 <styling>
1355 <style id="s2" style="s0" tts:color="cyan" tts:fontWeight="bold" />
1356 <style id="s1" style="s0" tts:color="yellow" tts:fontStyle="italic" />
1357 <style id="s3" style="s0" tts:color="lime" tts:textDecoration="underline" />
1358 <style id="s0" tts:backgroundColor="black" tts:fontStyle="normal" tts:fontSize="16" tts:fontFamily="sansSerif" tts:color="white" />
1359 </styling>
1360 </head>
1361 <body tts:textAlign="center" style="s0">
1362 <div>
1363 <p begin="00:00:02.08" id="p0" end="00:00:05.84">default style<span tts:color="red">custom style</span></p>
1364 <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>
1365 <p style="s3" begin="00:00:05.84" id="p1" end="00:00:09.56">line 3<br />part 3</p>
1366 <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>
1367 </div>
1368 </body>
1369 </tt>'''.encode('utf-8')
1370 srt_data = '''1
1371 00:00:02,080 --> 00:00:05,839
1372 <font color="white" face="sansSerif" size="16">default style<font color="red">custom style</font></font>
1373
1374 2
1375 00:00:02,080 --> 00:00:05,839
1376 <b><font color="cyan" face="sansSerif" size="16"><font color="lime">part 1
1377 </font>part 2</font></b>
1378
1379 3
1380 00:00:05,839 --> 00:00:09,560
1381 <u><font color="lime">line 3
1382 part 3</font></u>
1383
1384 4
1385 00:00:09,560 --> 00:00:12,359
1386 <i><u><font color="yellow"><font color="lime">inner
1387 </font>style</font></u></i>
1388
1389 '''
1390 self.assertEqual(dfxp2srt(dfxp_data_with_style), srt_data)
1391
1392 dfxp_data_non_utf8 = '''<?xml version="1.0" encoding="UTF-16"?>
1393 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
1394 <body>
1395 <div xml:lang="en">
1396 <p begin="0" end="1">Line 1</p>
1397 <p begin="1" end="2">第二行</p>
1398 </div>
1399 </body>
1400 </tt>'''.encode('utf-16')
1401 srt_data = '''1
1402 00:00:00,000 --> 00:00:01,000
1403 Line 1
1404
1405 2
1406 00:00:01,000 --> 00:00:02,000
1407 第二行
1408
1409 '''
1410 self.assertEqual(dfxp2srt(dfxp_data_non_utf8), srt_data)
1411
1412 def test_cli_option(self):
1413 self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
1414 self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
1415 self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
1416 self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
1417
1418 def test_cli_valueless_option(self):
1419 self.assertEqual(cli_valueless_option(
1420 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
1421 self.assertEqual(cli_valueless_option(
1422 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
1423 self.assertEqual(cli_valueless_option(
1424 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
1425 self.assertEqual(cli_valueless_option(
1426 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
1427 self.assertEqual(cli_valueless_option(
1428 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
1429 self.assertEqual(cli_valueless_option(
1430 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
1431
1432 def test_cli_bool_option(self):
1433 self.assertEqual(
1434 cli_bool_option(
1435 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
1436 ['--no-check-certificate', 'true'])
1437 self.assertEqual(
1438 cli_bool_option(
1439 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
1440 ['--no-check-certificate=true'])
1441 self.assertEqual(
1442 cli_bool_option(
1443 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1444 ['--check-certificate', 'false'])
1445 self.assertEqual(
1446 cli_bool_option(
1447 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1448 ['--check-certificate=false'])
1449 self.assertEqual(
1450 cli_bool_option(
1451 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1452 ['--check-certificate', 'true'])
1453 self.assertEqual(
1454 cli_bool_option(
1455 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1456 ['--check-certificate=true'])
1457 self.assertEqual(
1458 cli_bool_option(
1459 {}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1460 [])
1461
1462 def test_ohdave_rsa_encrypt(self):
1463 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
1464 e = 65537
1465
1466 self.assertEqual(
1467 ohdave_rsa_encrypt(b'aa111222', e, N),
1468 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
1469
1470 def test_pkcs1pad(self):
1471 data = [1, 2, 3]
1472 padded_data = pkcs1pad(data, 32)
1473 self.assertEqual(padded_data[:2], [0, 2])
1474 self.assertEqual(padded_data[28:], [0, 1, 2, 3])
1475
1476 self.assertRaises(ValueError, pkcs1pad, data, 8)
1477
1478 def test_encode_base_n(self):
1479 self.assertEqual(encode_base_n(0, 30), '0')
1480 self.assertEqual(encode_base_n(80, 30), '2k')
1481
1482 custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
1483 self.assertEqual(encode_base_n(0, 30, custom_table), '9')
1484 self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
1485
1486 self.assertRaises(ValueError, encode_base_n, 0, 70)
1487 self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
1488
1489 def test_caesar(self):
1490 self.assertEqual(caesar('ace', 'abcdef', 2), 'cea')
1491 self.assertEqual(caesar('cea', 'abcdef', -2), 'ace')
1492 self.assertEqual(caesar('ace', 'abcdef', -2), 'eac')
1493 self.assertEqual(caesar('eac', 'abcdef', 2), 'ace')
1494 self.assertEqual(caesar('ace', 'abcdef', 0), 'ace')
1495 self.assertEqual(caesar('xyz', 'abcdef', 2), 'xyz')
1496 self.assertEqual(caesar('abc', 'acegik', 2), 'ebg')
1497 self.assertEqual(caesar('ebg', 'acegik', -2), 'abc')
1498
1499 def test_rot47(self):
1500 self.assertEqual(rot47('yt-dlp'), r'JE\5=A')
1501 self.assertEqual(rot47('YT-DLP'), r'*%\s{!')
1502
1503 def test_urshift(self):
1504 self.assertEqual(urshift(3, 1), 1)
1505 self.assertEqual(urshift(-3, 1), 2147483646)
1506
1507 def test_get_element_by_class(self):
1508 html = '''
1509 <span class="foo bar">nice</span>
1510 '''
1511
1512 self.assertEqual(get_element_by_class('foo', html), 'nice')
1513 self.assertEqual(get_element_by_class('no-such-class', html), None)
1514
1515 def test_get_element_by_attribute(self):
1516 html = '''
1517 <span class="foo bar">nice</span>
1518 '''
1519
1520 self.assertEqual(get_element_by_attribute('class', 'foo bar', html), 'nice')
1521 self.assertEqual(get_element_by_attribute('class', 'foo', html), None)
1522 self.assertEqual(get_element_by_attribute('class', 'no-such-foo', html), None)
1523
1524 html = '''
1525 <div itemprop="author" itemscope>foo</div>
1526 '''
1527
1528 self.assertEqual(get_element_by_attribute('itemprop', 'author', html), 'foo')
1529
1530 def test_get_elements_by_class(self):
1531 html = '''
1532 <span class="foo bar">nice</span><span class="foo bar">also nice</span>
1533 '''
1534
1535 self.assertEqual(get_elements_by_class('foo', html), ['nice', 'also nice'])
1536 self.assertEqual(get_elements_by_class('no-such-class', html), [])
1537
1538 def test_get_elements_by_attribute(self):
1539 html = '''
1540 <span class="foo bar">nice</span><span class="foo bar">also nice</span>
1541 '''
1542
1543 self.assertEqual(get_elements_by_attribute('class', 'foo bar', html), ['nice', 'also nice'])
1544 self.assertEqual(get_elements_by_attribute('class', 'foo', html), [])
1545 self.assertEqual(get_elements_by_attribute('class', 'no-such-foo', html), [])
1546
1547 def test_iri_to_uri(self):
1548 self.assertEqual(
1549 iri_to_uri('https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b'),
1550 'https://www.google.com/search?q=foo&ie=utf-8&oe=utf-8&client=firefox-b') # Same
1551 self.assertEqual(
1552 iri_to_uri('https://www.google.com/search?q=Käsesoßenrührlöffel'), # German for cheese sauce stirring spoon
1553 'https://www.google.com/search?q=K%C3%A4seso%C3%9Fenr%C3%BChrl%C3%B6ffel')
1554 self.assertEqual(
1555 iri_to_uri('https://www.google.com/search?q=lt<+gt>+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#'),
1556 'https://www.google.com/search?q=lt%3C+gt%3E+eq%3D+amp%26+percent%25+hash%23+colon%3A+tilde~#trash=?&garbage=#')
1557 self.assertEqual(
1558 iri_to_uri('http://правозащита38.рф/category/news/'),
1559 'http://xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
1560 self.assertEqual(
1561 iri_to_uri('http://www.правозащита38.рф/category/news/'),
1562 'http://www.xn--38-6kcaak9aj5chl4a3g.xn--p1ai/category/news/')
1563 self.assertEqual(
1564 iri_to_uri('https://i❤.ws/emojidomain/👍👏🤝💪'),
1565 'https://xn--i-7iq.ws/emojidomain/%F0%9F%91%8D%F0%9F%91%8F%F0%9F%A4%9D%F0%9F%92%AA')
1566 self.assertEqual(
1567 iri_to_uri('http://日本語.jp/'),
1568 'http://xn--wgv71a119e.jp/')
1569 self.assertEqual(
1570 iri_to_uri('http://导航.中国/'),
1571 'http://xn--fet810g.xn--fiqs8s/')
1572
1573 def test_clean_podcast_url(self):
1574 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')
1575 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')
1576
1577 def test_LazyList(self):
1578 it = list(range(10))
1579
1580 self.assertEqual(list(LazyList(it)), it)
1581 self.assertEqual(LazyList(it).exhaust(), it)
1582 self.assertEqual(LazyList(it)[5], it[5])
1583
1584 self.assertEqual(LazyList(it)[5:], it[5:])
1585 self.assertEqual(LazyList(it)[:5], it[:5])
1586 self.assertEqual(LazyList(it)[::2], it[::2])
1587 self.assertEqual(LazyList(it)[1::2], it[1::2])
1588 self.assertEqual(LazyList(it)[5::-1], it[5::-1])
1589 self.assertEqual(LazyList(it)[6:2:-2], it[6:2:-2])
1590 self.assertEqual(LazyList(it)[::-1], it[::-1])
1591
1592 self.assertTrue(LazyList(it))
1593 self.assertFalse(LazyList(range(0)))
1594 self.assertEqual(len(LazyList(it)), len(it))
1595 self.assertEqual(repr(LazyList(it)), repr(it))
1596 self.assertEqual(str(LazyList(it)), str(it))
1597
1598 self.assertEqual(list(LazyList(it).reverse()), it[::-1])
1599 self.assertEqual(list(LazyList(it).reverse()[1:3:7]), it[::-1][1:3:7])
1600 self.assertEqual(list(LazyList(it).reverse()[::-1]), it)
1601
1602 def test_LazyList_laziness(self):
1603
1604 def test(ll, idx, val, cache):
1605 self.assertEqual(ll[idx], val)
1606 self.assertEqual(getattr(ll, '_LazyList__cache'), list(cache))
1607
1608 ll = LazyList(range(10))
1609 test(ll, 0, 0, range(1))
1610 test(ll, 5, 5, range(6))
1611 test(ll, -3, 7, range(10))
1612
1613 ll = LazyList(range(10)).reverse()
1614 test(ll, -1, 0, range(1))
1615 test(ll, 3, 6, range(10))
1616
1617 ll = LazyList(itertools.count())
1618 test(ll, 10, 10, range(11))
1619 ll.reverse()
1620 test(ll, -15, 14, range(15))
1621
1622
1623 if __name__ == '__main__':
1624 unittest.main()