]> jfr.im git - yt-dlp.git/blame - test/test_utils.py
[kaltura] fix extraction error for videos from multiple kaltura servers
[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
a6a173c2 408 def test_shell_quote(self):
4e408e47
PH
409 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
410 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
a6a173c2 411
f53c966a
JMF
412 def test_str_to_int(self):
413 self.assertEqual(str_to_int('123,456'), 123456)
414 self.assertEqual(str_to_int('123.456'), 123456)
415
29eb5174 416 def test_url_basename(self):
4e408e47
PH
417 self.assertEqual(url_basename('http://foo.de/'), '')
418 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
419 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
420 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
421 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
d6c7a367 422 self.assertEqual(
4e408e47
PH
423 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
424 'trailer.mp4')
9d4660ca 425
608d11f5
PH
426 def test_parse_duration(self):
427 self.assertEqual(parse_duration(None), None)
a5fb718c
S
428 self.assertEqual(parse_duration(False), None)
429 self.assertEqual(parse_duration('invalid'), None)
608d11f5
PH
430 self.assertEqual(parse_duration('1'), 1)
431 self.assertEqual(parse_duration('1337:12'), 80232)
432 self.assertEqual(parse_duration('9:12:43'), 33163)
2db806b4
S
433 self.assertEqual(parse_duration('12:00'), 720)
434 self.assertEqual(parse_duration('00:01:01'), 61)
608d11f5 435 self.assertEqual(parse_duration('x:y'), None)
2db806b4 436 self.assertEqual(parse_duration('3h11m53s'), 11513)
ca7b3246
S
437 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
438 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
439 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
2db806b4
S
440 self.assertEqual(parse_duration('62m45s'), 3765)
441 self.assertEqual(parse_duration('6m59s'), 419)
442 self.assertEqual(parse_duration('49s'), 49)
443 self.assertEqual(parse_duration('0h0m0s'), 0)
444 self.assertEqual(parse_duration('0m0s'), 0)
445 self.assertEqual(parse_duration('0s'), 0)
7adcbe75 446 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
6a68bb57 447 self.assertEqual(parse_duration('T30M38S'), 1838)
e8df5cee
PH
448 self.assertEqual(parse_duration('5 s'), 5)
449 self.assertEqual(parse_duration('3 min'), 180)
450 self.assertEqual(parse_duration('2.5 hours'), 9000)
8f4b58d7
PH
451 self.assertEqual(parse_duration('02:03:04'), 7384)
452 self.assertEqual(parse_duration('01:02:03:04'), 93784)
3e675fab 453 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
9c29bc69 454 self.assertEqual(parse_duration('87 Min.'), 5220)
acaff495 455 self.assertEqual(parse_duration('PT1H0.040S'), 3600.04)
608d11f5 456
5aafe895
PH
457 def test_fix_xml_ampersands(self):
458 self.assertEqual(
459 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
460 self.assertEqual(
461 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
462 '"&amp;x=y&amp;wrong;&amp;z=a')
463 self.assertEqual(
464 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
465 '&amp;&apos;&gt;&lt;&quot;')
466 self.assertEqual(
467 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
468 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
469
b7ab0590
PH
470 def test_paged_list(self):
471 def testPL(size, pagesize, sliceargs, expected):
472 def get_page(pagenum):
473 firstid = pagenum * pagesize
474 upto = min(size, pagenum * pagesize + pagesize)
475 for i in range(firstid, upto):
476 yield i
477
9c44d242 478 pl = OnDemandPagedList(get_page, pagesize)
b7ab0590
PH
479 got = pl.getslice(*sliceargs)
480 self.assertEqual(got, expected)
481
9c44d242
PH
482 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
483 got = iapl.getslice(*sliceargs)
484 self.assertEqual(got, expected)
485
b7ab0590
PH
486 testPL(5, 2, (), [0, 1, 2, 3, 4])
487 testPL(5, 2, (1,), [1, 2, 3, 4])
488 testPL(5, 2, (2,), [2, 3, 4])
489 testPL(5, 2, (4,), [4])
490 testPL(5, 2, (0, 3), [0, 1, 2])
491 testPL(5, 2, (1, 4), [1, 2, 3])
492 testPL(5, 2, (2, 99), [2, 3, 4])
493 testPL(5, 2, (20, 99), [])
494
62e609ab 495 def test_read_batch_urls(self):
4e408e47 496 f = io.StringIO('''\xef\xbb\xbf foo
62e609ab
PH
497 bar\r
498 baz
499 # More after this line\r
500 ; or after this
501 bam''')
4e408e47 502 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
62e609ab 503
b74fa8cd
JMF
504 def test_urlencode_postdata(self):
505 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
506 self.assertTrue(isinstance(data, bytes))
507
fb640d0a 508 def test_update_url_query(self):
509 def query_dict(url):
510 return compat_parse_qs(compat_urlparse.urlparse(url).query)
511 self.assertEqual(query_dict(update_url_query(
512 'http://example.com/path', {'quality': ['HD'], 'format': ['mp4']})),
513 query_dict('http://example.com/path?quality=HD&format=mp4'))
514 self.assertEqual(query_dict(update_url_query(
515 'http://example.com/path', {'system': ['LINUX', 'WINDOWS']})),
516 query_dict('http://example.com/path?system=LINUX&system=WINDOWS'))
517 self.assertEqual(query_dict(update_url_query(
518 'http://example.com/path', {'fields': 'id,formats,subtitles'})),
519 query_dict('http://example.com/path?fields=id,formats,subtitles'))
520 self.assertEqual(query_dict(update_url_query(
521 'http://example.com/path', {'fields': ('id,formats,subtitles', 'thumbnails')})),
522 query_dict('http://example.com/path?fields=id,formats,subtitles&fields=thumbnails'))
523 self.assertEqual(query_dict(update_url_query(
524 'http://example.com/path?manifest=f4m', {'manifest': []})),
525 query_dict('http://example.com/path'))
526 self.assertEqual(query_dict(update_url_query(
527 'http://example.com/path?system=LINUX&system=WINDOWS', {'system': 'LINUX'})),
528 query_dict('http://example.com/path?system=LINUX'))
529 self.assertEqual(query_dict(update_url_query(
530 'http://example.com/path', {'fields': b'id,formats,subtitles'})),
531 query_dict('http://example.com/path?fields=id,formats,subtitles'))
3201a67f 532 self.assertEqual(query_dict(update_url_query(
533 'http://example.com/path', {'width': 1080, 'height': 720})),
534 query_dict('http://example.com/path?width=1080&height=720'))
535 self.assertEqual(query_dict(update_url_query(
536 'http://example.com/path', {'bitrate': 5020.43})),
537 query_dict('http://example.com/path?bitrate=5020.43'))
538 self.assertEqual(query_dict(update_url_query(
539 'http://example.com/path', {'test': '第二行тест'})),
540 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 541
cbecc9b9 542 def test_dict_get(self):
86296ad2
S
543 FALSE_VALUES = {
544 'none': None,
545 'false': False,
546 'zero': 0,
547 'empty_string': '',
548 'empty_list': [],
cbecc9b9 549 }
86296ad2
S
550 d = FALSE_VALUES.copy()
551 d['a'] = 42
cbecc9b9
S
552 self.assertEqual(dict_get(d, 'a'), 42)
553 self.assertEqual(dict_get(d, 'b'), None)
554 self.assertEqual(dict_get(d, 'b', 42), 42)
555 self.assertEqual(dict_get(d, ('a', )), 42)
556 self.assertEqual(dict_get(d, ('b', 'a', )), 42)
557 self.assertEqual(dict_get(d, ('b', 'c', 'a', 'd', )), 42)
558 self.assertEqual(dict_get(d, ('b', 'c', )), None)
559 self.assertEqual(dict_get(d, ('b', 'c', ), 42), 42)
86296ad2
S
560 for key, false_value in FALSE_VALUES.items():
561 self.assertEqual(dict_get(d, ('b', 'c', key, )), None)
562 self.assertEqual(dict_get(d, ('b', 'c', key, ), skip_false_values=False), false_value)
cbecc9b9 563
6b77d52b
S
564 def test_encode_compat_str(self):
565 self.assertEqual(encode_compat_str(b'\xd1\x82\xd0\xb5\xd1\x81\xd1\x82', 'utf-8'), 'тест')
566 self.assertEqual(encode_compat_str('тест', 'utf-8'), 'тест')
567
912b38b4
PH
568 def test_parse_iso8601(self):
569 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
570 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
571 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
6ad4013d 572 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
52c3a6e4
S
573 self.assertEqual(parse_iso8601('2015-09-29T08:27:31.727'), 1443515251)
574 self.assertEqual(parse_iso8601('2015-09-29T08-27-31.727'), None)
912b38b4 575
fac55558
PH
576 def test_strip_jsonp(self):
577 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
578 d = json.loads(stripped)
579 self.assertEqual(d, [{"id": "532cb", "x": 3}])
580
609a61e3
PH
581 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
582 d = json.loads(stripped)
583 self.assertEqual(d, {'STATUS': 'OK'})
584
8411229b
S
585 stripped = strip_jsonp('ps.embedHandler({"status": "success"});')
586 d = json.loads(stripped)
587 self.assertEqual(d, {'status': 'success'})
588
173a7026 589 def test_uppercase_escape(self):
4e408e47
PH
590 self.assertEqual(uppercase_escape('aä'), 'aä')
591 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
fac55558 592
0fe2ff78
YCH
593 def test_lowercase_escape(self):
594 self.assertEqual(lowercase_escape('aä'), 'aä')
595 self.assertEqual(lowercase_escape('\\u0026'), '&')
596
a020a0dc
PH
597 def test_limit_length(self):
598 self.assertEqual(limit_length(None, 12), None)
599 self.assertEqual(limit_length('foo', 12), 'foo')
600 self.assertTrue(
601 limit_length('foo bar baz asd', 12).startswith('foo bar'))
602 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
603
d05cfe06
S
604 def test_escape_rfc3986(self):
605 reserved = "!*'();:@&=+$,/?#[]"
606 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
607 self.assertEqual(escape_rfc3986(reserved), reserved)
608 self.assertEqual(escape_rfc3986(unreserved), unreserved)
609 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
610 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
611 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
612 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
613
614 def test_escape_url(self):
615 self.assertEqual(
616 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
617 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
618 )
619 self.assertEqual(
620 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'),
621 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
622 )
623 self.assertEqual(
624 escape_url('http://тест.рф/фрагмент'),
2d60465e 625 'http://xn--e1aybc.xn--p1ai/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
d05cfe06
S
626 )
627 self.assertEqual(
628 escape_url('http://тест.рф/абв?абв=абв#абв'),
81f36eba 629 '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
630 )
631 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
632
e7b6d122 633 def test_js_to_json_realworld(self):
410f3e73 634 inp = '''{
e7b6d122 635 'clip':{'provider':'pseudo'}
410f3e73
PH
636 }'''
637 self.assertEqual(js_to_json(inp), '''{
e7b6d122 638 "clip":{"provider":"pseudo"}
410f3e73
PH
639 }''')
640 json.loads(js_to_json(inp))
641
e7b6d122
PH
642 inp = '''{
643 'playlist':[{'controls':{'all':null}}]
644 }'''
645 self.assertEqual(js_to_json(inp), '''{
646 "playlist":[{"controls":{"all":null}}]
647 }''')
648
d01949dc
S
649 inp = '''"The CW\\'s \\'Crazy Ex-Girlfriend\\'"'''
650 self.assertEqual(js_to_json(inp), '''"The CW's 'Crazy Ex-Girlfriend'"''')
651
d305dd73
PH
652 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
653 json_code = js_to_json(inp)
654 self.assertEqual(json.loads(json_code), json.loads(inp))
655
89ac4a19
S
656 inp = '''{
657 0:{src:'skipped', type: 'application/dash+xml'},
658 1:{src:'skipped', type: 'application/vnd.apple.mpegURL'},
659 }'''
660 self.assertEqual(js_to_json(inp), '''{
661 "0":{"src":"skipped", "type": "application/dash+xml"},
662 "1":{"src":"skipped", "type": "application/vnd.apple.mpegURL"}
663 }''')
664
47212f7b
YCH
665 inp = '''{"foo":101}'''
666 self.assertEqual(js_to_json(inp), '''{"foo":101}''')
667
e7b6d122
PH
668 def test_js_to_json_edgecases(self):
669 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
670 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
671
672 on = js_to_json('{"abc": true}')
673 self.assertEqual(json.loads(on), {'abc': True})
674
8f4b58d7
PH
675 # Ignore JavaScript code as well
676 on = js_to_json('''{
677 "x": 1,
678 y: "a",
679 z: some.code
680 }''')
681 d = json.loads(on)
682 self.assertEqual(d['x'], 1)
683 self.assertEqual(d['y'], 'a')
684
ba9e68f4
S
685 on = js_to_json('["abc", "def",]')
686 self.assertEqual(json.loads(on), ['abc', 'def'])
687
688 on = js_to_json('{"abc": "def",}')
689 self.assertEqual(json.loads(on), {'abc': 'def'})
690
bd1e4844 691 on = js_to_json('{ 0: /* " \n */ ",]" , }')
692 self.assertEqual(json.loads(on), {'0': ',]'})
693
694 on = js_to_json(r'["<p>x<\/p>"]')
695 self.assertEqual(json.loads(on), ['<p>x</p>'])
696
697 on = js_to_json(r'["\xaa"]')
698 self.assertEqual(json.loads(on), ['\u00aa'])
699
700 on = js_to_json("['a\\\nb']")
701 self.assertEqual(json.loads(on), ['ab'])
702
89ac4a19
S
703 on = js_to_json('{0xff:0xff}')
704 self.assertEqual(json.loads(on), {'255': 255})
705
706 on = js_to_json('{077:077}')
707 self.assertEqual(json.loads(on), {'63': 63})
708
709 on = js_to_json('{42:42}')
710 self.assertEqual(json.loads(on), {'42': 42})
711
8bb56eee
BF
712 def test_extract_attributes(self):
713 self.assertEqual(extract_attributes('<e x="y">'), {'x': 'y'})
714 self.assertEqual(extract_attributes("<e x='y'>"), {'x': 'y'})
715 self.assertEqual(extract_attributes('<e x=y>'), {'x': 'y'})
716 self.assertEqual(extract_attributes('<e x="a \'b\' c">'), {'x': "a 'b' c"})
717 self.assertEqual(extract_attributes('<e x=\'a "b" c\'>'), {'x': 'a "b" c'})
718 self.assertEqual(extract_attributes('<e x="&#121;">'), {'x': 'y'})
719 self.assertEqual(extract_attributes('<e x="&#x79;">'), {'x': 'y'})
720 self.assertEqual(extract_attributes('<e x="&amp;">'), {'x': '&'}) # XML
721 self.assertEqual(extract_attributes('<e x="&quot;">'), {'x': '"'})
c5229f39
S
722 self.assertEqual(extract_attributes('<e x="&pound;">'), {'x': '£'}) # HTML 3.2
723 self.assertEqual(extract_attributes('<e x="&lambda;">'), {'x': 'λ'}) # HTML 4.0
8bb56eee
BF
724 self.assertEqual(extract_attributes('<e x="&foo">'), {'x': '&foo'})
725 self.assertEqual(extract_attributes('<e x="\'">'), {'x': "'"})
726 self.assertEqual(extract_attributes('<e x=\'"\'>'), {'x': '"'})
727 self.assertEqual(extract_attributes('<e x >'), {'x': None})
728 self.assertEqual(extract_attributes('<e x=y a>'), {'x': 'y', 'a': None})
729 self.assertEqual(extract_attributes('<e x= y>'), {'x': 'y'})
730 self.assertEqual(extract_attributes('<e x=1 y=2 x=3>'), {'y': '2', 'x': '3'})
731 self.assertEqual(extract_attributes('<e \nx=\ny\n>'), {'x': 'y'})
732 self.assertEqual(extract_attributes('<e \nx=\n"y"\n>'), {'x': 'y'})
733 self.assertEqual(extract_attributes("<e \nx=\n'y'\n>"), {'x': 'y'})
734 self.assertEqual(extract_attributes('<e \nx="\ny\n">'), {'x': '\ny\n'})
c5229f39 735 self.assertEqual(extract_attributes('<e CAPS=x>'), {'caps': 'x'}) # Names lowercased
8bb56eee
BF
736 self.assertEqual(extract_attributes('<e x=1 X=2>'), {'x': '2'})
737 self.assertEqual(extract_attributes('<e X=1 x=2>'), {'x': '2'})
738 self.assertEqual(extract_attributes('<e _:funny-name1=1>'), {'_:funny-name1': '1'})
739 self.assertEqual(extract_attributes('<e x="Fáilte 世界 \U0001f600">'), {'x': 'Fáilte 世界 \U0001f600'})
740 self.assertEqual(extract_attributes('<e x="décompose&#769;">'), {'x': 'décompose\u0301'})
741 # "Narrow" Python builds don't support unicode code points outside BMP.
742 try:
743 compat_chr(0x10000)
744 supports_outside_bmp = True
745 except ValueError:
746 supports_outside_bmp = False
747 if supports_outside_bmp:
748 self.assertEqual(extract_attributes('<e x="Smile &#128512;!">'), {'x': 'Smile \U0001f600!'})
749
e4bdb37e
PH
750 def test_clean_html(self):
751 self.assertEqual(clean_html('a:\nb'), 'a: b')
752 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
753
4c0924bb
PH
754 def test_intlist_to_bytes(self):
755 self.assertEqual(
756 intlist_to_bytes([0, 1, 127, 128, 255]),
757 b'\x00\x01\x7f\x80\xff')
758
7d4111ed
PH
759 def test_args_to_str(self):
760 self.assertEqual(
761 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
762 'foo ba/r -baz \'2 be\' \'\''
763 )
764
be64b5b0
PH
765 def test_parse_filesize(self):
766 self.assertEqual(parse_filesize(None), None)
767 self.assertEqual(parse_filesize(''), None)
768 self.assertEqual(parse_filesize('91 B'), 91)
769 self.assertEqual(parse_filesize('foobar'), None)
770 self.assertEqual(parse_filesize('2 MiB'), 2097152)
771 self.assertEqual(parse_filesize('5 GB'), 5000000000)
772 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
4349c07d 773 self.assertEqual(parse_filesize('1,24 KB'), 1240)
be64b5b0 774
fb47597b
S
775 def test_parse_count(self):
776 self.assertEqual(parse_count(None), None)
777 self.assertEqual(parse_count(''), None)
778 self.assertEqual(parse_count('0'), 0)
779 self.assertEqual(parse_count('1000'), 1000)
780 self.assertEqual(parse_count('1.000'), 1000)
781 self.assertEqual(parse_count('1.1k'), 1100)
782 self.assertEqual(parse_count('1.1kk'), 1100000)
782b1b5b
JMF
783 self.assertEqual(parse_count('1.1kk '), 1100000)
784 self.assertEqual(parse_count('1.1kk views'), 1100000)
fb47597b 785
5f9b8394
PH
786 def test_version_tuple(self):
787 self.assertEqual(version_tuple('1'), (1,))
788 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
47d7c642 789 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
5f9b8394 790
cae97f65
PH
791 def test_detect_exe_version(self):
792 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
793built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
794configuration: --prefix=/usr --extra-'''), '1.2.1')
795 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
796built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
797 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
798Trying to open render node...
799Success at /dev/dri/renderD128.
800ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
801
05900629
PH
802 def test_age_restricted(self):
803 self.assertFalse(age_restricted(None, 10)) # unrestricted content
804 self.assertFalse(age_restricted(1, None)) # unrestricted policy
805 self.assertFalse(age_restricted(8, 10))
806 self.assertTrue(age_restricted(18, 14))
807 self.assertFalse(age_restricted(18, 18))
808
61ca9a80
PH
809 def test_is_html(self):
810 self.assertFalse(is_html(b'\x49\x44\x43<html'))
811 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
812 self.assertTrue(is_html( # UTF-8 with BOM
813 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
814 self.assertTrue(is_html( # UTF-16-LE
815 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
816 ))
817 self.assertTrue(is_html( # UTF-16-BE
818 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
819 ))
820 self.assertTrue(is_html( # UTF-32-BE
821 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'))
822 self.assertTrue(is_html( # UTF-32-LE
823 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'))
824
cfb56d1a
PH
825 def test_render_table(self):
826 self.assertEqual(
827 render_table(
828 ['a', 'bcd'],
829 [[123, 4], [9999, 51]]),
830 'a bcd\n'
831 '123 4\n'
832 '9999 51')
833
347de493
PH
834 def test_match_str(self):
835 self.assertRaises(ValueError, match_str, 'xy>foobar', {})
836 self.assertFalse(match_str('xy', {'x': 1200}))
837 self.assertTrue(match_str('!xy', {'x': 1200}))
838 self.assertTrue(match_str('x', {'x': 1200}))
839 self.assertFalse(match_str('!x', {'x': 1200}))
840 self.assertTrue(match_str('x', {'x': 0}))
841 self.assertFalse(match_str('x>0', {'x': 0}))
842 self.assertFalse(match_str('x>0', {}))
843 self.assertTrue(match_str('x>?0', {}))
844 self.assertTrue(match_str('x>1K', {'x': 1200}))
845 self.assertFalse(match_str('x>2K', {'x': 1200}))
846 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
847 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
848 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
849 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
850 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
851 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
852 self.assertFalse(match_str(
853 'like_count > 100 & dislike_count <? 50 & description',
854 {'like_count': 90, 'description': 'foo'}))
855 self.assertTrue(match_str(
856 'like_count > 100 & dislike_count <? 50 & description',
857 {'like_count': 190, 'description': 'foo'}))
858 self.assertFalse(match_str(
859 'like_count > 100 & dislike_count <? 50 & description',
860 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
861 self.assertFalse(match_str(
862 'like_count > 100 & dislike_count <? 50 & description',
863 {'like_count': 190, 'dislike_count': 10}))
864
bf6427d2 865 def test_parse_dfxp_time_expr(self):
d631d5f9
YCH
866 self.assertEqual(parse_dfxp_time_expr(None), None)
867 self.assertEqual(parse_dfxp_time_expr(''), None)
bf6427d2
YCH
868 self.assertEqual(parse_dfxp_time_expr('0.1'), 0.1)
869 self.assertEqual(parse_dfxp_time_expr('0.1s'), 0.1)
870 self.assertEqual(parse_dfxp_time_expr('00:00:01'), 1.0)
871 self.assertEqual(parse_dfxp_time_expr('00:00:01.100'), 1.1)
db2fe38b 872 self.assertEqual(parse_dfxp_time_expr('00:00:01:100'), 1.1)
bf6427d2
YCH
873
874 def test_dfxp2srt(self):
875 dfxp_data = '''<?xml version="1.0" encoding="UTF-8"?>
876 <tt xmlns="http://www.w3.org/ns/ttml" xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
877 <body>
878 <div xml:lang="en">
879 <p begin="0" end="1">The following line contains Chinese characters and special symbols</p>
880 <p begin="1" end="2">第二行<br/>♪♪</p>
7dff0363 881 <p begin="2" dur="1"><span>Third<br/>Line</span></p>
d631d5f9
YCH
882 <p begin="3" end="-1">Lines with invalid timestamps are ignored</p>
883 <p begin="-1" end="-1">Ignore, two</p>
884 <p begin="3" dur="-1">Ignored, three</p>
bf6427d2
YCH
885 </div>
886 </body>
887 </tt>'''
888 srt_data = '''1
88900:00:00,000 --> 00:00:01,000
890The following line contains Chinese characters and special symbols
891
8922
89300:00:01,000 --> 00:00:02,000
894第二行
895♪♪
896
8973
89800:00:02,000 --> 00:00:03,000
899Third
900Line
901
902'''
903 self.assertEqual(dfxp2srt(dfxp_data), srt_data)
904
1b0427e6
YCH
905 dfxp_data_no_default_namespace = '''<?xml version="1.0" encoding="UTF-8"?>
906 <tt xml:lang="en" xmlns:tts="http://www.w3.org/ns/ttml#parameter">
907 <body>
908 <div xml:lang="en">
909 <p begin="0" end="1">The first line</p>
910 </div>
911 </body>
912 </tt>'''
913 srt_data = '''1
91400:00:00,000 --> 00:00:01,000
915The first line
916
917'''
918 self.assertEqual(dfxp2srt(dfxp_data_no_default_namespace), srt_data)
919
f7126449
S
920 def test_cli_option(self):
921 self.assertEqual(cli_option({'proxy': '127.0.0.1:3128'}, '--proxy', 'proxy'), ['--proxy', '127.0.0.1:3128'])
922 self.assertEqual(cli_option({'proxy': None}, '--proxy', 'proxy'), [])
923 self.assertEqual(cli_option({}, '--proxy', 'proxy'), [])
924
925 def test_cli_valueless_option(self):
926 self.assertEqual(cli_valueless_option(
927 {'downloader': 'external'}, '--external-downloader', 'downloader', 'external'), ['--external-downloader'])
928 self.assertEqual(cli_valueless_option(
929 {'downloader': 'internal'}, '--external-downloader', 'downloader', 'external'), [])
930 self.assertEqual(cli_valueless_option(
931 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'), ['--no-check-certificate'])
932 self.assertEqual(cli_valueless_option(
933 {'nocheckcertificate': False}, '--no-check-certificate', 'nocheckcertificate'), [])
934 self.assertEqual(cli_valueless_option(
935 {'checkcertificate': True}, '--no-check-certificate', 'checkcertificate', False), [])
936 self.assertEqual(cli_valueless_option(
937 {'checkcertificate': False}, '--no-check-certificate', 'checkcertificate', False), ['--no-check-certificate'])
938
939 def test_cli_bool_option(self):
940 self.assertEqual(
941 cli_bool_option(
942 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate'),
943 ['--no-check-certificate', 'true'])
944 self.assertEqual(
945 cli_bool_option(
946 {'nocheckcertificate': True}, '--no-check-certificate', 'nocheckcertificate', separator='='),
947 ['--no-check-certificate=true'])
948 self.assertEqual(
949 cli_bool_option(
950 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
951 ['--check-certificate', 'false'])
952 self.assertEqual(
953 cli_bool_option(
954 {'nocheckcertificate': True}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
955 ['--check-certificate=false'])
956 self.assertEqual(
957 cli_bool_option(
958 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true'),
959 ['--check-certificate', 'true'])
960 self.assertEqual(
961 cli_bool_option(
962 {'nocheckcertificate': False}, '--check-certificate', 'nocheckcertificate', 'false', 'true', '='),
963 ['--check-certificate=true'])
964
5bc880b9
YCH
965 def test_ohdave_rsa_encrypt(self):
966 N = 0xab86b6371b5318aaa1d3c9e612a9f1264f372323c8c0f19875b5fc3b3fd3afcc1e5bec527aa94bfa85bffc157e4245aebda05389a5357b75115ac94f074aefcd
967 e = 65537
968
969 self.assertEqual(
970 ohdave_rsa_encrypt(b'aa111222', e, N),
971 '726664bd9a23fd0c70f9f1b84aab5e3905ce1e45a584e9cbcf9bcc7510338fc1986d6c599ff990d923aa43c51c0d9013cd572e13bc58f4ae48f2ed8c0b0ba881')
cfb56d1a 972
5eb6bdce
YCH
973 def test_encode_base_n(self):
974 self.assertEqual(encode_base_n(0, 30), '0')
975 self.assertEqual(encode_base_n(80, 30), '2k')
976
977 custom_table = '9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA'
978 self.assertEqual(encode_base_n(0, 30, custom_table), '9')
979 self.assertEqual(encode_base_n(80, 30, custom_table), '7P')
980
981 self.assertRaises(ValueError, encode_base_n, 0, 70)
982 self.assertRaises(ValueError, encode_base_n, 0, 60, custom_table)
983
1143535d
YCH
984 def test_urshift(self):
985 self.assertEqual(urshift(3, 1), 1)
986 self.assertEqual(urshift(-3, 1), 2147483646)
987
dae7c920 988if __name__ == '__main__':
59ae15a5 989 unittest.main()