Your IP : 216.73.216.196


Current Path : /opt/alt/python35/lib/python3.5/site-packages/cerberus/__pycache__/
Upload File :
Current File : //opt/alt/python35/lib/python3.5/site-packages/cerberus/__pycache__/validator.cpython-35.pyc



L�X���@swdZddlmZddlmZddlmZmZmZm	Z	ddl
m
Z
ddlmZmZddl
Z
ddlmZdd	lmZdd
lmZmZddlmZmZmZmZddlmZmZej�Zd
d�ZGdd�de �Z!Gdd�de �Z"Gdd�de#�Z$dZ%Gdd�de&�Z'e'de$fi�Z$dS)a

    Extensible validation for Python dictionaries.
    This module implements Cerberus Validator class

    :copyright: 2012-2016 by Nicola Iarocci.
    :license: ISC, see LICENSE for more details.

    Full documentation is available at http://python-cerberus.org
�)�absolute_import)�literal_eval)�Hashable�Iterable�Mapping�Sequence)�copy)�date�datetimeN)�warn)�errors)�
_int_types�	_str_type)�schema_registry�rules_set_registry�DefinitionSchema�SchemaError)�drop_item_from_tuple�isclasscCsdd�}|}||_|S)NcSstd��dS)NzcDummy method called. Its purpose is to hold justvalidation constraints for a rule in its docstring.)�RuntimeError)�self�
constraint�field�value�r�C/opt/alt/python35/lib/python3.5/site-packages/cerberus/validator.py�dummysz(dummy_for_rule_validation.<locals>.dummy)�__doc__)�rule_constraintsr�frrr�dummy_for_rule_validations	r c@seZdZdZdS)�
DocumentErrorzD Raised when the target document is missing or has the wrong format N)�__name__�
__module__�__qualname__rrrrrr!(sr!c@seZdZdZdS)�_SchemaRuleTypeErrorzs Raised when a schema (list) validation encounters a mapping.
        Not supposed to be used outside this module. N)r"r#r$rrrrrr%-sr%c@s8eZdZdZd�Zd�Ze�Zdd�Zdd�Z	d	d
�Z
edd��Zd
d�Z
dddd�Zdd�Zdd�Zdd�Zdd�Zdd�Zedd��Zejdd��Zedd ��Zed!d"��Zejd#d"��Zed$d%��Zed&d'��Zejd(d'��Zed)d*��Zejd+d*��Zed,d-��Zed.d/��Zed0d1��Zejd2d1��Zed3d4��Zed5d6��Z e jd7d6��Z ed8d9��Z!e!jd:d9��Z!dd;d<�Z"dd=d>d?�Z#d@dA�Z$dBdC�Z%dDdE�Z&dFdG�Z'dHdI�Z(dJdK�Z)dLdM�Z*dNdO�Z+e,dPdQ��Z-dRdS�Z.dTdU�Z/dVdW�Z0dXdY�Z1dZd[�Z2d\d]�Z3d^d_�Z4dd=d`dadb�Z5e5Z6dcdd�Z7dedf�Z8dgdh�Z9e:di�Z;djdk�Z<dldm�Z=dndo�Z>dpdq�Z?drds�Z@dtdu�ZAdvdw�ZBdxdy�ZCdzd{�ZDd|d}�ZEd~d�ZFd�d��ZGd�d��ZHd�d��ZId�d��ZJd�d��ZKd�d��ZLd�d��ZMd�d��ZNd�d��ZOd�d��ZPe:d��ZQd�d��ZRd�d��ZSd�d��ZTd�d��ZUd�d��ZVd�d��ZWd�d��ZXd�d��ZYd�d��ZZd�d��Z[d�d��Z\d�d��Z]d�d��Z^d�d��Z_d�d��Z`d�d��Zad�d��Zbd�d��ZcdS)��	Validatora6 Validator class. Normalizes and/or validates any mapping against a
    validation-schema which is provided as an argument at class instantiation
    or upon calling the :meth:`~cerberus.Validator.validate`,
    :meth:`~cerberus.Validator.validated` or
    :meth:`~cerberus.Validator.normalized` method. An instance itself is
    callable and executes a validation.

    All instantiation parameters are optional.

    There are the introspective properties :attr:`types`, :attr:`validators`,
    :attr:`coercers`, :attr:`default_setters`, :attr:`rules`,
    :attr:`normalization_rules` and :attr:`validation_rules`.

    The attributes reflecting the available rules are assembled considering
    constraints that are defined in the docstrings of rules' methods and is
    effectively used as validation schema for :attr:`schema`.

    :param schema: See :attr:`~cerberus.Validator.schema`.
                   Defaults to :obj:`None`.
    :type schema: any :term:`mapping`
    :param ignore_none_values: See :attr:`~cerberus.Validator.ignore_none_values`.
                               Defaults to ``False``.
    :type ignore_none_values: :class:`bool`
    :param allow_unknown: See :attr:`~cerberus.Validator.allow_unknown`.
                          Defaults to ``False``.
    :type allow_unknown: :class:`bool` or any :term:`mapping`
    :param purge_unknown: See :attr:`~cerberus.Validator.purge_unknown`.
                          Defaults to to ``False``.
    :type purge_unknown: :class:`bool`
    :param error_handler: The error handler that formats the result of
                          :attr:`~cerberus.Validator.errors`.
                          When given as two-value tuple with an error-handler
                          class and a dictionary, the latter is passed to the
                          initialization of the error handler.
                          Default: :class:`~cerberus.errors.BasicErrorHandler`.
    :type error_handler: class or instance based on
                         :class:`~cerberus.errors.BaseErrorHandler` or
                         :class:`tuple`
    �nullable�readonly�typecOs�d|_tj�|_d|_tj�|_tj�|_f|_	f|_
d|_|j|�|_
|j||�|jdd�|_|jdd�|_dS)z� The arguments will be treated as with this signature:

        __init__(self, schema=None, ignore_none_values=False,
                 allow_unknown=False, purge_unknown=False,
                 error_handler=errors.BasicErrorHandler)
        NF�schema�
allow_unknown)�documentr�	ErrorList�_errors�recent_error�DocumentErrorTree�document_error_tree�SchemaErrorTree�schema_error_tree�
document_path�schema_path�update�_Validator__init_error_handler�
error_handler�_Validator__store_config�getr*r+)r�args�kwargsrrr�__init__hs					zValidator.__init__cCs�|jdtj�}t|t�r3|\}}ni}t|�rat|tj�ra||�St|tj�rw|Std��dS)Nr8zInvalid error_handler.)	�popr�BasicErrorHandler�
isinstance�tupler�
issubclass�BaseErrorHandlerr)rr<r8�	eh_configrrr�__init_error_handler�s
zValidator.__init_error_handlercCsmd}xWt|dt|���D]9\}}||krNtd|��q#||||<q#W||_dS)z0 Assign args to kwargs and store configuration. r*�ignore_none_valuesr+�
purge_unknownNz.__init__ got multiple values for argument '%s')r*rFr+rG)�	enumerate�len�	TypeError�_config)rr;r<�	signature�i�prrr�__store_config�s)
	zValidator.__store_configcCs|jj�dS)z) Purge the cache of known valid schemas. N)�_valid_schemas�clear)�clsrrr�clear_caches�szValidator.clear_cachescGs�t|�dkry|jj|d�|jj�x�|dD]4}|j|7_|j|7_|jj|�q>Wnlt|�dkr�t|dt	�r�|j
|dtj|d�n&t|�dkr�|d}|dj
}|dj}|dd�}|j|f}|j}|tjj
krL|dk	rL|||f7}|s[d}	nA|j|j|�}
|dkr�|
j|d�}	n
|
|}	|jj|�}tj|||||	||�|_|j
|jg�dS)a� Creates and adds one or multiple errors.

        :param args: Accepts different argument's signatures.

                     *1. Bulk addition of errors:*

                     - :term:`iterable` of
                       :class:`~cerberus.errors.ValidationError`-instances

                     The errors will be added to
                     :attr:`~cerberus.Validator._errors`.

                     *2. Custom error:*

                     - the invalid field's name

                     - the error message

                     A custom error containing the message will be created and
                     added to :attr:`~cerberus.Validator._errors`.
                     There will however be fewer information contained in the
                     error (no reference to the violated rule and its
                     constraint).

                     *3. Defined error:*

                     - the invalid field's name

                     - the error-reference, see :mod:`cerberus.errors`

                     - arbitrary, supplemental information about the error

                     A :class:`~cerberus.errors.ValidationError` instance will
                     be created and added to
                     :attr:`~cerberus.Validator._errors`.
        �r�Nr'F)rIr.�extend�sortr1r3r8�emitr@r�_errorr�CUSTOM�code�ruler4r5�
UNKNOWN_FIELD�_resolve_rules_setr*r:r,�ValidationErrorr/)rr;�errorrr[r\�infor4r5r�field_definitionsrrrrrY�s8%
%!


		
zValidator._errorNcKs�|jj�}|j|�|js`d|d<t|d<|j|d<|j|d<|j|d<|j|�}|dkr�|j	|_	n(t
|t�s�|f}|j	||_	|dkr�|j|_n(t
|t�s�|f}|j||_|S)a@ Creates a new instance of Validator-(sub-)class. All initial
            parameters of the parent are passed to the initialization, unless
            a parameter is given as an explicit *keyword*-parameter.

        :param document_crumb: Extends the
                               :attr:`~cerberus.Validator.document_path`
                               of the child-validator.
        :type document_crumb: :class:`tuple` or :term:`hashable`
        :param schema_crumb: Extends the
                             :attr:`~cerberus.Validator.schema_path`
                             of the child-validator.
        :type schema_crumb: :class:`tuple` or hashable
        :param kwargs: Overriding keyword-arguments for initialization.
        :type kwargs: :class:`dict`

        :return: an instance of ``self.__class__``
        T�is_childr8�root_allow_unknown�
root_document�root_schemaN)
rKrr6rc�toy_error_handlerr+r,r*�	__class__r4r@rAr5)r�document_crumb�schema_crumbr<�child_config�child_validatorrrr�_get_child_validator�s(
	




		zValidator._get_child_validatorcCs.dj||jdd��}t||d�S)Nz_{0}_{1}� �_)�format�replace�getattr)r�domainr\�
methodnamerrr�__get_rule_handler,szValidator.__get_rule_handlercCs�t|j�}t|j�}x�|D]�}x3t|dd�D]}t|j||�|_q>Wx3t|dd�D]}t|j||�|_qtW|jr%|j|j||�q%WdS)a Removes nodes by index from an errorpath, relatively to the
            basepaths of self.

        :param errors: A list of :class:`errors.ValidationError` instances.
        :param dp_items: A list of integers, pointing at the nodes to drop from
                         the :attr:`document_path`.
        :param sp_items: Alike ``dp_items``, but for :attr:`schema_path`.
        �reverseTN)rIr4r5�sortedr�child_errors�_drop_nodes_from_errorpaths)rr.�dp_items�sp_items�dp_basedepth�sp_basedepthr`rMrrrry0s	
	z%Validator._drop_nodes_from_errorpathscCs�|jd�rC|dd�}|jd�r7|jn|j}n	|j}|jd�}x-|D]%}|j|�}|dkrbdSqbW|d|fS)a� Searches for a field as defined by path. This method is used by the
            ``dependency`` evaluation logic.

        :param path: Path elements are separated by a ``.``. A leading ``^``
                     indicates that the path relates to the document root,
                     otherwise it relates to the currently evaluated document,
                     which is possibly a subdocument.
                     The sequence ``^^`` at the start will be interpreted as a
                     literal ``^``.
        :type path: :class:`str`
        :returns: Either the found field name and its value or :obj:`None` for
                  both.
        :rtype: A two-value :class:`tuple`.
        �^rTN�.)NN���)�
startswithr,re�splitr:)r�path�context�parts�partrrr�
_lookup_fieldFs	
zValidator._lookup_fieldcCs6t|t�r|St|t�r2|jj|�SdS)N)r@rrrr:)r�	rules_setrrrr^ds
zValidator._resolve_rules_setcCs6t|t�r|St|t�r2|jj|�SdS)N)r@rrrr:)rr*rrr�_resolve_schemaks
zValidator._resolve_schemacCs|jjdd�S)a: If ``True`` unknown fields that are not defined in the schema will
            be ignored. If a mapping with a validation schema is given, any
            undefined field will be validated against its rules.
            Also see :ref:`allowing-the-unknown`.
            Type: :class:`bool` or any :term:`mapping` r+F)rKr:)rrrrr+tszValidator.allow_unknowncCsB|jpt|ttf�s1t|d|i�||jd<dS)Nr+)rcr@�boolrrK)rrrrrr+}scCs|j|j�S)z� The errors of the last processing formatted by the handler that is
            bound to :attr:`~cerberus.Validator.error_handler`. )r8r.)rrrrr�szValidator.errorscCs|jjdd�S)za Whether to not process :obj:`None`-values in a document or not.
            Type: :class:`bool` rFF)rKr:)rrrrrF�szValidator.ignore_none_valuescCs||jd<dS)NrF)rK)rrrrrrF�scCs|jjdd�S)z� ``True`` for child-validators obtained with
        :meth:`~cerberus.Validator._get_child_validator`.
        Type: :class:`bool` rcF)rKr:)rrrrrc�szValidator.is_childcCs|jjdd�S)z1 ``True`` if the document is already normalized. �
is_normalizedF)rKr:)rrrrr��szValidator.is_normalizedcCs||jd<dS)Nr�)rK)rrrrrr��scCs|jjdd�S)z� If ``True`` unknown fields will be deleted from the document
            unless a validation is called with disabled normalization.
            Also see :ref:`purging-unknown-fields`. Type: :class:`bool` rGF)rKr:)rrrrrG�szValidator.purge_unknowncCs||jd<dS)NrG)rK)rrrrrrG�scCs|jjd|j�S)zw The :attr:`~cerberus.Validator.allow_unknown` attribute of the
            first level ancestor of a child validator. rd)rKr:r+)rrrrrd�szValidator.root_allow_unknowncCs|jjd|j�S)zr The :attr:`~cerberus.Validator.document` attribute of the
            first level ancestor of a child validator. re)rKr:r,)rrrrre�szValidator.root_documentcCs|jjdt�S)z^ The registry that holds referenced rules sets.
            Type: :class:`~cerberus.Registry` r)rKr:r)rrrrr�szValidator.rules_set_registrycCs||jd<dS)Nr)rK)r�registryrrrr�scCs|jjd|j�S)zp The :attr:`~cerberus.Validator.schema` attribute of the
            first level ancestor of a child validator. rf)rKr:r*)rrrrrf�szValidator.root_schemacCs|jS)z� The validation schema of a validator. When a schema is passed to
            a method, it replaces this attribute.
            Type: any :term:`mapping` or :obj:`None` )�_schema)rrrrr*�szValidator.schemacCsR|dkrd|_n6|js0t|t�r<||_nt||�|_dS)N)r�rcr@r)rr*rrrr*�s
cCs|jjdt�S)zW The registry that holds referenced schemas.
        Type: :class:`~cerberus.Registry` r)rKr:r)rrrrr�szValidator.schema_registrycCs||jd<dS)Nr)rK)rr�rrrr�scCs�tj�|_d|_tj�|_tj�|_t|�|_	|dk	rft
||�|_n<|jdkr�t|j
t�r�i|_nttj��|dkr�ttj��t|t�s�ttjj|���|jj|�dS)N)rr-r.r/r0r1r2r3rr,rr*r@r+rr�r�SCHEMA_ERROR_MISSINGr!�DOCUMENT_MISSING�DOCUMENT_FORMATrpr8�start)rr,r*rrr�__init_processing�s"	zValidator.__init_processingFcCsU|j||�|j|j|j�|jj|�|jrJ|rJdS|jSdS)a Returns the document normalized according to the specified rules
        of a schema.

        :param document: The document to normalize.
        :type document: any :term:`mapping`
        :param schema: The validation schema. Defaults to :obj:`None`. If not
                       provided here, the schema must have been provided at
                       class instantiation.
        :type schema: any :term:`mapping`
        :param always_return_document: Return the document, even if an error
                                       occurred. Defaults to: ``False``.
        :type always_return_document: :class:`bool`
        :return: A normalized copy of the provided mapping or :obj:`None` if an
                 error occurred during normalization.
        N)�_Validator__init_processing�_Validator__normalize_mappingr,r*r8�endr.)rr,r*�always_return_documentrrr�
normalized�szValidator.normalizedcCs�t|t�r|j|�}|j�}x%|D]}|j||�||<q1W|j||�|jr{|j||�|j||�|j	||�|j
||�|j||�|S)N)r@rr�rr^�#_Validator__normalize_rename_fieldsrG�_normalize_purge_unknown�$_Validator__validate_readonly_fields�$_Validator__normalize_default_fields�_normalize_coerce� _Validator__normalize_containers)r�mappingr*rrrr�__normalize_mappings
	zValidator.__normalize_mappingcCs�tj}x�|D]�}||kr]d||kr]|j||d||||�||<qt|jt�rd|jkr|j|jd||||�||<qWdS)a {'oneof': [
                {'type': 'callable'},
                {'type': 'list',
                 'schema': {'oneof': [{'type': 'callable'},
                                      {'type': 'string'}]}},
                {'type': 'string'}
                ]} �coerceN)r�COERCION_FAILED�_Validator__normalize_coercer@r+r)rr�r*r`rrrrr�(s		
%zValidator._normalize_coercecCs�t|t�r$|jd|�}nht|t�r�|}xL|D]D}|j||||�}tj|jj|j	|f�kr@Pq@W|Sy||�SWnBt
k
r�}z"|j||t|��|SWYdd}~XnXdS)N�normalize_coerce)
r@r�_Validator__get_rule_handlerrr�rr�r1�fetch_errors_fromr4�	ExceptionrY�str)r�	processorrrr`�resultrN�errr�__normalize_coerce;s 
	zValidator.__normalize_coercecCs%x|D]}||krqt||t�r�d||krZ|j||||d�d||kr�|j||||d�t||�td�@ry|j|||�Wqtk
r�YqXqt||t�r�qqt||t�rd||kr|j	|||�qWdS)N�	keyschema�valueschemar+rGr*)r+rGr*)
r@r�+_Validator__normalize_mapping_per_keyschema�-_Validator__normalize_mapping_per_valueschema�set�(_Validator__normalize_mapping_per_schemar%rr�_Validator__normalize_sequence)rr�r*rrrr�__normalize_containersOs,


z Validator.__normalize_containersc	s[t�fdd�||D��}tdd�||D��}|jd|d|dfd|�}|j|dd	�}|jr�|j|jgd
dg�|j|j�x�|D]�}|||kr�q�||||kr.tdjd
dj|j	|f�d|��|||||||<q�|||||||<|||=q�WdS)Nc3s|]}|�fVqdS)Nr)�.0�k)�property_rulesrr�	<genexpr>isz>Validator.__normalize_mapping_per_keyschema.<locals>.<genexpr>css|]}||fVqdS)Nr)r�r�rrrr�jsrirjr�r*r�TrU�zHNormalizing keys of {path}: {key} already exists, its value is replaced.r�r�key)
�dictrmr�r.ryrYrrp�joinr4)	rrr�r�r*r,�	validatorr�r�r)r�r�!__normalize_mapping_per_keyschemahs&#			

z+Validator.__normalize_mapping_per_keyschemacs�t�fdd�||D��}|jd|d|dfd|�}|j||dd�||<|jr�|j|jgd	g�|j|j�dS)
Nc3s|]}|�fVqdS)Nr)r�r�)�value_rulesrrr��sz@Validator.__normalize_mapping_per_valueschema.<locals>.<genexpr>rirjr�r*r�TrU)r�rmr�r.ryrY)rrr�r�r*r�r)r�r�#__normalize_mapping_per_valueschemas#		
	z-Validator.__normalize_mapping_per_valueschemac
Cs�|jd|d|dfd||dd||jd|j�d||jd|j��}|j||dd�||<|jr�|j|j�dS)Nrirjr*r+rGr�T)rmr:r+rGr�r.rY)rrr�r*r�rrr�__normalize_mapping_per_schema�s	
	z(Validator.__normalize_mapping_per_schemacs�t��fdd�tt|���D���tdd�t|��D��}|jd�d�dfd��}|j|dd�}x |D]}|||�|<q�W|jr�|j|jgd	g�|j|j�dS)
Nc3s#|]}|��dfVqdS)r*Nr)r�r�)rr*rrr��sz1Validator.__normalize_sequence.<locals>.<genexpr>css!|]\}}||fVqdS)Nr)r�r��vrrrr��srirjr*r�TrU)	r��rangerIrHrmr�r.ryrY)rrr�r*r,r�r�rMr)rr*r�__normalize_sequence�s#		
	zValidator.__normalize_sequencecCs.x't|�D]}||kr
||=q
W|S)z {'type': 'boolean'} )rA)r�r*rrrrr��sz"Validator._normalize_purge_unknowncCs�x�t|�D]x}||krH|j|||�|j|||�q
t|jt�r
d|jkr
|j|||ji|�q
W|S)N�rename_handler)rA�_normalize_rename�_normalize_rename_handlerr@r+r)rr�r*rrrr�__normalize_rename_fields�sz#Validator.__normalize_rename_fieldscCs1d||kr-|||||d<||=dS)z {'type': 'hashable'} �renameNr)rr�r*rrrrr��szValidator._normalize_renamecCs\d||krdS|j||d||tj�}||krX||||<||=dS)a {'oneof': [
                {'type': 'callable'},
                {'type': 'list',
                 'schema': {'oneof': [{'type': 'callable'},
                                      {'type': 'string'}]}},
                {'type': 'string'}
                ]} r�N)r�r�RENAMING_FAILED)rr�r*r�new_namerrrr��sz#Validator._normalize_rename_handlercsMxF���fdd��D�D]%}�j�|d|�|�q WdS)Nc3s=|]3}|�kr�j�|�jd�r|VqdS)r(N)r^r:)r��x)r�r*rrrr��sz7Validator.__validate_readonly_fields.<locals>.<genexpr>r()�_validate_readonly)rr�r*rr)r�r*rr�__validate_readonly_fields�s&z$Validator.__validate_readonly_fieldsc	s���fdd��D�}y�fdd�|D�}Wntk
rSt�YnXx!|D]}|j��|�q[Wt�}�fdd�|D�}x�|r~|jd�}y|j��|�Wn_tk
r�|j|�YnAtk
r*}z!|j	|t
jt|��WYdd}~XnXt
|�}||krnx$|D]}|j	|t
jd�qJWPq�|j|�q�WdS)NcsIg|]?}|�ks?�|dkr�|jdd�r|�qS)Nr'F)r:)r�r�)r�r*rr�
<listcomp>�s	z8Validator.__normalize_default_fields.<locals>.<listcomp>cs&g|]}d�|kr|�qS)�defaultr)r�r�)r*rrr��s	cs&g|]}d�|kr|�qS)�default_setterr)r�r�)r*rrr��s	rz)Circular dependencies of default setters.)rJr%�_normalize_defaultr�r>�_normalize_default_setter�KeyError�appendr�rYr�SETTING_DEFAULT_FAILEDr�rA�add)	rr�r*�fields�fields_with_defaultr�known_fields_statesr��fields_stater)r�r*r�__normalize_default_fields�s0

		
/
z$Validator.__normalize_default_fieldscCs||d||<dS)z {'nullable': True} r�Nr)rr�r*rrrrr��szValidator._normalize_defaultcCsSd||krO||d}t|t�r?|jd|�}||�||<dS)zi {'oneof': [
                {'type': 'callable'},
                {'type': 'string'}
                ]} r��normalize_default_setterN)r@rr�)rr�r*r�setterrrrr��s		z#Validator._normalize_default_setterTcCs�||_t�|_|j||�|rJ|j|j|j�d|_xn|jD]c}|jry|j|dkryqT|jj	|�}|dk	r�|j
||�qT|j|�qTW|js�|j|j�|j
j|�t|j�S)aO Normalizes and validates a mapping against a validation-schema of
        defined rules.

        :param document: The document to normalize.
        :type document: any :term:`mapping`
        :param schema: The validation schema. Defaults to :obj:`None`. If not
                       provided here, the schema must have been provided at
                       class instantiation.
        :type schema: any :term:`mapping`
        :param update: If ``True``, required fields won't be checked.
        :type update: :class:`bool`
        :param normalize: If ``True``, normalize the document before validation.
        :type normalize: :class:`bool`

        :return: ``True`` if validation succeeds, otherwise ``False``. Check
                 the :func:`errors` property for a list of processing errors.
        :rtype: :class:`bool`
        TN)r6r��_unrequired_by_excludesr�r�r,r*r�rFr:� _Validator__validate_definitions�#_Validator__validate_unknown_fields�$_Validator__validate_required_fieldsr8r�r�r.)rr,r*r6�	normalizer�definitionsrrr�validates"			zValidator.validatecOsA|jdd�}|j||�|jr6|r6dS|jSdS)z� Wrapper around :meth:`~cerberus.Validator.validate` that returns
            the normalized and validated document or :obj:`None` if validation
            failed. r�FN)r>r�r.r,)rr;r<r�rrr�	validated0s
zValidator.validatedcCs�|jr�|j|}t|jttf�r�|jr=dnd}|jd|d||ji�}|||idd�s�|j|j�n|j|t	j
�dS)Nr+�__allow_unknown__rjr*r�F)r+r,r@rrrcrmrYr.rr])rrrrjr�rrr�__validate_unknown_fields;s	
	z#Validator.__validate_unknown_fieldscs�����fdd�}�j����j��t��fdd��jD��}x|D]}||�rcdSqcWt��}|t�j�O}|t|d�8}|t�j�8}x2|D]*}y||�Wq�tk
r�PYq�Xq�WdS)	z5 Validate a field's value against its defined rules. cs8�jd|�}|r4|�j|d����SdS)Nr�)r�r:)r\r�)r�rrrrr�
validate_ruleQsz7Validator.__validate_definitions.<locals>.validate_rulec3s0|]&}|�ks$|�jkr|VqdS)N)�mandatory_validations)r�r�)r�rrrr�Zsz3Validator.__validate_definitions.<locals>.<genexpr>Nr+�required)r+r�)r^r,rA�priority_validationsr�r��normalization_rulesr%)rr�rr��prior_rulesr\�rulesr)r�rrrr�__validate_definitionsNs 
%


z Validator.__validate_definitionsz� {'oneof': [{'type': 'boolean'},
                       {'type': ['dict', 'string'],
                        'validator': 'bulk_schema'}]} cCs�t|t�rZt|t�rZt|�t|�}|r||j|tjt|��n"||kr||j|tj|�dS)z {'type': 'list'} N)	r@rrr�rYr�UNALLOWED_VALUES�list�UNALLOWED_VALUE)r�allowed_valuesrr�	unallowedrrr�_validate_allowedpszValidator._validate_allowedcCs�t|t�r|g}t|t�r:|j||�nt|t�rY|j||�|jj|j|df�dk	r�dSdS)z- {'type': ['dict', 'hashable', 'hashables']} �dependenciesNT)	r@rr�*_Validator__validate_dependencies_sequencer�)_Validator__validate_dependencies_mappingr1�fetch_node_fromr5)rr�rrrrr�_validate_dependencieszs		z Validator._validate_dependenciesc	Cs�d}i}x�|j�D]u\}}t|t�sDt|t�rM|g}|j|�\}}||kr{|d7}q|j||i�qW|t|�kr�|j|tj	|�dS)NrrT)
�itemsr@rrr�r6rIrYr�DEPENDENCIES_FIELD_VALUE)	rr�r�validated_dependencies_counter�
error_info�dependency_name�dependency_values�wanted_field�wanted_field_valuerrr�__validate_dependencies_mapping�s	
z)Validator.__validate_dependencies_mappingcCsDx=|D]5}|j|�ddkr|j|tj|�qWdS)Nr)r�rYr�DEPENDENCIES_FIELD)rr�r�
dependencyrrr� __validate_dependencies_sequence�s
z*Validator.__validate_dependencies_sequencecCs?t|t�r;t|�dkr;|r;|j|tj�dS)z {'type': 'boolean'} rN)r@rrIrYr�EMPTY_NOT_ALLOWED)r�emptyrrrrr�_validate_empty�s(zValidator._validate_emptycs�t|t�r|g}d�j|krL�j|drL�jj|�xQ|D]I}|�jkrSd�j|krS�j|drS�jj|�qSW�fdd�|D�r�djdd�|D��}�j|tj|�dS)z% {'type': ['hashable', 'hashables']} r�cs%g|]}|�jkrd�qS)T)r,)r�r�)rrrr��s	z0Validator._validate_excludes.<locals>.<listcomp>z, css|]}dj|�VqdS)z'{0}'N)rp)r��wordrrrr��sz/Validator._validate_excludes.<locals>.<genexpr>N)	r@rr*r�r�r�rYr�EXCLUDES_FIELD)r�excludesrr�exclude�
exclusion_strr)rr�_validate_excludes�s	$

zValidator._validate_excludescCs�t|t�r4||kr�|j|tj|�n{t|t�r~t|�t|�@}|r�|j|tjt|��n1t|t	�r�||kr�|j|tj|�dS)z {'type': 'list'} N)
r@rrYr�FORBIDDEN_VALUErr��FORBIDDEN_VALUESr��int)r�forbidden_valuesrr�	forbiddenrrr�_validate_forbidden�szValidator._validate_forbiddencCs�t|�t|�kr@|j|tjt|�t|��n�tdd�t|�D��}|jd|d|dfd|�}|tdd�t|�D��d|jd	d
�s�|j|tj|j	�dS)z( {'type': 'list', 'validator': 'items'} css!|]\}}||fVqdS)Nr)r�rM�
definitionrrrr��sz,Validator._validate_items.<locals>.<genexpr>rirjr�r*css!|]\}}||fVqdS)Nr)r�rMrrrrr��sr6r�FN)
rIrYr�ITEMS_LENGTHr�rHrmr6�	BAD_ITEMSr.)rr�r�valuesr*r�rrr�_validate_items�s(	"zValidator._validate_itemscCs4d}tj�}xt|�D]\}}||j�i}	xJdD]B}
|
|	|krD|
|j|krD|j||
|	||
<qDWd|	|kr�|j|	|d<|jd|||fd|	dd�}||jd|jdd	�r�|d
7}q|j	|j
gdg�|j|j
�qW||fS)
z` Validates value against all definitions and logs errors according
            to the operator. rr+r)rjr*Tr6r�FrT�)r+r))rr-rHrr*r+rmr,r6ryr.rV)r�operatorr�rr�
valid_counterr.rMrr*r\r�rrr�__validate_logical�s"
#	
zValidator.__validate_logicalcCsP|jd|||�\}}|dkrL|j|tj||t|��dS)z& {'type': 'list', 'logical': 'anyof'} �anyofrTN)�_Validator__validate_logicalrYr�ANYOFrI)rr�rr�validsr.rrr�_validate_anyof�szValidator._validate_anyofcCsV|jd|||�\}}|t|�krR|j|tj||t|��dS)z& {'type': 'list', 'logical': 'allof'} �allofN)r rIrYr�ALLOF)rr�rrr"r.rrr�_validate_allof�szValidator._validate_allofcCsP|jd|||�\}}|dkrL|j|tj||t|��dS)z' {'type': 'list', 'logical': 'noneof'} �noneofrN)r rYr�NONEOFrI)rr�rrr"r.rrr�_validate_noneof�szValidator._validate_noneofcCsP|jd|||�\}}|dkrL|j|tj||t|��dS)z& {'type': 'list', 'logical': 'oneof'} �oneofrTN)r rYr�ONEOFrI)rr�rrr"r.rrr�_validate_oneofszValidator._validate_oneofcCs<y#||kr"|j|tj�Wntk
r7YnXdS)z {'nullable': False } N)rYr�	MAX_VALUErJ)r�	max_valuerrrrr�
_validate_maxs

zValidator._validate_maxcCs<y#||kr"|j|tj�Wntk
r7YnXdS)z {'nullable': False } N)rYr�	MIN_VALUErJ)r�	min_valuerrrrr�
_validate_mins

zValidator._validate_mincCsAt|t�r=t|�|kr=|j|tjt|��dS)z {'type': 'integer'} N)r@rrIrYr�
MAX_LENGTH)r�
max_lengthrrrrr�_validate_maxlengths!zValidator._validate_maxlengthcCsAt|t�r=t|�|kr=|j|tjt|��dS)z {'type': 'integer'} N)r@rrIrYr�
MIN_LENGTH)r�
min_lengthrrrrr�_validate_minlength!s!zValidator._validate_minlengthcCs1|dkr-|rdS|j|tj�dSdS)z {'type': 'boolean'} NT)rYr�NOT_NULLABLE)rr'rrrrr�_validate_nullable&s
zValidator._validate_nullablec
s�t|t�r�|jd|d|dfdt�fdd�|j�D���}|tdd�|j�D��dd	�s�|j|jgd
dg�|j|tj	|j�dS)
zq {'type': ['dict', 'string'], 'validator': 'bulk_schema',
            'forbidden': ['rename', 'rename_handler']} rirjr�r*c3s|]}|�fVqdS)Nr)r�r�)r*rrr�6sz0Validator._validate_keyschema.<locals>.<genexpr>css|]}||fVqdS)Nr)r�r�rrrr�7sr�FrUr�N)
r@rrmr��keysryr.rYr�	KEYSCHEMA)rr*rrr�r)r*r�_validate_keyschema/s	("	zValidator._validate_keyschemacCsb|r^|js&|j|tj�dStj|jj|j|f�k}|jr^|r^dSdS)z {'type': 'boolean'} TN)r�rYr�READONLY_FIELDr1r�r4)rr(rr�	has_errorrrrr�=s		zValidator._validate_readonlycCsat|t�sdS|jd�s,|d7}tj|�}|j|�s]|j|tj�dS)z {'type': 'string'} N�$)	r@r�endswith�re�compile�matchrYr�REGEX_MISMATCH)r�patternrr�re_objrrr�_validate_regexLs
zValidator._validate_regexz {'type': 'boolean'} c
s)y,t�fdd��jj�D��}Wn:tk
rh�jra�jddkrat�n�YnX|�j8}|t��fdd��D��}x!|D]}�j|t	j
�q�W�jr%t�fdd��D��}�jj|�r%x(�j|D]}�j|t	j
�qWdS)	zq Validates that required fields are not missing.

        :param document: The document being validated.
        c3s9|]/\}}�j|�jd�dkr|VqdS)r�TN)r^r:)r�rr)rrrr�^s	z7Validator.__validate_required_fields.<locals>.<genexpr>rTr*c3s4|]*}�j|�dk	s(�jr|VqdS)N)r:rF)r�r)r,rrrr�gsc3s*|] }�j|�dk	r|VqdS)N)r:)r�r)r,rrr�qsNr�)r�r*r��AttributeErrorrcr5r%r�rYr�REQUIRED_FIELD�
isdisjoint)rr,r��missingrr�r)r,rr�__validate_required_fieldsXs,
	
&
	z$Validator.__validate_required_fieldscCsk|dkrdSt|t�rEt|t�rE|j|||�n"t|t�rg|j|||�dS)z� {'type': ['dict', 'string'],
             'anyof': [{'validator': 'schema'},
                       {'validator': 'bulk_schema'}]} N)r@rr�$_Validator__validate_schema_sequencer�#_Validator__validate_schema_mapping)rr*rrrrr�_validate_schemawszValidator._validate_schemacCs�|j|�}|j|jd|j�}|jd|d|dfd|d|�}y/||d|jdd�s�|j|j�Wn(tk
r�|j|t	j
��YnXdS)Nr+rirjr*r6r�F)r�r*r:r+rmr6rYr.r%r�BAD_TYPE_FOR_SCHEMA)rrr*rr+r�rrr�__validate_schema_mapping�s	
z#Validator.__validate_schema_mappingc	s�t�fdd�tt|��D���|jd|d|dfd�d|j�}|tdd�t|�D��d|jd	d
�|jr�|j|jgdg�|j	|t
j|j�dS)Nc3s|]}|�fVqdS)Nr)r�rM)r*rrr��sz7Validator.__validate_schema_sequence.<locals>.<genexpr>rirjr*r+css!|]\}}||fVqdS)Nr)r�rMr�rrrr��sr6r�FrU)r�r�rIrmr+rHr6r.ryrYr�SEQUENCE_SCHEMA)rrr*rr�r)r*r�__validate_schema_sequence�s+	"	z$Validator.__validate_schema_sequencecs_t|t�r|gn|}t��fdd�|D��rDdS�j|tj�dSdS)z {'type': ['string', 'list']} c3s'|]}�jd|���VqdS)�
validate_typeN)r�)r�r�)rrrrr��sz+Validator._validate_type.<locals>.<genexpr>NT)r@r�anyrYr�BAD_TYPE)r�	data_typerr�typesr)rrr�_validate_type�s
zValidator._validate_typecCst|t�rdSdS)NT)r@r�)rrrrr�_validate_type_boolean�sz Validator._validate_type_booleancCst|t�rdSdS)NT)r@r	)rrrrr�_validate_type_date�szValidator._validate_type_datecCst|t�rdSdS)NT)r@r
)rrrrr�_validate_type_datetime�sz!Validator._validate_type_datetimecCst|t�rdSdS)NT)r@r)rrrrr�_validate_type_dict�szValidator._validate_type_dictcCst|ttf�rdSdS)NT)r@�floatr
)rrrrr�_validate_type_float�szValidator._validate_type_floatcCst|t�rdSdS)NT)r@r
)rrrrr�_validate_type_integer�sz Validator._validate_type_integercCst|ttf�rdSdS)NT)r@�bytes�	bytearray)rrrrr�_validate_type_binary�szValidator._validate_type_binarycCs't|t�r#t|t�r#dSdS)NT)r@rr)rrrrr�_validate_type_list�s
zValidator._validate_type_listcCs-t|ttf�r)t|t�r)dSdS)NT)r@r
r_r�)rrrrr�_validate_type_number�szValidator._validate_type_numbercCst|t�rdSdS)NT)r@r�)rrrrr�_validate_type_set�szValidator._validate_type_setcCst|t�rdSdS)NT)r@r)rrrrr�_validate_type_string�szValidator._validate_type_stringcCs~t|t�r1|jd|�}|||�nIt|t�rgx7|D]}|j|||�qGWn||||j�dS)a {'oneof': [
                {'type': 'callable'},
                {'type': 'list',
                 'schema': {'oneof': [{'type': 'callable'},
                                      {'type': 'string'}]}},
                {'type': 'string'}
                ]} r�N)r@rr�r�_validate_validatorrY)rr�rrr�rrrri�s
zValidator._validate_validatorc
s�|df}t|t�r�|jd|d|dt�fdd�|D���}||d|jdd	�|jr�|j|jgd
g�|j|tj	|j�dS)zq {'type': ['dict', 'string'], 'validator': 'bulk_schema',
            'forbidden': ['rename', 'rename_handler']} r�rirjr*c3s|]}|�fVqdS)Nr)r�r�)r*rrr��sz2Validator._validate_valueschema.<locals>.<genexpr>r6r�FrUN)
r@rrmr�r6r.ryrYr�VALUESCHEMA)rr*rrrjr�r)r*r�_validate_valueschema�s	"	zValidator._validate_valueschema)r')r'r(r))dr"r#r$rr�r�r�rPr=r7r9�classmethodrSrYrmr�ryr�r^r��propertyr+r�rrFrcr�rGrdrerrfr*rr�r�r�r�r�r�r�r�r�r��staticmethodr�r�r�r�r�r�r�r�r��__call__r�r�r�r �_validate_allow_unknownr�r�r�r�r	rrrr r#r&r)r,r/r2r5r8r:r=r�rH�_validate_requiredr�rPrOrNrZr[r\r]r^r`rardrerfrgrhrirkrrrrr&3s�'	*J.			+	


	

r&z7The rule's arguments are validated against this schema:csFeZdZdZ�fdd�Z�fdd�Zdd�Z�S)�InspectedValidatorz Metaclass for all validators csKd|dkr2|djd|ddji�tt|�j||�S)NrrUrTr)r6r�superrr�__new__)rRr;)rhrrrt�s"zInspectedValidator.__new__cs��fdd�}tt��j|�fi�_�_xb|d�D]T}|jd�r��j|td�d�f7_qH�jd|��j|<qHW�j�jdd<tdd	�|d
�D���_	�jd
d}�j	|dd
ddd<|dd<x/dd	��j
D�D]}d�j|d<q'Wffi�_�_�_
x�|d�D]�}|jd�r��j|td�d�f7_ql|jd�r��j|td�d�f7_ql�jd|��j
|<qlWxHdD]@}�j
|d}�j|dd
ddd<|dd<q�W�j�j
dddd<i�_�jj�j��jj�j
�dS)Ncs#t�fdd�t��D��S)Nc3s8|].}|jd��r|jdd�dVqdS)rorUrTNr�)r�r�)r�r�)�prefixrrr�szNInspectedValidator.__init__.<locals>.attributes_with_prefix.<locals>.<genexpr>)rA�dir)ru)rR)rur�attributes_with_prefixsz;InspectedValidator.__init__.<locals>.attributes_with_prefixr��type_�
_validate_r)�allowedcss|]}|VqdS)Nr)r�r�rrrr�sz.InspectedValidator.__init__.<locals>.<genexpr>r�r*rTr*rUcss!|]}|dkr|VqdS)r'Nr)r�r�rrrr�sTr�r��coerce_�default_setter_�_normalize_r�r�r�)r�r�)rsrrr=rY�validation_rulesr�rI�$_InspectedValidator__get_rule_schemarA�
validatorsr��coercers�default_settersr�r�r6)rRr;rw�	attributer�r\)rh)rRrr=s6%")%%
-	zInspectedValidator.__init__c
Cs�t||�j}|dkr'i}nPt|krF|jt�d}yt|j��}Wntk
rvi}YnX|s�td|jdd�d�|S)NrTz>No validation schema is defined for the arguments of rule '%s'rorUr�)rrr�RULE_SCHEMA_SEPARATORr�r�stripr�r)rR�method_name�	docstringr�rrr�__get_rule_schema,s	
z$InspectedValidator.__get_rule_schema)r"r#r$rrtr=rrr)rhrrr�s,rr)(r�
__future__r�astr�collectionsrrrrrr
r	rB�warningsr�cerberusr�cerberus.platformr
r�cerberus.schemarrrr�cerberus.utilsrr�ToyErrorHandlerrgr r�r!r%�objectr&r�r)rrrrrr�<module>	s.""
�����F