]> Raphaël G. Git Repositories - youtubedl/blob - test/test_utils.py
e6887be9f29847984be257a73af67e5750f4225c
[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 clean_html,
22 DateRange,
23 detect_exe_version,
24 determine_ext,
25 dict_get,
26 encode_compat_str,
27 encodeFilename,
28 escape_rfc3986,
29 escape_url,
30 ExtractorError,
31 find_xpath_attr,
32 fix_xml_ampersands,
33 InAdvancePagedList,
34 intlist_to_bytes,
35 is_html,
36 js_to_json,
37 limit_length,
38 ohdave_rsa_encrypt,
39 OnDemandPagedList,
40 orderedSet,
41 parse_duration,
42 parse_filesize,
43 parse_iso8601,
44 read_batch_urls,
45 sanitize_filename,
46 sanitize_path,
47 prepend_extension,
48 replace_extension,
49 remove_quotes,
50 shell_quote,
51 smuggle_url,
52 str_to_int,
53 strip_jsonp,
54 struct_unpack,
55 timeconvert,
56 unescapeHTML,
57 unified_strdate,
58 unsmuggle_url,
59 uppercase_escape,
60 lowercase_escape,
61 url_basename,
62 urlencode_postdata,
63 version_tuple,
64 xpath_with_ns,
65 xpath_element,
66 xpath_text,
67 xpath_attr,
68 render_table,
69 match_str,
70 parse_dfxp_time_expr,
71 dfxp2srt,
72 cli_option,
73 cli_valueless_option,
74 cli_bool_option,
75 )
76 from youtube_dl.compat import (
77 compat_etree_fromstring,
78 )
79
80
81 class TestUtil(unittest.TestCase):
82 def test_timeconvert(self):
83 self.assertTrue(timeconvert('') is None)
84 self.assertTrue(timeconvert('bougrg') is None)
85
86 def test_sanitize_filename(self):
87 self.assertEqual(sanitize_filename('abc'), 'abc')
88 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
89
90 self.assertEqual(sanitize_filename('123'), '123')
91
92 self.assertEqual('abc_de', sanitize_filename('abc/de'))
93 self.assertFalse('/' in sanitize_filename('abc/de///'))
94
95 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
96 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
97 self.assertEqual('yes no', sanitize_filename('yes? no'))
98 self.assertEqual('this - that', sanitize_filename('this: that'))
99
100 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
101 aumlaut = 'ä'
102 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
103 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
104 self.assertEqual(sanitize_filename(tests), tests)
105
106 self.assertEqual(
107 sanitize_filename('New World record at 0:12:34'),
108 'New World record at 0_12_34')
109
110 self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
111 self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
112 self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
113 self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
114
115 forbidden = '"\0\\/'
116 for fc in forbidden:
117 for fbc in forbidden:
118 self.assertTrue(fbc not in sanitize_filename(fc))
119
120 def test_sanitize_filename_restricted(self):
121 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
122 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
123
124 self.assertEqual(sanitize_filename('123', restricted=True), '123')
125
126 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
127 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
128
129 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
130 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
131 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
132 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
133
134 tests = 'a\xe4b\u4e2d\u56fd\u7684c'
135 self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
136 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
137
138 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
139 for fc in forbidden:
140 for fbc in forbidden:
141 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
142
143 # Handle a common case more neatly
144 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
145 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
146 # .. but make sure the file name is never empty
147 self.assertTrue(sanitize_filename('-', restricted=True) != '')
148 self.assertTrue(sanitize_filename(':', restricted=True) != '')
149
150 def test_sanitize_ids(self):
151 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
152 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
153 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
154
155 def test_sanitize_path(self):
156 if sys.platform != 'win32':
157 return
158
159 self.assertEqual(sanitize_path('abc'), 'abc')
160 self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
161 self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
162 self.assertEqual(sanitize_path('abc|def'), 'abc#def')
163 self.assertEqual(sanitize_path('<>:"|?*'), '#######')
164 self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
165 self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
166
167 self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
168 self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
169
170 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
171 self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
172 self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
173 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
174
175 self.assertEqual(
176 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
177 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
178
179 self.assertEqual(
180 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
181 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
182 self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
183 self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
184 self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
185
186 self.assertEqual(sanitize_path('../abc'), '..\\abc')
187 self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
188 self.assertEqual(sanitize_path('./abc'), 'abc')
189 self.assertEqual(sanitize_path('./../abc'), '..\\abc')
190
191 def test_prepend_extension(self):
192 self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
193 self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
194 self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
195 self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
196 self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
197 self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
198
199 def test_replace_extension(self):
200 self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
201 self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
202 self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
203 self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
204 self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
205 self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
206
207 def test_remove_quotes(self):
208 self.assertEqual(remove_quotes(None), None)
209 self.assertEqual(remove_quotes('"'), '"')
210 self.assertEqual(remove_quotes("'"), "'")
211 self.assertEqual(remove_quotes(';'), ';')
212 self.assertEqual(remove_quotes('";'), '";')
213 self.assertEqual(remove_quotes('""'), '')
214 self.assertEqual(remove_quotes('";"'), ';')
215
216 def test_ordered_set(self):
217 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
218 self.assertEqual(orderedSet([]), [])
219 self.assertEqual(orderedSet([1]), [1])
220 # keep the list ordered
221 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
222
223 def test_unescape_html(self):
224 self.assertEqual(unescapeHTML('%20;'), '%20;')
225 self.assertEqual(unescapeHTML('&#x2F;'), '/')
226 self.assertEqual(unescapeHTML('&#47;'), '/')
227 self.assertEqual(unescapeHTML('&eacute;'), 'é')
228 self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
229
230 def test_daterange(self):
231 _20century = DateRange("19000101", "20000101")
232 self.assertFalse("17890714" in _20century)
233 _ac = DateRange("00010101")
234 self.assertTrue("19690721" in _ac)
235 _firstmilenium = DateRange(end="10000101")
236 self.assertTrue("07110427" in _firstmilenium)
237
238 def test_unified_dates(self):
239 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
240 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
241 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
242 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
243 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
244 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
245 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
246 self.assertEqual(
247 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
248 '20141126')
249 self.assertEqual(
250 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
251 '20150202')
252 self.assertEqual(unified_strdate('25-09-2014'), '20140925')
253 self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
254
255 def test_determine_ext(self):
256 self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
257 self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
258 self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
259 self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
260 self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
261
262 def test_find_xpath_attr(self):
263 testxml = '''<root>
264 <node/>
265 <node x="a"/>
266 <node x="a" y="c" />
267 <node x="b" y="d" />
268 <node x="" />
269 </root>'''
270 doc = compat_etree_fromstring(testxml)
271
272 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
273 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
274 self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
275 self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
276 self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
277 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
278 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
279 self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
280 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
281 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
282 self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
283
284 def test_xpath_with_ns(self):
285 testxml = '''<root xmlns:media="http://example.com/">
286 <media:song>
287 <media:author>The Author</media:author>
288 <url>http://server.com/download.mp3</url>
289 </media:song>
290 </root>'''
291 doc = compat_etree_fromstring(testxml)
292 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
293 self.assertTrue(find('media:song') is not None)
294 self.assertEqual(find('media:song/media:author').text, 'The Author')
295 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
296
297 def test_xpath_element(self):
298 doc = xml.etree.ElementTree.Element('root')
299 div = xml.etree.ElementTree.SubElement(doc, 'div')
300 p = xml.etree.ElementTree.SubElement(div, 'p')
301 p.text = 'Foo'
302 self.assertEqual(xpath_element(doc, 'div/p'), p)
303 self.assertEqual(xpath_element(doc, ['div/p']), p)
304 self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
305 self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
306 self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
307 self.assertTrue(xpath_element(doc, 'div/bar') is None)
308 self.assertTrue(xpath_element(doc, ['div/bar']) is None)
309 self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
310 self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
311 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
312 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
313
314 def test_xpath_text(self):
315 testxml = '''<root>
316 <div>
317 <p>Foo</p>
318 </div>
319 </root>'''
320 doc = compat_etree_fromstring(testxml)
321 self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
322 self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
323 self.assertTrue(xpath_text(doc, 'div/bar') is None)
324 self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
325
326 def test_xpath_attr(self):
327 testxml = '''<root>
328 <div>
329 <p x="a">Foo</p>
330 </div>
331 </root>'''
332 doc = compat_etree_fromstring(testxml)
333 self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
334 self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
335 self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
336 self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
337 self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
338 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
339 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
340
341 def test_smuggle_url(self):
342 data = {"ö": "ö", "abc": [3]}
343 url = 'https://foo.bar/baz?x=y#a'
344 smug_url = smuggle_url(url, data)
345 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
346 self.assertEqual(url, unsmug_url)
347 self.assertEqual(data, unsmug_data)
348
349 res_url, res_data = unsmuggle_url(url)
350 self.assertEqual(res_url, url)
351 self.assertEqual(res_data, None)
352
353 def test_shell_quote(self):
354 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
355 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
356
357 def test_str_to_int(self):
358 self.assertEqual(str_to_int('123,456'), 123456)
359 self.assertEqual(str_to_int('123.456'), 123456)
360
361 def test_url_basename(self):
362 self.assertEqual(url_basename('http://foo.de/'), '')
363 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
364 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
365 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
366 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
367 self.assertEqual(
368 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
369 'trailer.mp4')
370
371 def test_parse_duration(self):
372 self.assertEqual(parse_duration(None), None)
373 self.assertEqual(parse_duration(False), None)
374 self.assertEqual(parse_duration('invalid'), None)
375 self.assertEqual(parse_duration('1'), 1)
376 self.assertEqual(parse_duration('1337:12'), 80232)
377 self.assertEqual(parse_duration('9:12:43'), 33163)
378 self.assertEqual(parse_duration('12:00'), 720)
379 self.assertEqual(parse_duration('00:01:01'), 61)
380 self.assertEqual(parse_duration('x:y'), None)
381 self.assertEqual(parse_duration('3h11m53s'), 11513)
382 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
383 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
384 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
385 self.assertEqual(parse_duration('62m45s'), 3765)
386 self.assertEqual(parse_duration('6m59s'), 419)
387 self.assertEqual(parse_duration('49s'), 49)
388 self.assertEqual(parse_duration('0h0m0s'), 0)
389 self.assertEqual(parse_duration('0m0s'), 0)
390 self.assertEqual(parse_duration('0s'), 0)
391 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
392 self.assertEqual(parse_duration('T30M38S'), 1838)
393 self.assertEqual(parse_duration('5 s'), 5)
394 self.assertEqual(parse_duration('3 min'), 180)
395 self.assertEqual(parse_duration('2.5 hours'), 9000)
396 self.assertEqual(parse_duration('02:03:04'), 7384)
397 self.assertEqual(parse_duration('01:02:03:04'), 93784)
398 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
399 self.assertEqual(parse_duration('87 Min.'), 5220)
400
401 def test_fix_xml_ampersands(self):
402 self.assertEqual(
403 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
404 self.assertEqual(
405 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
406 '"&amp;x=y&amp;wrong;&amp;z=a')
407 self.assertEqual(
408 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
409 '&amp;&apos;&gt;&lt;&quot;')
410 self.assertEqual(
411 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
412 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
413
414 def test_paged_list(self):
415 def testPL(size, pagesize, sliceargs, expected):
416 def get_page(pagenum):
417 firstid = pagenum * pagesize
418 upto = min(size, pagenum * pagesize + pagesize)
419 for i in range(firstid, upto):
420 yield i
421
422 pl = OnDemandPagedList(get_page, pagesize)
423 got = pl.getslice(*sliceargs)
424 self.assertEqual(got, expected)
425
426 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
427 got = iapl.getslice(*sliceargs)
428 self.assertEqual(got, expected)
429
430 testPL(5, 2, (), [0, 1, 2, 3, 4])
431 testPL(5, 2, (1,), [1, 2, 3, 4])
432 testPL(5, 2, (2,), [2, 3, 4])
433 testPL(5, 2, (4,), [4])
434 testPL(5, 2, (0, 3), [0, 1, 2])
435 testPL(5, 2, (1, 4), [1, 2, 3])
436 testPL(5, 2, (2, 99), [2, 3, 4])
437 testPL(5, 2, (20, 99), [])
438
439 def test_struct_unpack(self):
440 self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
441
442 def test_read_batch_urls(self):
443 f = io.StringIO('''\xef\xbb\xbf foo
444 bar\r
445 baz
446 # More after this line\r
447 ; or after this
448 bam''')
449 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
450
451 def test_urlencode_postdata(self):
452 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
453 self.assertTrue(isinstance(data, bytes))
454
455 def test_dict_get(self):
456 FALSE_VALUES = {
457 'none': None,
458 'false': False,
459 'zero': 0,
460 'empty_string': '',
461 'empty_list': [],
462 }
463 d = FALSE_VALUES.copy()
464 d['a'] = 42
465 self.assertEqual(dict_get(d, 'a'), 42)
466 self.assertEqual(dict_get(d, 'b'), None)
467 self.assertEqual(dict_get(d, 'b', 42), 42)
468 self.assertEqual(dict_get(d, ('a', )), 42)
469 self.assertEqual(dict_get(d, ('b', 'a', )), 42)
470 self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
471 self.assertEqual(dict_get(d, ('b', 'c', )), None)
472 self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
473 for key, false_value in FALSE_VALUES.items():
474 self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
475 self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
476
477 def test_encode_compat_str(self):
478 self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
479 self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
480
481 def test_parse_iso8601(self):
482 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
483 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
484 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
485 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
486 self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
487 self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
488
489 def test_strip_jsonp(self):
490 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
491 d = json.loads(stripped)
492 self.assertEqual(d, [{"id": "532cb", "x": 3}])
493
494 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
495 d = json.loads(stripped)
496 self.assertEqual(d, {'STATUS': 'OK'})
497
498 stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
499 d = json.loads(stripped)
500 self.assertEqual(d, {'status': 'success'})
501
502 def test_uppercase_escape(self):
503 self.assertEqual(uppercase_escape('aä'), 'aä')
504 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
505
506 def test_lowercase_escape(self):
507 self.assertEqual(lowercase_escape('aä'), 'aä')
508 self.assertEqual(lowercase_escape('\\u0026'), '&')
509
510 def test_limit_length(self):
511 self.assertEqual(limit_length(None, 12), None)
512 self.assertEqual(limit_length('foo', 12), 'foo')
513 self.assertTrue(
514 limit_length('foo bar baz asd', 12).startswith('foo bar'))
515 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
516
517 def test_escape_rfc3986(self):
518 reserved = "!*'();:@&=+$,/?#[]"
519 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
520 self.assertEqual(escape_rfc3986(reserved), reserved)
521 self.assertEqual(escape_rfc3986(unreserved), unreserved)
522 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
523 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
524 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
525 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
526
527 def test_escape_url(self):
528 self.assertEqual(
529 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
530 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
531 )
532 self.assertEqual(
533 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'),
534 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
535 )
536 self.assertEqual(
537 escape_url('http://тест.рф/фрагмент'),
538 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
539 )
540 self.assertEqual(
541 escape_url('http://тест.рф/абв?абв=абв#абв'),
542 'http://тест.рф/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
543 )
544 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
545
546 def test_js_to_json_realworld(self):
547 inp = '''{
548 'clip':{'provider':'pseudo'}
549 }'''
550 self.assertEqual(js_to_json(inp), '''{
551 "clip":{"provider":"pseudo"}
552 }''')
553 json.loads(js_to_json(inp))
554
555 inp = '''{
556 'playlist':[{'controls':{'all':null}}]
557 }'''
558 self.assertEqual(js_to_json(inp), '''{
559 "playlist":[{"controls":{"all":null}}]
560 }''')
561
562 inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
563 self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
564
565 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
566 json_code = js_to_json(inp)
567 self.assertEqual(json.loads(json_code), json.loads(inp))
568
569 def test_js_to_json_edgecases(self):
570 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
571 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
572
573 on = js_to_json('{"abc": true}')
574 self.assertEqual(json.loads(on), {'abc': True})
575
576 # Ignore JavaScript code as well
577 on = js_to_json('''{
578 "x": 1,
579 y: "a",
580 z: some.code
581 }''')
582 d = json.loads(on)
583 self.assertEqual(d['x'], 1)
584 self.assertEqual(d['y'], 'a')
585
586 on = js_to_json('["abc", "def",]')
587 self.assertEqual(json.loads(on), ['abc', 'def'])
588
589 on = js_to_json('{"abc": "def",}')
590 self.assertEqual(json.loads(on), {'abc': 'def'})
591
592 def test_clean_html(self):
593 self.assertEqual(clean_html('a:\nb'), 'a: b')
594 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
595
596 def test_intlist_to_bytes(self):
597 self.assertEqual(
598 intlist_to_bytes([0, 1, 127, 128, 255]),
599 b'\x00\x01\x7f\x80\xff')
600
601 def test_args_to_str(self):
602 self.assertEqual(
603 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
604 'foo ba/r -baz \'2 be\' \'\''
605 )
606
607 def test_parse_filesize(self):
608 self.assertEqual(parse_filesize(None), None)
609 self.assertEqual(parse_filesize(''), None)
610 self.assertEqual(parse_filesize('91 B'), 91)
611 self.assertEqual(parse_filesize('foobar'), None)
612 self.assertEqual(parse_filesize('2 MiB'), 2097152)
613 self.assertEqual(parse_filesize('5 GB'), 5000000000)
614 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
615 self.assertEqual(parse_filesize('1,24 KB'), 1240)
616
617 def test_version_tuple(self):
618 self.assertEqual(version_tuple('1'), (1,))
619 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
620 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
621
622 def test_detect_exe_version(self):
623 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
624 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
625 configuration: --prefix=/usr --extra-'''), '1.2.1')
626 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
627 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
628 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
629 Trying to open render node...
630 Success at /dev/dri/renderD128.
631 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
632
633 def test_age_restricted(self):
634 self.assertFalse(age_restricted(None, 10)) # unrestricted content
635 self.assertFalse(age_restricted(1, None)) # unrestricted policy
636 self.assertFalse(age_restricted(8, 10))
637 self.assertTrue(age_restricted(18, 14))
638 self.assertFalse(age_restricted(18, 18))
639
640 def test_is_html(self):
641 self.assertFalse(is_html(b'\x49\x44\x43<html'))
642 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
643 self.assertTrue(is_html( # UTF-8 with BOM
644 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
645 self.assertTrue(is_html( # UTF-16-LE
646 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
647 ))
648 self.assertTrue(is_html( # UTF-16-BE
649 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
650 ))
651 self.assertTrue(is_html( # UTF-32-BE
652 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'))
653 self.assertTrue(is_html( # UTF-32-LE
654 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'))
655
656 def test_render_table(self):
657 self.assertEqual(
658 render_table(
659 ['a', 'bcd'],
660 [[123, 4], [9999, 51]]),
661 'a bcd\n'
662 '123 4\n'
663 '9999 51')
664
665 def test_match_str(self):
666 self.assertRaises(ValueError, match_str, 'xy>foobar', {})
667 self.assertFalse(match_str('xy', {'x': 1200}))
668 self.assertTrue(match_str('!xy', {'x': 1200}))
669 self.assertTrue(match_str('x', {'x': 1200}))
670 self.assertFalse(match_str('!x', {'x': 1200}))
671 self.assertTrue(match_str('x', {'x': 0}))
672 self.assertFalse(match_str('x>0', {'x': 0}))
673 self.assertFalse(match_str('x>0', {}))
674 self.assertTrue(match_str('x>?0', {}))
675 self.assertTrue(match_str('x>1K', {'x': 1200}))
676 self.assertFalse(match_str('x>2K', {'x': 1200}))
677 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
678 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
679 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
680 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
681 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
682 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
683 self.assertFalse(match_str(
684 'like_count > 100 & dislike_count <? 50 & description',
685 {'like_count': 90, 'description': 'foo'}))
686 self.assertTrue(match_str(
687 'like_count > 100 & dislike_count <? 50 & description',
688 {'like_count': 190, 'description': 'foo'}))
689 self.assertFalse(match_str(
690 'like_count > 100 & dislike_count <? 50 & description',
691 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
692 self.assertFalse(match_str(
693 'like_count > 100 & dislike_count <? 50 & description',
694 {'like_count': 190, 'dislike_count': 10}))
695
696 def test_parse_dfxp_time_expr(self):
697 self.assertEqual(parse_dfxp_time_expr(None), None)
698 self.assertEqual(parse_dfxp_time_expr(''), None)
699 self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
700 self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
701 self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
702 self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
703 self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
704
705 def test_dfxp2srt(self):
706 dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
707 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
708 <body>
709 <div xml:lang="en">
710 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
711 <p begin="1" end="2">第二行<br/>♪♪</p>
712 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
713 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
714 <p begin="-1" end="-1">Ignore, two</p>
715 <p begin="3" dur="-1">Ignored, three</p>
716 </div>
717 </body>
718 </tt>'''
719 srt_data = '''1
720 00:00:00,000 --> 00:00:01,000
721 The following line contains Chinese characters and special symbols
722
723 2
724 00:00:01,000 --> 00:00:02,000
725 第二行
726 ♪♪
727
728 3
729 00:00:02,000 --> 00:00:03,000
730 Third
731 Line
732
733 '''
734 self.assertEqual(dfxp2srt(dfxp_data), srt_data)
735
736 dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
737 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
738 <body>
739 <div xml:lang="en">
740 <p begin="0" end="1">The first line</p>
741 </div>
742 </body>
743 </tt>'''
744 srt_data = '''1
745 00:00:00,000 --> 00:00:01,000
746 The first line
747
748 '''
749 self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
750
751 def test_cli_option(self):
752 self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
753 self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
754 self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
755
756 def test_cli_valueless_option(self):
757 self.assertEqual(cli_valueless_option(
758 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
759 self.assertEqual(cli_valueless_option(
760 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
761 self.assertEqual(cli_valueless_option(
762 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
763 self.assertEqual(cli_valueless_option(
764 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
765 self.assertEqual(cli_valueless_option(
766 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
767 self.assertEqual(cli_valueless_option(
768 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
769
770 def test_cli_bool_option(self):
771 self.assertEqual(
772 cli_bool_option(
773 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
774 ['--no-check-certificate', 'true'])
775 self.assertEqual(
776 cli_bool_option(
777 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
778 ['--no-check-certificate=true'])
779 self.assertEqual(
780 cli_bool_option(
781 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
782 ['--check-certificate', 'false'])
783 self.assertEqual(
784 cli_bool_option(
785 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
786 ['--check-certificate=false'])
787 self.assertEqual(
788 cli_bool_option(
789 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
790 ['--check-certificate', 'true'])
791 self.assertEqual(
792 cli_bool_option(
793 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
794 ['--check-certificate=true'])
795
796 def test_ohdave_rsa_encrypt(self):
797 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
798 e = 65537
799
800 self.assertEqual(
801 ohdave_rsa_encrypt(b'aa111222', e, N),
802 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
803
804 if __name__ == '__main__':
805 unittest.main()