Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/jsonschema/protocols.py: 81%

26 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-08 06:51 +0000

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 collections.abc import Mapping 

11from typing import ( 

12 TYPE_CHECKING, 

13 Any, 

14 ClassVar, 

15 Iterable, 

16 Protocol, 

17 runtime_checkable, 

18) 

19 

20# in order for Sphinx to resolve references accurately from type annotations, 

21# it needs to see names like `jsonschema.TypeChecker` 

22# therefore, only import at type-checking time (to avoid circular references), 

23# but use `jsonschema` for any types which will otherwise not be resolvable 

24if TYPE_CHECKING: 

25 from jsonschema import _typing 

26 import jsonschema 

27 import jsonschema.validators 

28 import referencing.jsonschema 

29 

30from jsonschema.exceptions import ValidationError 

31 

32# For code authors working on the validator protocol, these are the three 

33# use-cases which should be kept in mind: 

34# 

35# 1. As a protocol class, it can be used in type annotations to describe the 

36# available methods and attributes of a validator 

37# 2. It is the source of autodoc for the validator documentation 

38# 3. It is runtime_checkable, meaning that it can be used in isinstance() 

39# checks. 

40# 

41# Since protocols are not base classes, isinstance() checking is limited in 

42# its capabilities. See docs on runtime_checkable for detail 

43 

44 

45@runtime_checkable 

46class Validator(Protocol): 

47 """ 

48 The protocol to which all validator classes adhere. 

49 

50 Arguments: 

51 

52 schema: 

53 

54 The schema that the validator object will validate with. 

55 It is assumed to be valid, and providing 

56 an invalid schema can lead to undefined behavior. See 

57 `Validator.check_schema` to validate a schema first. 

58 

59 registry: 

60 

61 a schema registry that will be used for looking up JSON references 

62 

63 resolver: 

64 

65 a resolver that will be used to resolve :kw:`$ref` 

66 properties (JSON references). If unprovided, one will be created. 

67 

68 .. deprecated:: v4.18.0 

69 

70 `RefResolver <_RefResolver>` has been deprecated in favor of 

71 `referencing`, and with it, this argument. 

72 

73 format_checker: 

74 

75 if provided, a checker which will be used to assert about 

76 :kw:`format` properties present in the schema. If unprovided, 

77 *no* format validation is done, and the presence of format 

78 within schemas is strictly informational. Certain formats 

79 require additional packages to be installed in order to assert 

80 against instances. Ensure you've installed `jsonschema` with 

81 its `extra (optional) dependencies <index:extras>` when 

82 invoking ``pip``. 

83 

84 .. deprecated:: v4.12.0 

85 

86 Subclassing validator classes now explicitly warns this is not part of 

87 their public API. 

88 """ 

89 

90 #: An object representing the validator's meta schema (the schema that 

91 #: describes valid schemas in the given version). 

92 META_SCHEMA: ClassVar[Mapping] 

93 

94 #: A mapping of validation keywords (`str`\s) to functions that 

95 #: validate the keyword with that name. For more information see 

96 #: `creating-validators`. 

97 VALIDATORS: ClassVar[Mapping] 

98 

99 #: A `jsonschema.TypeChecker` that will be used when validating 

100 #: :kw:`type` keywords in JSON schemas. 

101 TYPE_CHECKER: ClassVar[jsonschema.TypeChecker] 

102 

103 #: A `jsonschema.FormatChecker` that will be used when validating 

104 #: :kw:`format` keywords in JSON schemas. 

105 FORMAT_CHECKER: ClassVar[jsonschema.FormatChecker] 

106 

107 #: A function which given a schema returns its ID. 

108 ID_OF: _typing.id_of 

109 

110 #: The schema that will be used to validate instances 

111 schema: Mapping | bool 

112 

113 def __init__( 

114 self, 

115 schema: Mapping | bool, 

116 registry: referencing.jsonschema.SchemaRegistry, 

117 format_checker: jsonschema.FormatChecker | None = None, 

118 ) -> None: 

119 ... 

120 

121 @classmethod 

122 def check_schema(cls, schema: Mapping | bool) -> None: 

123 """ 

124 Validate the given schema against the validator's `META_SCHEMA`. 

125 

126 Raises: 

127 

128 `jsonschema.exceptions.SchemaError`: 

129 

130 if the schema is invalid 

131 """ 

132 

133 def is_type(self, instance: Any, type: str) -> bool: 

134 """ 

135 Check if the instance is of the given (JSON Schema) type. 

136 

137 Arguments: 

138 

139 instance: 

140 

141 the value to check 

142 

143 type: 

144 

145 the name of a known (JSON Schema) type 

146 

147 Returns: 

148 

149 whether the instance is of the given type 

150 

151 Raises: 

152 

153 `jsonschema.exceptions.UnknownType`: 

154 

155 if ``type`` is not a known type 

156 """ 

157 

158 def is_valid(self, instance: Any) -> bool: 

159 """ 

160 Check if the instance is valid under the current `schema`. 

161 

162 Returns: 

163 

164 whether the instance is valid or not 

165 

166 >>> schema = {"maxItems" : 2} 

167 >>> Draft202012Validator(schema).is_valid([2, 3, 4]) 

168 False 

169 """ 

170 

171 def iter_errors(self, instance: Any) -> Iterable[ValidationError]: 

172 r""" 

173 Lazily yield each of the validation errors in the given instance. 

174 

175 >>> schema = { 

176 ... "type" : "array", 

177 ... "items" : {"enum" : [1, 2, 3]}, 

178 ... "maxItems" : 2, 

179 ... } 

180 >>> v = Draft202012Validator(schema) 

181 >>> for error in sorted(v.iter_errors([2, 3, 4]), key=str): 

182 ... print(error.message) 

183 4 is not one of [1, 2, 3] 

184 [2, 3, 4] is too long 

185 

186 .. deprecated:: v4.0.0 

187 

188 Calling this function with a second schema argument is deprecated. 

189 Use `Validator.evolve` instead. 

190 """ 

191 

192 def validate(self, instance: Any) -> None: 

193 """ 

194 Check if the instance is valid under the current `schema`. 

195 

196 Raises: 

197 

198 `jsonschema.exceptions.ValidationError`: 

199 

200 if the instance is invalid 

201 

202 >>> schema = {"maxItems" : 2} 

203 >>> Draft202012Validator(schema).validate([2, 3, 4]) 

204 Traceback (most recent call last): 

205 ... 

206 ValidationError: [2, 3, 4] is too long 

207 """ 

208 

209 def evolve(self, **kwargs) -> Validator: 

210 """ 

211 Create a new validator like this one, but with given changes. 

212 

213 Preserves all other attributes, so can be used to e.g. create a 

214 validator with a different schema but with the same :kw:`$ref` 

215 resolution behavior. 

216 

217 >>> validator = Draft202012Validator({}) 

218 >>> validator.evolve(schema={"type": "number"}) 

219 Draft202012Validator(schema={'type': 'number'}, format_checker=None) 

220 

221 The returned object satisfies the validator protocol, but may not 

222 be of the same concrete class! In particular this occurs 

223 when a :kw:`$ref` occurs to a schema with a different 

224 :kw:`$schema` than this one (i.e. for a different draft). 

225 

226 >>> validator.evolve( 

227 ... schema={"$schema": Draft7Validator.META_SCHEMA["$id"]} 

228 ... ) 

229 Draft7Validator(schema=..., format_checker=None) 

230 """