]> jfr.im git - yt-dlp.git/blame - test/test_utils.py
release 2015.05.04
[yt-dlp.git] / test / test_utils.py
CommitLineData
e387eb5a 1#!/usr/bin/env python
9d4660ca 2# coding: utf-8
e387eb5a 3
4e408e47
PH
4from __future__ import unicode_literals
5
44a5f171
PH
6# Allow direct execution
7import os
dae7c920 8import sys
44fb3454 9import unittest
44a5f171 10sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
44fb3454 11
44a5f171
PH
12
13# Various small unit tests
62e609ab 14import io
fac55558 15import json
44a5f171 16import xml.etree.ElementTree
dae7c920 17
a921f407 18from youtube_dl.utils import (
05900629 19 age_restricted,
cae97f65 20 args_to_str,
e4bdb37e 21 clean_html,
a921f407 22 DateRange,
cae97f65 23 detect_exe_version,
29eb5174 24 encodeFilename,
cae97f65
PH
25 escape_rfc3986,
26 escape_url,
5379a2d4 27 ExtractorError,
a921f407 28 find_xpath_attr,
5aafe895 29 fix_xml_ampersands,
9c44d242 30 InAdvancePagedList,
cae97f65 31 intlist_to_bytes,
61ca9a80 32 is_html,
cae97f65
PH
33 js_to_json,
34 limit_length,
35 OnDemandPagedList,
36 orderedSet,
608d11f5 37 parse_duration,
cae97f65
PH
38 parse_filesize,
39 parse_iso8601,
62e609ab 40 read_batch_urls,
29eb5174 41 sanitize_filename,
a2aaf4db 42 sanitize_path,
92a4793b 43 sanitize_url_path_consecutive_slashes,
a4bcaad7 44 prepend_extension,
b3ed15b7 45 replace_extension,
a6a173c2 46 shell_quote,
29eb5174 47 smuggle_url,
f53c966a 48 str_to_int,
cae97f65 49 strip_jsonp,
b53466e1 50 struct_unpack,
29eb5174
PH
51 timeconvert,
52 unescapeHTML,
53 unified_strdate,
54 unsmuggle_url,
cae97f65 55 uppercase_escape,
29eb5174 56 url_basename,
b74fa8cd 57 urlencode_postdata,
5f9b8394 58 version_tuple,
cae97f65 59 xpath_with_ns,
5379a2d4 60 xpath_text,
cfb56d1a 61 render_table,
347de493 62 match_str,
bf6427d2
YCH
63 parse_dfxp_time_expr,
64 dfxp2srt,
a921f407 65)
44fb3454 66
627dcfff 67
44fb3454 68class TestUtil(unittest.TestCase):
59ae15a5
PH
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')
4e408e47 88 aumlaut = 'ä'
59ae15a5 89 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
4e408e47 90 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
59ae15a5
PH
91 self.assertEqual(sanitize_filename(tests), tests)
92
2aeb06d6
PH
93 self.assertEqual(
94 sanitize_filename('New World record at 0:12:34'),
95 'New World record at 0_12_34')
a7440261 96
5a42414b
PH
97 self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
98 self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
a7440261
PH
99 self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
100 self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
2aeb06d6 101
59ae15a5
PH
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
4e408e47 121 tests = 'a\xe4b\u4e2d\u56fd\u7684c'
59ae15a5 122 self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
4e408e47 123 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
59ae15a5 124
627dcfff 125 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
59ae15a5
PH
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
4e408e47
PH
131 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
132 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
59ae15a5
PH
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
796173d0 137 def test_sanitize_ids(self):
314d506b
PH
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')
796173d0 141
a2aaf4db
S
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
f18ef2d1
S
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
2ebfeaca
S
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
92a4793b
S
178 def test_sanitize_url_path_consecutive_slashes(self):
179 self.assertEqual(
180 sanitize_url_path_consecutive_slashes('http://hostname/foo//bar/filename.html'),
181 'http://hostname/foo/bar/filename.html')
182 self.assertEqual(
183 sanitize_url_path_consecutive_slashes('http://hostname//foo/bar/filename.html'),
184 'http://hostname/foo/bar/filename.html')
185 self.assertEqual(
186 sanitize_url_path_consecutive_slashes('http://hostname//'),
187 'http://hostname/')
188 self.assertEqual(
189 sanitize_url_path_consecutive_slashes('http://hostname/foo/bar/filename.html'),
190 'http://hostname/foo/bar/filename.html')
191 self.assertEqual(
192 sanitize_url_path_consecutive_slashes('http://hostname/'),
193 'http://hostname/')
194 self.assertEqual(
195 sanitize_url_path_consecutive_slashes('http://hostname/abc//'),
196 'http://hostname/abc/')
197
a4bcaad7
S
198 def test_prepend_extension(self):
199 self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
200 self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
201 self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
202 self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
203 self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
204 self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
205
b3ed15b7
S
206 def test_replace_extension(self):
207 self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
208 self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
209 self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
210 self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
211 self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
212 self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
213
59ae15a5 214 def test_ordered_set(self):
627dcfff 215 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
59ae15a5
PH
216 self.assertEqual(orderedSet([]), [])
217 self.assertEqual(orderedSet([1]), [1])
5f6a1245 218 # keep the list ordered
627dcfff 219 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
59ae15a5
PH
220
221 def test_unescape_html(self):
4e408e47 222 self.assertEqual(unescapeHTML('%20;'), '%20;')
91757b0f
NJ
223 self.assertEqual(unescapeHTML('&#x2F;'), '/')
224 self.assertEqual(unescapeHTML('&#47;'), '/')
4e408e47
PH
225 self.assertEqual(
226 unescapeHTML('&eacute;'), 'é')
5f6a1245 227
bd558525 228 def test_daterange(self):
5f6a1245 229 _20century = DateRange("19000101", "20000101")
bd558525
JMF
230 self.assertFalse("17890714" in _20century)
231 _ac = DateRange("00010101")
232 self.assertTrue("19690721" in _ac)
233 _firstmilenium = DateRange(end="10000101")
234 self.assertTrue("07110427" in _firstmilenium)
37254abc 235
bf50b038
JMF
236 def test_unified_dates(self):
237 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
238 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
239 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
240 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
a69801e2 241 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
026fcc04 242 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
99b67fec 243 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
42bdd9d0
PH
244 self.assertEqual(
245 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
246 '20141126')
9bb8e0a3
PH
247 self.assertEqual(
248 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
249 '20150202')
8cf70de4 250 self.assertEqual(unified_strdate('25-09-2014'), '20140925')
dae7c920 251
59ae56fa 252 def test_find_xpath_attr(self):
4e408e47 253 testxml = '''<root>
59ae56fa
PH
254 <node/>
255 <node x="a"/>
256 <node x="a" y="c" />
257 <node x="b" y="d" />
258 </root>'''
259 doc = xml.etree.ElementTree.fromstring(testxml)
260
261 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
262 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
263 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
264
d7e66d39 265 def test_xpath_with_ns(self):
4e408e47 266 testxml = '''<root xmlns:media="http://example.com/">
d7e66d39
JMF
267 <media:song>
268 <media:author>The Author</media:author>
269 <url>http://server.com/download.mp3</url>
270 </media:song>
271 </root>'''
272 doc = xml.etree.ElementTree.fromstring(testxml)
273 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
274 self.assertTrue(find('media:song') is not None)
4e408e47
PH
275 self.assertEqual(find('media:song/media:author').text, 'The Author')
276 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
d7e66d39 277
5379a2d4
JMF
278 def test_xpath_text(self):
279 testxml = '''<root>
280 <div>
281 <p>Foo</p>
282 </div>
283 </root>'''
284 doc = xml.etree.ElementTree.fromstring(testxml)
285 self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
286 self.assertTrue(xpath_text(doc, 'div/bar') is None)
287 self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
288
9d4660ca 289 def test_smuggle_url(self):
e075a44a 290 data = {"ö": "ö", "abc": [3]}
9d4660ca
PH
291 url = 'https://foo.bar/baz?x=y#a'
292 smug_url = smuggle_url(url, data)
293 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
294 self.assertEqual(url, unsmug_url)
295 self.assertEqual(data, unsmug_data)
296
297 res_url, res_data = unsmuggle_url(url)
298 self.assertEqual(res_url, url)
299 self.assertEqual(res_data, None)
300
a6a173c2 301 def test_shell_quote(self):
4e408e47
PH
302 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
303 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
a6a173c2 304
f53c966a
JMF
305 def test_str_to_int(self):
306 self.assertEqual(str_to_int('123,456'), 123456)
307 self.assertEqual(str_to_int('123.456'), 123456)
308
29eb5174 309 def test_url_basename(self):
4e408e47
PH
310 self.assertEqual(url_basename('http://foo.de/'), '')
311 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
312 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
313 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
314 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
d6c7a367 315 self.assertEqual(
4e408e47
PH
316 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
317 'trailer.mp4')
9d4660ca 318
608d11f5
PH
319 def test_parse_duration(self):
320 self.assertEqual(parse_duration(None), None)
a5fb718c
S
321 self.assertEqual(parse_duration(False), None)
322 self.assertEqual(parse_duration('invalid'), None)
608d11f5
PH
323 self.assertEqual(parse_duration('1'), 1)
324 self.assertEqual(parse_duration('1337:12'), 80232)
325 self.assertEqual(parse_duration('9:12:43'), 33163)
2db806b4
S
326 self.assertEqual(parse_duration('12:00'), 720)
327 self.assertEqual(parse_duration('00:01:01'), 61)
608d11f5 328 self.assertEqual(parse_duration('x:y'), None)
2db806b4 329 self.assertEqual(parse_duration('3h11m53s'), 11513)
ca7b3246
S
330 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
331 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
332 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
2db806b4
S
333 self.assertEqual(parse_duration('62m45s'), 3765)
334 self.assertEqual(parse_duration('6m59s'), 419)
335 self.assertEqual(parse_duration('49s'), 49)
336 self.assertEqual(parse_duration('0h0m0s'), 0)
337 self.assertEqual(parse_duration('0m0s'), 0)
338 self.assertEqual(parse_duration('0s'), 0)
7adcbe75 339 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
6a68bb57 340 self.assertEqual(parse_duration('T30M38S'), 1838)
e8df5cee
PH
341 self.assertEqual(parse_duration('5 s'), 5)
342 self.assertEqual(parse_duration('3 min'), 180)
343 self.assertEqual(parse_duration('2.5 hours'), 9000)
8f4b58d7
PH
344 self.assertEqual(parse_duration('02:03:04'), 7384)
345 self.assertEqual(parse_duration('01:02:03:04'), 93784)
3e675fab 346 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
608d11f5 347
5aafe895
PH
348 def test_fix_xml_ampersands(self):
349 self.assertEqual(
350 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
351 self.assertEqual(
352 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
353 '"&amp;x=y&amp;wrong;&amp;z=a')
354 self.assertEqual(
355 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
356 '&amp;&apos;&gt;&lt;&quot;')
357 self.assertEqual(
358 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
359 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
360
b7ab0590
PH
361 def test_paged_list(self):
362 def testPL(size, pagesize, sliceargs, expected):
363 def get_page(pagenum):
364 firstid = pagenum * pagesize
365 upto = min(size, pagenum * pagesize + pagesize)
366 for i in range(firstid, upto):
367 yield i
368
9c44d242 369 pl = OnDemandPagedList(get_page, pagesize)
b7ab0590
PH
370 got = pl.getslice(*sliceargs)
371 self.assertEqual(got, expected)
372
9c44d242
PH
373 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
374 got = iapl.getslice(*sliceargs)
375 self.assertEqual(got, expected)
376
b7ab0590
PH
377 testPL(5, 2, (), [0, 1, 2, 3, 4])
378 testPL(5, 2, (1,), [1, 2, 3, 4])
379 testPL(5, 2, (2,), [2, 3, 4])
380 testPL(5, 2, (4,), [4])
381 testPL(5, 2, (0, 3), [0, 1, 2])
382 testPL(5, 2, (1, 4), [1, 2, 3])
383 testPL(5, 2, (2, 99), [2, 3, 4])
384 testPL(5, 2, (20, 99), [])
385
b53466e1 386 def test_struct_unpack(self):
4e408e47 387 self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
b53466e1 388
62e609ab 389 def test_read_batch_urls(self):
4e408e47 390 f = io.StringIO('''\xef\xbb\xbf foo
62e609ab
PH
391 bar\r
392 baz
393 # More after this line\r
394 ; or after this
395 bam''')
4e408e47 396 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
62e609ab 397
b74fa8cd
JMF
398 def test_urlencode_postdata(self):
399 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
400 self.assertTrue(isinstance(data, bytes))
401
912b38b4
PH
402 def test_parse_iso8601(self):
403 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
404 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
405 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
6ad4013d 406 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
912b38b4 407
fac55558
PH
408 def test_strip_jsonp(self):
409 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
410 d = json.loads(stripped)
411 self.assertEqual(d, [{"id": "532cb", "x": 3}])
412
609a61e3
PH
413 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
414 d = json.loads(stripped)
415 self.assertEqual(d, {'STATUS': 'OK'})
416
173a7026 417 def test_uppercase_escape(self):
4e408e47
PH
418 self.assertEqual(uppercase_escape('aä'), 'aä')
419 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
fac55558 420
a020a0dc
PH
421 def test_limit_length(self):
422 self.assertEqual(limit_length(None, 12), None)
423 self.assertEqual(limit_length('foo', 12), 'foo')
424 self.assertTrue(
425 limit_length('foo bar baz asd', 12).startswith('foo bar'))
426 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
427
d05cfe06
S
428 def test_escape_rfc3986(self):
429 reserved = "!*'();:@&=+$,/?#[]"
430 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
431 self.assertEqual(escape_rfc3986(reserved), reserved)
432 self.assertEqual(escape_rfc3986(unreserved), unreserved)
433 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
434 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
435 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
436 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
437
438 def test_escape_url(self):
439 self.assertEqual(
440 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
441 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
442 )
443 self.assertEqual(
444 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'),
445 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
446 )
447 self.assertEqual(
448 escape_url('http://тест.рф/фрагмент'),
449 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
450 )
451 self.assertEqual(
452 escape_url('http://тест.рф/абв?абв=абв#абв'),
453 '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'
454 )
455 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
456
e7b6d122 457 def test_js_to_json_realworld(self):
410f3e73 458 inp = '''{
e7b6d122 459 'clip':{'provider':'pseudo'}
410f3e73
PH
460 }'''
461 self.assertEqual(js_to_json(inp), '''{
e7b6d122 462 "clip":{"provider":"pseudo"}
410f3e73
PH
463 }''')
464 json.loads(js_to_json(inp))
465
e7b6d122
PH
466 inp = '''{
467 'playlist':[{'controls':{'all':null}}]
468 }'''
469 self.assertEqual(js_to_json(inp), '''{
470 "playlist":[{"controls":{"all":null}}]
471 }''')
472
d305dd73
PH
473 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
474 json_code = js_to_json(inp)
475 self.assertEqual(json.loads(json_code), json.loads(inp))
476
e7b6d122
PH
477 def test_js_to_json_edgecases(self):
478 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
479 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
480
481 on = js_to_json('{"abc": true}')
482 self.assertEqual(json.loads(on), {'abc': True})
483
8f4b58d7
PH
484 # Ignore JavaScript code as well
485 on = js_to_json('''{
486 "x": 1,
487 y: "a",
488 z: some.code
489 }''')
490 d = json.loads(on)
491 self.assertEqual(d['x'], 1)
492 self.assertEqual(d['y'], 'a')
493
ba9e68f4
S
494 on = js_to_json('["abc", "def",]')
495 self.assertEqual(json.loads(on), ['abc', 'def'])
496
497 on = js_to_json('{"abc": "def",}')
498 self.assertEqual(json.loads(on), {'abc': 'def'})
499
e4bdb37e
PH
500 def test_clean_html(self):
501 self.assertEqual(clean_html('a:\nb'), 'a: b')
502 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
503
4c0924bb
PH
504 def test_intlist_to_bytes(self):
505 self.assertEqual(
506 intlist_to_bytes([0, 1, 127, 128, 255]),
507 b'\x00\x01\x7f\x80\xff')
508
7d4111ed
PH
509 def test_args_to_str(self):
510 self.assertEqual(
511 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
512 'foo ba/r -baz \'2 be\' \'\''
513 )
514
be64b5b0
PH
515 def test_parse_filesize(self):
516 self.assertEqual(parse_filesize(None), None)
517 self.assertEqual(parse_filesize(''), None)
518 self.assertEqual(parse_filesize('91 B'), 91)
519 self.assertEqual(parse_filesize('foobar'), None)
520 self.assertEqual(parse_filesize('2 MiB'), 2097152)
521 self.assertEqual(parse_filesize('5 GB'), 5000000000)
522 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
4349c07d 523 self.assertEqual(parse_filesize('1,24 KB'), 1240)
be64b5b0 524
5f9b8394
PH
525 def test_version_tuple(self):
526 self.assertEqual(version_tuple('1'), (1,))
527 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
47d7c642 528 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
5f9b8394 529
cae97f65
PH
530 def test_detect_exe_version(self):
531 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
532built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
533configuration: --prefix=/usr --extra-'''), '1.2.1')
534 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
535built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
536 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
537Trying to open render node...
538Success at /dev/dri/renderD128.
539ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
540
05900629
PH
541 def test_age_restricted(self):
542 self.assertFalse(age_restricted(None, 10)) # unrestricted content
543 self.assertFalse(age_restricted(1, None)) # unrestricted policy
544 self.assertFalse(age_restricted(8, 10))
545 self.assertTrue(age_restricted(18, 14))
546 self.assertFalse(age_restricted(18, 18))
547
61ca9a80
PH
548 def test_is_html(self):
549 self.assertFalse(is_html(b'\x49\x44\x43<html'))
550 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
551 self.assertTrue(is_html( # UTF-8 with BOM
552 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
553 self.assertTrue(is_html( # UTF-16-LE
554 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
555 ))
556 self.assertTrue(is_html( # UTF-16-BE
557 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
558 ))
559 self.assertTrue(is_html( # UTF-32-BE
560 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'))
561 self.assertTrue(is_html( # UTF-32-LE
562 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'))
563
cfb56d1a
PH
564 def test_render_table(self):
565 self.assertEqual(
566 render_table(
567 ['a', 'bcd'],
568 [[123, 4], [9999, 51]]),
569 'a bcd\n'
570 '123 4\n'
571 '9999 51')
572
347de493
PH
573 def test_match_str(self):
574 self.assertRaises(ValueError, match_str, 'xy>foobar', {})
575 self.assertFalse(match_str('xy', {'x': 1200}))
576 self.assertTrue(match_str('!xy', {'x': 1200}))
577 self.assertTrue(match_str('x', {'x': 1200}))
578 self.assertFalse(match_str('!x', {'x': 1200}))
579 self.assertTrue(match_str('x', {'x': 0}))
580 self.assertFalse(match_str('x>0', {'x': 0}))
581 self.assertFalse(match_str('x>0', {}))
582 self.assertTrue(match_str('x>?0', {}))
583 self.assertTrue(match_str('x>1K', {'x': 1200}))
584 self.assertFalse(match_str('x>2K', {'x': 1200}))
585 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
586 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
587 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
588 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
589 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
590 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
591 self.assertFalse(match_str(
592 'like_count > 100 & dislike_count <? 50 & description',
593 {'like_count': 90, 'description': 'foo'}))
594 self.assertTrue(match_str(
595 'like_count > 100 & dislike_count <? 50 & description',
596 {'like_count': 190, 'description': 'foo'}))
597 self.assertFalse(match_str(
598 'like_count > 100 & dislike_count <? 50 & description',
599 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
600 self.assertFalse(match_str(
601 'like_count > 100 & dislike_count <? 50 & description',
602 {'like_count': 190, 'dislike_count': 10}))
603
bf6427d2
YCH
604 def test_parse_dfxp_time_expr(self):
605 self.assertEqual(parse_dfxp_time_expr(None), 0.0)
606 self.assertEqual(parse_dfxp_time_expr(''), 0.0)
607 self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
608 self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
609 self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
610 self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
611
612 def test_dfxp2srt(self):
613 dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
614 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
615 <body>
616 <div xml:lang="en">
617 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
618 <p begin="1" end="2">第二行<br/>♪♪</p>
619 <p begin="2" end="3"><span>Third<br/>Line</span></p>
620 </div>
621 </body>
622 </tt>'''
623 srt_data = '''1
62400:00:00,000 --> 00:00:01,000
625The following line contains Chinese characters and special symbols
626
6272
62800:00:01,000 --> 00:00:02,000
629第二行
630♪♪
631
6323
63300:00:02,000 --> 00:00:03,000
634Third
635Line
636
637'''
638 self.assertEqual(dfxp2srt(dfxp_data), srt_data)
639
cfb56d1a 640
dae7c920 641if __name__ == '__main__':
59ae15a5 642 unittest.main()