Merge branch 'douyutv' of https://github.com/bonfy/youtube-dl into bonfy-douyutv
[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     find_xpath_attr,
28     fix_xml_ampersands,
29     InAdvancePagedList,
30     intlist_to_bytes,
31     is_html,
32     js_to_json,
33     limit_length,
34     OnDemandPagedList,
35     orderedSet,
36     parse_duration,
37     parse_filesize,
38     parse_iso8601,
39     read_batch_urls,
40     sanitize_filename,
41     sanitize_path,
42     sanitize_url_path_consecutive_slashes,
43     shell_quote,
44     smuggle_url,
45     str_to_int,
46     strip_jsonp,
47     struct_unpack,
48     timeconvert,
49     unescapeHTML,
50     unified_strdate,
51     unsmuggle_url,
52     uppercase_escape,
53     url_basename,
54     urlencode_postdata,
55     version_tuple,
56     xpath_with_ns,
57     render_table,
58     match_str,
59 )
60
61
62 class TestUtil(unittest.TestCase):
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')
82         aumlaut = 'ä'
83         self.assertEqual(sanitize_filename(aumlaut), aumlaut)
84         tests = '\u043a\u0438\u0440\u0438\u043b\u043b\u0438\u0446\u0430'
85         self.assertEqual(sanitize_filename(tests), tests)
86
87         self.assertEqual(
88             sanitize_filename('New World record at 0:12:34'),
89             'New World record at 0_12_34')
90
91         self.assertEqual(sanitize_filename('--gasdgf'), '_-gasdgf')
92         self.assertEqual(sanitize_filename('--gasdgf', is_id=True), '--gasdgf')
93         self.assertEqual(sanitize_filename('.gasdgf'), 'gasdgf')
94         self.assertEqual(sanitize_filename('.gasdgf', is_id=True), '.gasdgf')
95
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
115         tests = 'a\xe4b\u4e2d\u56fd\u7684c'
116         self.assertEqual(sanitize_filename(tests, restricted=True), 'a_b_c')
117         self.assertTrue(sanitize_filename('\xf6', restricted=True) != '')  # No empty filename
118
119         forbidden = '"\0\\/&!: \'\t\n()[]{}$;`^,#'
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
125         self.assertEqual(sanitize_filename('\u5927\u58f0\u5e26 - Song', restricted=True), 'Song')
126         self.assertEqual(sanitize_filename('\u603b\u7edf: Speech', restricted=True), 'Speech')
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
131     def test_sanitize_ids(self):
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')
135
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
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
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
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
192     def test_ordered_set(self):
193         self.assertEqual(orderedSet([1, 1, 2, 3, 4, 4, 5, 6, 7, 3, 5]), [1, 2, 3, 4, 5, 6, 7])
194         self.assertEqual(orderedSet([]), [])
195         self.assertEqual(orderedSet([1]), [1])
196         # keep the list ordered
197         self.assertEqual(orderedSet([135, 1, 1, 1]), [135, 1])
198
199     def test_unescape_html(self):
200         self.assertEqual(unescapeHTML('%20;'), '%20;')
201         self.assertEqual(
202             unescapeHTML('&eacute;'), 'é')
203
204     def test_daterange(self):
205         _20century = DateRange("19000101", "20000101")
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)
211
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')
217         self.assertEqual(unified_strdate('1968 12 10'), '19681210')
218         self.assertEqual(unified_strdate('1968-12-10'), '19681210')
219         self.assertEqual(unified_strdate('28/01/2014 21:00:00 +0100'), '20140128')
220         self.assertEqual(
221             unified_strdate('11/26/2014 11:30:00 AM PST', day_first=False),
222             '20141126')
223         self.assertEqual(
224             unified_strdate('2/2/2015 6:47:40 PM', day_first=False),
225             '20150202')
226
227     def test_find_xpath_attr(self):
228         testxml = '''<root>
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
240     def test_xpath_with_ns(self):
241         testxml = '''<root xmlns:media="http://example.com/">
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)
250         self.assertEqual(find('media:song/media:author').text, 'The Author')
251         self.assertEqual(find('media:song/url').text, 'http://server.com/download.mp3')
252
253     def test_smuggle_url(self):
254         data = {"ö": "ö", "abc": [3]}
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
265     def test_shell_quote(self):
266         args = ['ffmpeg', '-i', encodeFilename('ñ€ß\'.mp4')]
267         self.assertEqual(shell_quote(args), """ffmpeg -i 'ñ€ß'"'"'.mp4'""")
268
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
273     def test_url_basename(self):
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')
279         self.assertEqual(
280             url_basename('http://media.w3.org/2010/05/sintel/trailer.mp4'),
281             'trailer.mp4')
282
283     def test_parse_duration(self):
284         self.assertEqual(parse_duration(None), None)
285         self.assertEqual(parse_duration(False), None)
286         self.assertEqual(parse_duration('invalid'), None)
287         self.assertEqual(parse_duration('1'), 1)
288         self.assertEqual(parse_duration('1337:12'), 80232)
289         self.assertEqual(parse_duration('9:12:43'), 33163)
290         self.assertEqual(parse_duration('12:00'), 720)
291         self.assertEqual(parse_duration('00:01:01'), 61)
292         self.assertEqual(parse_duration('x:y'), None)
293         self.assertEqual(parse_duration('3h11m53s'), 11513)
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)
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)
303         self.assertEqual(parse_duration('01:02:03.05'), 3723.05)
304         self.assertEqual(parse_duration('T30M38S'), 1838)
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)
308         self.assertEqual(parse_duration('02:03:04'), 7384)
309         self.assertEqual(parse_duration('01:02:03:04'), 93784)
310         self.assertEqual(parse_duration('1 hour 3 minutes'), 3780)
311
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
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
333             pl = OnDemandPagedList(get_page, pagesize)
334             got = pl.getslice(*sliceargs)
335             self.assertEqual(got, expected)
336
337             iapl = InAdvancePagedList(get_page, size // pagesize + 1, pagesize)
338             got = iapl.getslice(*sliceargs)
339             self.assertEqual(got, expected)
340
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
350     def test_struct_unpack(self):
351         self.assertEqual(struct_unpack('!B', b'\x00'), (0,))
352
353     def test_read_batch_urls(self):
354         f = io.StringIO('''\xef\xbb\xbf foo
355             bar\r
356             baz
357             # More after this line\r
358             ; or after this
359             bam''')
360         self.assertEqual(read_batch_urls(f), ['foo', 'bar', 'baz', 'bam'])
361
362     def test_urlencode_postdata(self):
363         data = urlencode_postdata({'username': 'foo@bar.com', 'password': '1234'})
364         self.assertTrue(isinstance(data, bytes))
365
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)
370         self.assertEqual(parse_iso8601('2014-03-23T22:04:26.1234Z'), 1395612266)
371
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
377         stripped = strip_jsonp('parseMetadata({"STATUS":"OK"})\n\n\n//epc')
378         d = json.loads(stripped)
379         self.assertEqual(d, {'STATUS': 'OK'})
380
381     def test_uppercase_escape(self):
382         self.assertEqual(uppercase_escape('aä'), 'aä')
383         self.assertEqual(uppercase_escape('\\U0001d550'), '𝕐')
384
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
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
421     def test_js_to_json_realworld(self):
422         inp = '''{
423             'clip':{'provider':'pseudo'}
424         }'''
425         self.assertEqual(js_to_json(inp), '''{
426             "clip":{"provider":"pseudo"}
427         }''')
428         json.loads(js_to_json(inp))
429
430         inp = '''{
431             'playlist':[{'controls':{'all':null}}]
432         }'''
433         self.assertEqual(js_to_json(inp), '''{
434             "playlist":[{"controls":{"all":null}}]
435         }''')
436
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
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
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
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
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
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
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)
481         self.assertEqual(parse_filesize('1,24 KB'), 1240)
482
483     def test_version_tuple(self):
484         self.assertEqual(version_tuple('1'), (1,))
485         self.assertEqual(version_tuple('10.23.344'), (10, 23, 344))
486         self.assertEqual(version_tuple('10.1-6'), (10, 1, 6))  # avconv style
487
488     def test_detect_exe_version(self):
489         self.assertEqual(detect_exe_version('''ffmpeg version 1.2.1
490 built on May 27 2013 08:37:26 with gcc 4.7 (Debian 4.7.3-4)
491 configuration: --prefix=/usr --extra-'''), '1.2.1')
492         self.assertEqual(detect_exe_version('''ffmpeg version N-63176-g1fb4685
493 built 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!
495 Trying to open render node...
496 Success at /dev/dri/renderD128.
497 ffmpeg version 2.4.4 Copyright (c) 2000-2014 the FFmpeg ...'''), '2.4.4')
498
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
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
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
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
562
563 if __name__ == '__main__':
564     unittest.main()