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