Coverage for plugin/schema.py: 83.0%
170 statements
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 02:31 +0000
« prev ^ index » next coverage.py v7.17.5, created at 2026-11-28 02:31 +0000
1"""Draft 2020-12 validation for the API contract across bundled jsonschema releases.
3Anki bundled jsonschema 3.2 (no Draft 2020-12) through 2.1.49 and 4.1 (no
4local ``$ref`` resolution under a URN ``$id``) through 25.02. Those releases use
5this validator, which implements the subset of keywords the contract uses.
6"""
7import re
9try:
10 import referencing # noqa: F401 - jsonschema 4.18 resolves references through it.
11 from jsonschema import Draft202012Validator
12except ImportError:
13 Draft202012Validator = None
15ANNOTATIONS = {'$schema', '$id', '$defs', '$comment', 'title', 'description', 'default',
16 'examples', 'format', 'contentEncoding', 'contentMediaType', 'deprecated',
17 'readOnly', 'writeOnly'}
20class ValidationError(Exception):
21 def __init__(self, message, path=(), context=()):
22 super().__init__(message)
23 self.message = message
24 self.path = list(path)
25 self.context = list(context)
28def equal(left, right):
29 if isinstance(left, bool) or isinstance(right, bool):
30 return type(left) is type(right) and left == right
31 if isinstance(left, dict) and isinstance(right, dict): 31 ↛ 32line 31 didn't jump to line 32 because the condition on line 31 was never true
32 return left.keys() == right.keys() and all(equal(left[key], right[key]) for key in left)
33 if isinstance(left, list) and isinstance(right, list): 33 ↛ 34line 33 didn't jump to line 34 because the condition on line 33 was never true
34 return len(left) == len(right) and all(equal(a, b) for a, b in zip(left, right))
35 return left == right
38def is_type(instance, kind):
39 number = isinstance(instance, (int, float)) and not isinstance(instance, bool)
40 return {
41 'object': isinstance(instance, dict),
42 'array': isinstance(instance, list),
43 'string': isinstance(instance, str),
44 'boolean': isinstance(instance, bool),
45 'null': instance is None,
46 'number': number,
47 'integer': number and (isinstance(instance, int) or instance.is_integer()),
48 }[kind]
51class Validator:
52 def __init__(self, schema):
53 self.root = schema
54 self.patterns = {}
56 def resolve(self, reference):
57 if not reference.startswith('#'): 57 ↛ 58line 57 didn't jump to line 58 because the condition on line 57 was never true
58 raise ValueError('Unsupported reference: ' + reference)
59 target = self.root
60 for part in reference[1:].split('/')[1:]:
61 target = target[part.replace('~1', '/').replace('~0', '~')]
62 return target
64 def is_valid(self, instance):
65 return not self.check(self.root, instance, [])[0]
67 def iter_errors(self, instance):
68 return iter(self.check(self.root, instance, [])[0])
70 def search(self, pattern, text):
71 if pattern not in self.patterns:
72 self.patterns[pattern] = re.compile(pattern)
73 return self.patterns[pattern].search(text)
75 def check(self, schema, instance, path):
76 """Return the errors and the object keys evaluated by successful subschemas."""
77 if schema is True: 77 ↛ 78line 77 didn't jump to line 78 because the condition on line 77 was never true
78 return [], set()
79 if schema is False: 79 ↛ 80line 79 didn't jump to line 80 because the condition on line 79 was never true
80 return [ValidationError('False schema does not allow {!r}'.format(instance), path)], set()
81 errors, evaluated = [], set()
82 def fail(message, context=()):
83 errors.append(ValidationError(message, path, context))
84 def apply(subschema):
85 return self.check(subschema, instance, path)
86 if '$ref' in schema:
87 found, keys = apply(self.resolve(schema['$ref']))
88 errors += found
89 evaluated |= keys
90 if 'type' in schema:
91 kinds = schema['type'] if isinstance(schema['type'], list) else [schema['type']]
92 if not any(is_type(instance, kind) for kind in kinds):
93 fail('{!r} is not of type {}'.format(instance, ', '.join(repr(kind) for kind in kinds)))
94 if 'const' in schema and not equal(instance, schema['const']):
95 fail('{!r} was expected'.format(schema['const']))
96 if 'enum' in schema and not any(equal(instance, value) for value in schema['enum']):
97 fail('{!r} is not one of {!r}'.format(instance, schema['enum']))
98 if is_type(instance, 'number'):
99 for keyword, failed, message in (
100 ('minimum', lambda bound: instance < bound, 'is less than the minimum of'),
101 ('maximum', lambda bound: instance > bound, 'is greater than the maximum of'),
102 ('exclusiveMinimum', lambda bound: instance <= bound, 'is less than or equal to the minimum of'),
103 ('exclusiveMaximum', lambda bound: instance >= bound, 'is greater than or equal to the maximum of')):
104 if keyword in schema and failed(schema[keyword]):
105 fail('{!r} {} {!r}'.format(instance, message, schema[keyword]))
106 if isinstance(instance, str):
107 if len(instance) < schema.get('minLength', 0):
108 fail('{!r} is too short'.format(instance))
109 if 'maxLength' in schema and len(instance) > schema['maxLength']: 109 ↛ 110line 109 didn't jump to line 110 because the condition on line 109 was never true
110 fail('{!r} is too long'.format(instance))
111 if 'pattern' in schema and not self.search(schema['pattern'], instance):
112 fail('{!r} does not match {!r}'.format(instance, schema['pattern']))
113 if isinstance(instance, list):
114 if len(instance) < schema.get('minItems', 0):
115 fail('{!r} is too short'.format(instance))
116 if 'maxItems' in schema and len(instance) > schema['maxItems']: 116 ↛ 117line 116 didn't jump to line 117 because the condition on line 116 was never true
117 fail('{!r} is too long'.format(instance))
118 if schema.get('uniqueItems') and any(equal(instance[i], instance[j]) for i in range(len(instance)) 118 ↛ 120line 118 didn't jump to line 120 because the condition on line 118 was never true
119 for j in range(i + 1, len(instance))):
120 fail('{!r} has non-unique elements'.format(instance))
121 if 'items' in schema:
122 for index, item in enumerate(instance):
123 errors += self.check(schema['items'], item, path + [index])[0]
124 if isinstance(instance, dict):
125 for name in schema.get('required', []):
126 if name not in instance:
127 fail('{!r} is a required property'.format(name))
128 if len(instance) < schema.get('minProperties', 0):
129 fail('{!r} does not have enough properties'.format(instance))
130 if 'maxProperties' in schema and len(instance) > schema['maxProperties']: 130 ↛ 131line 130 didn't jump to line 131 because the condition on line 130 was never true
131 fail('{!r} has too many properties'.format(instance))
132 for name, required in schema.get('dependentRequired', {}).items(): 132 ↛ 133line 132 didn't jump to line 133 because the loop on line 132 never started
133 if name in instance:
134 for other in required:
135 if other not in instance:
136 fail('{!r} is a dependency of {!r}'.format(other, name))
137 properties = schema.get('properties', {})
138 for name, subschema in properties.items():
139 if name in instance:
140 evaluated.add(name)
141 errors += self.check(subschema, instance[name], path + [name])[0]
142 matched = set()
143 for pattern, subschema in schema.get('patternProperties', {}).items(): 143 ↛ 144line 143 didn't jump to line 144 because the loop on line 143 never started
144 for name in instance:
145 if self.search(pattern, name):
146 matched.add(name)
147 errors += self.check(subschema, instance[name], path + [name])[0]
148 evaluated |= matched
149 if 'propertyNames' in schema:
150 for name in instance:
151 errors += self.check(schema['propertyNames'], name, path)[0]
152 if 'additionalProperties' in schema:
153 extra = [name for name in instance if name not in properties and name not in matched]
154 evaluated.update(extra)
155 if schema['additionalProperties'] is False and extra:
156 fail('Additional properties are not allowed ({} {} unexpected)'.format(
157 ', '.join(repr(name) for name in extra), 'was' if len(extra) == 1 else 'were'))
158 elif schema['additionalProperties'] is not False:
159 for name in extra:
160 errors += self.check(schema['additionalProperties'], instance[name], path + [name])[0]
161 for subschema in schema.get('allOf', []):
162 found, keys = apply(subschema)
163 errors += found
164 evaluated |= keys
165 if 'anyOf' in schema:
166 outcomes = [apply(subschema) for subschema in schema['anyOf']]
167 if all(found for found, _ in outcomes):
168 fail('{!r} is not valid under any of the given schemas'.format(instance),
169 [error for found, _ in outcomes for error in found])
170 for found, keys in outcomes:
171 if not found:
172 evaluated |= keys
173 if 'oneOf' in schema:
174 outcomes = [apply(subschema) for subschema in schema['oneOf']]
175 valid = [keys for found, keys in outcomes if not found]
176 if not valid:
177 fail('{!r} is not valid under any of the given schemas'.format(instance),
178 [error for found, _ in outcomes for error in found])
179 elif len(valid) > 1: 179 ↛ 180line 179 didn't jump to line 180 because the condition on line 179 was never true
180 fail('{!r} is valid under each of {}'.format(instance, ', '.join(
181 repr(subschema) for subschema, (found, _) in zip(schema['oneOf'], outcomes) if not found)))
182 else:
183 evaluated |= valid[0]
184 if 'not' in schema and not apply(schema['not'])[0]:
185 fail('{!r} should not be valid under {!r}'.format(instance, schema['not']))
186 if 'if' in schema:
187 found, keys = apply(schema['if'])
188 branch = 'else' if found else 'then'
189 if not found:
190 evaluated |= keys
191 if branch in schema:
192 found, keys = apply(schema[branch])
193 errors += found
194 if not found:
195 evaluated |= keys
196 if 'unevaluatedProperties' in schema and isinstance(instance, dict):
197 extra = [name for name in instance if name not in evaluated]
198 if schema['unevaluatedProperties'] is False and extra:
199 fail('Unevaluated properties are not allowed ({} {} unexpected)'.format(
200 ', '.join(repr(name) for name in extra), 'was' if len(extra) == 1 else 'were'))
201 elif schema['unevaluatedProperties'] is not False: 201 ↛ 202line 201 didn't jump to line 202 because the condition on line 201 was never true
202 for name in extra:
203 errors += self.check(schema['unevaluatedProperties'], instance[name], path + [name])[0]
204 evaluated.update(instance)
205 unknown = set(schema) - KEYWORDS - ANNOTATIONS
206 if unknown and not all(keyword.startswith('x-') for keyword in unknown): 206 ↛ 207line 206 didn't jump to line 207 because the condition on line 206 was never true
207 raise ValueError('Unsupported schema keywords: ' + ', '.join(sorted(unknown)))
208 return errors, evaluated if not errors else set()
211KEYWORDS = {'$ref', 'type', 'const', 'enum', 'minimum', 'maximum', 'exclusiveMinimum', 'exclusiveMaximum',
212 'minLength', 'maxLength', 'pattern', 'minItems', 'maxItems', 'uniqueItems', 'items', 'required',
213 'minProperties', 'maxProperties', 'dependentRequired', 'properties', 'patternProperties',
214 'propertyNames', 'additionalProperties', 'allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else',
215 'unevaluatedProperties'}
218def validator(schema):
219 """Return a Draft 2020-12 validator with ``is_valid`` and ``iter_errors``."""
220 if Draft202012Validator is not None: 220 ↛ 222line 220 didn't jump to line 222 because the condition on line 220 was always true
221 return Draft202012Validator(schema)
222 return Validator(schema)