Merge branch 'pornovoisines' of https://github.com/Roman2K/youtube-dl into Roman2K...
[youtube-dl] / 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     age_restricted,
20     args_to_str,
21     clean_html,
22     DateRange,
23     detect_exe_version,
24     encodeFilename,
25     escape_rfc3986,
26     escape_url,
27     ExtractorError,
28     find_xpath_attr,
29     fix_xml_ampersands,
30     InAdvancePagedList,
31     intlist_to_bytes,
32     is_html,
33     js_to_json,
34     limit_length,
35     OnDemandPagedList,
36     orderedSet,
37     parse_duration,
38     parse_filesize,
39     parse_iso8601,
40     read_batch_urls,
41     sanitize_filename,
42     sanitize_path,
43     sanitize_url_path_consecutive_slashes,
44     shell_quote,
45     smuggle_url,
46     str_to_int,
47     strip_jsonp,
48     struct_unpack,
49     timeconvert,
50     unescapeHTML,
51     unified_strdate,
52     unsmuggle_url,
53     uppercase_escape,
54     url_basename,
55     urlencode_postdata,
56     version_tuple,
57     xpath_with_ns,
58     xpath_text,
59     render_table,
60     match_str,
61 )
62
63
64 class TestUtil(unittest.TestCase):
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')
84         aumlaut = 'ä'
85         self.assertEqual(sanitize_filename(aumlaut), aumlaut)
86         tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
87         self.assertEqual(sanitize_filename(tests), tests)
88
89         self.assertEqual(
90             sanitize_filename('New World record at 0:12:34'),
91             'New World record at 0_12_34')
92
93         self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
94         self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
95         self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
96         self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
97
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
117         tests = 'a\xe4b\u4e2d\u56fd\u7684c'
118         self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
119         self.assertTrue(sanitize_filename('\xf6', restricted=True) != '')  # No empty filename
120
121         forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
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
127         self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
128         self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
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
133     def test_sanitize_ids(self):
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')
137
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
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
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
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
194     def test_ordered_set(self):
195         self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
196         self.assertEqual(orderedSet([]), [])
197         self.assertEqual(orderedSet([1]), [1])
198         # keep the list ordered
199         self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
200
201     def test_unescape_html(self):
202         self.assertEqual(unescapeHTML('%20;'), '%20;')
203         self.assertEqual(unescapeHTML('&#x2F;'), '/')
204         self.assertEqual(unescapeHTML('&#47;'), '/')
205         self.assertEqual(
206             unescapeHTML('&eacute;'), 'é')
207
208     def test_daterange(self):
209         _20century = DateRange("19000101", "20000101")
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)
215
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')
221         self.assertEqual(unified_strdate('1968 12 10'), '19681210')
222         self.assertEqual(unified_strdate('1968-12-10'), '19681210')
223         self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
224         self.assertEqual(
225             unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
226             '20141126')
227         self.assertEqual(
228             unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
229             '20150202')
230
231     def test_find_xpath_attr(self):
232         testxml = '''<root>
233             <node/>
234             <node x="a"/>
235             <node x="a" y="c" />
236             <node x="b" y="d" />
237         </root>'''
238         doc = xml.etree.ElementTree.fromstring(testxml)
239
240         self.assertEqual(find_xpath_attr(doc, './/fourohfour', 'n', 'v'), None)
241         self.assertEqual(find_xpath_attr(doc, './/node', 'x', 'a'), doc[1])
242         self.assertEqual(find_xpath_attr(doc, './/node', 'y', 'c'), doc[2])
243
244     def test_xpath_with_ns(self):
245         testxml = '''<root xmlns:media="http://example.com/">
246             <media:song>
247                 <media:author>The Author</media:author>
248                 <url>http://server.com/download.mp3</url>
249             </media:song>
250         </root>'''
251         doc = xml.etree.ElementTree.fromstring(testxml)
252         find = lambda p: doc.find(xpath_with_ns(p, {'media': 'http://example.com/'}))
253         self.assertTrue(find('media:song') is not None)
254         self.assertEqual(find('media:song/media:author').text, 'The Author')
255         self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
256
257     def test_xpath_text(self):
258         testxml = '''<root>
259             <div>
260                 <p>Foo</p>
261             </div>
262         </root>'''
263         doc = xml.etree.ElementTree.fromstring(testxml)
264         self.assertEqual(xpath_text(doc, 'div/p'), 'Foo')
265         self.assertTrue(xpath_text(doc, 'div/bar') is None)
266         self.assertRaises(ExtractorError, xpath_text, doc, 'div/bar', fatal=True)
267
268     def test_smuggle_url(self):
269         data = {"ö": "ö", "abc": [3]}
270         url = 'https://foo.bar/baz?x=y#a'
271         smug_url = smuggle_url(url, data)
272         unsmug_url, unsmug_data = unsmuggle_url(smug_url)
273         self.assertEqual(url, unsmug_url)
274         self.assertEqual(data, unsmug_data)
275
276         res_url, res_data = unsmuggle_url(url)
277         self.assertEqual(res_url, url)
278         self.assertEqual(res_data, None)
279
280     def test_shell_quote(self):
281         args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
282         self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
283
284     def test_str_to_int(self):
285         self.assertEqual(str_to_int('123,456'), 123456)
286         self.assertEqual(str_to_int('123.456'), 123456)
287
288     def test_url_basename(self):
289         self.assertEqual(url_basename('http://foo.de/'), '')
290         self.assertEqual(url_basename('http://foo.de/bar/baz'), 'baz')
291         self.assertEqual(url_basename('http://foo.de/bar/baz?x=y'), 'baz')
292         self.assertEqual(url_basename('http://foo.de/bar/baz#x=y'), 'baz')
293         self.assertEqual(url_basename('http://foo.de/bar/baz/'), 'baz')
294         self.assertEqual(
295             url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
296             'trailer.mp4')
297
298     def test_parse_duration(self):
299         self.assertEqual(parse_duration(None), None)
300         self.assertEqual(parse_duration(False), None)
301         self.assertEqual(parse_duration('invalid'), None)
302         self.assertEqual(parse_duration('1'), 1)
303         self.assertEqual(parse_duration('1337:12'), 80232)
304         self.assertEqual(parse_duration('9:12:43'), 33163)
305         self.assertEqual(parse_duration('12:00'), 720)
306         self.assertEqual(parse_duration('00:01:01'), 61)
307         self.assertEqual(parse_duration('x:y'), None)
308         self.assertEqual(parse_duration('3h11m53s'), 11513)
309         self.assertEqual(parse_duration('3h 11m 53s'), 11513)
310         self.assertEqual(parse_duration('3 hours 11 minutes 53 seconds'), 11513)
311         self.assertEqual(parse_duration('3 hours 11 mins 53 secs'), 11513)
312         self.assertEqual(parse_duration('62m45s'), 3765)
313         self.assertEqual(parse_duration('6m59s'), 419)
314         self.assertEqual(parse_duration('49s'), 49)
315         self.assertEqual(parse_duration('0h0m0s'), 0)
316         self.assertEqual(parse_duration('0m0s'), 0)
317         self.assertEqual(parse_duration('0s'), 0)
318         self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
319         self.assertEqual(parse_duration('T30M38S'), 1838)
320         self.assertEqual(parse_duration('5 s'), 5)
321         self.assertEqual(parse_duration('3 min'), 180)
322         self.assertEqual(parse_duration('2.5 hours'), 9000)
323         self.assertEqual(parse_duration('02:03:04'), 7384)
324         self.assertEqual(parse_duration('01:02:03:04'), 93784)
325         self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
326
327     def test_fix_xml_ampersands(self):
328         self.assertEqual(
329             fix_xml_ampersands('"&x=y&z=a'), '"&amp;x=y&amp;z=a')
330         self.assertEqual(
331             fix_xml_ampersands('"&amp;x=y&wrong;&z=a'),
332             '"&amp;x=y&amp;wrong;&amp;z=a')
333         self.assertEqual(
334             fix_xml_ampersands('&amp;&apos;&gt;&lt;&quot;'),
335             '&amp;&apos;&gt;&lt;&quot;')
336         self.assertEqual(
337             fix_xml_ampersands('&#1234;&#x1abC;'), '&#1234;&#x1abC;')
338         self.assertEqual(fix_xml_ampersands('&#&#'), '&amp;#&amp;#')
339
340     def test_paged_list(self):
341         def testPL(size, pagesize, sliceargs, expected):
342             def get_page(pagenum):
343                 firstid = pagenum * pagesize
344                 upto = min(size, pagenum * pagesize + pagesize)
345                 for i in range(firstid, upto):
346                     yield i
347
348             pl = OnDemandPagedList(get_page, pagesize)
349             got = pl.getslice(*sliceargs)
350             self.assertEqual(got, expected)
351
352             iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
353             got = iapl.getslice(*sliceargs)
354             self.assertEqual(got, expected)
355
356         testPL(5, 2, (), [0, 1, 2, 3, 4])
357         testPL(5, 2, (1,), [1, 2, 3, 4])
358         testPL(5, 2, (2,), [2, 3, 4])
359         testPL(5, 2, (4,), [4])
360         testPL(5, 2, (0, 3), [0, 1, 2])
361         testPL(5, 2, (1, 4), [1, 2, 3])
362         testPL(5, 2, (2, 99), [2, 3, 4])
363         testPL(5, 2, (20, 99), [])
364
365     def test_struct_unpack(self):
366         self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
367
368     def test_read_batch_urls(self):
369         f = io.StringIO('''\xef\xbb\xbf foo
370             bar\r
371             baz
372             # More after this line\r
373             ; or after this
374             bam''')
375         self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
376
377     def test_urlencode_postdata(self):
378         data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
379         self.assertTrue(isinstance(data, bytes))
380
381     def test_parse_iso8601(self):
382         self.assertEqual(parse_iso8601('2014-03-23T23:04:26+0100'), 1395612266)
383         self.assertEqual(parse_iso8601('2014-03-23T22:04:26+0000'), 1395612266)
384         self.assertEqual(parse_iso8601('2014-03-23T22:04:26Z'), 1395612266)
385         self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
386
387     def test_strip_jsonp(self):
388         stripped = strip_jsonp('cb ([ {"id":"532cb",\n\n\n"x":\n3}\n]\n);')
389         d = json.loads(stripped)
390         self.assertEqual(d, [{"id": "532cb", "x": 3}])
391
392         stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
393         d = json.loads(stripped)
394         self.assertEqual(d, {'STATUS': 'OK'})
395
396     def test_uppercase_escape(self):
397         self.assertEqual(uppercase_escape('aä'), 'aä')
398         self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
399
400     def test_limit_length(self):
401         self.assertEqual(limit_length(None, 12), None)
402         self.assertEqual(limit_length('foo', 12), 'foo')
403         self.assertTrue(
404             limit_length('foo bar baz asd', 12).startswith('foo bar'))
405         self.assertTrue('...' in limit_length('foo bar baz asd', 12))
406
407     def test_escape_rfc3986(self):
408         reserved = "!*'();:@&=+$,/?#[]"
409         unreserved = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~'
410         self.assertEqual(escape_rfc3986(reserved), reserved)
411         self.assertEqual(escape_rfc3986(unreserved), unreserved)
412         self.assertEqual(escape_rfc3986('тест'), '%D1%82%D0%B5%D1%81%D1%82')
413         self.assertEqual(escape_rfc3986('%D1%82%D0%B5%D1%81%D1%82'), '%D1%82%D0%B5%D1%81%D1%82')
414         self.assertEqual(escape_rfc3986('foo bar'), 'foo%20bar')
415         self.assertEqual(escape_rfc3986('foo%20bar'), 'foo%20bar')
416
417     def test_escape_url(self):
418         self.assertEqual(
419             escape_url('http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavré_FD.mp4'),
420             'http://wowza.imust.org/srv/vod/telemb/new/UPLOAD/UPLOAD/20224_IncendieHavre%CC%81_FD.mp4'
421         )
422         self.assertEqual(
423             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'),
424             'http://www.ardmediathek.de/tv/Sturm-der-Liebe/Folge-2036-Zu-Mann-und-Frau-erkl%C3%A4rt/Das-Erste/Video?documentId=22673108&bcastId=5290'
425         )
426         self.assertEqual(
427             escape_url('http://тест.рф/фрагмент'),
428             'http://тест.рф/%D1%84%D1%80%D0%B0%D0%B3%D0%BC%D0%B5%D0%BD%D1%82'
429         )
430         self.assertEqual(
431             escape_url('http://тест.рф/абв?абв=абв#абв'),
432             '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'
433         )
434         self.assertEqual(escape_url('http://vimeo.com/56015672#at=0'), 'http://vimeo.com/56015672#at=0')
435
436     def test_js_to_json_realworld(self):
437         inp = '''{
438             'clip':{'provider':'pseudo'}
439         }'''
440         self.assertEqual(js_to_json(inp), '''{
441             "clip":{"provider":"pseudo"}
442         }''')
443         json.loads(js_to_json(inp))
444
445         inp = '''{
446             'playlist':[{'controls':{'all':null}}]
447         }'''
448         self.assertEqual(js_to_json(inp), '''{
449             "playlist":[{"controls":{"all":null}}]
450         }''')
451
452         inp = '"SAND Number: SAND 2013-7800P\\nPresenter: Tom Russo\\nHabanero Software Training - Xyce Software\\nXyce, Sandia\\u0027s"'
453         json_code = js_to_json(inp)
454         self.assertEqual(json.loads(json_code), json.loads(inp))
455
456     def test_js_to_json_edgecases(self):
457         on = js_to_json("{abc_def:'1\\'\\\\2\\\\\\'3\"4'}")
458         self.assertEqual(json.loads(on), {"abc_def": "1'\\2\\'3\"4"})
459
460         on = js_to_json('{"abc": true}')
461         self.assertEqual(json.loads(on), {'abc': True})
462
463         # Ignore JavaScript code as well
464         on = js_to_json('''{
465             "x": 1,
466             y: "a",
467             z: some.code
468         }''')
469         d = json.loads(on)
470         self.assertEqual(d['x'], 1)
471         self.assertEqual(d['y'], 'a')
472
473         on = js_to_json('["abc", "def",]')
474         self.assertEqual(json.loads(on), ['abc', 'def'])
475
476         on = js_to_json('{"abc": "def",}')
477         self.assertEqual(json.loads(on), {'abc': 'def'})
478
479     def test_clean_html(self):
480         self.assertEqual(clean_html('a:\nb'), 'a: b')
481         self.assertEqual(clean_html('a:\n   "b"'), 'a:    "b"')
482
483     def test_intlist_to_bytes(self):
484         self.assertEqual(
485             intlist_to_bytes([0, 1, 127, 128, 255]),
486             b'\x00\x01\x7f\x80\xff')
487
488     def test_args_to_str(self):
489         self.assertEqual(
490             args_to_str(['foo', 'ba/r', '-baz', '2 be', '']),
491             'foo ba/r -baz \'2 be\' \'\''
492         )
493
494     def test_parse_filesize(self):
495         self.assertEqual(parse_filesize(None), None)
496         self.assertEqual(parse_filesize(''), None)
497         self.assertEqual(parse_filesize('91 B'), 91)
498         self.assertEqual(parse_filesize('foobar'), None)
499         self.assertEqual(parse_filesize('2 MiB'), 2097152)
500         self.assertEqual(parse_filesize('5 GB'), 5000000000)
501         self.assertEqual(parse_filesize('1.2Tb'), 1200000000000)
502         self.assertEqual(parse_filesize('1,24 KB'), 1240)
503
504     def test_version_tuple(self):
505         self.assertEqual(version_tuple('1'), (1,))
506         self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
507         self.assertEqual(version_tuple('10.1-6'), (10, 1, 6))  # avconv style
508
509     def test_detect_exe_version(self):
510         self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
511 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
512 configuration: --prefix=/usr --extra-'''), '1.2.1')
513         self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
514 built on May 15 2014 22:09:06 with gcc 4.8.2 (GCC)'''), 'N-63176-g1fb4685')
515         self.assertEqual(detect_exe_version('''X server found. dri2 connection failed!
516 Trying to open render node...
517 Success at /dev/dri/renderD128.
518 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
519
520     def test_age_restricted(self):
521         self.assertFalse(age_restricted(None, 10))  # unrestricted content
522         self.assertFalse(age_restricted(1, None))  # unrestricted policy
523         self.assertFalse(age_restricted(8, 10))
524         self.assertTrue(age_restricted(18, 14))
525         self.assertFalse(age_restricted(18, 18))
526
527     def test_is_html(self):
528         self.assertFalse(is_html(b'\x49\x44\x43<html'))
529         self.assertTrue(is_html(b'<!DOCTYPE foo>\xaaa'))
530         self.assertTrue(is_html(  # UTF-8 with BOM
531             b'\xef\xbb\xbf<!DOCTYPE foo>\xaaa'))
532         self.assertTrue(is_html(  # UTF-16-LE
533             b'\xff\xfe<\x00h\x00t\x00m\x00l\x00>\x00\xe4\x00'
534         ))
535         self.assertTrue(is_html(  # UTF-16-BE
536             b'\xfe\xff\x00<\x00h\x00t\x00m\x00l\x00>\x00\xe4'
537         ))
538         self.assertTrue(is_html(  # UTF-32-BE
539             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'))
540         self.assertTrue(is_html(  # UTF-32-LE
541             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'))
542
543     def test_render_table(self):
544         self.assertEqual(
545             render_table(
546                 ['a', 'bcd'],
547                 [[123, 4], [9999, 51]]),
548             'a    bcd\n'
549             '123  4\n'
550             '9999 51')
551
552     def test_match_str(self):
553         self.assertRaises(ValueError, match_str, 'xy>foobar', {})
554         self.assertFalse(match_str('xy', {'x': 1200}))
555         self.assertTrue(match_str('!xy', {'x': 1200}))
556         self.assertTrue(match_str('x', {'x': 1200}))
557         self.assertFalse(match_str('!x', {'x': 1200}))
558         self.assertTrue(match_str('x', {'x': 0}))
559         self.assertFalse(match_str('x>0', {'x': 0}))
560         self.assertFalse(match_str('x>0', {}))
561         self.assertTrue(match_str('x>?0', {}))
562         self.assertTrue(match_str('x>1K', {'x': 1200}))
563         self.assertFalse(match_str('x>2K', {'x': 1200}))
564         self.assertTrue(match_str('x>=1200 & x < 1300', {'x': 1200}))
565         self.assertFalse(match_str('x>=1100 & x < 1200', {'x': 1200}))
566         self.assertFalse(match_str('y=a212', {'y': 'foobar42'}))
567         self.assertTrue(match_str('y=foobar42', {'y': 'foobar42'}))
568         self.assertFalse(match_str('y!=foobar42', {'y': 'foobar42'}))
569         self.assertTrue(match_str('y!=foobar2', {'y': 'foobar42'}))
570         self.assertFalse(match_str(
571             'like_count > 100 & dislike_count <? 50 & description',
572             {'like_count': 90, 'description': 'foo'}))
573         self.assertTrue(match_str(
574             'like_count > 100 & dislike_count <? 50 & description',
575             {'like_count': 190, 'description': 'foo'}))
576         self.assertFalse(match_str(
577             'like_count > 100 & dislike_count <? 50 & description',
578             {'like_count': 190, 'dislike_count': 60, 'description': 'foo'}))
579         self.assertFalse(match_str(
580             'like_count > 100 & dislike_count <? 50 & description',
581             {'like_count': 190, 'dislike_count': 10}))
582
583
584 if __name__ == '__main__':
585     unittest.main()