]> jfr.im git - yt-dlp.git/blame - test/test_utils.py
use mimetype2ext to determine manifest ext in multiple extractors
[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,
5eb6bdce 21 encode_base_n,
e4bdb37e 22 clean_html,
eb9c3edd 23 date_from_str,
a921f407 24 DateRange,
cae97f65 25 detect_exe_version,
5035536e 26 determine_ext,
cbecc9b9 27 dict_get,
6b77d52b 28 encode_compat_str,
29eb5174 29 encodeFilename,
cae97f65
PH
30 escape_rfc3986,
31 escape_url,
8bb56eee 32 extract_attributes,
5379a2d4 33 ExtractorError,
a921f407 34 find_xpath_attr,
5aafe895 35 fix_xml_ampersands,
9c44d242 36 InAdvancePagedList,
cae97f65 37 intlist_to_bytes,
61ca9a80 38 is_html,
cae97f65
PH
39 js_to_json,
40 limit_length,
5bc880b9 41 ohdave_rsa_encrypt,
cae97f65
PH
42 OnDemandPagedList,
43 orderedSet,
608d11f5 44 parse_duration,
cae97f65 45 parse_filesize,
fb47597b 46 parse_count,
cae97f65 47 parse_iso8601,
62e609ab 48 read_batch_urls,
29eb5174 49 sanitize_filename,
a2aaf4db 50 sanitize_path,
a4bcaad7 51 prepend_extension,
b3ed15b7 52 replace_extension,
46bc9b7d
S
53 remove_start,
54 remove_end,
31b2051e 55 remove_quotes,
a6a173c2 56 shell_quote,
29eb5174 57 smuggle_url,
f53c966a 58 str_to_int,
cae97f65 59 strip_jsonp,
29eb5174
PH
60 timeconvert,
61 unescapeHTML,
62 unified_strdate,
46f59e89 63 unified_timestamp,
29eb5174 64 unsmuggle_url,
cae97f65 65 uppercase_escape,
0fe2ff78 66 lowercase_escape,
29eb5174 67 url_basename,
b74fa8cd 68 urlencode_postdata,
1143535d 69 urshift,
fb640d0a 70 update_url_query,
5f9b8394 71 version_tuple,
cae97f65 72 xpath_with_ns,
87f70ab3 73 xpath_element,
5379a2d4 74 xpath_text,
87f70ab3 75 xpath_attr,
cfb56d1a 76 render_table,
347de493 77 match_str,
bf6427d2
YCH
78 parse_dfxp_time_expr,
79 dfxp2srt,
f7126449
S
80 cli_option,
81 cli_valueless_option,
82 cli_bool_option,
a921f407 83)
36e6f62c 84from youtube_dl.compat import (
8bb56eee 85 compat_chr,
36e6f62c 86 compat_etree_fromstring,
fb640d0a 87 compat_urlparse,
88 compat_parse_qs,
36e6f62c 89)
44fb3454 90
627dcfff 91
44fb3454 92class TestUtil(unittest.TestCase):
59ae15a5
PH
93 def test_timeconvert(self):
94 self.assertTrue(timeconvert('') is None)
95 self.assertTrue(timeconvert('bougrg') is None)
96
97 def test_sanitize_filename(self):
98 self.assertEqual(sanitize_filename('abc'), 'abc')
99 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
100
101 self.assertEqual(sanitize_filename('123'), '123')
102
103 self.assertEqual('abc_de', sanitize_filename('abc/de'))
104 self.assertFalse('/' in sanitize_filename('abc/de///'))
105
106 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
107 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
108 self.assertEqual('yes no', sanitize_filename('yes? no'))
109 self.assertEqual('this - that', sanitize_filename('this: that'))
110
111 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
4e408e47 112 aumlaut = 'ä'
59ae15a5 113 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
4e408e47 114 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
59ae15a5
PH
115 self.assertEqual(sanitize_filename(tests), tests)
116
2aeb06d6
PH
117 self.assertEqual(
118 sanitize_filename('New World record at 0:12:34'),
119 'New World record at 0_12_34')
a7440261 120
5a42414b
PH
121 self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
122 self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
a7440261
PH
123 self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
124 self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
2aeb06d6 125
59ae15a5
PH
126 forbidden = '"\0\\/'
127 for fc in forbidden:
128 for fbc in forbidden:
129 self.assertTrue(fbc not in sanitize_filename(fc))
130
131 def test_sanitize_filename_restricted(self):
132 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
133 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
134
135 self.assertEqual(sanitize_filename('123', restricted=True), '123')
136
137 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
138 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
139
140 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
141 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
142 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
143 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
144
79a2e94e
AT
145 tests = 'aäb\u4e2d\u56fd\u7684c'
146 self.assertEqual(sanitize_filename(tests, restricted=True), 'aab_c')
4e408e47 147 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
59ae15a5 148
627dcfff 149 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
59ae15a5
PH
150 for fc in forbidden:
151 for fbc in forbidden:
152 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
153
154 # Handle a common case more neatly
4e408e47
PH
155 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
156 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
59ae15a5
PH
157 # .. but make sure the file name is never empty
158 self.assertTrue(sanitize_filename('-', restricted=True) != '')
159 self.assertTrue(sanitize_filename(':', restricted=True) != '')
160
79a2e94e 161 self.assertEqual(sanitize_filename(
b96f007e 162 'ÂÃÄÀÁÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖŐØŒÙÚÛÜŰÝÞßàáâãäåæçèéêëìíîïðñòóôõöőøœùúûüűýþÿ', restricted=True),
163 'AAAAAAAECEEEEIIIIDNOOOOOOOOEUUUUUYPssaaaaaaaeceeeeiiiionooooooooeuuuuuypy')
79a2e94e 164
796173d0 165 def test_sanitize_ids(self):
314d506b
PH
166 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
167 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
168 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
796173d0 169
a2aaf4db
S
170 def test_sanitize_path(self):
171 if sys.platform != 'win32':
172 return
173
174 self.assertEqual(sanitize_path('abc'), 'abc')
175 self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
176 self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
177 self.assertEqual(sanitize_path('abc|def'), 'abc#def')
178 self.assertEqual(sanitize_path('<>:"|?*'), '#######')
179 self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
180 self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
181
182 self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
183 self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
184
185 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
186 self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
187 self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
188 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
189
f18ef2d1
S
190 self.assertEqual(
191 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
192 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
193
194 self.assertEqual(
195 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
196 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
197 self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
198 self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
199 self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
200
2ebfeaca
S
201 self.assertEqual(sanitize_path('../abc'), '..\\abc')
202 self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
203 self.assertEqual(sanitize_path('./abc'), 'abc')
204 self.assertEqual(sanitize_path('./../abc'), '..\\abc')
205
a4bcaad7
S
206 def test_prepend_extension(self):
207 self.assertEqual(prepend_extension('abc.ext', 'temp'), 'abc.temp.ext')
208 self.assertEqual(prepend_extension('abc.ext', 'temp', 'ext'), 'abc.temp.ext')
209 self.assertEqual(prepend_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
210 self.assertEqual(prepend_extension('abc', 'temp'), 'abc.temp')
211 self.assertEqual(prepend_extension('.abc', 'temp'), '.abc.temp')
212 self.assertEqual(prepend_extension('.abc.ext', 'temp'), '.abc.temp.ext')
213
b3ed15b7
S
214 def test_replace_extension(self):
215 self.assertEqual(replace_extension('abc.ext', 'temp'), 'abc.temp')
216 self.assertEqual(replace_extension('abc.ext', 'temp', 'ext'), 'abc.temp')
217 self.assertEqual(replace_extension('abc.unexpected_ext', 'temp', 'ext'), 'abc.unexpected_ext.temp')
218 self.assertEqual(replace_extension('abc', 'temp'), 'abc.temp')
219 self.assertEqual(replace_extension('.abc', 'temp'), '.abc.temp')
220 self.assertEqual(replace_extension('.abc.ext', 'temp'), '.abc.temp')
221
46bc9b7d
S
222 def test_remove_start(self):
223 self.assertEqual(remove_start(None, 'A - '), None)
224 self.assertEqual(remove_start('A - B', 'A - '), 'B')
225 self.assertEqual(remove_start('B - A', 'A - '), 'B - A')
226
227 def test_remove_end(self):
228 self.assertEqual(remove_end(None, ' - B'), None)
229 self.assertEqual(remove_end('A - B', ' - B'), 'A')
230 self.assertEqual(remove_end('B - A', ' - B'), 'B - A')
231
31b2051e
S
232 def test_remove_quotes(self):
233 self.assertEqual(remove_quotes(None), None)
234 self.assertEqual(remove_quotes('"'), '"')
235 self.assertEqual(remove_quotes("'"), "'")
236 self.assertEqual(remove_quotes(';'), ';')
237 self.assertEqual(remove_quotes('";'), '";')
238 self.assertEqual(remove_quotes('""'), '')
239 self.assertEqual(remove_quotes('";"'), ';')
240
59ae15a5 241 def test_ordered_set(self):
627dcfff 242 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
59ae15a5
PH
243 self.assertEqual(orderedSet([]), [])
244 self.assertEqual(orderedSet([1]), [1])
5f6a1245 245 # keep the list ordered
627dcfff 246 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
59ae15a5
PH
247
248 def test_unescape_html(self):
4e408e47 249 self.assertEqual(unescapeHTML('%20;'), '%20;')
91757b0f
NJ
250 self.assertEqual(unescapeHTML('&#x2F;'), '/')
251 self.assertEqual(unescapeHTML('&#47;'), '/')
7aefc49c
S
252 self.assertEqual(unescapeHTML('&eacute;'), 'é')
253 self.assertEqual(unescapeHTML('&#2013266066;'), '&#2013266066;')
55b2f099
YCH
254 # HTML5 entities
255 self.assertEqual(unescapeHTML('&period;&apos;'), '.\'')
5f6a1245 256
eb9c3edd
JMF
257 def test_date_from_str(self):
258 self.assertEqual(date_from_str('yesterday'), date_from_str('now-1day'))
259 self.assertEqual(date_from_str('now+7day'), date_from_str('now+1week'))
260 self.assertEqual(date_from_str('now+14day'), date_from_str('now+2week'))
261 self.assertEqual(date_from_str('now+365day'), date_from_str('now+1year'))
262 self.assertEqual(date_from_str('now+30day'), date_from_str('now+1month'))
263
bd558525 264 def test_daterange(self):
5f6a1245 265 _20century = DateRange("19000101", "20000101")
bd558525
JMF
266 self.assertFalse("17890714" in _20century)
267 _ac = DateRange("00010101")
268 self.assertTrue("19690721" in _ac)
269 _firstmilenium = DateRange(end="10000101")
270 self.assertTrue("07110427" in _firstmilenium)
37254abc 271
bf50b038
JMF
272 def test_unified_dates(self):
273 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
274 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
275 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
276 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
a69801e2 277 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
026fcc04 278 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
99b67fec 279 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
42bdd9d0
PH
280 self.assertEqual(
281 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
282 '20141126')
9bb8e0a3
PH
283 self.assertEqual(
284 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
285 '20150202')
f160785c 286 self.assertEqual(unified_strdate('Feb 14th 2016 5:45PM'), '20160214')
8cf70de4 287 self.assertEqual(unified_strdate('25-09-2014'), '20140925')
46f59e89 288 self.assertEqual(unified_strdate('27.02.2016 17:30'), '20160227')
6a750402 289 self.assertEqual(unified_strdate('UNKNOWN DATE FORMAT'), None)
dae7c920 290
46f59e89
S
291 def test_unified_timestamps(self):
292 self.assertEqual(unified_timestamp('December 21, 2010'), 1292889600)
293 self.assertEqual(unified_timestamp('8/7/2009'), 1247011200)
294 self.assertEqual(unified_timestamp('Dec 14, 2012'), 1355443200)
295 self.assertEqual(unified_timestamp('2012/10/11 01:56:38 +0000'), 1349920598)
296 self.assertEqual(unified_timestamp('1968 12 10'), -33436800)
297 self.assertEqual(unified_timestamp('1968-12-10'), -33436800)
298 self.assertEqual(unified_timestamp('28/01/2014 21:00:00 +0100'), 1390939200)
299 self.assertEqual(
300 unified_timestamp('11/26/2014 11:30:00 AM PST', day_first=False),
301 1417001400)
302 self.assertEqual(
303 unified_timestamp('2/2/2015 6:47:40 PM', day_first=False),
304 1422902860)
305 self.assertEqual(unified_timestamp('Feb 14th 2016 5:45PM'), 1455471900)
306 self.assertEqual(unified_timestamp('25-09-2014'), 1411603200)
307 self.assertEqual(unified_timestamp('27.02.2016 17:30'), 1456594200)
308 self.assertEqual(unified_timestamp('UNKNOWN DATE FORMAT'), None)
309
5035536e
S
310 def test_determine_ext(self):
311 self.assertEqual(determine_ext('http://example.com/foo/bar.mp4/?download'), 'mp4')
312 self.assertEqual(determine_ext('http://example.com/foo/bar/?download', None), None)
9cb9a5df
S
313 self.assertEqual(determine_ext('http://example.com/foo/bar.nonext/?download', None), None)
314 self.assertEqual(determine_ext('http://example.com/foo/bar/mp4?download', None), None)
315 self.assertEqual(determine_ext('http://example.com/foo/bar.m3u8//?download'), 'm3u8')
5035536e 316
59ae56fa 317 def test_find_xpath_attr(self):
4e408e47 318 testxml = '''<root>
59ae56fa
PH
319 <node/>
320 <node x="a"/>
321 <node x="a" y="c" />
322 <node x="b" y="d" />
ee114368 323 <node x="" />
59ae56fa 324 </root>'''
36e6f62c 325 doc = compat_etree_fromstring(testxml)
59ae56fa 326
ee114368 327 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n'), None)
59ae56fa 328 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
ee114368
S
329 self.assertEqual(find_xpath_attr(doc, './/node', 'n'), None)
330 self.assertEqual(find_xpath_attr(doc, './/node', 'n', 'v'), None)
331 self.assertEqual(find_xpath_attr(doc, './/node', 'x'), doc[1])
59ae56fa 332 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
ee114368
S
333 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'b'), doc[3])
334 self.assertEqual(find_xpath_attr(doc, './/node', 'y'), doc[2])
59ae56fa 335 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
ee114368
S
336 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'd'), doc[3])
337 self.assertEqual(find_xpath_attr(doc, './/node', 'x', ''), doc[4])
59ae56fa 338
d7e66d39 339 def test_xpath_with_ns(self):
4e408e47 340 testxml = '''<root xmlns:media="http://example.com/">
d7e66d39
JMF
341 <media:song>
342 <media:author>The Author</media:author>
343 <url>http://server.com/download.mp3</url>
344 </media:song>
345 </root>'''
36e6f62c 346 doc = compat_etree_fromstring(testxml)
d7e66d39
JMF
347 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
348 self.assertTrue(find('media:song') is not None)
4e408e47
PH
349 self.assertEqual(find('media:song/media:author').text, 'The Author')
350 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
d7e66d39 351
87f70ab3
S
352 def test_xpath_element(self):
353 doc = xml.etree.ElementTree.Element('root')
354 div = xml.etree.ElementTree.SubElement(doc, 'div')
355 p = xml.etree.ElementTree.SubElement(div, 'p')
356 p.text = 'Foo'
357 self.assertEqual(xpath_element(doc, 'div/p'), p)
578c0745
S
358 self.assertEqual(xpath_element(doc, ['div/p']), p)
359 self.assertEqual(xpath_element(doc, ['div/bar', 'div/p']), p)
87f70ab3 360 self.assertEqual(xpath_element(doc, 'div/bar', default='default'), 'default')
578c0745 361 self.assertEqual(xpath_element(doc, ['div/bar'], default='default'), 'default')
87f70ab3 362 self.assertTrue(xpath_element(doc, 'div/bar') is None)
578c0745
S
363 self.assertTrue(xpath_element(doc, ['div/bar']) is None)
364 self.assertTrue(xpath_element(doc, ['div/bar'], 'div/baz') is None)
87f70ab3 365 self.assertRaises(ExtractorError, xpath_element, doc, 'div/bar', fatal=True)
578c0745
S
366 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar'], fatal=True)
367 self.assertRaises(ExtractorError, xpath_element, doc, ['div/bar', 'div/baz'], fatal=True)
87f70ab3 368
5379a2d4
JMF
369 def test_xpath_text(self):
370 testxml = '''<root>
371 <div>
372 <p>Foo</p>
373 </div>
374 </root>'''
36e6f62c 375 doc = compat_etree_fromstring(testxml)
5379a2d4 376 self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
87f70ab3 377 self.assertEqual(xpath_text(doc, 'div/bar', default='default'), 'default')
5379a2d4
JMF
378 self.assertTrue(xpath_text(doc, 'div/bar') is None)
379 self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
380
87f70ab3
S
381 def test_xpath_attr(self):
382 testxml = '''<root>
383 <div>
384 <p x="a">Foo</p>
385 </div>
386 </root>'''
36e6f62c 387 doc = compat_etree_fromstring(testxml)
87f70ab3
S
388 self.assertEqual(xpath_attr(doc, 'div/p', 'x'), 'a')
389 self.assertEqual(xpath_attr(doc, 'div/bar', 'x'), None)
390 self.assertEqual(xpath_attr(doc, 'div/p', 'y'), None)
391 self.assertEqual(xpath_attr(doc, 'div/bar', 'x', default='default'), 'default')
392 self.assertEqual(xpath_attr(doc, 'div/p', 'y', default='default'), 'default')
393 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/bar', 'x', fatal=True)
394 self.assertRaises(ExtractorError, xpath_attr, doc, 'div/p', 'y', fatal=True)
395
9d4660ca 396 def test_smuggle_url(self):
e075a44a 397 data = {"ö": "ö", "abc": [3]}
9d4660ca
PH
398 url = 'https://foo.bar/baz?x=y#a'
399 smug_url = smuggle_url(url, data)
400 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
401 self.assertEqual(url, unsmug_url)
402 self.assertEqual(data, unsmug_data)
403
404 res_url, res_data = unsmuggle_url(url)
405 self.assertEqual(res_url, url)
406 self.assertEqual(res_data, None)
407
dfaa86b7
RA
408 smug_url = smuggle_url(url, {'a': 'b'})
409 smug_smug_url = smuggle_url(smug_url, {'c': 'd'})
410 res_url, res_data = unsmuggle_url(smug_smug_url)
411 self.assertEqual(res_url, url)
412 self.assertEqual(res_data, {'a': 'b', 'c': 'd'})
413
a6a173c2 414 def test_shell_quote(self):
4e408e47
PH
415 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
416 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
a6a173c2 417
f53c966a
JMF
418 def test_str_to_int(self):
419 self.assertEqual(str_to_int('123,456'), 123456)
420 self.assertEqual(str_to_int('123.456'), 123456)
421
29eb5174 422 def test_url_basename(self):
4e408e47
PH
423 self.assertEqual(url_basename('http://foo.de/'), '')
424 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
425 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
426 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
427 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
d6c7a367 428 self.assertEqual(
4e408e47
PH
429 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
430 'trailer.mp4')
9d4660ca 431
608d11f5
PH
432 def test_parse_duration(self):
433 self.assertEqual(parse_duration(None), None)
a5fb718c
S
434 self.assertEqual(parse_duration(False), None)
435 self.assertEqual(parse_duration('invalid'), None)
608d11f5
PH
436 self.assertEqual(parse_duration('1'), 1)
437 self.assertEqual(parse_duration('1337:12'), 80232)
438 self.assertEqual(parse_duration('9:12:43'), 33163)
2db806b4
S
439 self.assertEqual(parse_duration('12:00'), 720)
440 self.assertEqual(parse_duration('00:01:01'), 61)
608d11f5 441 self.assertEqual(parse_duration('x:y'), None)
2db806b4 442 self.assertEqual(parse_duration('3h11m53s'), 11513)
ca7b3246
S
443 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
444 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
445 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
2db806b4
S
446 self.assertEqual(parse_duration('62m45s'), 3765)
447 self.assertEqual(parse_duration('6m59s'), 419)
448 self.assertEqual(parse_duration('49s'), 49)
449 self.assertEqual(parse_duration('0h0m0s'), 0)
450 self.assertEqual(parse_duration('0m0s'), 0)
451 self.assertEqual(parse_duration('0s'), 0)
7adcbe75 452 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
6a68bb57 453 self.assertEqual(parse_duration('T30M38S'), 1838)
e8df5cee
PH
454 self.assertEqual(parse_duration('5 s'), 5)
455 self.assertEqual(parse_duration('3 min'), 180)
456 self.assertEqual(parse_duration('2.5 hours'), 9000)
8f4b58d7
PH
457 self.assertEqual(parse_duration('02:03:04'), 7384)
458 self.assertEqual(parse_duration('01:02:03:04'), 93784)
3e675fab 459 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
9c29bc69 460 self.assertEqual(parse_duration('87 Min.'), 5220)
acaff495 461 self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
608d11f5 462
5aafe895
PH
463 def test_fix_xml_ampersands(self):
464 self.assertEqual(
465 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
466 self.assertEqual(
467 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
468 '"&amp;x=y&amp;wrong;&amp;z=a')
469 self.assertEqual(
470 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
471 '&amp;&apos;&gt;&lt;&quot;')
472 self.assertEqual(
473 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
474 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
475
b7ab0590
PH
476 def test_paged_list(self):
477 def testPL(size, pagesize, sliceargs, expected):
478 def get_page(pagenum):
479 firstid = pagenum * pagesize
480 upto = min(size, pagenum * pagesize + pagesize)
481 for i in range(firstid, upto):
482 yield i
483
9c44d242 484 pl = OnDemandPagedList(get_page, pagesize)
b7ab0590
PH
485 got = pl.getslice(*sliceargs)
486 self.assertEqual(got, expected)
487
9c44d242
PH
488 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
489 got = iapl.getslice(*sliceargs)
490 self.assertEqual(got, expected)
491
b7ab0590
PH
492 testPL(5, 2, (), [0, 1, 2, 3, 4])
493 testPL(5, 2, (1,), [1, 2, 3, 4])
494 testPL(5, 2, (2,), [2, 3, 4])
495 testPL(5, 2, (4,), [4])
496 testPL(5, 2, (0, 3), [0, 1, 2])
497 testPL(5, 2, (1, 4), [1, 2, 3])
498 testPL(5, 2, (2, 99), [2, 3, 4])
499 testPL(5, 2, (20, 99), [])
500
62e609ab 501 def test_read_batch_urls(self):
4e408e47 502 f = io.StringIO('''\xef\xbb\xbf foo
62e609ab
PH
503 bar\r
504 baz
505 # More after this line\r
506 ; or after this
507 bam''')
4e408e47 508 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
62e609ab 509
b74fa8cd
JMF
510 def test_urlencode_postdata(self):
511 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
512 self.assertTrue(isinstance(data, bytes))
513
fb640d0a 514 def test_update_url_query(self):
515 def query_dict(url):
516 return compat_parse_qs(compat_urlparse.urlparse(url).query)
517 self.assertEqual(query_dict(update_url_query(
518 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
519 query_dict('http://example.com/path?quality=HD&format=mp4'))
520 self.assertEqual(query_dict(update_url_query(
521 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
522 query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
523 self.assertEqual(query_dict(update_url_query(
524 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
525 query_dict('http://example.com/path?fields=id,formats,subtitles'))
526 self.assertEqual(query_dict(update_url_query(
527 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
528 query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
529 self.assertEqual(query_dict(update_url_query(
530 'http://example.com/path?manifest=f4m', {'manifest': []})),
531 query_dict('http://example.com/path'))
532 self.assertEqual(query_dict(update_url_query(
533 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
534 query_dict('http://example.com/path?system=LINUX'))
535 self.assertEqual(query_dict(update_url_query(
536 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
537 query_dict('http://example.com/path?fields=id,formats,subtitles'))
3201a67f 538 self.assertEqual(query_dict(update_url_query(
539 'http://example.com/path', {'width': 1080, 'height': 720})),
540 query_dict('http://example.com/path?width=1080&height=720'))
541 self.assertEqual(query_dict(update_url_query(
542 'http://example.com/path', {'bitrate': 5020.43})),
543 query_dict('http://example.com/path?bitrate=5020.43'))
544 self.assertEqual(query_dict(update_url_query(
545 'http://example.com/path', {'test': '第二行тест'})),
546 query_dict('http://example.com/path?test=%E7%AC%AC%E4%BA%8C%E8%A1%8C%D1%82%D0%B5%D1%81%D1%82'))
fb640d0a 547
cbecc9b9 548 def test_dict_get(self):
86296ad2
S
549 FALSE_VALUES = {
550 'none': None,
551 'false': False,
552 'zero': 0,
553 'empty_string': '',
554 'empty_list': [],
cbecc9b9 555 }
86296ad2
S
556 d = FALSE_VALUES.copy()
557 d['a'] = 42
cbecc9b9
S
558 self.assertEqual(dict_get(d, 'a'), 42)
559 self.assertEqual(dict_get(d, 'b'), None)
560 self.assertEqual(dict_get(d, 'b', 42), 42)
561 self.assertEqual(dict_get(d, ('a', )), 42)
562 self.assertEqual(dict_get(d, ('b', 'a', )), 42)
563 self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
564 self.assertEqual(dict_get(d, ('b', 'c', )), None)
565 self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
86296ad2
S
566 for key, false_value in FALSE_VALUES.items():
567 self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
568 self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
cbecc9b9 569
6b77d52b
S
570 def test_encode_compat_str(self):
571 self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
572 self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
573
912b38b4
PH
574 def test_parse_iso8601(self):
575 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
576 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
577 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
6ad4013d 578 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
52c3a6e4
S
579 self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
580 self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
912b38b4 581
fac55558
PH
582 def test_strip_jsonp(self):
583 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
584 d = json.loads(stripped)
585 self.assertEqual(d, [{"id": "532cb", "x": 3}])
586
609a61e3
PH
587 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
588 d = json.loads(stripped)
589 self.assertEqual(d, {'STATUS': 'OK'})
590
8411229b
S
591 stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
592 d = json.loads(stripped)
593 self.assertEqual(d, {'status': 'success'})
594
173a7026 595 def test_uppercase_escape(self):
4e408e47
PH
596 self.assertEqual(uppercase_escape('aä'), 'aä')
597 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
fac55558 598
0fe2ff78
YCH
599 def test_lowercase_escape(self):
600 self.assertEqual(lowercase_escape('aä'), 'aä')
601 self.assertEqual(lowercase_escape('\\u0026'), '&')
602
a020a0dc
PH
603 def test_limit_length(self):
604 self.assertEqual(limit_length(None, 12), None)
605 self.assertEqual(limit_length('foo', 12), 'foo')
606 self.assertTrue(
607 limit_length('foo bar baz asd', 12).startswith('foo bar'))
608 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
609
d05cfe06
S
610 def test_escape_rfc3986(self):
611 reserved = "!*'();:@&=+$,/?#[]"
612 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
613 self.assertEqual(escape_rfc3986(reserved), reserved)
614 self.assertEqual(escape_rfc3986(unreserved), unreserved)
615 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
616 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
617 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
618 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
619
620 def test_escape_url(self):
621 self.assertEqual(
622 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
623 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
624 )
625 self.assertEqual(
626 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'),
627 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
628 )
629 self.assertEqual(
630 escape_url('http://тест.рф/фрагмент'),
2d60465e 631 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
d05cfe06
S
632 )
633 self.assertEqual(
634 escape_url('http://тест.рф/абв?абв=абв#абв'),
81f36eba 635 'http://xn--e1aybc.xn--p1ai/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
d05cfe06
S
636 )
637 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
638
e7b6d122 639 def test_js_to_json_realworld(self):
410f3e73 640 inp = '''{
e7b6d122 641 'clip':{'provider':'pseudo'}
410f3e73
PH
642 }'''
643 self.assertEqual(js_to_json(inp), '''{
e7b6d122 644 "clip":{"provider":"pseudo"}
410f3e73
PH
645 }''')
646 json.loads(js_to_json(inp))
647
e7b6d122
PH
648 inp = '''{
649 'playlist':[{'controls':{'all':null}}]
650 }'''
651 self.assertEqual(js_to_json(inp), '''{
652 "playlist":[{"controls":{"all":null}}]
653 }''')
654
d01949dc
S
655 inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
656 self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
657
d305dd73
PH
658 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
659 json_code = js_to_json(inp)
660 self.assertEqual(json.loads(json_code), json.loads(inp))
661
89ac4a19
S
662 inp = '''{
663 0:{src:'skipped', type: 'application/dash+xml'},
664 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
665 }'''
666 self.assertEqual(js_to_json(inp), '''{
667 "0":{"src":"skipped", "type": "application/dash+xml"},
668 "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
669 }''')
670
47212f7b
YCH
671 inp = '''{"foo":101}'''
672 self.assertEqual(js_to_json(inp), '''{"foo":101}''')
673
e7b6d122
PH
674 def test_js_to_json_edgecases(self):
675 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
676 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
677
678 on = js_to_json('{"abc": true}')
679 self.assertEqual(json.loads(on), {'abc': True})
680
8f4b58d7
PH
681 # Ignore JavaScript code as well
682 on = js_to_json('''{
683 "x": 1,
684 y: "a",
685 z: some.code
686 }''')
687 d = json.loads(on)
688 self.assertEqual(d['x'], 1)
689 self.assertEqual(d['y'], 'a')
690
ba9e68f4
S
691 on = js_to_json('["abc", "def",]')
692 self.assertEqual(json.loads(on), ['abc', 'def'])
693
694 on = js_to_json('{"abc": "def",}')
695 self.assertEqual(json.loads(on), {'abc': 'def'})
696
bd1e4844 697 on = js_to_json('{ 0: /* " \n */ ",]" , }')
698 self.assertEqual(json.loads(on), {'0': ',]'})
699
700 on = js_to_json(r'["<p>x<\/p>"]')
701 self.assertEqual(json.loads(on), ['<p>x</p>'])
702
703 on = js_to_json(r'["\xaa"]')
704 self.assertEqual(json.loads(on), ['\u00aa'])
705
706 on = js_to_json("['a\\\nb']")
707 self.assertEqual(json.loads(on), ['ab'])
708
89ac4a19
S
709 on = js_to_json('{0xff:0xff}')
710 self.assertEqual(json.loads(on), {'255': 255})
711
712 on = js_to_json('{077:077}')
713 self.assertEqual(json.loads(on), {'63': 63})
714
715 on = js_to_json('{42:42}')
716 self.assertEqual(json.loads(on), {'42': 42})
717
8bb56eee
BF
718 def test_extract_attributes(self):
719 self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
720 self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
721 self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
722 self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
723 self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
724 self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
725 self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
726 self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
727 self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
c5229f39
S
728 self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
729 self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
8bb56eee
BF
730 self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
731 self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
732 self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
733 self.assertEqual(extract_attributes('<e x >'), {'x': None})
734 self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
735 self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
736 self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
737 self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
738 self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
739 self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
740 self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
c5229f39 741 self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
8bb56eee
BF
742 self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
743 self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
744 self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
745 self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
746 self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
747 # "Narrow" Python builds don't support unicode code points outside BMP.
748 try:
749 compat_chr(0x10000)
750 supports_outside_bmp = True
751 except ValueError:
752 supports_outside_bmp = False
753 if supports_outside_bmp:
754 self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
755
e4bdb37e
PH
756 def test_clean_html(self):
757 self.assertEqual(clean_html('a:\nb'), 'a: b')
758 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
759
4c0924bb
PH
760 def test_intlist_to_bytes(self):
761 self.assertEqual(
762 intlist_to_bytes([0, 1, 127, 128, 255]),
763 b'\x00\x01\x7f\x80\xff')
764
7d4111ed
PH
765 def test_args_to_str(self):
766 self.assertEqual(
767 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
768 'foo ba/r -baz \'2 be\' \'\''
769 )
770
be64b5b0
PH
771 def test_parse_filesize(self):
772 self.assertEqual(parse_filesize(None), None)
773 self.assertEqual(parse_filesize(''), None)
774 self.assertEqual(parse_filesize('91 B'), 91)
775 self.assertEqual(parse_filesize('foobar'), None)
776 self.assertEqual(parse_filesize('2 MiB'), 2097152)
777 self.assertEqual(parse_filesize('5 GB'), 5000000000)
778 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
4349c07d 779 self.assertEqual(parse_filesize('1,24 KB'), 1240)
be64b5b0 780
fb47597b
S
781 def test_parse_count(self):
782 self.assertEqual(parse_count(None), None)
783 self.assertEqual(parse_count(''), None)
784 self.assertEqual(parse_count('0'), 0)
785 self.assertEqual(parse_count('1000'), 1000)
786 self.assertEqual(parse_count('1.000'), 1000)
787 self.assertEqual(parse_count('1.1k'), 1100)
788 self.assertEqual(parse_count('1.1kk'), 1100000)
782b1b5b
JMF
789 self.assertEqual(parse_count('1.1kk '), 1100000)
790 self.assertEqual(parse_count('1.1kk views'), 1100000)
fb47597b 791
5f9b8394
PH
792 def test_version_tuple(self):
793 self.assertEqual(version_tuple('1'), (1,))
794 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
47d7c642 795 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
5f9b8394 796
cae97f65
PH
797 def test_detect_exe_version(self):
798 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
799built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
800configuration: --prefix=/usr --extra-'''), '1.2.1')
801 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
802built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
803 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
804Trying to open render node...
805Success at /dev/dri/renderD128.
806ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
807
05900629
PH
808 def test_age_restricted(self):
809 self.assertFalse(age_restricted(None, 10)) # unrestricted content
810 self.assertFalse(age_restricted(1, None)) # unrestricted policy
811 self.assertFalse(age_restricted(8, 10))
812 self.assertTrue(age_restricted(18, 14))
813 self.assertFalse(age_restricted(18, 18))
814
61ca9a80
PH
815 def test_is_html(self):
816 self.assertFalse(is_html(b'\x49\x44\x43<html'))
817 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
818 self.assertTrue(is_html( # UTF-8 with BOM
819 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
820 self.assertTrue(is_html( # UTF-16-LE
821 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
822 ))
823 self.assertTrue(is_html( # UTF-16-BE
824 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
825 ))
826 self.assertTrue(is_html( # UTF-32-BE
827 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'))
828 self.assertTrue(is_html( # UTF-32-LE
829 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'))
830
cfb56d1a
PH
831 def test_render_table(self):
832 self.assertEqual(
833 render_table(
834 ['a', 'bcd'],
835 [[123, 4], [9999, 51]]),
836 'a bcd\n'
837 '123 4\n'
838 '9999 51')
839
347de493
PH
840 def test_match_str(self):
841 self.assertRaises(ValueError, match_str, 'xy>foobar', {})
842 self.assertFalse(match_str('xy', {'x': 1200}))
843 self.assertTrue(match_str('!xy', {'x': 1200}))
844 self.assertTrue(match_str('x', {'x': 1200}))
845 self.assertFalse(match_str('!x', {'x': 1200}))
846 self.assertTrue(match_str('x', {'x': 0}))
847 self.assertFalse(match_str('x>0', {'x': 0}))
848 self.assertFalse(match_str('x>0', {}))
849 self.assertTrue(match_str('x>?0', {}))
850 self.assertTrue(match_str('x>1K', {'x': 1200}))
851 self.assertFalse(match_str('x>2K', {'x': 1200}))
852 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
853 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
854 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
855 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
856 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
857 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
858 self.assertFalse(match_str(
859 'like_count > 100 & dislike_count <? 50 & description',
860 {'like_count': 90, 'description': 'foo'}))
861 self.assertTrue(match_str(
862 'like_count > 100 & dislike_count <? 50 & description',
863 {'like_count': 190, 'description': 'foo'}))
864 self.assertFalse(match_str(
865 'like_count > 100 & dislike_count <? 50 & description',
866 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
867 self.assertFalse(match_str(
868 'like_count > 100 & dislike_count <? 50 & description',
869 {'like_count': 190, 'dislike_count': 10}))
870
bf6427d2 871 def test_parse_dfxp_time_expr(self):
d631d5f9
YCH
872 self.assertEqual(parse_dfxp_time_expr(None), None)
873 self.assertEqual(parse_dfxp_time_expr(''), None)
bf6427d2
YCH
874 self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
875 self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
876 self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
877 self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
db2fe38b 878 self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
bf6427d2
YCH
879
880 def test_dfxp2srt(self):
881 dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
882 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
883 <body>
884 <div xml:lang="en">
885 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
886 <p begin="1" end="2">第二行<br/>♪♪</p>
7dff0363 887 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
d631d5f9
YCH
888 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
889 <p begin="-1" end="-1">Ignore, two</p>
890 <p begin="3" dur="-1">Ignored, three</p>
bf6427d2
YCH
891 </div>
892 </body>
893 </tt>'''
894 srt_data = '''1
89500:00:00,000 --> 00:00:01,000
896The following line contains Chinese characters and special symbols
897
8982
89900:00:01,000 --> 00:00:02,000
900第二行
901♪♪
902
9033
90400:00:02,000 --> 00:00:03,000
905Third
906Line
907
908'''
909 self.assertEqual(dfxp2srt(dfxp_data), srt_data)
910
1b0427e6
YCH
911 dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
912 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
913 <body>
914 <div xml:lang="en">
915 <p begin="0" end="1">The first line</p>
916 </div>
917 </body>
918 </tt>'''
919 srt_data = '''1
92000:00:00,000 --> 00:00:01,000
921The first line
922
923'''
924 self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
925
f7126449
S
926 def test_cli_option(self):
927 self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
928 self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
929 self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
930
931 def test_cli_valueless_option(self):
932 self.assertEqual(cli_valueless_option(
933 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
934 self.assertEqual(cli_valueless_option(
935 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
936 self.assertEqual(cli_valueless_option(
937 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
938 self.assertEqual(cli_valueless_option(
939 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
940 self.assertEqual(cli_valueless_option(
941 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
942 self.assertEqual(cli_valueless_option(
943 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
944
945 def test_cli_bool_option(self):
946 self.assertEqual(
947 cli_bool_option(
948 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
949 ['--no-check-certificate', 'true'])
950 self.assertEqual(
951 cli_bool_option(
952 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
953 ['--no-check-certificate=true'])
954 self.assertEqual(
955 cli_bool_option(
956 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
957 ['--check-certificate', 'false'])
958 self.assertEqual(
959 cli_bool_option(
960 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
961 ['--check-certificate=false'])
962 self.assertEqual(
963 cli_bool_option(
964 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
965 ['--check-certificate', 'true'])
966 self.assertEqual(
967 cli_bool_option(
968 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
969 ['--check-certificate=true'])
970
5bc880b9
YCH
971 def test_ohdave_rsa_encrypt(self):
972 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
973 e = 65537
974
975 self.assertEqual(
976 ohdave_rsa_encrypt(b'aa111222', e, N),
977 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
cfb56d1a 978
5eb6bdce
YCH
979 def test_encode_base_n(self):
980 self.assertEqual(encode_base_n(0, 30), '0')
981 self.assertEqual(encode_base_n(80, 30), '2k')
982
983 custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
984 self.assertEqual(encode_base_n(0, 30, custom_table), '9')
985 self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
986
987 self.assertRaises(ValueError, encode_base_n, 0, 70)
988 self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
989
1143535d
YCH
990 def test_urshift(self):
991 self.assertEqual(urshift(3, 1), 1)
992 self.assertEqual(urshift(-3, 1), 2147483646)
993
dae7c920 994if __name__ == '__main__':
59ae15a5 995 unittest.main()