Пример #1
0
    def setUp(self):
        conf = open('testdata/test.txts.conf')
        try:
            self.confparser = ConfParser(conf.readlines())
        finally:
            conf.close()

        self.expected_styles = []
Пример #2
0
    def test_raise_exception(self):
        """An exception should be raised when html_template doesn't exist or
         when html_template is not a directory.
         """
        confparser = ConfParser()
        with self.assertRaises(ConfException) as excep:
            confparser.read_html_template(configuration_file="./test1_conf.txt")

        with self.assertRaises(ConfException) as excep:
            confparser.read_html_template(configuration_file="./test2_conf.txt")
Пример #3
0
 def read_page(self, file_name, section_name, sec=None):
     """If sec is not None,sec will be used
     instead of the section specified by section_name
     """
     with open(self.htmls[file_name]) as f:
         file_content = f.read()
     confparser = ConfParser()
     template = Template(file_content)
     if sec is None:
         sec = confparser.read_section(section=section_name)
     return template.substitute(sec)
Пример #4
0
    def __init__(self):
        self.htmls = {}
        try:
            confparser = ConfParser()
            self.htmls = confparser.read_html_template()
        except ConfException as cex:
            sys.stderr.writelines(cex)

        # if a customized error file is not provided, use the default one.
        if "error_page" not in self.htmls or self.htmls["error_page"] is None\
                or "" == self.htmls["error_page"]:
            self.htmls["error_page"] = self.default_error_file
Пример #5
0
def test_parser_conf_dict_type_is_not_dict():
    with pytest.raises(ConfParserException):
        ConfParser(conf_dict=1)

    with pytest.raises(ConfParserException):
        ConfParser(conf_dict='test')

    with pytest.raises(ConfParserException):
        ConfParser(conf_dict=())

    with pytest.raises(ConfParserException):
        ConfParser(conf_dict=[])
Пример #6
0
 def setUp(self):
     conf = open('testdata/test.txts.conf')
     try:
         self.confparser = ConfParser(conf.readlines())
     finally:
         conf.close()
     
     self.expected_styles = []
Пример #7
0
    def handle_request(self):

        http_request = self.create_http_request()
        http_response = HttpResponse()

        field_storage = cgi.FieldStorage()
        action = field_storage.getfirst("action").strip()

        confparser = ConfParser()
        handler_section = confparser.read_section(section="handler")

        try:
            handler_class_name = handler_section[action]
        except KeyError:
            handler_class_name = "view.handler.ErrorPageHandler"

        handler_class = load_class(handler_class_name)
        handler = handler_class()
        handler.handle(http_request, http_response)
        print(http_response)
Пример #8
0
    def __init__(self,
                 kerberosPath,
                 confPath=None,
                 rulesPath=None,
                 hfilePath=None):
        self.parser = ConfParser(kerberosPath)
        if confPath is not None:
            content = self._readConfigFile(confPath)
            rulesPath = content['RulesPath']
            hfilePath = content['HfilePath']
        if rulesPath is not None and hfilePath is not None:
            self.rules = self._loadRules(rulesPath)
            self.validKeys = SupportedKeys(hfilePath).validKeys.union(
                self.rules['Attributes'])
        else:
            raise ValueError(
                'Invalid arguments for validator: no path to rules and definition files'
            )

        self._attribute_pattern = re.compile(r'^\w+$')
        self._lowercase_pattern = re.compile(r'[a-z]')
Пример #9
0
 def load_settings_from_plugin(self, path="./"):
     """
     Read the plugin's configuration file into a dictionary where each
     section of the config is a sub-dictionary that contains some properties.
     """
     plugin_name = ""
     # Remove last slash to parse data
     if path[-1] == "/":
         path = path[:-1]
     plugin_name = path.split("/")[-1]
     path = path + "/settings.conf"
     return ConfParser.parse_config(plugin_name, path)
Пример #10
0
 def load_settings_from_plugin(self, path="./"):
     """
     Read the plugin's configuration file into a dictionary where each
     section of the config is a sub-dictionary that contains some properties.
     """
     plugin_name = ""
     # Remove last slash to parse data
     if path[-1] == "/":
         path = path[:-1]
     plugin_name = path.split("/")[-1]
     path = path + "/settings.conf"
     return ConfParser.parse_config(plugin_name, path)
Пример #11
0
 def __init__(self, kerberosPath, confPath=None, rulesPath=None, hfilePath=None):
     self.parser = ConfParser(kerberosPath)
     if confPath is not None:
         content = self._readConfigFile(confPath)
         rulesPath = content['RulesPath']
         hfilePath = content['HfilePath']
     if rulesPath is not None and hfilePath is not None:    
         self.rules = self._loadRules(rulesPath)
         self.validKeys = SupportedKeys(hfilePath).validKeys.union(self.rules['Attributes'])
     else:
         raise ValueError('Invalid arguments for validator: no path to rules and definition files')
     
     self._attribute_pattern = re.compile(r'^\w+$')
     self._lowercase_pattern = re.compile(r'[a-z]')
Пример #12
0
def test_parser_with_conf_dict():
    config = ConfParser(conf_dict={
        'debug': True,
        'server': {
            'dev': {
                'debug': True,
                'port': 8000,
            },
            'prod': {
                'debug': False,
                'port': 80,
            }
        }
    }, ).to_obj()
    assert isinstance(config, ConfParserDict)
    assert config == {
        'debug': True,
        'server': {
            'dev': {
                'debug': True,
                'port': 8000
            },
            'prod': {
                'debug': False,
                'port': 80
            }
        }
    }
    assert config.debug is True
    assert isinstance(config.server, ConfParserDict)
    assert config.server == {
        'dev': {
            'debug': True,
            'port': 8000
        },
        'prod': {
            'debug': False,
            'port': 80
        }
    }
    assert isinstance(config.server.dev, ConfParserDict)
    assert config.server.dev == {'debug': True, 'port': 8000}
    assert isinstance(config.server.prod, ConfParserDict)
    assert config.server.prod == {'debug': False, 'port': 80}
    assert config.server.dev.debug is True
    assert config.server.dev.port == 8000
    assert config.server.prod.debug is False
    assert config.server.prod.port == 80
Пример #13
0
def test_parser_with_do_not_exist_path():
    with pytest.raises(ConfParserException):
        ConfParser(path='unknown')
Пример #14
0
class Validator(object):
    def __init__(self, kerberosPath, confPath=None, rulesPath=None, hfilePath=None):
        self.parser = ConfParser(kerberosPath)
        if confPath is not None:
            content = self._readConfigFile(confPath)
            rulesPath = content['RulesPath']
            hfilePath = content['HfilePath']
        if rulesPath is not None and hfilePath is not None:    
            self.rules = self._loadRules(rulesPath)
            self.validKeys = SupportedKeys(hfilePath).validKeys.union(self.rules['Attributes'])
        else:
            raise ValueError('Invalid arguments for validator: no path to rules and definition files')
        
        self._attribute_pattern = re.compile(r'^\w+$')
        self._lowercase_pattern = re.compile(r'[a-z]')

    def _readConfigFile(self,path):
        f = open(path)
        result = dict()
        for line in f:
            line = line.rstrip()
            fields = line.split('=')
            result[fields[0]] = fields[1]
        
        return result
    
    def _loadRules(self, path):
        f = open(path)
        rules = yaml.load(f)
        f.close()
        
        return rules
        
    def validate(self):
        typeInfo = self.rules['Types']
        
        for node in self.parser.walk():
            self._validateTypes(node, typeInfo)
            self._validateAttrubutes(node, self.validKeys)
            # self._validateRealm(node)


    def _validateTypes(self, node, typeInfo):
        (path, dirs, avs) = node
        for (key, value) in avs:
            valid_type_pattern = typeInfo.get(key)
            if valid_type_pattern is not None:
                for t in value:
                    if re.match(valid_type_pattern, t) is None:
                        print 'Wrong type %s for attribute %s.%s' % (t,path,key)
                        
    def _validateAttrubutes(self, node, validKeys):
        (path, dirs, avs) = node 
        attributes = list()
        for attr in dirs:
            if self._attribute_pattern.match(attr) is not None:
                attributes.append(attr)
        for (attr, value) in avs:
            if self._attribute_pattern.match(attr) is not None:
                attributes.append(attr)

        for attr in attributes:
            if attr not in validKeys:
                print 'Unrecognized attribute %s at %s' % (attr, path)
Пример #15
0
def test_parser_with_path_and_conf_dict():
    with pytest.raises(ConfParserException):
        ConfParser(path='./config.yml', conf_dict={'debug': True})
Пример #16
0
def test_parser_with_none_path_and_none_conf_dict():
    with pytest.raises(ConfParserException):
        ConfParser()
Пример #17
0
 def _load_conf(self):
     return ConfParser(self.server_name)
Пример #18
0
class ConfParserTests(unittest.TestCase):
    def setUp(self):
        conf = open('testdata/test.txts.conf')
        try:
            self.confparser = ConfParser(conf.readlines())
        finally:
            conf.close()
        
        self.expected_styles = []

    def tearDown(self):
        self.confparser = None
        self.expected_styles = None

    def expect_regex_style(self, pattern, transforms, apply_to_whole_line=False):
        self.expected_styles.append(RegexStyle(pattern, transforms, apply_to_whole_line))

    def expect_index_style(self, regions, transforms):
        self.expected_styles.append(IndexStyle(regions, transforms))

    def test_example_style(self):
        styles = self.confparser.get_styles('example')
        self.expect_regex_style(r'error', ['red'], True)
        self.expect_regex_style(r'evil\.org', ['red'])
        self.expect_regex_style(r'\d{4}-\d\d-\d\d', ['green'])
        self.expect_regex_style(r'\d\d:\d\d:\d\d', ['green', 'bold'])
        self.expect_regex_style(r'\d+\.\d+\.\d+\.\d+(:\d+)?', ['yellow', 'underline'])
        self.expect_regex_style(r'\[samplesession\]', ['magenta'])
        self.expect_regex_style(r'\[[^\]]+\]', ['blue'])
        self.expect_regex_style(r'\b\d+\b', ['cyan', 'bold'])
        self.assert_regex_styles(styles)

    def test_get_first(self):
        styles = self.confparser.get_styles('first')
        self.expect_regex_style(r'some error', ['red'])
        self.expect_regex_style(r'\d\d-\d\d-\d\d\d\d', ['blue'])
        self.expect_regex_style(r'some pattern', ['green'])
        self.expect_regex_style(r'\[(xyz.*x+y?z+)\]', ['underline'])
        self.assert_regex_styles(styles)
        
    def test_get_second(self):
        styles = self.confparser.get_styles('second')
        self.expect_regex_style('\w+', ['blue'])
        self.assert_regex_styles(styles)

    def test_get_third(self):
        styles = self.confparser.get_styles('third')
        self.expect_regex_style(r':on-red : \d+', ['on-red'])
        self.expect_regex_style(r'\\:\\[\s+]foo.*(foo).*bar\\\\', ['grey'])
        self.expect_regex_style(r': double: quotes', ['yellow'])
        self.assert_regex_styles(styles)

    def test_get_fourth(self):
        styles = self.confparser.get_styles('fourth')
        assert styles == []

    def test_get_fifth(self):
        self.assert_style_error(
            'fifth', 'Invalid style definition: green regex("some pattern")')
        
    def test_get_sixth(self):
        try:
            styles = self.confparser.get_styles('sixth')
            self.fail('should fail on invalid style key')
        except Exception, e:
            self.assertEqual(e.message, 'Invalid style key: "some-bad-key"')
Пример #19
0
 def test_html_template(self):
     confparser = ConfParser()
     res = confparser.read_html_template(configuration_file="./test3_conf.txt")
     self.assertTrue(isinstance(res, dict))
     self.assertEqual(res["login_file"], "./html_template/login.html")
Пример #20
0
class Validator(object):
    def __init__(self,
                 kerberosPath,
                 confPath=None,
                 rulesPath=None,
                 hfilePath=None):
        self.parser = ConfParser(kerberosPath)
        if confPath is not None:
            content = self._readConfigFile(confPath)
            rulesPath = content['RulesPath']
            hfilePath = content['HfilePath']
        if rulesPath is not None and hfilePath is not None:
            self.rules = self._loadRules(rulesPath)
            self.validKeys = SupportedKeys(hfilePath).validKeys.union(
                self.rules['Attributes'])
        else:
            raise ValueError(
                'Invalid arguments for validator: no path to rules and definition files'
            )

        self._attribute_pattern = re.compile(r'^\w+$')
        self._lowercase_pattern = re.compile(r'[a-z]')

    def _readConfigFile(self, path):
        f = open(path)
        result = dict()
        for line in f:
            line = line.rstrip()
            fields = line.split('=')
            result[fields[0]] = fields[1]

        return result

    def _loadRules(self, path):
        f = open(path)
        rules = yaml.load(f)
        f.close()

        return rules

    def validate(self):
        typeInfo = self.rules['Types']

        for node in self.parser.walk():
            self._validateTypes(node, typeInfo)
            self._validateAttrubutes(node, self.validKeys)
            # self._validateRealm(node)

    def _validateTypes(self, node, typeInfo):
        (path, dirs, avs) = node
        for (key, value) in avs:
            valid_type_pattern = typeInfo.get(key)
            if valid_type_pattern is not None:
                for t in value:
                    if re.match(valid_type_pattern, t) is None:
                        print 'Wrong type %s for attribute %s.%s' % (t, path,
                                                                     key)

    def _validateAttrubutes(self, node, validKeys):
        (path, dirs, avs) = node
        attributes = list()
        for attr in dirs:
            if self._attribute_pattern.match(attr) is not None:
                attributes.append(attr)
        for (attr, value) in avs:
            if self._attribute_pattern.match(attr) is not None:
                attributes.append(attr)

        for attr in attributes:
            if attr not in validKeys:
                print 'Unrecognized attribute %s at %s' % (attr, path)
Пример #21
0
 def test_error_file(self):
     confparser = ConfParser()
     res = confparser.read_html_template(configuration_file="./test4_conf.txt")["error_file"]
     self.assertEqual(res, "")
Пример #22
0
class ConfParserTests(unittest.TestCase):
    def setUp(self):
        conf = open('testdata/test.txts.conf')
        try:
            self.confparser = ConfParser(conf.readlines())
        finally:
            conf.close()

        self.expected_styles = []

    def tearDown(self):
        self.confparser = None
        self.expected_styles = None

    def expect_regex_style(self,
                           pattern,
                           transforms,
                           apply_to_whole_line=False):
        self.expected_styles.append(
            RegexStyle(pattern, transforms, apply_to_whole_line))

    def expect_index_style(self, regions, transforms):
        self.expected_styles.append(IndexStyle(regions, transforms))

    def test_example_style(self):
        styles = self.confparser.get_styles('example')
        self.expect_regex_style(r'error', ['red'], True)
        self.expect_regex_style(r'evil\.org', ['red'])
        self.expect_regex_style(r'\d{4}-\d\d-\d\d', ['green'])
        self.expect_regex_style(r'\d\d:\d\d:\d\d', ['green', 'bold'])
        self.expect_regex_style(r'\d+\.\d+\.\d+\.\d+(:\d+)?',
                                ['yellow', 'underline'])
        self.expect_regex_style(r'\[samplesession\]', ['magenta'])
        self.expect_regex_style(r'\[[^\]]+\]', ['blue'])
        self.expect_regex_style(r'\b\d+\b', ['cyan', 'bold'])
        self.assert_regex_styles(styles)

    def test_get_first(self):
        styles = self.confparser.get_styles('first')
        self.expect_regex_style(r'some error', ['red'])
        self.expect_regex_style(r'\d\d-\d\d-\d\d\d\d', ['blue'])
        self.expect_regex_style(r'some pattern', ['green'])
        self.expect_regex_style(r'\[(xyz.*x+y?z+)\]', ['underline'])
        self.assert_regex_styles(styles)

    def test_get_second(self):
        styles = self.confparser.get_styles('second')
        self.expect_regex_style('\w+', ['blue'])
        self.assert_regex_styles(styles)

    def test_get_third(self):
        styles = self.confparser.get_styles('third')
        self.expect_regex_style(r':on-red : \d+', ['on-red'])
        self.expect_regex_style(r'\\:\\[\s+]foo.*(foo).*bar\\\\', ['grey'])
        self.expect_regex_style(r': double: quotes', ['yellow'])
        self.assert_regex_styles(styles)

    def test_get_fourth(self):
        styles = self.confparser.get_styles('fourth')
        assert styles == []

    def test_get_fifth(self):
        self.assert_style_error(
            'fifth', 'Invalid style definition: green regex("some pattern")')

    def test_get_sixth(self):
        try:
            styles = self.confparser.get_styles('sixth')
            self.fail('should fail on invalid style key')
        except Exception, e:
            self.assertEqual(e.message, 'Invalid style key: "some-bad-key"')