o >]r@sdZddlmZddlmZddlZddlZddlZddlm Z ddl m Z m Z m Z mZmZddlmZmZmZmZmZmZmZmZmZmZddlmZeGd d d eZiZe Z!dId d Z"e#e$ee%dej&e'edZ(e j)e"e(dZ*ddZ+ddZ,Gddde%Z-ddZ.d ddde.fddZ/dJddZ0e/e 1didej2dej3dej4d e j5d!e j6d"ej7d#ej8d$e j9d%ej:d&e j;d'ej<d(ej=d)e j>d*ej?d+ej@d,e jAd-ejBejCe jDe jEejFd.e jGdd/d0d1ZHe/e 1d2idej2dej3dej4d3ejId4ejJd ejKd#ej8d%ej:d&e j;d'ej<d(ej=d5ejLd)e j>d*ej?d+ej@d6ejMd,e jAej7ejNejOejBejCejPejQej%ejFd7 e jRd2d8d0d1ZSe/e 1d9idej2dej3dej4d3ejId4ejJd:ejTd;ejUd ejKd#ej8de j\d9d?Z]e/e 1d@idej2dej3dej4d3ejId4ejJd:ejTd;ejUd ejKd#ej8d.gen_type_check..type_check)rflatten)r$r%rr#rgen_type_checkIs  z4_generate_legacy_type_checks..gen_type_check)dictr )typesr' definitionstypenamer$rrr_generate_legacy_type_checks9s  r,)arraybooleanintegernullnumberobjectstring 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)clsmeta_schema_idversionrr _validates}s  zvalidates.._validatesr)r>r?rr=r validatesis r@cCs$|jdurttdtdd|jS)NzcThe DEFAULT_TYPES attribute is deprecated. See the type checker attached to this validator instead. stacklevel)_CREATED_WITH_DEFAULT_TYPESrrDeprecationWarning_DEFAULT_TYPESrrrrrFs rFc@seZdZeeZdS)!_DefaultTypesDeprecatingMetaClassN)rrrpropertyrF DEFAULT_TYPESrrrrrGs rGcCs |dus|dur dS|ddS)NTFz$idgetschemarrr_id_ofs rOcsdurdur tddtdtddtjtdntdur)dtn tur0dndtt Gfd d d t }|durZt ||}| 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.rArBr4FcseZdZeZeZZeZe e Z eZ Z   dfdd Z eddZdfdd Zdd d Zd d Zd dZdddZdS)zcreate..ValidatorrNcsP|rtdtdd|jt||_|durtj|d}||_||_||_ dS)NzaThe types argument is deprecated. Provide a type_checker to jsonschema.validators.extend instead.rArBid_of) rrE TYPE_CHECKER redefine_manyr, RefResolver from_schemaresolverformat_checkerrN)rrNr)rVrWrPrr__init__s  z"create..Validator.__init__cSs$||j|D]}tj|dSr6)r9 iter_errorsr SchemaError create_from)r;rNerrorrrr check_schema#s z&create..Validator.check_schemac 3s|dur|j}|durdS|dur"tjd|fdd||dVdS|}|r.|j|zU|d}|dur>d|fg}nt|}|D]3\}}|j|}|durSqD|||||p[d} | D]} | j||||d|dkrs| j || Vq^qDW|r|j dSdS|r|j ww)NTFzFalse schema does not allow %r) validatorvalidator_valuer"rN$refr) rNr ValidationErrorrV push_scoperLr VALIDATORS_set schema_path appendleft pop_scope) rr"_schemascoperefr7kvr^errorsr\rPrrrY(sX       z%create..Validator.iter_errorscssF|||D]}|dur|j||dur|j||VqdSr6)rYpathrfre)rr"rNrnrer\rrrdescendWs  z!create..Validator.descendc_s|j|i|D]}|dSr6)rY)rargskwargsr\rrrvalidate_sz"create..Validator.validatecSs2z|j||WStjyt|||jwr6)rRis_typer UndefinedTypeCheck UnknownTyperN)rr"typerrrrscs z!create..Validator.is_typecSst|||d}|duSr6)nextrY)rr"rhr\rrris_validisz"create..Validator.is_validrNNr6)NN)rrrr(rcr9rR staticmethodr8rHrFrIrDrX classmethodr]rYrorrrsrxr_created_with_default_types default_typesrQ meta_schema type_checkerr7rr Validators&  /r rJ) TypeErrorrrEr TypeCheckerr,_DEPRECATED_DEFAULT_TYPES*_TYPE_CHECKER_FOR_DEPRECATED_DEFAULT_TYPESrrGr2r@titlereplacer)rr7r>r~rrQrrr|rcreates6@ r rcCsHt|j}|||dur|j}n|jrtdt|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.)rr7r>rrQ) r(rcupdaterRrDrrr9r8)r^r7r>rall_validatorsrrrextendts 5 rdraft3r`additionalItemsadditionalProperties dependenciesdisallow divisibleByenumextendsformatitemsmaxItems maxLengthmaximumminItems minLengthminimumpattern)patternProperties propertiesrv uniqueItemscC |ddSNidrJrKrMrrr r)rr7rr>rQdraft4allOfanyOf maxProperties minProperties) multipleOfnotoneOfrrrrequiredrvrcCrrrKrMrrrrrdraft6constcontainsexclusiveMaximumexclusiveMinimum)rrrrrrrrrr propertyNamesrrvr)rr7rr>draft7if)rrrrrrrrrrrrrrvrc@seZdZdZ     dddZeefddZd d Zd d Z e d dZ e ddZ e jddZe jddZddZddZddZddZdS)rTa 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|dur tdt}|durtd|j}||_||_t||_|g|_t ddt t D|_ |j |||j |<||_||_dS)Nicss|] \}}||jfVqdSr6)r9).0rr^rrr s  z'RefResolver.__init__..)r rresolve_from_urlreferrer cache_remoter(handlers _scopes_stackrURIDictr r:storer_urljoin_cache _remote_cache)rbase_urirrrr urljoin_cache remote_cacherrrrX|s      zRefResolver.__init__cOs|||||d|S)z Construct a resolver from a JSON schema object. Arguments: schema: the referring schema Returns: `RefResolver` )rrr)r;rNrQrprqrrrrUszRefResolver.from_schemacCs|j||j|dS)z Enter a given sub-scope. Treats further dereferences as being performed underneath the given scope. N)rappendrresolution_scoperrirrrrbs zRefResolver.push_scopecCs*z|jWdStytdw)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 RefResolutionErrorrrrrrgs  zRefResolver.pop_scopecCs |jdS)z8 Retrieve the current resolution scope. )rrrrrrs zRefResolver.resolution_scopecCst|j\}}|S)zL Retrieve the current base URI, not including any fragment. )rr)ruri_rrrrszRefResolver.base_uriccs,||z dVW|dS|w)zT Temporarily enter the given scope for the duration of the context. N)rbrgrrrrin_scopes  zRefResolver.in_scopeccs:||\}}||z |VW|dS|w)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)resolverbrg)rrjurlresolvedrrr resolvings  zRefResolver.resolvingcCs||j|}|||fS)z. Resolve the given reference. )rrr)rrjrrrrrszRefResolver.resolvec Cslt|\}}z|j|}Wn"ty/z||}Wnty,}zt|d}~wwYnw|||S)z/ Resolve the given remote URL. N)rrKeyErrorresolve_remote Exceptionr rresolve_fragment)rrfragmentdocumentexcrrrrs    zRefResolver.resolve_from_urlc Cs|d}|rt|dng}|D]7}|dddd}t|tr3zt|}Wn ty2Ynwz||}Wqtt fyIt d|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) lstriprsplitrrr int ValueErrorr LookupErrorr r)rrrpartspartrrrrs$     zRefResolver.resolve_fragmentcCszddl}Wn tyd}Ynwt|j}||jvr$|j||}n,|dvr2|r2||}nt|}t| d}Wdn1sKwY|j rX||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 ImportErrorrschemerrLjsonrloadsreaddecoderr)rrrrresultrrrrr3s        zRefResolver.resolve_remote)rTrNN)rrrrrXr{rOrUrbrgrHrr contextlibcontextmanagerrrrrrrrrrrrTPs0/       $rTcOsP|durt|}||||g|Ri|}t||}|dur&|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_forr]r best_matchrY)r"rNr;rprqr^r\rrrrrgs8 rrcCsF|dus |dus d|vr|S|dtvrtdtddt|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.rArB)r:rrErL_LATEST_VERSION)rNdefaultrrrrs  r)rryr6)fr __future__rwarningsrrrnumberssixr jsonschemarrrrr jsonschema.compatr r r r rrrrrrjsonschema.exceptionsrrrr7rr:r,listr rvNumberr(rrrr@rFrGrOrr load_schemarjrrdependencies_draft3disallow_draft3rrextends_draft3ritems_draft3_draft4rrmaximum_draft3_draft4rrminimum_draft3_draft4rrproperties_draft3 type_draft3rdraft3_type_checkerDraft3Validatorrrrrrnot_rrrdraft4_type_checkerDraft4Validatorrrrrrrrrdraft6_type_checkerDraft6Validatorif_draft7_type_checkerDraft7Validatorrr2rTrrrrrrrs   0   #   VI          #     !'     "( B