<commit_before>"""
=====================
rororo.schemas.schema
=====================

Implement class for validating request and response data against JSON Schema.

"""

import logging
import types

from typing import Any, Callable, Optional, Type  # noqa: F401

try:
    from multidict import MultiDict, MultiDictProxy
except ImportError:  # pragma: no cover
    MultiDict, MultiDictProxy = None, None

from jsonschema.exceptions import ValidationError

from .exceptions import Error
from .utils import AnyMapping, defaults, validate_func_factory, ValidateFunc
from .validators import DefaultValidator


__all__ = ('Schema', )


logger = logging.getLogger(__name__)


class Schema(object):

    """Validate request and response data against JSON Schema."""

    __slots__ = (
        'error_class', 'module', 'response_factory', 'validate_func',
        'validation_error_class', 'validator_class', '_valid_request',
    )

    def __init__(self,
                 module: types.ModuleType,
                 *,
                 response_factory: Callable[..., Any]=None,
                 error_class: Type[Exception]=Error,
                 validator_class: Any=DefaultValidator,
                 validation_error_class: Type[Exception]=ValidationError,
                 validate_func: ValidateFunc=None) -> None:
        """Initialize Schema object.

        :param module: Module contains at least request and response schemas.
        :param response_factory: Put valid response data to this factory func.
        :param error_class:
            Wrap all errors in given class. If empty real errors would be
            reraised.
        :param validator_class:
            Validator class to use for validating request and response data.
            By default: ``rororo.schemas.validators.DefaultValidator``
        :param validation_error_class:
            Error class to be expected in case of validation error. By default:
            ``jsonschema.exceptions.ValidationError``
        :param validate_func:
            Validate function to be called for validating request and response
            data. Function will receive 2 args: ``schema`` and ``pure_data``.
            By default: ``None``
        """
        self._valid_request = None  # type: Optional[bool]

        self.module = module
        self.response_factory = response_factory
        self.error_class = error_class

        self.validator_class = validator_class
        self.validate_func = (
            validate_func or
            validate_func_factory(validator_class))
        self.validation_error_class = validation_error_class

    def make_error(self,
                   message: str,
                   *,
                   error: Exception=None,
                   # ``error_class: Type[Exception]=None`` doesn't work on
                   # Python 3.5.2, but that is exact version ran by Read the
                   # Docs :( More info: http://stackoverflow.com/q/42942867
                   error_class: Any=None) -> Exception:
        """Return error instantiated from given message.

        :param message: Message to wrap.
        :param error: Validation error.
        :param error_class:
            Special class to wrap error message into. When omitted
            ``self.error_class`` will be used.
        """
        return (error_class or self.error_class)(message)

    def make_response(self,
                      data: AnyMapping=None,<commit_msg>Fix wrong type hint in Schema constructor.<commit_after>"""
=====================
rororo.schemas.schema
=====================

Implement class for validating request and response data against JSON Schema.

"""

import logging
import types

from typing import Any, Callable, Optional, Type  # noqa: F401

try:
    from multidict import MultiDict, MultiDictProxy
except ImportError:  # pragma: no cover
    MultiDict, MultiDictProxy = None, None

from jsonschema.exceptions import ValidationError

from .exceptions import Error
from .utils import AnyMapping, defaults, validate_func_factory, ValidateFunc
from .validators import DefaultValidator


__all__ = ('Schema', )


logger = logging.getLogger(__name__)


class Schema(object):

    """Validate request and response data against JSON Schema."""

    __slots__ = (
        'error_class', 'module', 'response_factory', 'validate_func',
        'validation_error_class', 'validator_class', '_valid_request',
    )

    def __init__(self,
                 module: types.ModuleType,
                 *,
                 response_factory: Callable[..., Any]=None,
                 error_class: Any=None,
                 validator_class: Any=DefaultValidator,
                 validation_error_class: Type[Exception]=ValidationError,
                 validate_func: ValidateFunc=None) -> None:
        """Initialize Schema object.

        :param module: Module contains at least request and response schemas.
        :param response_factory: Put valid response data to this factory func.
        :param error_class:
            Wrap all errors in given class. If empty real errors would be
            reraised.
        :param validator_class:
            Validator class to use for validating request and response data.
            By default: ``rororo.schemas.validators.DefaultValidator``
        :param validation_error_class:
            Error class to be expected in case of validation error. By default:
            ``jsonschema.exceptions.ValidationError``
        :param validate_func:
            Validate function to be called for validating request and response
            data. Function will receive 2 args: ``schema`` and ``pure_data``.
            By default: ``None``
        """
        self._valid_request = None  # type: Optional[bool]

        self.module = module
        self.response_factory = response_factory
        self.error_class = error_class

        self.validator_class = validator_class
        self.validate_func = (
            validate_func or
            validate_func_factory(validator_class))
        self.validation_error_class = validation_error_class

    def make_error(self,
                   message: str,
                   *,
                   error: Exception=None,
                   # ``error_class: Type[Exception]=None`` doesn't work on
                   # Python 3.5.2, but that is exact version ran by Read the
                   # Docs :( More info: http://stackoverflow.com/q/42942867
                   error_class: Any=None) -> Exception:
        """Return error instantiated from given message.

        :param message: Message to wrap.
        :param error: Validation error.
        :param error_class:
            Special class to wrap error message into. When omitted
            ``self.error_class`` will be used.
        """
        if error_class is None:
            error_class = self.error_class if self.error_class else Error
        return error_class(message)

    def make_response(self,
                      data: AnyMapping=None,
{'fraction_non_alphanumeric': 0.08606440581362211, 'fraction_numerical': 0.004274722143060701, 'mean_word_length': 2.3583732057416267, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '482115', 'n_tokens_mistral': 1768, 'n_tokens_neox': 1697, 'n_words': 563}