Merge remote-tracking branch 'origin/master'
[ytdl] / test / test_utils.py
1 #!/usr/bin/env python
2 # coding: utf-8
3
4 # Allow direct execution
5 import os
6 import sys
7 import unittest
8 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
9
10
11 # Various small unit tests
12 import io
13 import xml.etree.ElementTree
14
15 #from youtube_dl.utils import htmlentity_transform
16 from youtube_dl.utils import (
17     DateRange,
18     encodeFilename,
19     find_xpath_attr,
20     fix_xml_ampersands,
21     get_meta_content,
22     orderedSet,
23     PagedList,
24     parse_duration,
25     read_batch_urls,
26     sanitize_filename,
27     shell_quote,
28     smuggle_url,
29     str_to_int,
30     struct_unpack,
31     timeconvert,
32     unescapeHTML,
33     unified_strdate,
34     unsmuggle_url,
35     url_basename,
36     urlencode_postdata,
37     xpath_with_ns,
38     parse_iso8601,
39 )
40
41 if sys.version_info < (3, 0):
42     _compat_str = lambda b: b.decode('unicode-escape')
43 else:
44     _compat_str = lambda s: s
45
46
47 class TestUtil(unittest.TestCase):
48     def test_timeconvert(self):
49         self.assertTrue(timeconvert('') is None)
50         self.assertTrue(timeconvert('bougrg') is None)
51
52     def test_sanitize_filename(self):
53         self.assertEqual(sanitize_filename('abc'), 'abc')
54         self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
55
56         self.assertEqual(sanitize_filename('123'), '123')
57
58         self.assertEqual('abc_de', sanitize_filename('abc/de'))
59         self.assertFalse('/' in sanitize_filename('abc/de///'))
60
61         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
62         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
63         self.assertEqual('yes no', sanitize_filename('yes? no'))
64         self.assertEqual('this - that', sanitize_filename('this: that'))
65
66         self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
67         aumlaut = _compat_str('\xe4')
68         self.assertEqual(sanitize_filename(aumlaut), aumlaut)
69         tests = _compat_str('\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430')
70         self.assertEqual(sanitize_filename(tests), tests)
71
72         forbidden = '"\0\\/'
73         for fc in forbidden:
74             for fbc in forbidden:
75                 self.assertTrue(fbc not in sanitize_filename(fc))
76
77     def test_sanitize_filename_restricted(self):
78         self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
79         self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
80
81         self.assertEqual(sanitize_filename('123', restricted=True), '123')
82
83         self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
84         self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
85
86         self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
87         self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
88         self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
89         self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
90
91         tests = _compat_str('a\xe4b\u4e2d\u56fd\u7684c')
92         self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
93         self.assertTrue(sanitize_filename(_compat_str('\xf6'), restricted=True) != '')  # No empty filename
94
95         forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
96         for fc in forbidden:
97             for fbc in forbidden:
98                 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
99
100         # Handle a common case more neatly
101         self.assertEqual(sanitize_filename(_compat_str('\u5927\u58f0\u5e26 - Song'), restricted=True), 'Song')
102         self.assertEqual(sanitize_filename(_compat_str('\u603b\u7edf: Speech'), restricted=True), 'Speech')
103         # .. but make sure the file name is never empty
104         self.assertTrue(sanitize_filename('-', restricted=True) != '')
105         self.assertTrue(sanitize_filename(':', restricted=True) != '')
106
107     def test_sanitize_ids(self):
108         self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
109         self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
110         self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
111
112     def test_ordered_set(self):
113         self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
114         self.assertEqual(orderedSet([]), [])
115         self.assertEqual(orderedSet([1]), [1])
116         #keep the list ordered
117         self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
118
119     def test_unescape_html(self):
120         self.assertEqual(unescapeHTML(_compat_str('%20;')), _compat_str('%20;'))
121         
122     def test_daterange(self):
123         _20century = DateRange("19000101","20000101")
124         self.assertFalse("17890714" in _20century)
125         _ac = DateRange("00010101")
126         self.assertTrue("19690721" in _ac)
127         _firstmilenium = DateRange(end="10000101")
128         self.assertTrue("07110427" in _firstmilenium)
129
130     def test_unified_dates(self):
131         self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
132         self.assertEqual(unified_strdate('8/7/2009'), '20090708')
133         self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
134         self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
135         self.assertEqual(unified_strdate('1968-12-10'), '19681210')
136
137     def test_find_xpath_attr(self):
138         testxml = u'''<root>
139             <node/>
140             <node x="a"/>
141             <node x="a" y="c" />
142             <node x="b" y="d" />
143         </root>'''
144         doc = xml.etree.ElementTree.fromstring(testxml)
145
146         self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
147         self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
148         self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
149
150     def test_meta_parser(self):
151         testhtml = u'''
152         <head>
153             <meta name="description" content="foo &amp; bar">
154             <meta content='Plato' name='author'/>
155         </head>
156         '''
157         get_meta = lambda name: get_meta_content(name, testhtml)
158         self.assertEqual(get_meta('description'), u'foo & bar')
159         self.assertEqual(get_meta('author'), 'Plato')
160
161     def test_xpath_with_ns(self):
162         testxml = u'''<root xmlns:media="http://example.com/">
163             <media:song>
164                 <media:author>The Author</media:author>
165                 <url>http://server.com/download.mp3</url>
166             </media:song>
167         </root>'''
168         doc = xml.etree.ElementTree.fromstring(testxml)
169         find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
170         self.assertTrue(find('media:song') is not None)
171         self.assertEqual(find('media:song/media:author').text, u'The Author')
172         self.assertEqual(find('media:song/url').text, u'http://server.com/download.mp3')
173
174     def test_smuggle_url(self):
175         data = {u"ö": u"ö", u"abc": [3]}
176         url = 'https://foo.bar/baz?x=y#a'
177         smug_url = smuggle_url(url, data)
178         unsmug_url, unsmug_data = unsmuggle_url(smug_url)
179         self.assertEqual(url, unsmug_url)
180         self.assertEqual(data, unsmug_data)
181
182         res_url, res_data = unsmuggle_url(url)
183         self.assertEqual(res_url, url)
184         self.assertEqual(res_data, None)
185
186     def test_shell_quote(self):
187         args = ['ffmpeg', '-i', encodeFilename(u'ñ€ß\'.mp4')]
188         self.assertEqual(shell_quote(args), u"""ffmpeg -i 'ñ€ß'"'"'.mp4'""")
189
190     def test_str_to_int(self):
191         self.assertEqual(str_to_int('123,456'), 123456)
192         self.assertEqual(str_to_int('123.456'), 123456)
193
194     def test_url_basename(self):
195         self.assertEqual(url_basename(u'http://foo.de/'), u'')
196         self.assertEqual(url_basename(u'http://foo.de/bar/baz'), u'baz')
197         self.assertEqual(url_basename(u'http://foo.de/bar/baz?x=y'), u'baz')
198         self.assertEqual(url_basename(u'http://foo.de/bar/baz#x=y'), u'baz')
199         self.assertEqual(url_basename(u'http://foo.de/bar/baz/'), u'baz')
200         self.assertEqual(
201             url_basename(u'http://media.w3.org/2010/05/sintel/trailer.mp4'),
202             u'trailer.mp4')
203
204     def test_parse_duration(self):
205         self.assertEqual(parse_duration(None), None)
206         self.assertEqual(parse_duration('1'), 1)
207         self.assertEqual(parse_duration('1337:12'), 80232)
208         self.assertEqual(parse_duration('9:12:43'), 33163)
209         self.assertEqual(parse_duration('12:00'), 720)
210         self.assertEqual(parse_duration('00:01:01'), 61)
211         self.assertEqual(parse_duration('x:y'), None)
212         self.assertEqual(parse_duration('3h11m53s'), 11513)
213         self.assertEqual(parse_duration('62m45s'), 3765)
214         self.assertEqual(parse_duration('6m59s'), 419)
215         self.assertEqual(parse_duration('49s'), 49)
216         self.assertEqual(parse_duration('0h0m0s'), 0)
217         self.assertEqual(parse_duration('0m0s'), 0)
218         self.assertEqual(parse_duration('0s'), 0)
219
220     def test_fix_xml_ampersands(self):
221         self.assertEqual(
222             fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
223         self.assertEqual(
224             fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
225             '"&amp;x=y&amp;wrong;&amp;z=a')
226         self.assertEqual(
227             fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
228             '&amp;&apos;&gt;&lt;&quot;')
229         self.assertEqual(
230             fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
231         self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
232
233     def test_paged_list(self):
234         def testPL(size, pagesize, sliceargs, expected):
235             def get_page(pagenum):
236                 firstid = pagenum * pagesize
237                 upto = min(size, pagenum * pagesize + pagesize)
238                 for i in range(firstid, upto):
239                     yield i
240
241             pl = PagedList(get_page, pagesize)
242             got = pl.getslice(*sliceargs)
243             self.assertEqual(got, expected)
244
245         testPL(5, 2, (), [0, 1, 2, 3, 4])
246         testPL(5, 2, (1,), [1, 2, 3, 4])
247         testPL(5, 2, (2,), [2, 3, 4])
248         testPL(5, 2, (4,), [4])
249         testPL(5, 2, (0, 3), [0, 1, 2])
250         testPL(5, 2, (1, 4), [1, 2, 3])
251         testPL(5, 2, (2, 99), [2, 3, 4])
252         testPL(5, 2, (20, 99), [])
253
254     def test_struct_unpack(self):
255         self.assertEqual(struct_unpack(u'!B', b'\x00'), (0,))
256
257     def test_read_batch_urls(self):
258         f = io.StringIO(u'''\xef\xbb\xbf foo
259             bar\r
260             baz
261             # More after this line\r
262             ; or after this
263             bam''')
264         self.assertEqual(read_batch_urls(f), [u'foo', u'bar', u'baz', u'bam'])
265
266     def test_urlencode_postdata(self):
267         data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
268         self.assertTrue(isinstance(data, bytes))
269
270     def test_parse_iso8601(self):
271         self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
272         self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
273         self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
274
275 if __name__ == '__main__':
276     unittest.main()