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