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