Esempio n. 1
0
    def process(self, data: dict):
        unmarshall = self.schema.load(data)
        if unmarshall.errors:
            raise OutputValidationException(
                'Error when validate ouput: {}'.format(str(
                    unmarshall.errors), ))

        return unmarshall.data
Esempio n. 2
0
 def validate(self, data: typing.Any) -> None:
     clean_data = self.clean_data(data)
     errors = self.schema.load(clean_data).errors
     if errors:
         raise OutputValidationException(
             'Error when validate input: {}'.format(
                 str(errors),
             )
         )
Esempio n. 3
0
 def _validate_output_file(self, data: typing.Any) -> None:
     """
     Raise OutputValidationException if given object cannot be accepted as file
     :param data: object to be check as acceptable file
     """
     validation_error_message = self._get_ouput_file_validation_error_message(
         data)
     if validation_error_message:
         raise OutputValidationException(
             "Error when validate output file : {}".format(
                 validation_error_message))
Esempio n. 4
0
    def process(self, data: dict):
        clean_data = self.clean_data(data)
        unmarshall = self.schema.load(clean_data)
        additional_errors = self._get_files_errors(unmarshall.data)

        if unmarshall.errors:
            raise OutputValidationException(
                'Error when validate ouput: {}'.format(
                    str(unmarshall.errors),
                )
            )

        if additional_errors:
            raise OutputValidationException(
                'Error when validate ouput: {}'.format(
                    str(additional_errors),
                )
            )

        return unmarshall.data
Esempio n. 5
0
    def load_files_input(self, input_data: typing.Any) -> typing.Any:
        """
        Validate input files and raise OutputValidationException if validation errors.
        :param input_data: input data containing files
        :return:
        """
        clean_data = self.clean_data(input_data)
        unmarshall = self.schema.load(clean_data)
        additional_errors = self._get_input_files_errors(unmarshall.data)

        if unmarshall.errors or additional_errors:
            raise OutputValidationException(
                "Error when validate ouput: {}".format(", ".join(
                    [str(unmarshall.errors),
                     str(additional_errors)])))

        return unmarshall.data
Esempio n. 6
0
    def dump_output(
            self,
            output_data: typing.Any) -> typing.Union[typing.Dict, typing.List]:
        """
        Dump output data and raise OutputValidationException if validation error
        :param output_data: output data to validate
        :return: given data
        """
        clean_data = self.clean_data(output_data)
        dump_data = self.schema.dump(clean_data).data

        # Validate
        errors = self.schema.load(dump_data).errors
        if errors:
            raise OutputValidationException(
                "Error when validate input: {}".format(str(errors)))

        return dump_data
Esempio n. 7
0
    def _get_dumped_error_from_validation_error(
            self, error: ProcessValidationError) -> typing.Any:
        """
        Build dumped error from given validation error.
        Raise OutputValidationException if error built from error_builder is
        not valid.
        :param error: ProcessValidationError instance
        :return: dumped error object
        """
        error_builder = self.default_error_builder
        error_content = error_builder.build_from_validation_error(error)
        processor = self._processor_class(error_builder.get_schema())

        try:
            return processor.dump(error_content)
        except ValidationException as exc:
            raise OutputValidationException(
                "Validation error of error response: {}".format(
                    str(exc))) from exc
Esempio n. 8
0
    def get_validation_error_response(
        self,
        error: ProcessValidationError,
        http_code: HTTPStatus = HTTPStatus.BAD_REQUEST,
    ) -> typing.Any:
        # TODO BS 20171010: Manage error schemas, see #4
        from hapic.hapic import _default_global_error_schema
        unmarshall = _default_global_error_schema.dump(error)
        if unmarshall.errors:
            raise OutputValidationException(
                'Validation error during dump of error response: {}'.format(
                    str(unmarshall.errors)))

        return bottle.HTTPResponse(
            body=json.dumps(unmarshall.data),
            headers=[
                ('Content-Type', 'application/json'),
            ],
            status=int(http_code),
        )
Esempio n. 9
0
    def _get_dumped_error_from_exception_error(
            self, exception: Exception) -> typing.Any:
        """
        Build dumped error from given exception.
        Raise OutputValidationException if error built from error_builder is
        not valid.
        :param exception: exception to use to build error
        :return: dumped error object
        """
        error_builder = self.default_error_builder
        error_body = error_builder.build_from_exception(
            exception, include_traceback=self.is_debug())
        processor = self._processor_class(error_builder.get_schema())

        try:
            return processor.dump(error_body)
        except ValidationException as exc:
            raise OutputValidationException(
                "Validation error of error response: {}".format(
                    str(exc))) from exc
Esempio n. 10
0
    def load_files_input(self, input_data: typing.Dict[str,
                                                       typing.Any]) -> object:
        """
        Validate input files and raise OutputValidationException
        if validation errors.
        :param input_data: input data containing files
        :return: original data
        """
        missing_names = []

        for field in dataclasses.fields(self.schema):
            # FIXME - G.M - 2019-03-27 - Does not work with pyramid Framework
            # because cgi.FieldStorage is not convertable to bool (not here
            # cause TypeError. We should adapt code to use same type of file
            # for all frameworks.
            # see #170: https://github.com/algoo/hapic/issues/170
            if not input_data.get(field.name, None):
                missing_names.append(field.name)

        if missing_names:
            raise OutputValidationException('"{}" files are missing'.format(
                '", "'.join(missing_names)))

        return self.schema(**input_data)
Esempio n. 11
0
    def _build_error_response(self, exc: Exception) -> typing.Any:
        response_content = self.error_builder.build_from_exception(
            exc, include_traceback=self.context.is_debug())
        processor = self._processor_factory(self.error_builder.get_schema())
        # Check error format
        try:
            dumped = processor.dump(response_content)
        except ValidationException as exc:
            raise OutputValidationException("Validation error during dump "
                                            "of error response: {}".format(
                                                str(exc))) from exc

        error_response = self.context.get_response(json.dumps(dumped),
                                                   self.error_http_code)
        self._logger = logging.getLogger(LOGGER_NAME)
        self._logger.info("Exception {exc} occured, return "
                          "{http_code} http_code : {msg}".format(
                              exc=type(exc).__name__,
                              http_code=self.error_http_code,
                              msg=str(exc)))
        # NOTE BS 2018-09-28: log on debug because it is an http framework error,
        # managed and dumped in response. Not an hapic error.
        self._logger.debug(traceback.format_exc())
        return error_response