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