Coverage for /pythoncovmergedfiles/medio/medio/src/jsonschema/jsonschema/protocols.py: 73%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2typing.Protocol classes for jsonschema interfaces.
3"""
5# for reference material on Protocols, see
6# https://www.python.org/dev/peps/pep-0544/
8from __future__ import annotations
10from typing import TYPE_CHECKING, Any, ClassVar, Protocol, runtime_checkable
12# in order for Sphinx to resolve references accurately from type annotations,
13# it needs to see names like `jsonschema.TypeChecker`
14# therefore, only import at type-checking time (to avoid circular references),
15# but use `jsonschema` for any types which will otherwise not be resolvable
16if TYPE_CHECKING:
17 from collections.abc import Iterable, Mapping
19 import referencing.jsonschema
21 from jsonschema import _typing
22 from jsonschema.exceptions import ValidationError
23 import jsonschema
24 import jsonschema.validators
26# For code authors working on the validator protocol, these are the three
27# use-cases which should be kept in mind:
28#
29# 1. As a protocol class, it can be used in type annotations to describe the
30# available methods and attributes of a validator
31# 2. It is the source of autodoc for the validator documentation
32# 3. It is runtime_checkable, meaning that it can be used in isinstance()
33# checks.
34#
35# Since protocols are not base classes, isinstance() checking is limited in
36# its capabilities. See docs on runtime_checkable for detail
39@runtime_checkable
40class Validator(Protocol):
41 """
42 The protocol to which all validator classes adhere.
44 Arguments:
46 schema:
48 The schema that the validator object will validate with.
49 It is assumed to be valid, and providing
50 an invalid schema can lead to undefined behavior. See
51 `Validator.check_schema` to validate a schema first.
53 registry:
55 a schema registry that will be used for looking up JSON references
57 resolver:
59 a resolver that will be used to resolve :kw:`$ref`
60 properties (JSON references). If unprovided, one will be created.
62 .. deprecated:: v4.18.0
64 `RefResolver <_RefResolver>` has been deprecated in favor of
65 `referencing`, and with it, this argument.
67 format_checker:
69 if provided, a checker which will be used to assert about
70 :kw:`format` properties present in the schema. If unprovided,
71 *no* format validation is done, and the presence of format
72 within schemas is strictly informational. Certain formats
73 require additional packages to be installed in order to assert
74 against instances. Ensure you've installed `jsonschema` with
75 its `extra (optional) dependencies <index:extras>` when
76 invoking ``pip``.
78 .. deprecated:: v4.12.0
80 Subclassing validator classes now explicitly warns this is not part of
81 their public API.
83 """
85 #: An object representing the validator's meta schema (the schema that
86 #: describes valid schemas in the given version).
87 META_SCHEMA: ClassVar[Mapping]
89 #: A mapping of validation keywords (`str`\s) to functions that
90 #: validate the keyword with that name. For more information see
91 #: `creating-validators`.
92 VALIDATORS: ClassVar[Mapping]
94 #: A `jsonschema.TypeChecker` that will be used when validating
95 #: :kw:`type` keywords in JSON schemas.
96 TYPE_CHECKER: ClassVar[jsonschema.TypeChecker]
98 #: A `jsonschema.FormatChecker` that will be used when validating
99 #: :kw:`format` keywords in JSON schemas.
100 FORMAT_CHECKER: ClassVar[jsonschema.FormatChecker]
102 #: A function which given a schema returns its ID.
103 ID_OF: _typing.id_of
105 #: The schema that will be used to validate instances
106 schema: Mapping | bool
108 def __init__(
109 self,
110 schema: Mapping | bool,
111 registry: referencing.jsonschema.SchemaRegistry,
112 format_checker: jsonschema.FormatChecker | None = None,
113 ) -> None:
114 ...
116 @classmethod
117 def check_schema(cls, schema: Mapping | bool) -> None:
118 """
119 Validate the given schema against the validator's `META_SCHEMA`.
121 Raises:
123 `jsonschema.exceptions.SchemaError`:
125 if the schema is invalid
127 """
129 def is_type(self, instance: Any, type: str) -> bool:
130 """
131 Check if the instance is of the given (JSON Schema) type.
133 Arguments:
135 instance:
137 the value to check
139 type:
141 the name of a known (JSON Schema) type
143 Returns:
145 whether the instance is of the given type
147 Raises:
149 `jsonschema.exceptions.UnknownType`:
151 if ``type`` is not a known type
153 """
155 def is_valid(self, instance: Any) -> bool:
156 """
157 Check if the instance is valid under the current `schema`.
159 Returns:
161 whether the instance is valid or not
163 >>> schema = {"maxItems" : 2}
164 >>> Draft202012Validator(schema).is_valid([2, 3, 4])
165 False
167 """
169 def iter_errors(self, instance: Any) -> Iterable[ValidationError]:
170 r"""
171 Lazily yield each of the validation errors in the given instance.
173 >>> schema = {
174 ... "type" : "array",
175 ... "items" : {"enum" : [1, 2, 3]},
176 ... "maxItems" : 2,
177 ... }
178 >>> v = Draft202012Validator(schema)
179 >>> for error in sorted(v.iter_errors([2, 3, 4]), key=str):
180 ... print(error.message)
181 4 is not one of [1, 2, 3]
182 [2, 3, 4] is too long
184 .. deprecated:: v4.0.0
186 Calling this function with a second schema argument is deprecated.
187 Use `Validator.evolve` instead.
188 """
190 def validate(self, instance: Any) -> None:
191 """
192 Check if the instance is valid under the current `schema`.
194 Raises:
196 `jsonschema.exceptions.ValidationError`:
198 if the instance is invalid
200 >>> schema = {"maxItems" : 2}
201 >>> Draft202012Validator(schema).validate([2, 3, 4])
202 Traceback (most recent call last):
203 ...
204 ValidationError: [2, 3, 4] is too long
206 """
208 def evolve(self, **kwargs) -> Validator:
209 """
210 Create a new validator like this one, but with given changes.
212 Preserves all other attributes, so can be used to e.g. create a
213 validator with a different schema but with the same :kw:`$ref`
214 resolution behavior.
216 >>> validator = Draft202012Validator({})
217 >>> validator.evolve(schema={"type": "number"})
218 Draft202012Validator(schema={'type': 'number'}, format_checker=None)
220 The returned object satisfies the validator protocol, but may not
221 be of the same concrete class! In particular this occurs
222 when a :kw:`$ref` occurs to a schema with a different
223 :kw:`$schema` than this one (i.e. for a different draft).
225 >>> validator.evolve(
226 ... schema={"$schema": Draft7Validator.META_SCHEMA["$id"]}
227 ... )
228 Draft7Validator(schema=..., format_checker=None)
229 """