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