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