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