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