Coverage for curator/validators/schemacheck.py: 100%
41 statements
« prev ^ index » next coverage.py v7.3.0, created at 2023-08-16 15:27 -0600
« prev ^ index » next coverage.py v7.3.0, created at 2023-08-16 15:27 -0600
1from voluptuous import Schema
2from curator.exceptions import ConfigurationError
3import re
4import logging
6class SchemaCheck(object):
7 def __init__(self, config, schema, test_what, location):
8 """
9 Validate ``config`` with the provided voluptuous ``schema``.
10 ``test_what`` and ``location`` are for reporting the results, in case of
11 failure. If validation is successful, the method returns ``config`` as
12 valid.
14 :arg config: A configuration dictionary.
15 :type config: dict
16 :arg schema: A voluptuous schema definition
17 :type schema: :class:`voluptuous.Schema`
18 :arg test_what: which configuration block is being validated
19 :type test_what: str
20 :arg location: An string to report which configuration sub-block is
21 being tested.
22 :type location: str
23 """
24 self.loggit = logging.getLogger('curator.validators.SchemaCheck')
25 # Set the Schema for validation...
26 self.loggit.debug('Schema: {0}'.format(schema))
27 self.loggit.debug('"{0}" config: {1}'.format(test_what, config))
28 self.config = config
29 self.schema = schema
30 self.test_what = test_what
31 self.location = location
33 def __parse_error(self):
34 """
35 Report the error, and try to report the bad key or value as well.
36 """
37 def get_badvalue(data_string, data):
38 elements = re.sub(r'[\'\]]', '', data_string).split('[')
39 elements.pop(0) # Get rid of data as the first element
40 value = None
41 for k in elements:
42 try:
43 key = int(k)
44 except ValueError:
45 key = k
46 if value == None:
47 value = data[key]
48 # if this fails, it's caught below
49 return value
50 try:
51 self.badvalue = get_badvalue(str(self.error).split()[-1], self.config)
52 except:
53 self.badvalue = '(could not determine)'
55 def result(self):
56 try:
57 return self.schema(self.config)
58 except Exception as e:
59 try:
60 # pylint: disable=E1101
61 self.error = e.errors[0]
62 except:
63 self.error = '{0}'.format(e)
64 self.__parse_error()
65 self.loggit.error('Schema error: {0}'.format(self.error))
66 raise ConfigurationError(
67 'Configuration: {0}: Location: {1}: Bad Value: "{2}", {3}. '
68 'Check configuration file.'.format(
69 self.test_what, self.location, self.badvalue, self.error)
70 )