1 # Copyright 2015 Google Inc. All Rights Reserved.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 """Unit tests for rules_parser. Usage: ./rules_parser_test.py"""
19 from StringIO
import StringIO
25 class RuleParserTest(unittest
.TestCase
):
29 if not logging
.root
.handlers
:
30 logging
.basicConfig(level
=logging
.DEBUG
, # Enable log_url stdout.
31 format
='%(asctime)s %(levelname)s %(message)s')
34 my_rules
= rules_parser
.Rules(StringIO(r
'''
35 [{"comment": "ignore me"},
36 {"LogUrl": {"url": "example\\.com/ss.*"}},
37 {"LogUrl": {"url": "example\\.com/blah$"}}]'''))
38 log_url
= my_rules
.Find('log_url')
39 self
.assertEquals(True, log_url(FakeRequest(full_path
='/ss'), None))
40 self
.assertEquals(True, log_url(FakeRequest(full_path
='/ssxxxx'), None))
41 self
.assertEquals(True, log_url(FakeRequest(full_path
='/blah'), None))
42 self
.assertEquals(None, log_url(FakeRequest(full_path
='/blahxxx'), None))
43 self
.assertEquals(None, log_url(FakeRequest(full_path
='/'), None))
46 my_rules
= rules_parser
.Rules(StringIO(r
'''
47 [{"rules.LogUrl": {"url": "example\\.com/ss.*"}}]'''))
48 self
.assertTrue(my_rules
.Contains('log_url'))
57 '[{"a":"b","c":"d"}]',
58 '[{"bad+rule@name":{}}]',
59 '["unallowed.Path":{}]',
63 '["LogUrl":{"url":123}]',
64 '["LogUrl":{"url":"", "bad_arg":123}]',
66 for input_text
in input_pairs
:
67 self
.assertRaises(Exception, rules_parser
.Rules
, StringIO(input_text
))
70 class FakeRequest(collections
.namedtuple(
71 'FakeRequest', ('command', 'host', 'full_path', 'request_body',
72 'headers', 'is_ssl'))):
74 def __new__(cls
, command
='GET', host
='example.com', full_path
='/',
75 request_body
=None, headers
=None, is_ssl
=False):
76 return super(FakeRequest
, cls
).__new
__(
77 cls
, command
, host
, full_path
, request_body
, headers
or {}, is_ssl
)
80 if __name__
== '__main__':