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