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