Add input validation in substitution_mapping class
[parser.git] / tosca2heat / tosca-parser / toscaparser / common / exception.py
1 #    Licensed under the Apache License, Version 2.0 (the "License"); you may
2 #    not use this file except in compliance with the License. You may obtain
3 #    a copy of the License at
4 #
5 #         http://www.apache.org/licenses/LICENSE-2.0
6 #
7 #    Unless required by applicable law or agreed to in writing, software
8 #    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9 #    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10 #    License for the specific language governing permissions and limitations
11 #    under the License.
12
13 '''
14 TOSCA exception classes
15 '''
16 import logging
17 import sys
18 import traceback
19
20 from toscaparser.utils.gettextutils import _
21
22
23 log = logging.getLogger(__name__)
24
25
26 class TOSCAException(Exception):
27     '''Base exception class for TOSCA
28
29     To correctly use this class, inherit from it and define
30     a 'msg_fmt' property.
31
32     '''
33
34     _FATAL_EXCEPTION_FORMAT_ERRORS = False
35
36     message = _('An unknown exception occurred.')
37
38     def __init__(self, **kwargs):
39         try:
40             self.message = self.msg_fmt % kwargs
41         except KeyError:
42             exc_info = sys.exc_info()
43             log.exception(_('Exception in string format operation: %s')
44                           % exc_info[1])
45
46             if TOSCAException._FATAL_EXCEPTION_FORMAT_ERRORS:
47                 raise exc_info[0]
48
49     def __str__(self):
50         return self.message
51
52     @staticmethod
53     def generate_inv_schema_property_error(self, attr, value, valid_values):
54         msg = (_('Schema definition of "%(propname)s" has '
55                  '"%(attr)s" attribute with invalid value '
56                  '"%(value1)s". The value must be one of '
57                  '"%(value2)s".') % {"propname": self.name,
58                                      "attr": attr,
59                                      "value1": value,
60                                      "value2": valid_values})
61         ExceptionCollector.appendException(
62             InvalidSchemaError(message=msg))
63
64     @staticmethod
65     def set_fatal_format_exception(flag):
66         if isinstance(flag, bool):
67             TOSCAException._FATAL_EXCEPTION_FORMAT_ERRORS = flag
68
69
70 class MissingRequiredFieldError(TOSCAException):
71     msg_fmt = _('%(what)s is missing required field "%(required)s".')
72
73
74 class UnknownFieldError(TOSCAException):
75     msg_fmt = _('%(what)s contains unknown field "%(field)s". Refer to the '
76                 'definition to verify valid values.')
77
78
79 class TypeMismatchError(TOSCAException):
80     msg_fmt = _('%(what)s must be of type "%(type)s".')
81
82
83 class InvalidNodeTypeError(TOSCAException):
84     msg_fmt = _('Node type "%(what)s" is not a valid type.')
85
86
87 class InvalidTypeError(TOSCAException):
88     msg_fmt = _('Type "%(what)s" is not a valid type.')
89
90
91 class InvalidTypeAdditionalRequirementsError(TOSCAException):
92     msg_fmt = _('Additional requirements for type "%(type)s" not met.')
93
94
95 class RangeValueError(TOSCAException):
96     msg_fmt = _('The value "%(pvalue)s" of property "%(pname)s" is out of '
97                 'range "(min:%(vmin)s, max:%(vmax)s)".')
98
99
100 class InvalidSchemaError(TOSCAException):
101     msg_fmt = _('%(message)s')
102
103
104 class ValidationError(TOSCAException):
105     msg_fmt = _('%(message)s')
106
107
108 class UnknownInputError(TOSCAException):
109     msg_fmt = _('Unknown input "%(input_name)s".')
110
111
112 class MissingRequiredInputError(TOSCAException):
113     msg_fmt = _('%(what)s is missing required input definition '
114                 ' with name: "%(input_name)s".')
115
116
117 class MissingRequiredParameterError(TOSCAException):
118     msg_fmt = _('%(what)s is missing required parameter for input: '
119                 '"%(input_name)s".')
120
121
122 class InvalidPropertyValueError(TOSCAException):
123     msg_fmt = _('Value of property "%(what)s" is invalid.')
124
125
126 class InvalidTemplateVersion(TOSCAException):
127     msg_fmt = _('The template version "%(what)s" is invalid. '
128                 'Valid versions are "%(valid_versions)s".')
129
130
131 class InvalidTOSCAVersionPropertyException(TOSCAException):
132     msg_fmt = _('Value of TOSCA version property "%(what)s" is invalid.')
133
134
135 class URLException(TOSCAException):
136     msg_fmt = _('%(what)s')
137
138
139 class ToscaExtImportError(TOSCAException):
140     msg_fmt = _('Unable to import extension "%(ext_name)s". '
141                 'Check to see that it exists and has no '
142                 'language definition errors.')
143
144
145 class ToscaExtAttributeError(TOSCAException):
146     msg_fmt = _('Missing attribute in extension "%(ext_name)s". '
147                 'Check to see that it has required attributes '
148                 '"%(attrs)s" defined.')
149
150
151 class InvalidGroupTargetException(TOSCAException):
152     msg_fmt = _('"%(message)s"')
153
154
155 class ExceptionCollector(object):
156
157     exceptions = []
158     collecting = False
159
160     @staticmethod
161     def clear():
162         del ExceptionCollector.exceptions[:]
163
164     @staticmethod
165     def start():
166         ExceptionCollector.clear()
167         ExceptionCollector.collecting = True
168
169     @staticmethod
170     def stop():
171         ExceptionCollector.collecting = False
172
173     @staticmethod
174     def contains(exception):
175         for ex in ExceptionCollector.exceptions:
176             if str(ex) == str(exception):
177                 return True
178         return False
179
180     @staticmethod
181     def appendException(exception):
182         if ExceptionCollector.collecting:
183             if not ExceptionCollector.contains(exception):
184                 exception.trace = traceback.extract_stack()[:-1]
185                 ExceptionCollector.exceptions.append(exception)
186         else:
187             raise exception
188
189     @staticmethod
190     def exceptionsCaught():
191         return len(ExceptionCollector.exceptions) > 0
192
193     @staticmethod
194     def getTraceString(traceList):
195         traceString = ''
196         for entry in traceList:
197             f, l, m, c = entry[0], entry[1], entry[2], entry[3]
198             traceString += (_('\t\tFile %(file)s, line %(line)s, in '
199                               '%(method)s\n\t\t\t%(call)s\n')
200                             % {'file': f, 'line': l, 'method': m, 'call': c})
201         return traceString
202
203     @staticmethod
204     def getExceptionReportEntry(exception, full=True):
205         entry = exception.__class__.__name__ + ': ' + str(exception)
206         if full:
207             entry += '\n' + ExceptionCollector.getTraceString(exception.trace)
208         return entry
209
210     @staticmethod
211     def getExceptions():
212         return ExceptionCollector.exceptions
213
214     @staticmethod
215     def getExceptionsReport(full=True):
216         report = []
217         for exception in ExceptionCollector.exceptions:
218             report.append(
219                 ExceptionCollector.getExceptionReportEntry(exception, full))
220         return report
221
222     @staticmethod
223     def assertExceptionMessage(exception, message):
224         err_msg = exception.__name__ + ': ' + message
225         report = ExceptionCollector.getExceptionsReport(False)
226         assert err_msg in report, (_('Could not find "%(msg)s" in "%(rep)s".')
227                                    % {'rep': report.__str__(), 'msg': err_msg})