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