|
| 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 | +import jsonschema |
| 14 | + |
| 15 | +from zun.common import exception |
| 16 | +from zun.common.i18n import _ |
| 17 | + |
| 18 | + |
| 19 | +class SchemaValidator(object): |
| 20 | + """Resource reference validator class.""" |
| 21 | + |
| 22 | + validator_org = jsonschema.Draft4Validator |
| 23 | + |
| 24 | + def __init__(self, schema): |
| 25 | + validators = { |
| 26 | + 'minimum': self._validate_minimum, |
| 27 | + 'maximum': self._validate_maximum |
| 28 | + } |
| 29 | + validator_cls = jsonschema.validators.extend(self.validator_org, |
| 30 | + validators) |
| 31 | + fc = jsonschema.FormatChecker() |
| 32 | + self.validator = validator_cls(schema, format_checker=fc) |
| 33 | + |
| 34 | + def validate(self, *args, **kwargs): |
| 35 | + try: |
| 36 | + self.validator.validate(*args, **kwargs) |
| 37 | + except jsonschema.ValidationError as ex: |
| 38 | + if len(ex.path) > 0: |
| 39 | + detail = _("Invalid input for field '%(path)s'. Value: " |
| 40 | + "'%(value)s'. %(message)s") % { |
| 41 | + 'path': ex.path.pop(), |
| 42 | + 'value': ex.instance, |
| 43 | + 'message': ex.message} |
| 44 | + else: |
| 45 | + detail = ex.message |
| 46 | + raise exception.SchemaValidationError(detail=detail) |
| 47 | + |
| 48 | + def _number_from_str(self, instance): |
| 49 | + try: |
| 50 | + value = int(instance) |
| 51 | + except (ValueError, TypeError): |
| 52 | + try: |
| 53 | + value = float(instance) |
| 54 | + except (ValueError, TypeError): |
| 55 | + return None |
| 56 | + return value |
| 57 | + |
| 58 | + def _validate_minimum(self, validator, minimum, instance, schema): |
| 59 | + instance = self._number_from_str(instance) |
| 60 | + if instance is None: |
| 61 | + return |
| 62 | + return self.validator_org.VALIDATORS['minimum'](validator, minimum, |
| 63 | + instance, schema) |
| 64 | + |
| 65 | + def _validate_maximum(self, validator, maximum, instance, schema): |
| 66 | + instance = self._number_from_str(instance) |
| 67 | + if instance is None: |
| 68 | + return |
| 69 | + return self.validator_org.VALIDATORS['maximum'](validator, maximum, |
| 70 | + instance, schema) |
0 commit comments