]> gitweb @ CieloNegro.org - youtube-dl.git/blob - test/test_utils.py
Merge commit '98703c7fbfcf06348220aa63f9422cdd792cfe1a'
[youtube-dl.git] / 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     DateRange,
20     encodeFilename,
21     find_xpath_attr,
22     fix_xml_ampersands,
23     get_meta_content,
24     orderedSet,
25     PagedList,
26     parse_duration,
27     read_batch_urls,
28     sanitize_filename,
29     shell_quote,
30     smuggle_url,
31     str_to_int,
32     struct_unpack,
33     timeconvert,
34     unescapeHTML,
35     unified_strdate,
36     unsmuggle_url,
37     url_basename,
38     urlencode_postdata,
39     xpath_with_ns,
40     parse_iso8601,
41     strip_jsonp,
42     uppercase_escape,
43     limit_length,
44     escape_rfc3986,
45     escape_url,
46 )
47
48
49 class TestUtil(unittest.TestCase):
50     def test_timeconvert(self):
51         self.assertTrue(timeconvert('') is None)
52         self.assertTrue(timeconvert('bougrg') is None)
53
54     def test_sanitize_filename(self):
55         self.assertEqual(sanitize_filename('abc'), 'abc')
56         self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
57
58         self.assertEqual(sanitize_filename('123'), '123')
59
60         self.assertEqual('abc_de', sanitize_filename('abc/de'))
61         self.assertFalse('/' in sanitize_filename('abc/de///'))
62
63         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
64         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
65         self.assertEqual('yes no', sanitize_filename('yes? no'))
66         self.assertEqual('this - that', sanitize_filename('this: that'))
67
68         self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
69         aumlaut = 'ä'
70         self.assertEqual(sanitize_filename(aumlaut), aumlaut)
71         tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
72         self.assertEqual(sanitize_filename(tests), tests)
73
74         forbidden = '"\0\\/'
75         for fc in forbidden:
76             for fbc in forbidden:
77                 self.assertTrue(fbc not in sanitize_filename(fc))
78
79     def test_sanitize_filename_restricted(self):
80         self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
81         self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
82
83         self.assertEqual(sanitize_filename('123', restricted=True), '123')
84
85         self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
86         self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
87
88         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
89         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
90         self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
91         self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
92
93         tests = 'a\xe4b\u4e2d\u56fd\u7684c'
94         self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
95         self.assertTrue(sanitize_filename('\xf6', restricted=True) != '')  # No empty filename
96
97         forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
98         for fc in forbidden:
99             for fbc in forbidden:
100                 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
101
102         # Handle a common case more neatly
103         self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
104         self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
105         # .. but make sure the file name is never empty
106         self.assertTrue(sanitize_filename('-', restricted=True) != '')
107         self.assertTrue(sanitize_filename(':', restricted=True) != '')
108
109     def test_sanitize_ids(self):
110         self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
111         self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
112         self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
113
114     def test_ordered_set(self):
115         self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
116         self.assertEqual(orderedSet([]), [])
117         self.assertEqual(orderedSet([1]), [1])
118         #keep the list ordered
119         self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
120
121     def test_unescape_html(self):
122         self.assertEqual(unescapeHTML('%20;'), '%20;')
123         self.assertEqual(
124             unescapeHTML('&eacute;'), 'é')
125         
126     def test_daterange(self):
127         _20century = DateRange("19000101","20000101")
128         self.assertFalse("17890714" in _20century)
129         _ac = DateRange("00010101")
130         self.assertTrue("19690721" in _ac)
131         _firstmilenium = DateRange(end="10000101")
132         self.assertTrue("07110427" in _firstmilenium)
133
134     def test_unified_dates(self):
135         self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
136         self.assertEqual(unified_strdate('8/7/2009'), '20090708')
137         self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
138         self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
139         self.assertEqual(unified_strdate('1968-12-10'), '19681210')
140
141     def test_find_xpath_attr(self):
142         testxml = '''<root>
143             <node/>
144             <node x="a"/>
145             <node x="a" y="c" />
146             <node x="b" y="d" />
147         </root>'''
148         doc = xml.etree.ElementTree.fromstring(testxml)
149
150         self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
151         self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
152         self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
153
154     def test_meta_parser(self):
155         testhtml = '''
156         <head>
157             <meta name="description" content="foo &amp; bar">
158             <meta content='Plato' name='author'/>
159         </head>
160         '''
161         get_meta = lambda name: get_meta_content(name, testhtml)
162         self.assertEqual(get_meta('description'), 'foo & bar')
163         self.assertEqual(get_meta('author'), 'Plato')
164
165     def test_xpath_with_ns(self):
166         testxml = '''<root xmlns:media="http://example.com/">
167             <media:song>
168                 <media:author>The Author</media:author>
169                 <url>http://server.com/download.mp3</url>
170             </media:song>
171         </root>'''
172         doc = xml.etree.ElementTree.fromstring(testxml)
173         find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
174         self.assertTrue(find('media:song') is not None)
175         self.assertEqual(find('media:song/media:author').text, 'The Author')
176         self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
177
178     def test_smuggle_url(self):
179         data = {u"ö": u"ö", u"abc": [3]}
180         url = 'https://foo.bar/baz?x=y#a'
181         smug_url = smuggle_url(url, data)
182         unsmug_url, unsmug_data = unsmuggle_url(smug_url)
183         self.assertEqual(url, unsmug_url)
184         self.assertEqual(data, unsmug_data)
185
186         res_url, res_data = unsmuggle_url(url)
187         self.assertEqual(res_url, url)
188         self.assertEqual(res_data, None)
189
190     def test_shell_quote(self):
191         args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
192         self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
193
194     def test_str_to_int(self):
195         self.assertEqual(str_to_int('123,456'), 123456)
196         self.assertEqual(str_to_int('123.456'), 123456)
197
198     def test_url_basename(self):
199         self.assertEqual(url_basename('http://foo.de/'), '')
200         self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
201         self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
202         self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
203         self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
204         self.assertEqual(
205             url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
206             'trailer.mp4')
207
208     def test_parse_duration(self):
209         self.assertEqual(parse_duration(None), None)
210         self.assertEqual(parse_duration('1'), 1)
211         self.assertEqual(parse_duration('1337:12'), 80232)
212         self.assertEqual(parse_duration('9:12:43'), 33163)
213         self.assertEqual(parse_duration('12:00'), 720)
214         self.assertEqual(parse_duration('00:01:01'), 61)
215         self.assertEqual(parse_duration('x:y'), None)
216         self.assertEqual(parse_duration('3h11m53s'), 11513)
217         self.assertEqual(parse_duration('3h 11m 53s'), 11513)
218         self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
219         self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
220         self.assertEqual(parse_duration('62m45s'), 3765)
221         self.assertEqual(parse_duration('6m59s'), 419)
222         self.assertEqual(parse_duration('49s'), 49)
223         self.assertEqual(parse_duration('0h0m0s'), 0)
224         self.assertEqual(parse_duration('0m0s'), 0)
225         self.assertEqual(parse_duration('0s'), 0)
226         self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
227
228     def test_fix_xml_ampersands(self):
229         self.assertEqual(
230             fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
231         self.assertEqual(
232             fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
233             '"&amp;x=y&amp;wrong;&amp;z=a')
234         self.assertEqual(
235             fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
236             '&amp;&apos;&gt;&lt;&quot;')
237         self.assertEqual(
238             fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
239         self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
240
241     def test_paged_list(self):
242         def testPL(size, pagesize, sliceargs, expected):
243             def get_page(pagenum):
244                 firstid = pagenum * pagesize
245                 upto = min(size, pagenum * pagesize + pagesize)
246                 for i in range(firstid, upto):
247                     yield i
248
249             pl = PagedList(get_page, pagesize)
250             got = pl.getslice(*sliceargs)
251             self.assertEqual(got, expected)
252
253         testPL(5, 2, (), [0, 1, 2, 3, 4])
254         testPL(5, 2, (1,), [1, 2, 3, 4])
255         testPL(5, 2, (2,), [2, 3, 4])
256         testPL(5, 2, (4,), [4])
257         testPL(5, 2, (0, 3), [0, 1, 2])
258         testPL(5, 2, (1, 4), [1, 2, 3])
259         testPL(5, 2, (2, 99), [2, 3, 4])
260         testPL(5, 2, (20, 99), [])
261
262     def test_struct_unpack(self):
263         self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
264
265     def test_read_batch_urls(self):
266         f = io.StringIO('''\xef\xbb\xbf foo
267             bar\r
268             baz
269             # More after this line\r
270             ; or after this
271             bam''')
272         self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
273
274     def test_urlencode_postdata(self):
275         data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
276         self.assertTrue(isinstance(data, bytes))
277
278     def test_parse_iso8601(self):
279         self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
280         self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
281         self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
282
283     def test_strip_jsonp(self):
284         stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
285         d = json.loads(stripped)
286         self.assertEqual(d, [{"id": "532cb", "x": 3}])
287
288     def test_uppercase_escape(self):
289         self.assertEqual(uppercase_escape('aä'), 'aä')
290         self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
291
292     def test_limit_length(self):
293         self.assertEqual(limit_length(None, 12), None)
294         self.assertEqual(limit_length('foo', 12), 'foo')
295         self.assertTrue(
296             limit_length('foo bar baz asd', 12).startswith('foo bar'))
297         self.assertTrue('...' in limit_length('foo bar baz asd', 12))
298
299     def test_escape_rfc3986(self):
300         reserved = "!*'();:@&=+$,/?#[]"
301         unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
302         self.assertEqual(escape_rfc3986(reserved), reserved)
303         self.assertEqual(escape_rfc3986(unreserved), unreserved)
304         self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
305         self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
306         self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
307         self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
308
309     def test_escape_url(self):
310         self.assertEqual(
311             escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
312             'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
313         )
314         self.assertEqual(
315             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'),
316             'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
317         )
318         self.assertEqual(
319             escape_url('http://тест.рф/фрагмент'),
320             'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
321         )
322         self.assertEqual(
323             escape_url('http://тест.рф/абв?абв=абв#абв'),
324             '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'
325         )
326         self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
327
328 if __name__ == '__main__':
329     unittest.main()