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