1"""
2typing.Protocol classes for jsonschema interfaces.
3"""
4
5# for reference material on Protocols, see
6# https://www.python.org/dev/peps/pep-0544/
7
8from __future__ import annotations
9
10from typing import TYPE_CHECKING, Any, ClassVar, Protocol, runtime_checkable
11
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
18
19 import referencing.jsonschema
20
21 from jsonschema import _typing
22 from jsonschema.exceptions import ValidationError
23 import jsonschema
24 import jsonschema.validators
25
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
37
38
39@runtime_checkable
40class Validator(Protocol):
41 """
42 The protocol to which all validator classes adhere.
43
44 Arguments:
45
46 schema:
47
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.
52
53 registry:
54
55 a schema registry that will be used for looking up JSON references
56
57 resolver:
58
59 a resolver that will be used to resolve :kw:`$ref`
60 properties (JSON references). If unprovided, one will be created.
61
62 .. deprecated:: v4.18.0
63
64 `RefResolver <_RefResolver>` has been deprecated in favor of
65 `referencing`, and with it, this argument.
66
67 format_checker:
68
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``.
77
78 .. deprecated:: v4.12.0
79
80 Subclassing validator classes now explicitly warns this is not part of
81 their public API.
82
83 """
84
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]
88
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]
93
94 #: A `jsonschema.TypeChecker` that will be used when validating
95 #: :kw:`type` keywords in JSON schemas.
96 TYPE_CHECKER: ClassVar[jsonschema.TypeChecker]
97
98 #: A `jsonschema.FormatChecker` that will be used when validating
99 #: :kw:`format` keywords in JSON schemas.
100 FORMAT_CHECKER: ClassVar[jsonschema.FormatChecker]
101
102 #: A function which given a schema returns its ID.
103 ID_OF: _typing.id_of
104
105 #: The schema that will be used to validate instances
106 schema: Mapping | bool
107
108 def __init__(
109 self,
110 schema: Mapping | bool,
111 registry: referencing.jsonschema.SchemaRegistry,
112 format_checker: jsonschema.FormatChecker | None = None,
113 ) -> None:
114 ...
115
116 @classmethod
117 def check_schema(cls, schema: Mapping | bool) -> None:
118 """
119 Validate the given schema against the validator's `META_SCHEMA`.
120
121 Raises:
122
123 `jsonschema.exceptions.SchemaError`:
124
125 if the schema is invalid
126
127 """
128
129 def is_type(self, instance: Any, type: str) -> bool:
130 """
131 Check if the instance is of the given (JSON Schema) type.
132
133 Arguments:
134
135 instance:
136
137 the value to check
138
139 type:
140
141 the name of a known (JSON Schema) type
142
143 Returns:
144
145 whether the instance is of the given type
146
147 Raises:
148
149 `jsonschema.exceptions.UnknownType`:
150
151 if ``type`` is not a known type
152
153 """
154
155 def is_valid(self, instance: Any) -> bool:
156 """
157 Check if the instance is valid under the current `schema`.
158
159 Returns:
160
161 whether the instance is valid or not
162
163 >>> schema = {"maxItems" : 2}
164 >>> Draft202012Validator(schema).is_valid([2, 3, 4])
165 False
166
167 """
168
169 def iter_errors(self, instance: Any) -> Iterable[ValidationError]:
170 r"""
171 Lazily yield each of the validation errors in the given instance.
172
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
183
184 .. deprecated:: v4.0.0
185
186 Calling this function with a second schema argument is deprecated.
187 Use `Validator.evolve` instead.
188 """
189
190 def validate(self, instance: Any) -> None:
191 """
192 Check if the instance is valid under the current `schema`.
193
194 Raises:
195
196 `jsonschema.exceptions.ValidationError`:
197
198 if the instance is invalid
199
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
205
206 """
207
208 def evolve(self, **kwargs) -> Validator:
209 """
210 Create a new validator like this one, but with given changes.
211
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.
215
216 >>> validator = Draft202012Validator({})
217 >>> validator.evolve(schema={"type": "number"})
218 Draft202012Validator(schema={'type': 'number'}, format_checker=None)
219
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).
224
225 >>> validator.evolve(
226 ... schema={"$schema": Draft7Validator.META_SCHEMA["$id"]}
227 ... )
228 Draft7Validator(schema=..., format_checker=None)
229 """