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