a $]r#@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)rZflatten)r#r$rr"rgen_type_checkIs  z4_generate_legacy_type_checks..gen_type_check)dictr )typesr%Z definitionstypenamer#rrr_generate_legacy_type_checks9s  r))ZarrayZbooleanZintegerZnullZnumberobjectstringZ 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|<|SN) validatorsID_OF META_SCHEMA meta_schemas)clsZmeta_schema_idversionrr _validates}s  zvalidates.._validatesr)r4r5rr3r validatesis r6cCs$|jdurttdtdd|jS)NzcThe DEFAULT_TYPES attribute is deprecated. See the type checker attached to this validator instead. stacklevel)_CREATED_WITH_DEFAULT_TYPESrrDeprecationWarning_DEFAULT_TYPESrrrrr<s r<c@seZdZeeZdS)!_DefaultTypesDeprecatingMetaClassN)rrrpropertyr< DEFAULT_TYPESrrrrr=sr=cCs |dus|durdS|ddS)NTFz$idgetschemarrr_id_ofsrEcsdur<durtddtdtddtjtdn(tdurRdtntur`dndtt Gfd d d t }|durt ||}| 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.r7r8r,FcseZdZeZeZZeZe e Z eZ Z dfdd Z eddZdfdd Zdd d Zd d Zd dZdddZdS)zcreate..ValidatorrNcsP|r$tdtdd|jt||_|dur:tj|d}||_||_||_ dS)NzaThe types argument is deprecated. Provide a type_checker to jsonschema.validators.extend instead.r7r8id_of) rr; TYPE_CHECKERZ redefine_manyr) RefResolver from_schemaresolverformat_checkerrD)rrDr'rKrLrFrr__init__s z"create..Validator.__init__cSs&||j|D]}tj|qdSr-)r0 iter_errorsr Z SchemaErrorZ create_from)r2rDerrorrrr check_schema#sz&create..Validator.check_schemac 3s|dur|j}|durdS|durBtjd|fdd||dVdS|}|rZ|j|z|d}|durzd|fg}nt|}|D]f\}}|j|}|durq|||||pd} | D]0} | j||||d|dkr| j || VqqW|r|j n|r|j 0dS)NTFzFalse schema does not allow %r) validatorZvalidator_valuer!rD$refr) rDr ZValidationErrorrK push_scoperBr VALIDATORSZ_set schema_path appendleft pop_scope) rr!_schemascoperefr.kvrQerrorsrOrFrrrN(sP        z%create..Validator.iter_errorscssD|||D]2}|dur$|j||dur8|j||Vq dSr-)rNpathrVrU)rr!rDr^rUrOrrrdescendWs   z!create..Validator.descendc_s|j|i|D]}|qdSr-)rN)rargskwargsrOrrrvalidate_sz"create..Validator.validatecSs:z|j||WStjy4t|||jYn0dSr-)rHis_typer ZUndefinedTypeCheckZ UnknownTyperD)rr!typerrrrccsz!create..Validator.is_typecSst|||d}|duSr-)nextrN)rr!rXrOrrris_validisz"create..Validator.is_valid)rNN)N)NN)N)rrrr&rTr0rH staticmethodr/r>r<r?r:rM classmethodrPrNr_rbrcrfrZ_created_with_default_types default_typesrG meta_schema type_checkerr.rr Validators$ / rm r@) TypeErrorrr;r TypeCheckerr)_DEPRECATED_DEFAULT_TYPES*_TYPE_CHECKER_FOR_DEPRECATED_DEFAULT_TYPESrr=r*r6titlereplacer)rkr.r4rjrlrGrmrrircreates6@ r rucCsHt|j}|||dur$|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.)rkr.r4rlrG) r&rTupdaterHr:rorur0r/)rQr.r4rlZall_validatorsrrrextendts5  rwZdraft3)rRadditionalItemsadditionalProperties dependenciesZdisallowZ divisibleByenumZextendsformatitemsmaxItems maxLengthmaximumminItems minLengthminimumpatternpatternProperties propertiesrd uniqueItemscCs |ddSNidr@rArCrrrr)rkr.rlr4rGZdraft4)rRrxryallOfanyOfrzr{r|r}r~r maxPropertiesrrr minPropertiesr multipleOfnotoneOfrrrrequiredrdrcCs |ddSrrArCrrrrrZdraft6)rRrxryrrconstcontainsrzr{exclusiveMaximumexclusiveMinimumr|r}r~rrrrrrrrrrrrr propertyNamesrrdr)rkr.rlr4Zdraft7) rRrxryrrrrrzr{rrr|ifr}r~rrrrrrrrrrrrrrrrdrc@seZdZdZdddZeefddZd d Zd d Z e d dZ e ddZ e jddZe jddZddZddZddZddZdS)rIa 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|durtdt}|dur*td|j}||_||_t||_|g|_t ddt t D|_ |j |||j |<||_||_dS)Nicss|]\}}||jfVqdSr-)r0).0rrQrrr sz'RefResolver.__init__..)r rresolve_from_urlreferrer cache_remoter&handlers _scopes_stackrURIDictr r1storerv_urljoin_cache _remote_cache)rbase_urirrrrZ urljoin_cacheZ remote_cacherrrrM|s       zRefResolver.__init__cOs|||||d|S)z Construct a resolver from a JSON schema object. Arguments: schema: the referring schema Returns: `RefResolver` )rrr)r2rDrGr`rarrrrJszRefResolver.from_schemacCs|j||j|dS)z Enter a given sub-scope. Treats further dereferences as being performed underneath the given scope. N)rappendrresolution_scoperrYrrrrSs zRefResolver.push_scopecCs0z|jWnty*tdYn0dS)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 RefResolutionErrorrrrrrWs  zRefResolver.pop_scopecCs |jdS)z8 Retrieve the current resolution scope. )rrrrrrszRefResolver.resolution_scopecCst|j\}}|S)zL Retrieve the current base URI, not including any fragment. )rr)ruri_rrrrszRefResolver.base_uriccs,||zdVW|n |0dS)zT Temporarily enter the given scope for the duration of the context. N)rSrWrrrrin_scopes zRefResolver.in_scopeccs:||\}}||z|VW|n |0dS)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)resolverSrW)rrZurlZresolvedrrr resolvings  zRefResolver.resolvingcCs||j|}|||fS)z. Resolve the given reference. )rrr)rrZrrrrrszRefResolver.resolvec Csxt|\}}z|j|}WnPtyjz||}Wn.tyd}zt|WYd}~n d}~00Yn0|||S)z/ Resolve the given remote URL. N)rrKeyErrorresolve_remote Exceptionr rresolve_fragment)rrfragmentdocumentexcrrrrs  &zRefResolver.resolve_from_urlc Cs|d}|rt|dng}|D]t}|dddd}t|trfz t|}WntydYn0z ||}Wq$tt fyt d|Yq$0q$|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) lstriprsplitrtrr int ValueErrorro LookupErrorr r)rrrpartspartrrrrs       zRefResolver.resolve_fragmentcCsz ddl}Wnty"d}Yn0t|j}||jvrH|j||}nX|dvrd|rd||}nrr contextlibcontextmanagerrrrrrrrrrrrIPs./      $rIcOsP|durt|}||||g|Ri|}t||}|durL|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_forrPr Z best_matchrN)r!rDr2r`rarQrOrrrrbgs8 rbcCsF|dus|dusd|vr|S|dtvr6tdtddt|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.r7r8)r1rr;rB_LATEST_VERSION)rDdefaultrrrrs  r)r)rNN)N)frZ __future__rwarningsrrrZnumbersZsixrZ jsonschemarrrrr Zjsonschema.compatr r r r rrrrrrZjsonschema.exceptionsrrrr.rr1r)listr rdNumberr&rqrprrr6r<r=rErurwZ load_schemarZrxryZdependencies_draft3Zdisallow_draft3rr{Zextends_draft3r|Zitems_draft3_draft4r~rZmaximum_draft3_draft4rrZminimum_draft3_draft4rrZproperties_draft3Z type_draft3rZdraft3_type_checkerZDraft3Validatorrrrzrrnot_rrrZdraft4_type_checkerZDraft4Validatorrrrrr}rrrZdraft6_type_checkerZDraft6ValidatorZif_Zdraft7_type_checkerZDraft7Validatorrr*rIrbrrrrrsf   0   #  V I#!'"( B