B pSer#@sdZddlmZddlmZddlZddlZddlZddlm Z ddl m Z m Z m Z mZmZddlmZmZmZmZmZmZmZmZmZmZddlmZeGd d d eZiZe Z!d/d d Z"e#e$ee%dej&e'edZ(e j)e"e(dZ*ddZ+ddZ,Gddde%Z-ddZ.d ddde.fddZ/d0ddZ0e/e 1dej2ej3ej4e j5e j6ej7ej8e j9ej:e j;ejej?ej@e jAejBejCe jDe jEejFde jGdddd ZHe/e 1d!ej2ej3ej4ejIejJejKej8ej:e j;ejej?ej@ejMe jAej7ejNejOejBejCejPejQej%ejFd"e jRd!d#dd ZSe/e 1d$ej2ej3ej4ejIejJejTejUejKej8ejVejWej:ejXej.gen_type_check..type_check)rflatten)r!r"r)r!rgen_type_checkIs  z4_generate_legacy_type_checks..gen_type_check)dictr )typesr$ definitionstypenamer!rrr_generate_legacy_type_checks9s  r))arrayZbooleanintegernullnumberobjectstring) type_checkerscsfdd}|S)a Register the decorated validator for a ``version`` of the specification. Registered validators and their meta schemas will be considered when parsing ``$schema`` properties' URIs. Arguments: version (str): An identifier to use as the version's name Returns: collections.Callable: a class decorator to decorate the validator with the version cs$|t<||j}|r |t|<|S)N) validatorsID_OF META_SCHEMA meta_schemas)clsZmeta_schema_id)versionrr _validates}s  zvalidates.._validatesr)r6r7r)r6r validatesis r8cCs$|jdkrttdtdd|jS)NzcThe DEFAULT_TYPES attribute is deprecated. See the type checker attached to this validator instead.) stacklevel)_CREATED_WITH_DEFAULT_TYPESrrDeprecationWarning_DEFAULT_TYPES)rrrrr=s r=c@seZdZeeZdS)!_DefaultTypesDeprecatingMetaClassN)rrrpropertyr= DEFAULT_TYPESrrrrr>sr>cCs |dks|dkrdS|ddS)NTFz$id)get)schemarrr_id_ofsrDcsdk r<dk rtddtdtddtjtdn(tdkrRdtntkr`dndtt Gfd d d t }|dk rt ||}| d d d |_|S) a Create a new validator class. Arguments: meta_schema (collections.Mapping): the meta schema for the new validator class validators (collections.Mapping): a mapping from names to callables, where each callable will validate the schema property with the given name. Each callable should take 4 arguments: 1. a validator instance, 2. the value of the property being validated within the instance 3. the instance 4. the schema version (str): an identifier for the version that this validator class will validate. If provided, the returned validator class will have its ``__name__`` set to include the version, and also will have `jsonschema.validators.validates` automatically called for the given version. type_checker (jsonschema.TypeChecker): a type checker, used when applying the :validator:`type` validator. If unprovided, a `jsonschema.TypeChecker` will be created with a set of default types typical of JSON Schema drafts. default_types (collections.Mapping): .. deprecated:: 3.0.0 Please use the type_checker argument instead. If set, it provides mappings of JSON types to Python types that will be converted to functions and redefined in this object's `jsonschema.TypeChecker`. id_of (collections.Callable): A function that given a schema, returns its ID. Returns: a new `jsonschema.IValidator` class Nz;Do not specify default_types when providing a type checker.TzPThe default_types argument is deprecated. Use the type_checker argument instead.r9)r:)r0FcseZdZeZeZZeZe e Z eZ Z dfdd Z eddZdfdd Zdd d Zd d Zd dZdddZdS)zcreate..ValidatorrNcsP|r$tdtdd|jt||_|dkr:tj|d}||_||_||_ dS)NzaThe types argument is deprecated. Provide a type_checker to jsonschema.validators.extend instead.r9)r:)id_of) rr< TYPE_CHECKERZ redefine_manyr) RefResolver from_schemaresolverformat_checkerrC)rrCr&rIrJ)rErr__init__s z"create..Validator.__init__cSs*x$||j|D]}tj|qWdS)N)r3 iter_errorsr Z SchemaErrorZ create_from)r5rCerrorrrr check_schema#sz&create..Validator.check_schemac 3s|dkr|j}|dkrdS|dkrBtjd|fdd||dVdS|}|rZ|j|z|d}|dk rzd|fg}nt|}xr|D]j\}}|j|}|dkrq|||||pd} x8| D]0} | j||||d|dkr| j || VqWqWWd|r |j XdS)NTFzFalse schema does not allow %r) validatorZvalidator_valuer rCz$refr) rCr ZValidationErrorrI push_scoperBr VALIDATORSZ_set schema_path appendleft pop_scope) rr _schemascoperefr1kvrOerrorsrM)rErrrL(sH       z%create..Validator.iter_errorscssHxB|||D]2}|dk r&|j||dk r:|j||VqWdS)N)rLpathrSrR)rr rCr[rRrMrrrdescendWs   z!create..Validator.descendc_sx|j||D]}|qWdS)N)rL)rargskwargsrMrrrvalidate_sz"create..Validator.validatecSs:y|j||Stjk r4t|||jYnXdS)N)rFis_typer ZUndefinedTypeCheckZ UnknownTyperC)rr typerrrr`csz!create..Validator.is_typecSst|||d}|dkS)N)nextrL)rr rUrMrrris_validisz"create..Validator.is_valid)rNN)N)NN)N)rrrr%rQr3rF staticmethodr2r?r=r@r;rK classmethodrNrLr\r_r`rcr)_created_with_default_types default_typesrE meta_schema type_checkerr1rr Validators  / rj rA) TypeErrorrr<r TypeCheckerr)_DEPRECATED_DEFAULT_TYPES*_TYPE_CHECKER_FOR_DEPRECATED_DEFAULT_TYPESrr>r.r8titlereplacer)rhr1r6rgrirErjr)rfrgrErhrir1rcreates0@r rrcCsHt|j}|||dkr$|j}n|jr2tdt|j||||jdS)a Create a new validator class by extending an existing one. Arguments: validator (jsonschema.IValidator): an existing validator class validators (collections.Mapping): a mapping of new validator callables to extend with, whose structure is as in `create`. .. note:: Any validator callables with the same name as an existing one will (silently) replace the old validator callable entirely, effectively overriding any validation done in the "parent" validator class. If you wish to instead extend the behavior of a parent's validator callable, delegate and call it directly in the new validator function by retrieving it using ``OldValidator.VALIDATORS["validator_name"]``. version (str): a version for the new validator class type_checker (jsonschema.TypeChecker): a type checker, used when applying the :validator:`type` validator. If unprovided, the type checker of the extended `jsonschema.IValidator` will be carried along.` Returns: a new `jsonschema.IValidator` class extending the one provided .. note:: Meta Schemas The new validator class will have its parent's meta schema. If you wish to change or extend the meta schema in the new validator class, modify ``META_SCHEMA`` directly on the returned class. Note that no implicit copying is done, so a copy should likely be made before modifying it, in order to not affect the old validator. NzCannot extend a validator created with default_types with a type_checker. Update the validator to use a type_checker when created.)rhr1r6rirE) r%rQupdaterFr;rlrrr3r2)rOr1r6riZall_validatorsrrrextendts5  rtZdraft3)z$refadditionalItemsadditionalProperties dependenciesZdisallowZ divisibleByenumZextendsformatitemsmaxItems maxLengthmaximumminItems minLengthminimumpatternpatternProperties propertiesra uniqueItemscCs |ddS)NidrA)rB)rCrrrr)rhr1rir6rEZdraft4)z$refrurvallOfanyOfrwrxryrzr{r| maxPropertiesr}r~r minPropertiesr multipleOfnotoneOfrrrrequiredrarcCs |ddS)NrrA)rB)rCrrrrrZdraft6)z$refrurvrrconstcontainsrwrxexclusiveMaximumexclusiveMinimumryrzr{r|rr}r~rrrrrrrrr propertyNamesrrar)rhr1rir6Zdraft7) z$refrurvrrrrrwrxrrryifrzr{r|rr}r~rrrrrrrrrrrrarc@seZdZdZdddZeefddZd d Zd d Z e d dZ e ddZ e jddZe jddZddZddZddZddZdS)rGa Resolve JSON References. Arguments: base_uri (str): The URI of the referring document referrer: The actual referring document store (dict): A mapping from URIs to documents to cache cache_remote (bool): Whether remote refs should be cached after first resolution handlers (dict): A mapping from URI schemes to functions that should be used to retrieve them urljoin_cache (:func:`functools.lru_cache`): A cache that will be used for caching the results of joining the resolution scope to subscopes. remote_cache (:func:`functools.lru_cache`): A cache that will be used for caching the results of resolved remote URLs. Attributes: cache_remote (bool): Whether remote refs should be cached after first resolution rTNcCs|dkrtdt}|dkr*td|j}||_||_t||_|g|_t ddt t D|_ |j |||j |<||_||_dS)Nicss|]\}}||jfVqdS)N)r3).0rrOrrr sz'RefResolver.__init__..)r rresolve_from_urlreferrer cache_remoter%handlers _scopes_stackrURIDictr r4storers_urljoin_cache _remote_cache)rbase_urirrrrZ urljoin_cacheZ remote_cacherrrrK|s     zRefResolver.__init__cOs|||||d|S)z Construct a resolver from a JSON schema object. Arguments: schema: the referring schema Returns: `RefResolver` )rrr)r5rCrEr]r^rrrrHszRefResolver.from_schemacCs|j||j|dS)z Enter a given sub-scope. Treats further dereferences as being performed underneath the given scope. N)rappendrresolution_scope)rrVrrrrPszRefResolver.push_scopecCs2y|jWntk r,tdYnXdS)z Exit the most recent entered scope. Treats further dereferences as being performed underneath the original scope. Don't call this method more times than `push_scope` has been called. znFailed to pop the scope from an empty stack. `pop_scope()` should only be called once for every `push_scope()`N)rpop IndexErrorr RefResolutionError)rrrrrTs zRefResolver.pop_scopecCs |jdS)z8 Retrieve the current resolution scope. )r)rrrrrszRefResolver.resolution_scopecCst|j\}}|S)zL Retrieve the current base URI, not including any fragment. )rr)ruri_rrrrszRefResolver.base_uriccs$||z dVWd|XdS)zT Temporarily enter the given scope for the duration of the context. N)rPrT)rrVrrrin_scopes  zRefResolver.in_scopeccs2||\}}||z |VWd|XdS)z Resolve the given ``ref`` and enter its resolution scope. Exits the scope on exit of this context manager. Arguments: ref (str): The reference to resolve N)resolverPrT)rrWurlZresolvedrrr resolvings   zRefResolver.resolvingcCs||j|}|||fS)z. Resolve the given reference. )rrr)rrWrrrrrszRefResolver.resolvec Csxt|\}}y|j|}WnPtk rjy||}Wn,tk rd}zt|Wdd}~XYnXYnX|||S)z/ Resolve the given remote URL. N)rrKeyErrorresolve_remote Exceptionr rresolve_fragment)rrfragmentdocumentexcrrrrs "zRefResolver.resolve_from_urlc Cs|d}|rt|dng}x|D]x}|dddd}t|trjy t|}Wntk rhYnXy ||}Wq&tt fk rt d|Yq&Xq&W|S)z Resolve a ``fragment`` within the referenced ``document``. Arguments: document: The referent document fragment (str): a URI fragment to resolve within it /z~1z~0~zUnresolvable JSON pointer: %r) lstriprsplitrqrr int ValueErrorrl LookupErrorr r)rrrpartspartrrrrs     zRefResolver.resolve_fragmentc Csy ddl}Wntk r$d}YnXt|j}||jkrJ|j||}nD|dkrf|rf||}n(t|}t| d}WdQRX|j r||j |<|S)a Resolve a remote ``uri``. If called directly, does not check the store first, but after retrieving the document at the specified URI it will be saved in the store if :attr:`cache_remote` is True. .. note:: If the requests_ library is present, ``jsonschema`` will use it to request the remote ``uri``, so that the correct encoding is detected and used. If it isn't, or if the scheme of the ``uri`` is not ``http`` or ``https``, UTF-8 is assumed. Arguments: uri (str): The URI to resolve Returns: The retrieved document .. _requests: https://pypi.org/project/requests/ rN)httphttpszutf-8) requests ImportErrorrschemerrBjsonrloadsreaddecoderr)rrrrresultrrrrr3s       zRefResolver.resolve_remote)rTrNN)rrrrrKrerDrHrPrTr?rr contextlibcontextmanagerrrrrrrrrrrrGPs$*     $rGcOsJ|dkrt|}||||f||}t||}|dk rF|dS)a Validate an instance under the given schema. >>> validate([2, 3, 4], {"maxItems": 2}) Traceback (most recent call last): ... ValidationError: [2, 3, 4] is too long :func:`validate` will first verify that the provided schema is itself valid, since not doing so can lead to less obvious error messages and fail in less obvious or consistent ways. If you know you have a valid schema already, especially if you intend to validate multiple instances with the same schema, you likely would prefer using the `IValidator.validate` method directly on a specific validator (e.g. ``Draft7Validator.validate``). Arguments: instance: The instance to validate schema: The schema to validate with cls (IValidator): The class that will be used to validate the instance. If the ``cls`` argument is not provided, two things will happen in accordance with the specification. First, if the schema has a :validator:`$schema` property containing a known meta-schema [#]_ then the proper validator will be used. The specification recommends that all schemas contain :validator:`$schema` properties for this reason. If no :validator:`$schema` property is found, the default validator class is the latest released draft. Any other provided positional and keyword arguments will be passed on when instantiating the ``cls``. Raises: `jsonschema.exceptions.ValidationError` if the instance is invalid `jsonschema.exceptions.SchemaError` if the schema itself is invalid .. rubric:: Footnotes .. [#] known by a validator registered with `jsonschema.validators.validates` N) validator_forrNr best_matchrL)r rCr5r]r^rOrMrrrr_gs8 r_cCsF|dks|dksd|kr|S|dtkr6tdtddt|dtS)a Retrieve the validator class appropriate for validating the given schema. Uses the :validator:`$schema` property that should be present in the given schema to look up the appropriate validator class. Arguments: schema (collections.Mapping or bool): the schema to look at default: the default to return if the appropriate validator class cannot be determined. If unprovided, the default is to return the latest supported draft. TFz$schemazThe metaschema specified by $schema was not found. Using the latest draft to validate, but this will raise an error in the future.r9)r:)r4rr<rB_LATEST_VERSION)rCdefaultrrrrs r)r)rNN)N)fr __future__rwarningsrrrnumbersZsixrZ jsonschemarrrrr Zjsonschema.compatr r r r rrrrrrZjsonschema.exceptionsrrrr1rr4r)listrraNumberr%rnrmror8r=r>rDrrrtZ load_schemarWrurvZdependencies_draft3Zdisallow_draft3rrxZextends_draft3ryZitems_draft3_draft4r{r|Zmaximum_draft3_draft4r~rZminimum_draft3_draft4rrZproperties_draft3Z type_draft3rZdraft3_type_checkerZDraft3Validatorrrrwrrnot_rrrZdraft4_type_checkerZDraft4Validatorrrrrrzr}rrZdraft6_type_checkerZDraft6ValidatorZif_Zdraft7_type_checkerZDraft7Validatorrr.rGr_rrrrrsP   0   #  P I   B