]> Raphaël G. Git Repositories - youtubedl/blob - test/test_utils.py
debian/control: Update list of supported sites.
[youtubedl] / test / test_utils.py
1 #!/usr/bin/env python
2 # coding: utf-8
3
4 from __future__ import unicode_literals
5
6 # Allow direct execution
7 import os
8 import sys
9 import unittest
10 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
11
12
13 # Various small unit tests
14 import io
15 import json
16 import xml.etree.ElementTree
17
18 from youtube_dl.utils import (
19 age_restricted,
20 args_to_str,
21 clean_html,
22 DateRange,
23 detect_exe_version,
24 encodeFilename,
25 escape_rfc3986,
26 escape_url,
27 find_xpath_attr,
28 fix_xml_ampersands,
29 InAdvancePagedList,
30 intlist_to_bytes,
31 is_html,
32 js_to_json,
33 limit_length,
34 OnDemandPagedList,
35 orderedSet,
36 parse_duration,
37 parse_filesize,
38 parse_iso8601,
39 read_batch_urls,
40 sanitize_filename,
41 shell_quote,
42 smuggle_url,
43 str_to_int,
44 strip_jsonp,
45 struct_unpack,
46 timeconvert,
47 unescapeHTML,
48 unified_strdate,
49 unsmuggle_url,
50 uppercase_escape,
51 url_basename,
52 urlencode_postdata,
53 version_tuple,
54 xpath_with_ns,
55 render_table,
56 )
57
58
59 class TestUtil(unittest.TestCase):
60 def test_timeconvert(self):
61 self.assertTrue(timeconvert('') is None)
62 self.assertTrue(timeconvert('bougrg') is None)
63
64 def test_sanitize_filename(self):
65 self.assertEqual(sanitize_filename('abc'), 'abc')
66 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
67
68 self.assertEqual(sanitize_filename('123'), '123')
69
70 self.assertEqual('abc_de', sanitize_filename('abc/de'))
71 self.assertFalse('/' in sanitize_filename('abc/de///'))
72
73 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
74 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
75 self.assertEqual('yes no', sanitize_filename('yes? no'))
76 self.assertEqual('this - that', sanitize_filename('this: that'))
77
78 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
79 aumlaut = 'ä'
80 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
81 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
82 self.assertEqual(sanitize_filename(tests), tests)
83
84 self.assertEqual(
85 sanitize_filename('New World record at 0:12:34'),
86 'New World record at 0_12_34')
87
88 forbidden = '"\0\\/'
89 for fc in forbidden:
90 for fbc in forbidden:
91 self.assertTrue(fbc not in sanitize_filename(fc))
92
93 def test_sanitize_filename_restricted(self):
94 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
95 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
96
97 self.assertEqual(sanitize_filename('123', restricted=True), '123')
98
99 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
100 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
101
102 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
103 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
104 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
105 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
106
107 tests = 'a\xe4b\u4e2d\u56fd\u7684c'
108 self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
109 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
110
111 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
112 for fc in forbidden:
113 for fbc in forbidden:
114 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
115
116 # Handle a common case more neatly
117 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
118 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
119 # .. but make sure the file name is never empty
120 self.assertTrue(sanitize_filename('-', restricted=True) != '')
121 self.assertTrue(sanitize_filename(':', restricted=True) != '')
122
123 def test_sanitize_ids(self):
124 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
125 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
126 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
127
128 def test_ordered_set(self):
129 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
130 self.assertEqual(orderedSet([]), [])
131 self.assertEqual(orderedSet([1]), [1])
132 # keep the list ordered
133 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
134
135 def test_unescape_html(self):
136 self.assertEqual(unescapeHTML('%20;'), '%20;')
137 self.assertEqual(
138 unescapeHTML('&eacute;'), 'é')
139
140 def test_daterange(self):
141 _20century = DateRange("19000101", "20000101")
142 self.assertFalse("17890714" in _20century)
143 _ac = DateRange("00010101")
144 self.assertTrue("19690721" in _ac)
145 _firstmilenium = DateRange(end="10000101")
146 self.assertTrue("07110427" in _firstmilenium)
147
148 def test_unified_dates(self):
149 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
150 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
151 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
152 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
153 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
154 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
155 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
156 self.assertEqual(
157 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
158 '20141126')
159 self.assertEqual(
160 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
161 '20150202')
162
163 def test_find_xpath_attr(self):
164 testxml = '''<root>
165 <node/>
166 <node x="a"/>
167 <node x="a" y="c" />
168 <node x="b" y="d" />
169 </root>'''
170 doc = xml.etree.ElementTree.fromstring(testxml)
171
172 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
173 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
174 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
175
176 def test_xpath_with_ns(self):
177 testxml = '''<root xmlns:media="http://example.com/">
178 <media:song>
179 <media:author>The Author</media:author>
180 <url>http://server.com/download.mp3</url>
181 </media:song>
182 </root>'''
183 doc = xml.etree.ElementTree.fromstring(testxml)
184 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
185 self.assertTrue(find('media:song') is not None)
186 self.assertEqual(find('media:song/media:author').text, 'The Author')
187 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
188
189 def test_smuggle_url(self):
190 data = {"ö": "ö", "abc": [3]}
191 url = 'https://foo.bar/baz?x=y#a'
192 smug_url = smuggle_url(url, data)
193 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
194 self.assertEqual(url, unsmug_url)
195 self.assertEqual(data, unsmug_data)
196
197 res_url, res_data = unsmuggle_url(url)
198 self.assertEqual(res_url, url)
199 self.assertEqual(res_data, None)
200
201 def test_shell_quote(self):
202 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
203 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
204
205 def test_str_to_int(self):
206 self.assertEqual(str_to_int('123,456'), 123456)
207 self.assertEqual(str_to_int('123.456'), 123456)
208
209 def test_url_basename(self):
210 self.assertEqual(url_basename('http://foo.de/'), '')
211 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
212 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
213 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
214 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
215 self.assertEqual(
216 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
217 'trailer.mp4')
218
219 def test_parse_duration(self):
220 self.assertEqual(parse_duration(None), None)
221 self.assertEqual(parse_duration(False), None)
222 self.assertEqual(parse_duration('invalid'), None)
223 self.assertEqual(parse_duration('1'), 1)
224 self.assertEqual(parse_duration('1337:12'), 80232)
225 self.assertEqual(parse_duration('9:12:43'), 33163)
226 self.assertEqual(parse_duration('12:00'), 720)
227 self.assertEqual(parse_duration('00:01:01'), 61)
228 self.assertEqual(parse_duration('x:y'), None)
229 self.assertEqual(parse_duration('3h11m53s'), 11513)
230 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
231 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
232 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
233 self.assertEqual(parse_duration('62m45s'), 3765)
234 self.assertEqual(parse_duration('6m59s'), 419)
235 self.assertEqual(parse_duration('49s'), 49)
236 self.assertEqual(parse_duration('0h0m0s'), 0)
237 self.assertEqual(parse_duration('0m0s'), 0)
238 self.assertEqual(parse_duration('0s'), 0)
239 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
240 self.assertEqual(parse_duration('T30M38S'), 1838)
241 self.assertEqual(parse_duration('5 s'), 5)
242 self.assertEqual(parse_duration('3 min'), 180)
243 self.assertEqual(parse_duration('2.5 hours'), 9000)
244 self.assertEqual(parse_duration('02:03:04'), 7384)
245 self.assertEqual(parse_duration('01:02:03:04'), 93784)
246
247 def test_fix_xml_ampersands(self):
248 self.assertEqual(
249 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
250 self.assertEqual(
251 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
252 '"&amp;x=y&amp;wrong;&amp;z=a')
253 self.assertEqual(
254 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
255 '&amp;&apos;&gt;&lt;&quot;')
256 self.assertEqual(
257 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
258 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
259
260 def test_paged_list(self):
261 def testPL(size, pagesize, sliceargs, expected):
262 def get_page(pagenum):
263 firstid = pagenum * pagesize
264 upto = min(size, pagenum * pagesize + pagesize)
265 for i in range(firstid, upto):
266 yield i
267
268 pl = OnDemandPagedList(get_page, pagesize)
269 got = pl.getslice(*sliceargs)
270 self.assertEqual(got, expected)
271
272 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
273 got = iapl.getslice(*sliceargs)
274 self.assertEqual(got, expected)
275
276 testPL(5, 2, (), [0, 1, 2, 3, 4])
277 testPL(5, 2, (1,), [1, 2, 3, 4])
278 testPL(5, 2, (2,), [2, 3, 4])
279 testPL(5, 2, (4,), [4])
280 testPL(5, 2, (0, 3), [0, 1, 2])
281 testPL(5, 2, (1, 4), [1, 2, 3])
282 testPL(5, 2, (2, 99), [2, 3, 4])
283 testPL(5, 2, (20, 99), [])
284
285 def test_struct_unpack(self):
286 self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
287
288 def test_read_batch_urls(self):
289 f = io.StringIO('''\xef\xbb\xbf foo
290 bar\r
291 baz
292 # More after this line\r
293 ; or after this
294 bam''')
295 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
296
297 def test_urlencode_postdata(self):
298 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
299 self.assertTrue(isinstance(data, bytes))
300
301 def test_parse_iso8601(self):
302 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
303 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
304 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
305 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
306
307 def test_strip_jsonp(self):
308 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
309 d = json.loads(stripped)
310 self.assertEqual(d, [{"id": "532cb", "x": 3}])
311
312 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
313 d = json.loads(stripped)
314 self.assertEqual(d, {'STATUS': 'OK'})
315
316 def test_uppercase_escape(self):
317 self.assertEqual(uppercase_escape('aä'), 'aä')
318 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
319
320 def test_limit_length(self):
321 self.assertEqual(limit_length(None, 12), None)
322 self.assertEqual(limit_length('foo', 12), 'foo')
323 self.assertTrue(
324 limit_length('foo bar baz asd', 12).startswith('foo bar'))
325 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
326
327 def test_escape_rfc3986(self):
328 reserved = "!*'();:@&=+$,/?#[]"
329 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
330 self.assertEqual(escape_rfc3986(reserved), reserved)
331 self.assertEqual(escape_rfc3986(unreserved), unreserved)
332 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
333 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
334 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
335 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
336
337 def test_escape_url(self):
338 self.assertEqual(
339 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
340 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
341 )
342 self.assertEqual(
343 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'),
344 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
345 )
346 self.assertEqual(
347 escape_url('http://тест.рф/фрагмент'),
348 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
349 )
350 self.assertEqual(
351 escape_url('http://тест.рф/абв?абв=абв#абв'),
352 'http://тест.рф/%D0%B0%D0%B1%D0%B2?%D0%B0%D0%B1%D0%B2=%D0%B0%D0%B1%D0%B2#%D0%B0%D0%B1%D0%B2'
353 )
354 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
355
356 def test_js_to_json_realworld(self):
357 inp = '''{
358 'clip':{'provider':'pseudo'}
359 }'''
360 self.assertEqual(js_to_json(inp), '''{
361 "clip":{"provider":"pseudo"}
362 }''')
363 json.loads(js_to_json(inp))
364
365 inp = '''{
366 'playlist':[{'controls':{'all':null}}]
367 }'''
368 self.assertEqual(js_to_json(inp), '''{
369 "playlist":[{"controls":{"all":null}}]
370 }''')
371
372 def test_js_to_json_edgecases(self):
373 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
374 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
375
376 on = js_to_json('{"abc": true}')
377 self.assertEqual(json.loads(on), {'abc': True})
378
379 # Ignore JavaScript code as well
380 on = js_to_json('''{
381 "x": 1,
382 y: "a",
383 z: some.code
384 }''')
385 d = json.loads(on)
386 self.assertEqual(d['x'], 1)
387 self.assertEqual(d['y'], 'a')
388
389 def test_clean_html(self):
390 self.assertEqual(clean_html('a:\nb'), 'a: b')
391 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
392
393 def test_intlist_to_bytes(self):
394 self.assertEqual(
395 intlist_to_bytes([0, 1, 127, 128, 255]),
396 b'\x00\x01\x7f\x80\xff')
397
398 def test_args_to_str(self):
399 self.assertEqual(
400 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
401 'foo ba/r -baz \'2 be\' \'\''
402 )
403
404 def test_parse_filesize(self):
405 self.assertEqual(parse_filesize(None), None)
406 self.assertEqual(parse_filesize(''), None)
407 self.assertEqual(parse_filesize('91 B'), 91)
408 self.assertEqual(parse_filesize('foobar'), None)
409 self.assertEqual(parse_filesize('2 MiB'), 2097152)
410 self.assertEqual(parse_filesize('5 GB'), 5000000000)
411 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
412 self.assertEqual(parse_filesize('1,24 KB'), 1240)
413
414 def test_version_tuple(self):
415 self.assertEqual(version_tuple('1'), (1,))
416 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
417 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
418
419 def test_detect_exe_version(self):
420 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
421 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
422 configuration: --prefix=/usr --extra-'''), '1.2.1')
423 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
424 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
425 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
426 Trying to open render node...
427 Success at /dev/dri/renderD128.
428 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
429
430 def test_age_restricted(self):
431 self.assertFalse(age_restricted(None, 10)) # unrestricted content
432 self.assertFalse(age_restricted(1, None)) # unrestricted policy
433 self.assertFalse(age_restricted(8, 10))
434 self.assertTrue(age_restricted(18, 14))
435 self.assertFalse(age_restricted(18, 18))
436
437 def test_is_html(self):
438 self.assertFalse(is_html(b'\x49\x44\x43<html'))
439 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
440 self.assertTrue(is_html( # UTF-8 with BOM
441 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
442 self.assertTrue(is_html( # UTF-16-LE
443 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
444 ))
445 self.assertTrue(is_html( # UTF-16-BE
446 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
447 ))
448 self.assertTrue(is_html( # UTF-32-BE
449 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'))
450 self.assertTrue(is_html( # UTF-32-LE
451 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'))
452
453 def test_render_table(self):
454 self.assertEqual(
455 render_table(
456 ['a', 'bcd'],
457 [[123, 4], [9999, 51]]),
458 'a bcd\n'
459 '123 4\n'
460 '9999 51')
461
462
463 if __name__ == '__main__':
464 unittest.main()