]> jfr.im git - yt-dlp.git/blame - test/test_utils.py
[cspan] Extract subtitles
[yt-dlp.git] / test / test_utils.py
CommitLineData
e387eb5a 1#!/usr/bin/env python
9d4660ca 2# coding: utf-8
e387eb5a 3
4e408e47
PH
4from __future__ import unicode_literals
5
44a5f171
PH
6# Allow direct execution
7import os
dae7c920 8import sys
44fb3454 9import unittest
44a5f171 10sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
44fb3454 11
44a5f171
PH
12
13# Various small unit tests
62e609ab 14import io
fac55558 15import json
44a5f171 16import xml.etree.ElementTree
dae7c920 17
a921f407 18from youtube_dl.utils import (
05900629 19 age_restricted,
cae97f65 20 args_to_str,
e4bdb37e 21 clean_html,
a921f407 22 DateRange,
cae97f65 23 detect_exe_version,
29eb5174 24 encodeFilename,
cae97f65
PH
25 escape_rfc3986,
26 escape_url,
5379a2d4 27 ExtractorError,
a921f407 28 find_xpath_attr,
5aafe895 29 fix_xml_ampersands,
9c44d242 30 InAdvancePagedList,
cae97f65 31 intlist_to_bytes,
61ca9a80 32 is_html,
cae97f65
PH
33 js_to_json,
34 limit_length,
35 OnDemandPagedList,
36 orderedSet,
608d11f5 37 parse_duration,
cae97f65
PH
38 parse_filesize,
39 parse_iso8601,
62e609ab 40 read_batch_urls,
29eb5174 41 sanitize_filename,
a2aaf4db 42 sanitize_path,
92a4793b 43 sanitize_url_path_consecutive_slashes,
a6a173c2 44 shell_quote,
29eb5174 45 smuggle_url,
f53c966a 46 str_to_int,
cae97f65 47 strip_jsonp,
b53466e1 48 struct_unpack,
29eb5174
PH
49 timeconvert,
50 unescapeHTML,
51 unified_strdate,
52 unsmuggle_url,
cae97f65 53 uppercase_escape,
29eb5174 54 url_basename,
b74fa8cd 55 urlencode_postdata,
5f9b8394 56 version_tuple,
cae97f65 57 xpath_with_ns,
5379a2d4 58 xpath_text,
cfb56d1a 59 render_table,
347de493 60 match_str,
a921f407 61)
44fb3454 62
627dcfff 63
44fb3454 64class TestUtil(unittest.TestCase):
59ae15a5
PH
65 def test_timeconvert(self):
66 self.assertTrue(timeconvert('') is None)
67 self.assertTrue(timeconvert('bougrg') is None)
68
69 def test_sanitize_filename(self):
70 self.assertEqual(sanitize_filename('abc'), 'abc')
71 self.assertEqual(sanitize_filename('abc_d-e'), 'abc_d-e')
72
73 self.assertEqual(sanitize_filename('123'), '123')
74
75 self.assertEqual('abc_de', sanitize_filename('abc/de'))
76 self.assertFalse('/' in sanitize_filename('abc/de///'))
77
78 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de'))
79 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|'))
80 self.assertEqual('yes no', sanitize_filename('yes? no'))
81 self.assertEqual('this - that', sanitize_filename('this: that'))
82
83 self.assertEqual(sanitize_filename('AT&T'), 'AT&T')
4e408e47 84 aumlaut = 'ä'
59ae15a5 85 self.assertEqual(sanitize_filename(aumlaut), aumlaut)
4e408e47 86 tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
59ae15a5
PH
87 self.assertEqual(sanitize_filename(tests), tests)
88
2aeb06d6
PH
89 self.assertEqual(
90 sanitize_filename('New World record at 0:12:34'),
91 'New World record at 0_12_34')
a7440261 92
5a42414b
PH
93 self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
94 self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
a7440261
PH
95 self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
96 self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
2aeb06d6 97
59ae15a5
PH
98 forbidden = '"\0\\/'
99 for fc in forbidden:
100 for fbc in forbidden:
101 self.assertTrue(fbc not in sanitize_filename(fc))
102
103 def test_sanitize_filename_restricted(self):
104 self.assertEqual(sanitize_filename('abc', restricted=True), 'abc')
105 self.assertEqual(sanitize_filename('abc_d-e', restricted=True), 'abc_d-e')
106
107 self.assertEqual(sanitize_filename('123', restricted=True), '123')
108
109 self.assertEqual('abc_de', sanitize_filename('abc/de', restricted=True))
110 self.assertFalse('/' in sanitize_filename('abc/de///', restricted=True))
111
112 self.assertEqual('abc_de', sanitize_filename('abc/<>\\*|de', restricted=True))
113 self.assertEqual('xxx', sanitize_filename('xxx/<>\\*|', restricted=True))
114 self.assertEqual('yes_no', sanitize_filename('yes? no', restricted=True))
115 self.assertEqual('this_-_that', sanitize_filename('this: that', restricted=True))
116
4e408e47 117 tests = 'a\xe4b\u4e2d\u56fd\u7684c'
59ae15a5 118 self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
4e408e47 119 self.assertTrue(sanitize_filename('\xf6', restricted=True) != '') # No empty filename
59ae15a5 120
627dcfff 121 forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
59ae15a5
PH
122 for fc in forbidden:
123 for fbc in forbidden:
124 self.assertTrue(fbc not in sanitize_filename(fc, restricted=True))
125
126 # Handle a common case more neatly
4e408e47
PH
127 self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
128 self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
59ae15a5
PH
129 # .. but make sure the file name is never empty
130 self.assertTrue(sanitize_filename('-', restricted=True) != '')
131 self.assertTrue(sanitize_filename(':', restricted=True) != '')
132
796173d0 133 def test_sanitize_ids(self):
314d506b
PH
134 self.assertEqual(sanitize_filename('_n_cd26wFpw', is_id=True), '_n_cd26wFpw')
135 self.assertEqual(sanitize_filename('_BD_eEpuzXw', is_id=True), '_BD_eEpuzXw')
136 self.assertEqual(sanitize_filename('N0Y__7-UOdI', is_id=True), 'N0Y__7-UOdI')
796173d0 137
a2aaf4db
S
138 def test_sanitize_path(self):
139 if sys.platform != 'win32':
140 return
141
142 self.assertEqual(sanitize_path('abc'), 'abc')
143 self.assertEqual(sanitize_path('abc/def'), 'abc\\def')
144 self.assertEqual(sanitize_path('abc\\def'), 'abc\\def')
145 self.assertEqual(sanitize_path('abc|def'), 'abc#def')
146 self.assertEqual(sanitize_path('<>:"|?*'), '#######')
147 self.assertEqual(sanitize_path('C:/abc/def'), 'C:\\abc\\def')
148 self.assertEqual(sanitize_path('C?:/abc/def'), 'C##\\abc\\def')
149
150 self.assertEqual(sanitize_path('\\\\?\\UNC\\ComputerName\\abc'), '\\\\?\\UNC\\ComputerName\\abc')
151 self.assertEqual(sanitize_path('\\\\?\\UNC/ComputerName/abc'), '\\\\?\\UNC\\ComputerName\\abc')
152
153 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
154 self.assertEqual(sanitize_path('\\\\?\\C:/abc'), '\\\\?\\C:\\abc')
155 self.assertEqual(sanitize_path('\\\\?\\C:\\ab?c\\de:f'), '\\\\?\\C:\\ab#c\\de#f')
156 self.assertEqual(sanitize_path('\\\\?\\C:\\abc'), '\\\\?\\C:\\abc')
157
f18ef2d1
S
158 self.assertEqual(
159 sanitize_path('youtube/%(uploader)s/%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s'),
160 'youtube\\%(uploader)s\\%(autonumber)s-%(title)s-%(upload_date)s.%(ext)s')
161
162 self.assertEqual(
163 sanitize_path('youtube/TheWreckingYard ./00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part'),
164 'youtube\\TheWreckingYard #\\00001-Not bad, Especially for Free! (1987 Yamaha 700)-20141116.mp4.part')
165 self.assertEqual(sanitize_path('abc/def...'), 'abc\\def..#')
166 self.assertEqual(sanitize_path('abc.../def'), 'abc..#\\def')
167 self.assertEqual(sanitize_path('abc.../def...'), 'abc..#\\def..#')
168
2ebfeaca
S
169 self.assertEqual(sanitize_path('../abc'), '..\\abc')
170 self.assertEqual(sanitize_path('../../abc'), '..\\..\\abc')
171 self.assertEqual(sanitize_path('./abc'), 'abc')
172 self.assertEqual(sanitize_path('./../abc'), '..\\abc')
173
92a4793b
S
174 def test_sanitize_url_path_consecutive_slashes(self):
175 self.assertEqual(
176 sanitize_url_path_consecutive_slashes('http://hostname/foo//bar/filename.html'),
177 'http://hostname/foo/bar/filename.html')
178 self.assertEqual(
179 sanitize_url_path_consecutive_slashes('http://hostname//foo/bar/filename.html'),
180 'http://hostname/foo/bar/filename.html')
181 self.assertEqual(
182 sanitize_url_path_consecutive_slashes('http://hostname//'),
183 'http://hostname/')
184 self.assertEqual(
185 sanitize_url_path_consecutive_slashes('http://hostname/foo/bar/filename.html'),
186 'http://hostname/foo/bar/filename.html')
187 self.assertEqual(
188 sanitize_url_path_consecutive_slashes('http://hostname/'),
189 'http://hostname/')
190 self.assertEqual(
191 sanitize_url_path_consecutive_slashes('http://hostname/abc//'),
192 'http://hostname/abc/')
193
59ae15a5 194 def test_ordered_set(self):
627dcfff 195 self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
59ae15a5
PH
196 self.assertEqual(orderedSet([]), [])
197 self.assertEqual(orderedSet([1]), [1])
5f6a1245 198 # keep the list ordered
627dcfff 199 self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
59ae15a5
PH
200
201 def test_unescape_html(self):
4e408e47 202 self.assertEqual(unescapeHTML('%20;'), '%20;')
91757b0f
NJ
203 self.assertEqual(unescapeHTML('&#x2F;'), '/')
204 self.assertEqual(unescapeHTML('&#47;'), '/')
4e408e47
PH
205 self.assertEqual(
206 unescapeHTML('&eacute;'), 'é')
5f6a1245 207
bd558525 208 def test_daterange(self):
5f6a1245 209 _20century = DateRange("19000101", "20000101")
bd558525
JMF
210 self.assertFalse("17890714" in _20century)
211 _ac = DateRange("00010101")
212 self.assertTrue("19690721" in _ac)
213 _firstmilenium = DateRange(end="10000101")
214 self.assertTrue("07110427" in _firstmilenium)
37254abc 215
bf50b038
JMF
216 def test_unified_dates(self):
217 self.assertEqual(unified_strdate('December 21, 2010'), '20101221')
218 self.assertEqual(unified_strdate('8/7/2009'), '20090708')
219 self.assertEqual(unified_strdate('Dec 14, 2012'), '20121214')
220 self.assertEqual(unified_strdate('2012/10/11 01:56:38 +0000'), '20121011')
a69801e2 221 self.assertEqual(unified_strdate('1968 12 10'), '19681210')
026fcc04 222 self.assertEqual(unified_strdate('1968-12-10'), '19681210')
99b67fec 223 self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
42bdd9d0
PH
224 self.assertEqual(
225 unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
226 '20141126')
9bb8e0a3
PH
227 self.assertEqual(
228 unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
229 '20150202')
8cf70de4 230 self.assertEqual(unified_strdate('25-09-2014'), '20140925')
dae7c920 231
59ae56fa 232 def test_find_xpath_attr(self):
4e408e47 233 testxml = '''<root>
59ae56fa
PH
234 <node/>
235 <node x="a"/>
236 <node x="a" y="c" />
237 <node x="b" y="d" />
238 </root>'''
239 doc = xml.etree.ElementTree.fromstring(testxml)
240
241 self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
242 self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
243 self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
244
d7e66d39 245 def test_xpath_with_ns(self):
4e408e47 246 testxml = '''<root xmlns:media="http://example.com/">
d7e66d39
JMF
247 <media:song>
248 <media:author>The Author</media:author>
249 <url>http://server.com/download.mp3</url>
250 </media:song>
251 </root>'''
252 doc = xml.etree.ElementTree.fromstring(testxml)
253 find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
254 self.assertTrue(find('media:song') is not None)
4e408e47
PH
255 self.assertEqual(find('media:song/media:author').text, 'The Author')
256 self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
d7e66d39 257
5379a2d4
JMF
258 def test_xpath_text(self):
259 testxml = '''<root>
260 <div>
261 <p>Foo</p>
262 </div>
263 </root>'''
264 doc = xml.etree.ElementTree.fromstring(testxml)
265 self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
266 self.assertTrue(xpath_text(doc, 'div/bar') is None)
267 self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
268
9d4660ca 269 def test_smuggle_url(self):
e075a44a 270 data = {"ö": "ö", "abc": [3]}
9d4660ca
PH
271 url = 'https://foo.bar/baz?x=y#a'
272 smug_url = smuggle_url(url, data)
273 unsmug_url, unsmug_data = unsmuggle_url(smug_url)
274 self.assertEqual(url, unsmug_url)
275 self.assertEqual(data, unsmug_data)
276
277 res_url, res_data = unsmuggle_url(url)
278 self.assertEqual(res_url, url)
279 self.assertEqual(res_data, None)
280
a6a173c2 281 def test_shell_quote(self):
4e408e47
PH
282 args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
283 self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
a6a173c2 284
f53c966a
JMF
285 def test_str_to_int(self):
286 self.assertEqual(str_to_int('123,456'), 123456)
287 self.assertEqual(str_to_int('123.456'), 123456)
288
29eb5174 289 def test_url_basename(self):
4e408e47
PH
290 self.assertEqual(url_basename('http://foo.de/'), '')
291 self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
292 self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
293 self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
294 self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
d6c7a367 295 self.assertEqual(
4e408e47
PH
296 url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
297 'trailer.mp4')
9d4660ca 298
608d11f5
PH
299 def test_parse_duration(self):
300 self.assertEqual(parse_duration(None), None)
a5fb718c
S
301 self.assertEqual(parse_duration(False), None)
302 self.assertEqual(parse_duration('invalid'), None)
608d11f5
PH
303 self.assertEqual(parse_duration('1'), 1)
304 self.assertEqual(parse_duration('1337:12'), 80232)
305 self.assertEqual(parse_duration('9:12:43'), 33163)
2db806b4
S
306 self.assertEqual(parse_duration('12:00'), 720)
307 self.assertEqual(parse_duration('00:01:01'), 61)
608d11f5 308 self.assertEqual(parse_duration('x:y'), None)
2db806b4 309 self.assertEqual(parse_duration('3h11m53s'), 11513)
ca7b3246
S
310 self.assertEqual(parse_duration('3h 11m 53s'), 11513)
311 self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
312 self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
2db806b4
S
313 self.assertEqual(parse_duration('62m45s'), 3765)
314 self.assertEqual(parse_duration('6m59s'), 419)
315 self.assertEqual(parse_duration('49s'), 49)
316 self.assertEqual(parse_duration('0h0m0s'), 0)
317 self.assertEqual(parse_duration('0m0s'), 0)
318 self.assertEqual(parse_duration('0s'), 0)
7adcbe75 319 self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
6a68bb57 320 self.assertEqual(parse_duration('T30M38S'), 1838)
e8df5cee
PH
321 self.assertEqual(parse_duration('5 s'), 5)
322 self.assertEqual(parse_duration('3 min'), 180)
323 self.assertEqual(parse_duration('2.5 hours'), 9000)
8f4b58d7
PH
324 self.assertEqual(parse_duration('02:03:04'), 7384)
325 self.assertEqual(parse_duration('01:02:03:04'), 93784)
3e675fab 326 self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
608d11f5 327
5aafe895
PH
328 def test_fix_xml_ampersands(self):
329 self.assertEqual(
330 fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
331 self.assertEqual(
332 fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
333 '"&amp;x=y&amp;wrong;&amp;z=a')
334 self.assertEqual(
335 fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
336 '&amp;&apos;&gt;&lt;&quot;')
337 self.assertEqual(
338 fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
339 self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
340
b7ab0590
PH
341 def test_paged_list(self):
342 def testPL(size, pagesize, sliceargs, expected):
343 def get_page(pagenum):
344 firstid = pagenum * pagesize
345 upto = min(size, pagenum * pagesize + pagesize)
346 for i in range(firstid, upto):
347 yield i
348
9c44d242 349 pl = OnDemandPagedList(get_page, pagesize)
b7ab0590
PH
350 got = pl.getslice(*sliceargs)
351 self.assertEqual(got, expected)
352
9c44d242
PH
353 iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
354 got = iapl.getslice(*sliceargs)
355 self.assertEqual(got, expected)
356
b7ab0590
PH
357 testPL(5, 2, (), [0, 1, 2, 3, 4])
358 testPL(5, 2, (1,), [1, 2, 3, 4])
359 testPL(5, 2, (2,), [2, 3, 4])
360 testPL(5, 2, (4,), [4])
361 testPL(5, 2, (0, 3), [0, 1, 2])
362 testPL(5, 2, (1, 4), [1, 2, 3])
363 testPL(5, 2, (2, 99), [2, 3, 4])
364 testPL(5, 2, (20, 99), [])
365
b53466e1 366 def test_struct_unpack(self):
4e408e47 367 self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
b53466e1 368
62e609ab 369 def test_read_batch_urls(self):
4e408e47 370 f = io.StringIO('''\xef\xbb\xbf foo
62e609ab
PH
371 bar\r
372 baz
373 # More after this line\r
374 ; or after this
375 bam''')
4e408e47 376 self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
62e609ab 377
b74fa8cd
JMF
378 def test_urlencode_postdata(self):
379 data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
380 self.assertTrue(isinstance(data, bytes))
381
912b38b4
PH
382 def test_parse_iso8601(self):
383 self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
384 self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
385 self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
6ad4013d 386 self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
912b38b4 387
fac55558
PH
388 def test_strip_jsonp(self):
389 stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
390 d = json.loads(stripped)
391 self.assertEqual(d, [{"id": "532cb", "x": 3}])
392
609a61e3
PH
393 stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
394 d = json.loads(stripped)
395 self.assertEqual(d, {'STATUS': 'OK'})
396
173a7026 397 def test_uppercase_escape(self):
4e408e47
PH
398 self.assertEqual(uppercase_escape('aä'), 'aä')
399 self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
fac55558 400
a020a0dc
PH
401 def test_limit_length(self):
402 self.assertEqual(limit_length(None, 12), None)
403 self.assertEqual(limit_length('foo', 12), 'foo')
404 self.assertTrue(
405 limit_length('foo bar baz asd', 12).startswith('foo bar'))
406 self.assertTrue('...' in limit_length('foo bar baz asd', 12))
407
d05cfe06
S
408 def test_escape_rfc3986(self):
409 reserved = "!*'();:@&=+$,/?#[]"
410 unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
411 self.assertEqual(escape_rfc3986(reserved), reserved)
412 self.assertEqual(escape_rfc3986(unreserved), unreserved)
413 self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
414 self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
415 self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
416 self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
417
418 def test_escape_url(self):
419 self.assertEqual(
420 escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
421 'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
422 )
423 self.assertEqual(
424 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'),
425 'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
426 )
427 self.assertEqual(
428 escape_url('http://тест.рф/фрагмент'),
429 'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
430 )
431 self.assertEqual(
432 escape_url('http://тест.рф/абв?абв=абв#абв'),
433 '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'
434 )
435 self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
436
e7b6d122 437 def test_js_to_json_realworld(self):
410f3e73 438 inp = '''{
e7b6d122 439 'clip':{'provider':'pseudo'}
410f3e73
PH
440 }'''
441 self.assertEqual(js_to_json(inp), '''{
e7b6d122 442 "clip":{"provider":"pseudo"}
410f3e73
PH
443 }''')
444 json.loads(js_to_json(inp))
445
e7b6d122
PH
446 inp = '''{
447 'playlist':[{'controls':{'all':null}}]
448 }'''
449 self.assertEqual(js_to_json(inp), '''{
450 "playlist":[{"controls":{"all":null}}]
451 }''')
452
d305dd73
PH
453 inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
454 json_code = js_to_json(inp)
455 self.assertEqual(json.loads(json_code), json.loads(inp))
456
e7b6d122
PH
457 def test_js_to_json_edgecases(self):
458 on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
459 self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
460
461 on = js_to_json('{"abc": true}')
462 self.assertEqual(json.loads(on), {'abc': True})
463
8f4b58d7
PH
464 # Ignore JavaScript code as well
465 on = js_to_json('''{
466 "x": 1,
467 y: "a",
468 z: some.code
469 }''')
470 d = json.loads(on)
471 self.assertEqual(d['x'], 1)
472 self.assertEqual(d['y'], 'a')
473
ba9e68f4
S
474 on = js_to_json('["abc", "def",]')
475 self.assertEqual(json.loads(on), ['abc', 'def'])
476
477 on = js_to_json('{"abc": "def",}')
478 self.assertEqual(json.loads(on), {'abc': 'def'})
479
e4bdb37e
PH
480 def test_clean_html(self):
481 self.assertEqual(clean_html('a:\nb'), 'a: b')
482 self.assertEqual(clean_html('a:\n "b"'), 'a: "b"')
483
4c0924bb
PH
484 def test_intlist_to_bytes(self):
485 self.assertEqual(
486 intlist_to_bytes([0, 1, 127, 128, 255]),
487 b'\x00\x01\x7f\x80\xff')
488
7d4111ed
PH
489 def test_args_to_str(self):
490 self.assertEqual(
491 args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
492 'foo ba/r -baz \'2 be\' \'\''
493 )
494
be64b5b0
PH
495 def test_parse_filesize(self):
496 self.assertEqual(parse_filesize(None), None)
497 self.assertEqual(parse_filesize(''), None)
498 self.assertEqual(parse_filesize('91 B'), 91)
499 self.assertEqual(parse_filesize('foobar'), None)
500 self.assertEqual(parse_filesize('2 MiB'), 2097152)
501 self.assertEqual(parse_filesize('5 GB'), 5000000000)
502 self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
4349c07d 503 self.assertEqual(parse_filesize('1,24 KB'), 1240)
be64b5b0 504
5f9b8394
PH
505 def test_version_tuple(self):
506 self.assertEqual(version_tuple('1'), (1,))
507 self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
47d7c642 508 self.assertEqual(version_tuple('10.1-6'), (10, 1, 6)) # avconv style
5f9b8394 509
cae97f65
PH
510 def test_detect_exe_version(self):
511 self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
512built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
513configuration: --prefix=/usr --extra-'''), '1.2.1')
514 self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
515built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
516 self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
517Trying to open render node...
518Success at /dev/dri/renderD128.
519ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
520
05900629
PH
521 def test_age_restricted(self):
522 self.assertFalse(age_restricted(None, 10)) # unrestricted content
523 self.assertFalse(age_restricted(1, None)) # unrestricted policy
524 self.assertFalse(age_restricted(8, 10))
525 self.assertTrue(age_restricted(18, 14))
526 self.assertFalse(age_restricted(18, 18))
527
61ca9a80
PH
528 def test_is_html(self):
529 self.assertFalse(is_html(b'\x49\x44\x43<html'))
530 self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
531 self.assertTrue(is_html( # UTF-8 with BOM
532 b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
533 self.assertTrue(is_html( # UTF-16-LE
534 b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
535 ))
536 self.assertTrue(is_html( # UTF-16-BE
537 b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
538 ))
539 self.assertTrue(is_html( # UTF-32-BE
540 b'\x00\x00\xFE\xFF\x00\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4'))
541 self.assertTrue(is_html( # UTF-32-LE
542 b'\xFF\xFE\x00\x00<\x00\x00\x00h\x00\x00\x00t\x00\x00\x00m\x00\x00\x00l\x00\x00\x00>\x00\x00\x00\xe4\x00\x00\x00'))
543
cfb56d1a
PH
544 def test_render_table(self):
545 self.assertEqual(
546 render_table(
547 ['a', 'bcd'],
548 [[123, 4], [9999, 51]]),
549 'a bcd\n'
550 '123 4\n'
551 '9999 51')
552
347de493
PH
553 def test_match_str(self):
554 self.assertRaises(ValueError, match_str, 'xy>foobar', {})
555 self.assertFalse(match_str('xy', {'x': 1200}))
556 self.assertTrue(match_str('!xy', {'x': 1200}))
557 self.assertTrue(match_str('x', {'x': 1200}))
558 self.assertFalse(match_str('!x', {'x': 1200}))
559 self.assertTrue(match_str('x', {'x': 0}))
560 self.assertFalse(match_str('x>0', {'x': 0}))
561 self.assertFalse(match_str('x>0', {}))
562 self.assertTrue(match_str('x>?0', {}))
563 self.assertTrue(match_str('x>1K', {'x': 1200}))
564 self.assertFalse(match_str('x>2K', {'x': 1200}))
565 self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
566 self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
567 self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
568 self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
569 self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
570 self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
571 self.assertFalse(match_str(
572 'like_count > 100 & dislike_count <? 50 & description',
573 {'like_count': 90, 'description': 'foo'}))
574 self.assertTrue(match_str(
575 'like_count > 100 & dislike_count <? 50 & description',
576 {'like_count': 190, 'description': 'foo'}))
577 self.assertFalse(match_str(
578 'like_count > 100 & dislike_count <? 50 & description',
579 {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
580 self.assertFalse(match_str(
581 'like_count > 100 & dislike_count <? 50 & description',
582 {'like_count': 190, 'dislike_count': 10}))
583
cfb56d1a 584
dae7c920 585if __name__ == '__main__':
59ae15a5 586 unittest.main()