]> Raphaël G. Git Repositories - youtubedl/blob - test/test_utils.py
2e3cd0179db9dd97792fafa695f7e7a043542a38
[youtubedl] / 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 youtube_dl.utils import (
19 age_restricted,
20 args_to_str,
21 encode_base_n,
22 clean_html,
23 date_from_str,
24 DateRange,
25 detect_exe_version,
26 determine_ext,
27 dict_get,
28 encode_compat_str,
29 encodeFilename,
30 escape_rfc3986,
31 escape_url,
32 extract_attributes,
33 ExtractorError,
34 find_xpath_attr,
35 fix_xml_ampersands,
36 get_element_by_class,
37 InAdvancePagedList,
38 intlist_to_bytes,
39 is_html,
40 js_to_json,
41 limit_length,
42 mimetype2ext,
43 month_by_name,
44 ohdave_rsa_encrypt,
45 OnDemandPagedList,
46 orderedSet,
47 parse_age_limit,
48 parse_duration,
49 parse_filesize,
50 parse_count,
51 parse_iso8601,
52 read_batch_urls,
53 sanitize_filename,
54 sanitize_path,
55 prepend_extension,
56 replace_extension,
57 remove_start,
58 remove_end,
59 remove_quotes,
60 shell_quote,
61 smuggle_url,
62 str_to_int,
63 strip_jsonp,
64 timeconvert,
65 unescapeHTML,
66 unified_strdate,
67 unified_timestamp,
68 unsmuggle_url,
69 uppercase_escape,
70 lowercase_escape,
71 url_basename,
72 base_url,
73 urlencode_postdata,
74 urshift,
75 update_url_query,
76 version_tuple,
77 xpath_with_ns,
78 xpath_element,
79 xpath_text,
80 xpath_attr,
81 render_table,
82 match_str,
83 parse_dfxp_time_expr,
84 dfxp2srt,
85 cli_option,
86 cli_valueless_option,
87 cli_bool_option,
88 parse_codecs,
89 )
90 from youtube_dl.compat import (
91 compat_chr,
92 compat_etree_fromstring,
93 compat_urlparse,
94 compat_parse_qs,
95 )
96
97
98 class TestUtil(unittest.TestCase):
99 def test_timeconvert(self):
100 self.assertTrue(timeconvert('') is None)
101 self.assertTrue(timeconvert('bougrg') is None)
102
103 def test_sanitize_filename(self):
104 self.assertEqual(sanitize_filename('abc'), 'abc')
105 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
106
107 self.assertEqual(sanitize_filename('123'), '123')
108
109 self.assertEqual('abc_de', sanitize_filename('abc/de'))
110 self.assertFalse('/' in sanitize_filename('abc/de///'))
111
112 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
113 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
114 self.assertEqual('yes no', sanitize_filename('yes? no'))
115 self.assertEqual('this - that', sanitize_filename('this: that'))
116
117 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
118 aumlaut = 'ä'
119 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
120 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
121 self.assertEqual(sanitize_filename(tests), tests)
122
123 self.assertEqual(
124 sanitize_filename('New World record at 0:12:34'),
125 'New World record at 0_12_34')
126
127 self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
128 self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
129 self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
130 self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
131
132 forbidden = '"\0\\/'
133 for fc in forbidden:
134 for fbc in forbidden:
135 self.assertTrue(fbc not in sanitize_filename(fc))
136
137 def test_sanitize_filename_restricted(self):
138 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
139 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
140
141 self.assertEqual(sanitize_filename('123', restricted=True), '123')
142
143 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
144 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
145
146 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
147 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
148 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
149 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
150
151 tests = 'aäb\u4e2d\u56fd\u7684c'
152 self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
153 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
154
155 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
156 for fc in forbidden:
157 for fbc in forbidden:
158 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
159
160 # Handle a common case more neatly
161 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
162 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
163 # .. but make sure the file name is never empty
164 self.assertTrue(sanitize_filename('-', restricted=True) != '')
165 self.assertTrue(sanitize_filename(':', restricted=True) != '')
166
167 self.assertEqual(sanitize_filename(
168 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
169 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYPssaaaaaaaeceeeeiiiionooooooooeuuuuuypy')
170
171 def test_sanitize_ids(self):
172 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
173 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
174 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
175
176 def test_sanitize_path(self):
177 if sys.platform != 'win32':
178 return
179
180 self.assertEqual(sanitize_path('abc'), 'abc')
181 self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
182 self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
183 self.assertEqual(sanitize_path('abc|def'), 'abc#def')
184 self.assertEqual(sanitize_path('<>:"|?*'), '#######')
185 self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
186 self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
187
188 self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
189 self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
190
191 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
192 self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
193 self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
194 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
195
196 self.assertEqual(
197 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
198 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
199
200 self.assertEqual(
201 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
202 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
203 self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
204 self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
205 self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
206
207 self.assertEqual(sanitize_path('../abc'), '..\\abc')
208 self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
209 self.assertEqual(sanitize_path('./abc'), 'abc')
210 self.assertEqual(sanitize_path('./../abc'), '..\\abc')
211
212 def test_prepend_extension(self):
213 self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
214 self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
215 self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
216 self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
217 self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
218 self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
219
220 def test_replace_extension(self):
221 self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
222 self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
223 self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
224 self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
225 self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
226 self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
227
228 def test_remove_start(self):
229 self.assertEqual(remove_start(None, 'A - '), None)
230 self.assertEqual(remove_start('A - B', 'A - '), 'B')
231 self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
232
233 def test_remove_end(self):
234 self.assertEqual(remove_end(None, ' - B'), None)
235 self.assertEqual(remove_end('A - B', ' - B'), 'A')
236 self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
237
238 def test_remove_quotes(self):
239 self.assertEqual(remove_quotes(None), None)
240 self.assertEqual(remove_quotes('"'), '"')
241 self.assertEqual(remove_quotes("'"), "'")
242 self.assertEqual(remove_quotes(';'), ';')
243 self.assertEqual(remove_quotes('";'), '";')
244 self.assertEqual(remove_quotes('""'), '')
245 self.assertEqual(remove_quotes('";"'), ';')
246
247 def test_ordered_set(self):
248 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
249 self.assertEqual(orderedSet([]), [])
250 self.assertEqual(orderedSet([1]), [1])
251 # keep the list ordered
252 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
253
254 def test_unescape_html(self):
255 self.assertEqual(unescapeHTML('%20;'), '%20;')
256 self.assertEqual(unescapeHTML('&#x2F;'), '/')
257 self.assertEqual(unescapeHTML('&#47;'), '/')
258 self.assertEqual(unescapeHTML('&eacute;'), 'é')
259 self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
260 # HTML5 entities
261 self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
262
263 def test_date_from_str(self):
264 self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
265 self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
266 self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
267 self.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
268 self.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
269
270 def test_daterange(self):
271 _20century = DateRange("19000101", "20000101")
272 self.assertFalse("17890714" in _20century)
273 _ac = DateRange("00010101")
274 self.assertTrue("19690721" in _ac)
275 _firstmilenium = DateRange(end="10000101")
276 self.assertTrue("07110427" in _firstmilenium)
277
278 def test_unified_dates(self):
279 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
280 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
281 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
282 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
283 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
284 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
285 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
286 self.assertEqual(
287 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
288 '20141126')
289 self.assertEqual(
290 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
291 '20150202')
292 self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
293 self.assertEqual(unified_strdate('25-09-2014'), '20140925')
294 self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
295 self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
296 self.assertEqual(unified_strdate('Feb 7, 2016 at 6:35 pm'), '20160207')
297
298 def test_unified_timestamps(self):
299 self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
300 self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
301 self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
302 self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
303 self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
304 self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
305 self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
306 self.assertEqual(
307 unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
308 1417001400)
309 self.assertEqual(
310 unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
311 1422902860)
312 self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
313 self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
314 self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
315 self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
316 self.assertEqual(unified_timestamp('May 16, 2016 11:15 PM'), 1463440500)
317 self.assertEqual(unified_timestamp('Feb 7, 2016 at 6:35 pm'), 1454870100)
318
319 def test_determine_ext(self):
320 self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
321 self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
322 self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
323 self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
324 self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
325
326 def test_find_xpath_attr(self):
327 testxml = '''<root>
328 <node/>
329 <node x="a"/>
330 <node x="a" y="c" />
331 <node x="b" y="d" />
332 <node x="" />
333 </root>'''
334 doc = compat_etree_fromstring(testxml)
335
336 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
337 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
338 self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
339 self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
340 self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
341 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
342 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
343 self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
344 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
345 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
346 self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
347
348 def test_xpath_with_ns(self):
349 testxml = '''<root xmlns:media="http://example.com/">
350 <media:song>
351 <media:author>The Author</media:author>
352 <url>http://server.com/download.mp3</url>
353 </media:song>
354 </root>'''
355 doc = compat_etree_fromstring(testxml)
356 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
357 self.assertTrue(find('media:song') is not None)
358 self.assertEqual(find('media:song/media:author').text, 'The Author')
359 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
360
361 def test_xpath_element(self):
362 doc = xml.etree.ElementTree.Element('root')
363 div = xml.etree.ElementTree.SubElement(doc, 'div')
364 p = xml.etree.ElementTree.SubElement(div, 'p')
365 p.text = 'Foo'
366 self.assertEqual(xpath_element(doc, 'div/p'), p)
367 self.assertEqual(xpath_element(doc, ['div/p']), p)
368 self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
369 self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
370 self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
371 self.assertTrue(xpath_element(doc, 'div/bar') is None)
372 self.assertTrue(xpath_element(doc, ['div/bar']) is None)
373 self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
374 self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
375 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
376 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
377
378 def test_xpath_text(self):
379 testxml = '''<root>
380 <div>
381 <p>Foo</p>
382 </div>
383 </root>'''
384 doc = compat_etree_fromstring(testxml)
385 self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
386 self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
387 self.assertTrue(xpath_text(doc, 'div/bar') is None)
388 self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
389
390 def test_xpath_attr(self):
391 testxml = '''<root>
392 <div>
393 <p x="a">Foo</p>
394 </div>
395 </root>'''
396 doc = compat_etree_fromstring(testxml)
397 self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
398 self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
399 self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
400 self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
401 self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
402 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
403 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
404
405 def test_smuggle_url(self):
406 data = {"ö": "ö", "abc": [3]}
407 url = 'https://foo.bar/baz?x=y#a'
408 smug_url = smuggle_url(url, data)
409 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
410 self.assertEqual(url, unsmug_url)
411 self.assertEqual(data, unsmug_data)
412
413 res_url, res_data = unsmuggle_url(url)
414 self.assertEqual(res_url, url)
415 self.assertEqual(res_data, None)
416
417 smug_url = smuggle_url(url, {'a': 'b'})
418 smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
419 res_url, res_data = unsmuggle_url(smug_smug_url)
420 self.assertEqual(res_url, url)
421 self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
422
423 def test_shell_quote(self):
424 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
425 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
426
427 def test_str_to_int(self):
428 self.assertEqual(str_to_int('123,456'), 123456)
429 self.assertEqual(str_to_int('123.456'), 123456)
430
431 def test_url_basename(self):
432 self.assertEqual(url_basename('http://foo.de/'), '')
433 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
434 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
435 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
436 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
437 self.assertEqual(
438 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
439 'trailer.mp4')
440
441 def test_base_url(self):
442 self.assertEqual(base_url('http://foo.de/'), 'http://foo.de/')
443 self.assertEqual(base_url('http://foo.de/bar'), 'http://foo.de/')
444 self.assertEqual(base_url('http://foo.de/bar/'), 'http://foo.de/bar/')
445 self.assertEqual(base_url('http://foo.de/bar/baz'), 'http://foo.de/bar/')
446 self.assertEqual(base_url('http://foo.de/bar/baz?x=z/x/c'), 'http://foo.de/bar/')
447
448 def test_parse_age_limit(self):
449 self.assertEqual(parse_age_limit(None), None)
450 self.assertEqual(parse_age_limit(False), None)
451 self.assertEqual(parse_age_limit('invalid'), None)
452 self.assertEqual(parse_age_limit(0), 0)
453 self.assertEqual(parse_age_limit(18), 18)
454 self.assertEqual(parse_age_limit(21), 21)
455 self.assertEqual(parse_age_limit(22), None)
456 self.assertEqual(parse_age_limit('18'), 18)
457 self.assertEqual(parse_age_limit('18+'), 18)
458 self.assertEqual(parse_age_limit('PG-13'), 13)
459 self.assertEqual(parse_age_limit('TV-14'), 14)
460 self.assertEqual(parse_age_limit('TV-MA'), 17)
461
462 def test_parse_duration(self):
463 self.assertEqual(parse_duration(None), None)
464 self.assertEqual(parse_duration(False), None)
465 self.assertEqual(parse_duration('invalid'), None)
466 self.assertEqual(parse_duration('1'), 1)
467 self.assertEqual(parse_duration('1337:12'), 80232)
468 self.assertEqual(parse_duration('9:12:43'), 33163)
469 self.assertEqual(parse_duration('12:00'), 720)
470 self.assertEqual(parse_duration('00:01:01'), 61)
471 self.assertEqual(parse_duration('x:y'), None)
472 self.assertEqual(parse_duration('3h11m53s'), 11513)
473 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
474 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
475 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
476 self.assertEqual(parse_duration('62m45s'), 3765)
477 self.assertEqual(parse_duration('6m59s'), 419)
478 self.assertEqual(parse_duration('49s'), 49)
479 self.assertEqual(parse_duration('0h0m0s'), 0)
480 self.assertEqual(parse_duration('0m0s'), 0)
481 self.assertEqual(parse_duration('0s'), 0)
482 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
483 self.assertEqual(parse_duration('T30M38S'), 1838)
484 self.assertEqual(parse_duration('5 s'), 5)
485 self.assertEqual(parse_duration('3 min'), 180)
486 self.assertEqual(parse_duration('2.5 hours'), 9000)
487 self.assertEqual(parse_duration('02:03:04'), 7384)
488 self.assertEqual(parse_duration('01:02:03:04'), 93784)
489 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
490 self.assertEqual(parse_duration('87 Min.'), 5220)
491 self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
492
493 def test_fix_xml_ampersands(self):
494 self.assertEqual(
495 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
496 self.assertEqual(
497 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
498 '"&amp;x=y&amp;wrong;&amp;z=a')
499 self.assertEqual(
500 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
501 '&amp;&apos;&gt;&lt;&quot;')
502 self.assertEqual(
503 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
504 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
505
506 def test_paged_list(self):
507 def testPL(size, pagesize, sliceargs, expected):
508 def get_page(pagenum):
509 firstid = pagenum * pagesize
510 upto = min(size, pagenum * pagesize + pagesize)
511 for i in range(firstid, upto):
512 yield i
513
514 pl = OnDemandPagedList(get_page, pagesize)
515 got = pl.getslice(*sliceargs)
516 self.assertEqual(got, expected)
517
518 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
519 got = iapl.getslice(*sliceargs)
520 self.assertEqual(got, expected)
521
522 testPL(5, 2, (), [0, 1, 2, 3, 4])
523 testPL(5, 2, (1,), [1, 2, 3, 4])
524 testPL(5, 2, (2,), [2, 3, 4])
525 testPL(5, 2, (4,), [4])
526 testPL(5, 2, (0, 3), [0, 1, 2])
527 testPL(5, 2, (1, 4), [1, 2, 3])
528 testPL(5, 2, (2, 99), [2, 3, 4])
529 testPL(5, 2, (20, 99), [])
530
531 def test_read_batch_urls(self):
532 f = io.StringIO('''\xef\xbb\xbf foo
533 bar\r
534 baz
535 # More after this line\r
536 ; or after this
537 bam''')
538 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
539
540 def test_urlencode_postdata(self):
541 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
542 self.assertTrue(isinstance(data, bytes))
543
544 def test_update_url_query(self):
545 def query_dict(url):
546 return compat_parse_qs(compat_urlparse.urlparse(url).query)
547 self.assertEqual(query_dict(update_url_query(
548 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
549 query_dict('http://example.com/path?quality=HD&format=mp4'))
550 self.assertEqual(query_dict(update_url_query(
551 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
552 query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
553 self.assertEqual(query_dict(update_url_query(
554 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
555 query_dict('http://example.com/path?fields=id,formats,subtitles'))
556 self.assertEqual(query_dict(update_url_query(
557 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
558 query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
559 self.assertEqual(query_dict(update_url_query(
560 'http://example.com/path?manifest=f4m', {'manifest': []})),
561 query_dict('http://example.com/path'))
562 self.assertEqual(query_dict(update_url_query(
563 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
564 query_dict('http://example.com/path?system=LINUX'))
565 self.assertEqual(query_dict(update_url_query(
566 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
567 query_dict('http://example.com/path?fields=id,formats,subtitles'))
568 self.assertEqual(query_dict(update_url_query(
569 'http://example.com/path', {'width': 1080, 'height': 720})),
570 query_dict('http://example.com/path?width=1080&height=720'))
571 self.assertEqual(query_dict(update_url_query(
572 'http://example.com/path', {'bitrate': 5020.43})),
573 query_dict('http://example.com/path?bitrate=5020.43'))
574 self.assertEqual(query_dict(update_url_query(
575 'http://example.com/path', {'test': '第二行тест'})),
576 query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
577
578 def test_dict_get(self):
579 FALSE_VALUES = {
580 'none': None,
581 'false': False,
582 'zero': 0,
583 'empty_string': '',
584 'empty_list': [],
585 }
586 d = FALSE_VALUES.copy()
587 d['a'] = 42
588 self.assertEqual(dict_get(d, 'a'), 42)
589 self.assertEqual(dict_get(d, 'b'), None)
590 self.assertEqual(dict_get(d, 'b', 42), 42)
591 self.assertEqual(dict_get(d, ('a', )), 42)
592 self.assertEqual(dict_get(d, ('b', 'a', )), 42)
593 self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
594 self.assertEqual(dict_get(d, ('b', 'c', )), None)
595 self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
596 for key, false_value in FALSE_VALUES.items():
597 self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
598 self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
599
600 def test_encode_compat_str(self):
601 self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
602 self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
603
604 def test_parse_iso8601(self):
605 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
606 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
607 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
608 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
609 self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
610 self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
611
612 def test_strip_jsonp(self):
613 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
614 d = json.loads(stripped)
615 self.assertEqual(d, [{"id": "532cb", "x": 3}])
616
617 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
618 d = json.loads(stripped)
619 self.assertEqual(d, {'STATUS': 'OK'})
620
621 stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
622 d = json.loads(stripped)
623 self.assertEqual(d, {'status': 'success'})
624
625 def test_uppercase_escape(self):
626 self.assertEqual(uppercase_escape('aä'), 'aä')
627 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
628
629 def test_lowercase_escape(self):
630 self.assertEqual(lowercase_escape('aä'), 'aä')
631 self.assertEqual(lowercase_escape('\\u0026'), '&')
632
633 def test_limit_length(self):
634 self.assertEqual(limit_length(None, 12), None)
635 self.assertEqual(limit_length('foo', 12), 'foo')
636 self.assertTrue(
637 limit_length('foo bar baz asd', 12).startswith('foo bar'))
638 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
639
640 def test_mimetype2ext(self):
641 self.assertEqual(mimetype2ext(None), None)
642 self.assertEqual(mimetype2ext('video/x-flv'), 'flv')
643 self.assertEqual(mimetype2ext('application/x-mpegURL'), 'm3u8')
644 self.assertEqual(mimetype2ext('text/vtt'), 'vtt')
645 self.assertEqual(mimetype2ext('text/vtt;charset=utf-8'), 'vtt')
646 self.assertEqual(mimetype2ext('text/html; charset=utf-8'), 'html')
647
648 def test_month_by_name(self):
649 self.assertEqual(month_by_name(None), None)
650 self.assertEqual(month_by_name('December', 'en'), 12)
651 self.assertEqual(month_by_name('décembre', 'fr'), 12)
652 self.assertEqual(month_by_name('December'), 12)
653 self.assertEqual(month_by_name('décembre'), None)
654 self.assertEqual(month_by_name('Unknown', 'unknown'), None)
655
656 def test_parse_codecs(self):
657 self.assertEqual(parse_codecs(''), {})
658 self.assertEqual(parse_codecs('avc1.77.30, mp4a.40.2'), {
659 'vcodec': 'avc1.77.30',
660 'acodec': 'mp4a.40.2',
661 })
662 self.assertEqual(parse_codecs('mp4a.40.2'), {
663 'vcodec': 'none',
664 'acodec': 'mp4a.40.2',
665 })
666 self.assertEqual(parse_codecs('mp4a.40.5,avc1.42001e'), {
667 'vcodec': 'avc1.42001e',
668 'acodec': 'mp4a.40.5',
669 })
670 self.assertEqual(parse_codecs('avc3.640028'), {
671 'vcodec': 'avc3.640028',
672 'acodec': 'none',
673 })
674 self.assertEqual(parse_codecs(', h264,,newcodec,aac'), {
675 'vcodec': 'h264',
676 'acodec': 'aac',
677 })
678
679 def test_escape_rfc3986(self):
680 reserved = "!*'();:@&=+$,/?#[]"
681 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
682 self.assertEqual(escape_rfc3986(reserved), reserved)
683 self.assertEqual(escape_rfc3986(unreserved), unreserved)
684 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
685 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
686 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
687 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
688
689 def test_escape_url(self):
690 self.assertEqual(
691 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
692 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
693 )
694 self.assertEqual(
695 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'),
696 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
697 )
698 self.assertEqual(
699 escape_url('http://тест.рф/фрагмент'),
700 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
701 )
702 self.assertEqual(
703 escape_url('http://тест.рф/абв?абв=абв#абв'),
704 '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'
705 )
706 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
707
708 def test_js_to_json_realworld(self):
709 inp = '''{
710 'clip':{'provider':'pseudo'}
711 }'''
712 self.assertEqual(js_to_json(inp), '''{
713 "clip":{"provider":"pseudo"}
714 }''')
715 json.loads(js_to_json(inp))
716
717 inp = '''{
718 'playlist':[{'controls':{'all':null}}]
719 }'''
720 self.assertEqual(js_to_json(inp), '''{
721 "playlist":[{"controls":{"all":null}}]
722 }''')
723
724 inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
725 self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
726
727 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
728 json_code = js_to_json(inp)
729 self.assertEqual(json.loads(json_code), json.loads(inp))
730
731 inp = '''{
732 0:{src:'skipped', type: 'application/dash+xml'},
733 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
734 }'''
735 self.assertEqual(js_to_json(inp), '''{
736 "0":{"src":"skipped", "type": "application/dash+xml"},
737 "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
738 }''')
739
740 inp = '''{"foo":101}'''
741 self.assertEqual(js_to_json(inp), '''{"foo":101}''')
742
743 inp = '''{"duration": "00:01:07"}'''
744 self.assertEqual(js_to_json(inp), '''{"duration": "00:01:07"}''')
745
746 def test_js_to_json_edgecases(self):
747 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
748 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
749
750 on = js_to_json('{"abc": true}')
751 self.assertEqual(json.loads(on), {'abc': True})
752
753 # Ignore JavaScript code as well
754 on = js_to_json('''{
755 "x": 1,
756 y: "a",
757 z: some.code
758 }''')
759 d = json.loads(on)
760 self.assertEqual(d['x'], 1)
761 self.assertEqual(d['y'], 'a')
762
763 on = js_to_json('["abc", "def",]')
764 self.assertEqual(json.loads(on), ['abc', 'def'])
765
766 on = js_to_json('{"abc": "def",}')
767 self.assertEqual(json.loads(on), {'abc': 'def'})
768
769 on = js_to_json('{ 0: /* " \n */ ",]" , }')
770 self.assertEqual(json.loads(on), {'0': ',]'})
771
772 on = js_to_json(r'["<p>x<\/p>"]')
773 self.assertEqual(json.loads(on), ['<p>x</p>'])
774
775 on = js_to_json(r'["\xaa"]')
776 self.assertEqual(json.loads(on), ['\u00aa'])
777
778 on = js_to_json("['a\\\nb']")
779 self.assertEqual(json.loads(on), ['ab'])
780
781 on = js_to_json('{0xff:0xff}')
782 self.assertEqual(json.loads(on), {'255': 255})
783
784 on = js_to_json('{077:077}')
785 self.assertEqual(json.loads(on), {'63': 63})
786
787 on = js_to_json('{42:42}')
788 self.assertEqual(json.loads(on), {'42': 42})
789
790 def test_extract_attributes(self):
791 self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
792 self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
793 self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
794 self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
795 self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
796 self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
797 self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
798 self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
799 self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
800 self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
801 self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
802 self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
803 self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
804 self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
805 self.assertEqual(extract_attributes('<e x >'), {'x': None})
806 self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
807 self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
808 self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
809 self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
810 self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
811 self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
812 self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
813 self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
814 self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
815 self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
816 self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
817 self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
818 self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
819 # "Narrow" Python builds don't support unicode code points outside BMP.
820 try:
821 compat_chr(0x10000)
822 supports_outside_bmp = True
823 except ValueError:
824 supports_outside_bmp = False
825 if supports_outside_bmp:
826 self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
827
828 def test_clean_html(self):
829 self.assertEqual(clean_html('a:\nb'), 'a: b')
830 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
831
832 def test_intlist_to_bytes(self):
833 self.assertEqual(
834 intlist_to_bytes([0, 1, 127, 128, 255]),
835 b'\x00\x01\x7f\x80\xff')
836
837 def test_args_to_str(self):
838 self.assertEqual(
839 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
840 'foo ba/r -baz \'2 be\' \'\''
841 )
842
843 def test_parse_filesize(self):
844 self.assertEqual(parse_filesize(None), None)
845 self.assertEqual(parse_filesize(''), None)
846 self.assertEqual(parse_filesize('91 B'), 91)
847 self.assertEqual(parse_filesize('foobar'), None)
848 self.assertEqual(parse_filesize('2 MiB'), 2097152)
849 self.assertEqual(parse_filesize('5 GB'), 5000000000)
850 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
851 self.assertEqual(parse_filesize('1.2tb'), 1200000000000)
852 self.assertEqual(parse_filesize('1,24 KB'), 1240)
853 self.assertEqual(parse_filesize('1,24 kb'), 1240)
854 self.assertEqual(parse_filesize('8.5 megabytes'), 8500000)
855
856 def test_parse_count(self):
857 self.assertEqual(parse_count(None), None)
858 self.assertEqual(parse_count(''), None)
859 self.assertEqual(parse_count('0'), 0)
860 self.assertEqual(parse_count('1000'), 1000)
861 self.assertEqual(parse_count('1.000'), 1000)
862 self.assertEqual(parse_count('1.1k'), 1100)
863 self.assertEqual(parse_count('1.1kk'), 1100000)
864 self.assertEqual(parse_count('1.1kk '), 1100000)
865 self.assertEqual(parse_count('1.1kk views'), 1100000)
866
867 def test_version_tuple(self):
868 self.assertEqual(version_tuple('1'), (1,))
869 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
870 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
871
872 def test_detect_exe_version(self):
873 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
874 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
875 configuration: --prefix=/usr --extra-'''), '1.2.1')
876 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
877 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
878 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
879 Trying to open render node...
880 Success at /dev/dri/renderD128.
881 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
882
883 def test_age_restricted(self):
884 self.assertFalse(age_restricted(None, 10)) # unrestricted content
885 self.assertFalse(age_restricted(1, None)) # unrestricted policy
886 self.assertFalse(age_restricted(8, 10))
887 self.assertTrue(age_restricted(18, 14))
888 self.assertFalse(age_restricted(18, 18))
889
890 def test_is_html(self):
891 self.assertFalse(is_html(b'\x49\x44\x43<html'))
892 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
893 self.assertTrue(is_html( # UTF-8 with BOM
894 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
895 self.assertTrue(is_html( # UTF-16-LE
896 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
897 ))
898 self.assertTrue(is_html( # UTF-16-BE
899 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
900 ))
901 self.assertTrue(is_html( # UTF-32-BE
902 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'))
903 self.assertTrue(is_html( # UTF-32-LE
904 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'))
905
906 def test_render_table(self):
907 self.assertEqual(
908 render_table(
909 ['a', 'bcd'],
910 [[123, 4], [9999, 51]]),
911 'a bcd\n'
912 '123 4\n'
913 '9999 51')
914
915 def test_match_str(self):
916 self.assertRaises(ValueError, match_str, 'xy>foobar', {})
917 self.assertFalse(match_str('xy', {'x': 1200}))
918 self.assertTrue(match_str('!xy', {'x': 1200}))
919 self.assertTrue(match_str('x', {'x': 1200}))
920 self.assertFalse(match_str('!x', {'x': 1200}))
921 self.assertTrue(match_str('x', {'x': 0}))
922 self.assertFalse(match_str('x>0', {'x': 0}))
923 self.assertFalse(match_str('x>0', {}))
924 self.assertTrue(match_str('x>?0', {}))
925 self.assertTrue(match_str('x>1K', {'x': 1200}))
926 self.assertFalse(match_str('x>2K', {'x': 1200}))
927 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
928 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
929 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
930 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
931 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
932 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
933 self.assertFalse(match_str(
934 'like_count > 100 & dislike_count <? 50 & description',
935 {'like_count': 90, 'description': 'foo'}))
936 self.assertTrue(match_str(
937 'like_count > 100 & dislike_count <? 50 & description',
938 {'like_count': 190, 'description': 'foo'}))
939 self.assertFalse(match_str(
940 'like_count > 100 & dislike_count <? 50 & description',
941 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
942 self.assertFalse(match_str(
943 'like_count > 100 & dislike_count <? 50 & description',
944 {'like_count': 190, 'dislike_count': 10}))
945
946 def test_parse_dfxp_time_expr(self):
947 self.assertEqual(parse_dfxp_time_expr(None), None)
948 self.assertEqual(parse_dfxp_time_expr(''), None)
949 self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
950 self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
951 self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
952 self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
953 self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
954
955 def test_dfxp2srt(self):
956 dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
957 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
958 <body>
959 <div xml:lang="en">
960 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
961 <p begin="1" end="2">第二行<br/>♪♪</p>
962 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
963 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
964 <p begin="-1" end="-1">Ignore, two</p>
965 <p begin="3" dur="-1">Ignored, three</p>
966 </div>
967 </body>
968 </tt>'''
969 srt_data = '''1
970 00:00:00,000 --> 00:00:01,000
971 The following line contains Chinese characters and special symbols
972
973 2
974 00:00:01,000 --> 00:00:02,000
975 第二行
976 ♪♪
977
978 3
979 00:00:02,000 --> 00:00:03,000
980 Third
981 Line
982
983 '''
984 self.assertEqual(dfxp2srt(dfxp_data), srt_data)
985
986 dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
987 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
988 <body>
989 <div xml:lang="en">
990 <p begin="0" end="1">The first line</p>
991 </div>
992 </body>
993 </tt>'''
994 srt_data = '''1
995 00:00:00,000 --> 00:00:01,000
996 The first line
997
998 '''
999 self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
1000
1001 def test_cli_option(self):
1002 self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
1003 self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
1004 self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
1005 self.assertEqual(cli_option({'retries': 10}, '--retries', 'retries'), ['--retries', '10'])
1006
1007 def test_cli_valueless_option(self):
1008 self.assertEqual(cli_valueless_option(
1009 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
1010 self.assertEqual(cli_valueless_option(
1011 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
1012 self.assertEqual(cli_valueless_option(
1013 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
1014 self.assertEqual(cli_valueless_option(
1015 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
1016 self.assertEqual(cli_valueless_option(
1017 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
1018 self.assertEqual(cli_valueless_option(
1019 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
1020
1021 def test_cli_bool_option(self):
1022 self.assertEqual(
1023 cli_bool_option(
1024 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
1025 ['--no-check-certificate', 'true'])
1026 self.assertEqual(
1027 cli_bool_option(
1028 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
1029 ['--no-check-certificate=true'])
1030 self.assertEqual(
1031 cli_bool_option(
1032 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1033 ['--check-certificate', 'false'])
1034 self.assertEqual(
1035 cli_bool_option(
1036 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1037 ['--check-certificate=false'])
1038 self.assertEqual(
1039 cli_bool_option(
1040 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
1041 ['--check-certificate', 'true'])
1042 self.assertEqual(
1043 cli_bool_option(
1044 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
1045 ['--check-certificate=true'])
1046
1047 def test_ohdave_rsa_encrypt(self):
1048 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
1049 e = 65537
1050
1051 self.assertEqual(
1052 ohdave_rsa_encrypt(b'aa111222', e, N),
1053 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
1054
1055 def test_encode_base_n(self):
1056 self.assertEqual(encode_base_n(0, 30), '0')
1057 self.assertEqual(encode_base_n(80, 30), '2k')
1058
1059 custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
1060 self.assertEqual(encode_base_n(0, 30, custom_table), '9')
1061 self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
1062
1063 self.assertRaises(ValueError, encode_base_n, 0, 70)
1064 self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
1065
1066 def test_urshift(self):
1067 self.assertEqual(urshift(3, 1), 1)
1068 self.assertEqual(urshift(-3, 1), 2147483646)
1069
1070 def test_get_element_by_class(self):
1071 html = '''
1072 <span class="foo bar">nice</span>
1073 '''
1074
1075 self.assertEqual(get_element_by_class('foo', html), 'nice')
1076 self.assertEqual(get_element_by_class('no-such-class', html), None)
1077
1078
1079 if __name__ == '__main__':
1080 unittest.main()