]>
Raphaël G. Git Repositories - youtubedl/blob - test/test_utils.py
0fa8731473317577f6ef7534d9ad5ead2064e32b
4 from __future__
import unicode_literals
6 # Allow direct execution
10 sys
.path
.insert(0, os
.path
.dirname(os
.path
.dirname(os
.path
.abspath(__file__
))))
13 # Various small unit tests
16 import xml
.etree
.ElementTree
18 from youtube_dl
.utils
import (
48 get_filesystem_encoding
,
53 class TestUtil(unittest
.TestCase
):
54 def test_timeconvert(self
):
55 self
.assertTrue(timeconvert('') is None)
56 self
.assertTrue(timeconvert('bougrg') is None)
58 def test_sanitize_filename(self
):
59 self
.assertEqual(sanitize_filename('abc'), 'abc')
60 self
.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
62 self
.assertEqual(sanitize_filename('123'), '123')
64 self
.assertEqual('abc_de', sanitize_filename('abc/de'))
65 self
.assertFalse('/' in sanitize_filename('abc/de///'))
67 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
68 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
69 self
.assertEqual('yes no', sanitize_filename('yes? no'))
70 self
.assertEqual('this - that', sanitize_filename('this: that'))
72 self
.assertEqual(sanitize_filename('AT&T'), 'AT&T')
74 self
.assertEqual(sanitize_filename(aumlaut
), aumlaut
)
75 tests
= '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
76 self
.assertEqual(sanitize_filename(tests
), tests
)
81 self
.assertTrue(fbc
not in sanitize_filename(fc
))
83 def test_sanitize_filename_restricted(self
):
84 self
.assertEqual(sanitize_filename('abc', restricted
=True), 'abc')
85 self
.assertEqual(sanitize_filename('abc_d-e', restricted
=True), 'abc_d-e')
87 self
.assertEqual(sanitize_filename('123', restricted
=True), '123')
89 self
.assertEqual('abc_de', sanitize_filename('abc/de', restricted
=True))
90 self
.assertFalse('/' in sanitize_filename('abc/de///', restricted
=True))
92 self
.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted
=True))
93 self
.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted
=True))
94 self
.assertEqual('yes_no', sanitize_filename('yes? no', restricted
=True))
95 self
.assertEqual('this_-_that', sanitize_filename('this: that', restricted
=True))
97 tests
= 'a\xe4b\u4e2d\u56fd\u7684c'
98 self
.assertEqual(sanitize_filename(tests
, restricted
=True), 'a_b_c')
99 self
.assertTrue(sanitize_filename('\xf6', restricted
=True) != '') # No empty filename
101 forbidden
= '"\0\\/&!: \'\t\n()[]{}$;`^,#'
103 for fbc
in forbidden
:
104 self
.assertTrue(fbc
not in sanitize_filename(fc
, restricted
=True))
106 # Handle a common case more neatly
107 self
.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted
=True), 'Song')
108 self
.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted
=True), 'Speech')
109 # .. but make sure the file name is never empty
110 self
.assertTrue(sanitize_filename('-', restricted
=True) != '')
111 self
.assertTrue(sanitize_filename(':', restricted
=True) != '')
113 def test_sanitize_ids(self
):
114 self
.assertEqual(sanitize_filename('_n_cd26wFpw', is_id
=True), '_n_cd26wFpw')
115 self
.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id
=True), '_BD_eEpuzXw')
116 self
.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id
=True), 'N0Y__7-UOdI')
118 def test_ordered_set(self
):
119 self
.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
120 self
.assertEqual(orderedSet([]), [])
121 self
.assertEqual(orderedSet([1]), [1])
122 #keep the list ordered
123 self
.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
125 def test_unescape_html(self
):
126 self
.assertEqual(unescapeHTML('%20;'), '%20;')
128 unescapeHTML('é'), 'é')
130 def test_daterange(self
):
131 _20century
= DateRange("19000101","20000101")
132 self
.assertFalse("17890714" in _20century
)
133 _ac
= DateRange("00010101")
134 self
.assertTrue("19690721" in _ac
)
135 _firstmilenium
= DateRange(end
="10000101")
136 self
.assertTrue("07110427" in _firstmilenium
)
138 def test_unified_dates(self
):
139 self
.assertEqual(unified_strdate('December 21, 2010'), '20101221')
140 self
.assertEqual(unified_strdate('8/7/2009'), '20090708')
141 self
.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
142 self
.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
143 self
.assertEqual(unified_strdate('1968-12-10'), '19681210')
144 self
.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
146 def test_find_xpath_attr(self
):
153 doc
= xml
.etree
.ElementTree
.fromstring(testxml
)
155 self
.assertEqual(find_xpath_attr(doc
, './/fourohfour', 'n', 'v'), None)
156 self
.assertEqual(find_xpath_attr(doc
, './/node', 'x', 'a'), doc
[1])
157 self
.assertEqual(find_xpath_attr(doc
, './/node', 'y', 'c'), doc
[2])
159 def test_xpath_with_ns(self
):
160 testxml
= '''<root xmlns:media="http://example.com/">
162 <media:author>The Author</media:author>
163 <url>http://server.com/download.mp3</url>
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
, 'The Author')
170 self
.assertEqual(find('media:song/url').text
, 'http://server.com/download.mp3')
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
)
180 res_url
, res_data
= unsmuggle_url(url
)
181 self
.assertEqual(res_url
, url
)
182 self
.assertEqual(res_data
, None)
184 def test_shell_quote(self
):
185 args
= ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
186 self
.assertEqual(shell_quote(args
), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
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)
192 def test_url_basename(self
):
193 self
.assertEqual(url_basename('http://foo.de/'), '')
194 self
.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
195 self
.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
196 self
.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
197 self
.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
199 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
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('3h 11m 53s'), 11513)
212 self
.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
213 self
.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
214 self
.assertEqual(parse_duration('62m45s'), 3765)
215 self
.assertEqual(parse_duration('6m59s'), 419)
216 self
.assertEqual(parse_duration('49s'), 49)
217 self
.assertEqual(parse_duration('0h0m0s'), 0)
218 self
.assertEqual(parse_duration('0m0s'), 0)
219 self
.assertEqual(parse_duration('0s'), 0)
220 self
.assertEqual(parse_duration('01:02:03.05'), 3723.05)
221 self
.assertEqual(parse_duration('T30M38S'), 1838)
223 def test_fix_xml_ampersands(self
):
225 fix_xml_ampersands('"&x=y&z=a'), '"&x=y&z=a')
227 fix_xml_ampersands('"&x=y&wrong;&z=a'),
228 '"&x=y&wrong;&z=a')
230 fix_xml_ampersands('&'><"'),
231 '&'><"')
233 fix_xml_ampersands('Ӓ᪼'), 'Ӓ᪼')
234 self
.assertEqual(fix_xml_ampersands('&#&#'), '&#&#')
236 def test_paged_list(self
):
237 def testPL(size
, pagesize
, sliceargs
, expected
):
238 def get_page(pagenum
):
239 firstid
= pagenum
* pagesize
240 upto
= min(size
, pagenum
* pagesize
+ pagesize
)
241 for i
in range(firstid
, upto
):
244 pl
= OnDemandPagedList(get_page
, pagesize
)
245 got
= pl
.getslice(*sliceargs
)
246 self
.assertEqual(got
, expected
)
248 iapl
= InAdvancePagedList(get_page
, size
// pagesize
+ 1, pagesize
)
249 got
= iapl
.getslice(*sliceargs
)
250 self
.assertEqual(got
, expected
)
252 testPL(5, 2, (), [0, 1, 2, 3, 4])
253 testPL(5, 2, (1,), [1, 2, 3, 4])
254 testPL(5, 2, (2,), [2, 3, 4])
255 testPL(5, 2, (4,), [4])
256 testPL(5, 2, (0, 3), [0, 1, 2])
257 testPL(5, 2, (1, 4), [1, 2, 3])
258 testPL(5, 2, (2, 99), [2, 3, 4])
259 testPL(5, 2, (20, 99), [])
261 def test_struct_unpack(self
):
262 self
.assertEqual(struct_unpack('!B', b
'\x00'), (0,))
264 def test_read_batch_urls(self
):
265 f
= io
.StringIO('''\xef\xbb\xbf foo
268 # More after this line\r
271 self
.assertEqual(read_batch_urls(f
), ['foo', 'bar', 'baz', 'bam'])
273 def test_urlencode_postdata(self
):
274 data
= urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
275 self
.assertTrue(isinstance(data
, bytes))
277 def test_parse_iso8601(self
):
278 self
.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
279 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
280 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
281 self
.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
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}])
288 stripped
= strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
289 d
= json
.loads(stripped
)
290 self
.assertEqual(d
, {'STATUS': 'OK'})
292 def test_uppercase_escape(self
):
293 self
.assertEqual(uppercase_escape('aä'), 'aä')
294 self
.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
296 def test_limit_length(self
):
297 self
.assertEqual(limit_length(None, 12), None)
298 self
.assertEqual(limit_length('foo', 12), 'foo')
300 limit_length('foo bar baz asd', 12).startswith('foo bar'))
301 self
.assertTrue('...' in limit_length('foo bar baz asd', 12))
303 def test_escape_rfc3986(self
):
304 reserved
= "!*'();:@&=+$,/?#[]"
305 unreserved
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
306 self
.assertEqual(escape_rfc3986(reserved
), reserved
)
307 self
.assertEqual(escape_rfc3986(unreserved
), unreserved
)
308 self
.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
309 self
.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
310 self
.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
311 self
.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
313 def test_escape_url(self
):
315 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
316 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
319 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'),
320 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
323 escape_url('http://тест.рф/фрагмент'),
324 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
327 escape_url('http://тест.рф/абв?абв=абв#абв'),
328 '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'
330 self
.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
332 def test_js_to_json_realworld(self
):
334 'clip':{'provider':'pseudo'}
336 self
.assertEqual(js_to_json(inp
), '''{
337 "clip":{"provider":"pseudo"}
339 json
.loads(js_to_json(inp
))
342 'playlist':[{'controls':{'all':null}}]
344 self
.assertEqual(js_to_json(inp
), '''{
345 "playlist":[{"controls":{"all":null}}]
348 def test_js_to_json_edgecases(self
):
349 on
= js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
350 self
.assertEqual(json
.loads(on
), {"abc_def": "1'\\2\\'3\"4"})
352 on
= js_to_json('{"abc": true}')
353 self
.assertEqual(json
.loads(on
), {'abc': True})
355 def test_clean_html(self
):
356 self
.assertEqual(clean_html('a:\nb'), 'a: b')
357 self
.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
359 def test_intlist_to_bytes(self
):
361 intlist_to_bytes([0, 1, 127, 128, 255]),
362 b
'\x00\x01\x7f\x80\xff')
364 if __name__
== '__main__':