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