| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import collections |
| 4 |
import contextlib |
| 5 |
import os.path |
| 6 |
import re |
| 7 |
import sys |
| 8 |
|
| 9 |
|
| 10 |
class ValidationError(ValueError): |
| 11 |
def __init__(self, error_msg, ctx=None): |
| 12 |
super().__init__(error_msg) |
| 13 |
self.error_msg = error_msg |
| 14 |
self.ctx = ctx |
| 15 |
|
| 16 |
def __str__(self): |
| 17 |
out = '\n' |
| 18 |
err = self |
| 19 |
while err.ctx is not None: |
| 20 |
out += f'==> {err.ctx}\n' |
| 21 |
err = err.error_msg |
| 22 |
out += f'=====> {err.error_msg}' |
| 23 |
return out |
| 24 |
|
| 25 |
|
| 26 |
MISSING = collections.namedtuple('Missing', ())() |
| 27 |
type(MISSING).__repr__ = lambda self: 'MISSING' |
| 28 |
|
| 29 |
|
| 30 |
@contextlib.contextmanager |
| 31 |
def validate_context(msg): |
| 32 |
try: |
| 33 |
yield |
| 34 |
except ValidationError as e: |
| 35 |
_, _, tb = sys.exc_info() |
| 36 |
raise ValidationError(e, ctx=msg).with_traceback(tb) from None |
| 37 |
|
| 38 |
|
| 39 |
@contextlib.contextmanager |
| 40 |
def reraise_as(tp): |
| 41 |
try: |
| 42 |
yield |
| 43 |
except ValidationError as e: |
| 44 |
_, _, tb = sys.exc_info() |
| 45 |
raise tp(e).with_traceback(tb) from None |
| 46 |
|
| 47 |
|
| 48 |
def _dct_noop(self, dct): |
| 49 |
pass |
| 50 |
|
| 51 |
|
| 52 |
def _check_optional(self, dct): |
| 53 |
if self.key not in dct: |
| 54 |
return |
| 55 |
with validate_context(f'At key: {self.key}'): |
| 56 |
self.check_fn(dct[self.key]) |
| 57 |
|
| 58 |
|
| 59 |
def _apply_default_optional(self, dct): |
| 60 |
dct.setdefault(self.key, self.default) |
| 61 |
|
| 62 |
|
| 63 |
def _remove_default_optional(self, dct): |
| 64 |
if dct.get(self.key, MISSING) == self.default: |
| 65 |
del dct[self.key] |
| 66 |
|
| 67 |
|
| 68 |
def _require_key(self, dct): |
| 69 |
if self.key not in dct: |
| 70 |
raise ValidationError(f'Missing required key: {self.key}') |
| 71 |
|
| 72 |
|
| 73 |
def _check_required(self, dct): |
| 74 |
_require_key(self, dct) |
| 75 |
_check_optional(self, dct) |
| 76 |
|
| 77 |
|
| 78 |
@property |
| 79 |
def _check_fn_recurse(self): |
| 80 |
def check_fn(val): |
| 81 |
validate(val, self.schema) |
| 82 |
return check_fn |
| 83 |
|
| 84 |
|
| 85 |
def _apply_default_required_recurse(self, dct): |
| 86 |
dct[self.key] = apply_defaults(dct[self.key], self.schema) |
| 87 |
|
| 88 |
|
| 89 |
def _remove_default_required_recurse(self, dct): |
| 90 |
dct[self.key] = remove_defaults(dct[self.key], self.schema) |
| 91 |
|
| 92 |
|
| 93 |
def _apply_default_optional_recurse(self, dct): |
| 94 |
if self.key not in dct: |
| 95 |
_apply_default_optional(self, dct) |
| 96 |
_apply_default_required_recurse(self, dct) |
| 97 |
|
| 98 |
|
| 99 |
def _remove_default_optional_recurse(self, dct): |
| 100 |
if self.key in dct: |
| 101 |
_remove_default_required_recurse(self, dct) |
| 102 |
_remove_default_optional(self, dct) |
| 103 |
|
| 104 |
|
| 105 |
def _get_check_conditional(inner): |
| 106 |
def _check_conditional(self, dct): |
| 107 |
if dct.get(self.condition_key, MISSING) == self.condition_value: |
| 108 |
inner(self, dct) |
| 109 |
elif ( |
| 110 |
self.condition_key in dct and |
| 111 |
self.ensure_absent and self.key in dct |
| 112 |
): |
| 113 |
if hasattr(self.condition_value, 'describe_opposite'): |
| 114 |
explanation = self.condition_value.describe_opposite() |
| 115 |
else: |
| 116 |
explanation = f'is not {self.condition_value!r}' |
| 117 |
raise ValidationError( |
| 118 |
f'Expected {self.key} to be absent when {self.condition_key} ' |
| 119 |
f'{explanation}, found {self.key}: {dct[self.key]!r}', |
| 120 |
) |
| 121 |
return _check_conditional |
| 122 |
|
| 123 |
|
| 124 |
def _apply_default_conditional_optional(self, dct): |
| 125 |
if dct.get(self.condition_key, MISSING) == self.condition_value: |
| 126 |
_apply_default_optional(self, dct) |
| 127 |
|
| 128 |
|
| 129 |
def _remove_default_conditional_optional(self, dct): |
| 130 |
if dct.get(self.condition_key, MISSING) == self.condition_value: |
| 131 |
_remove_default_optional(self, dct) |
| 132 |
|
| 133 |
|
| 134 |
def _apply_default_conditional_recurse(self, dct): |
| 135 |
if dct.get(self.condition_key, MISSING) == self.condition_value: |
| 136 |
_apply_default_required_recurse(self, dct) |
| 137 |
|
| 138 |
|
| 139 |
def _remove_default_conditional_recurse(self, dct): |
| 140 |
if dct.get(self.condition_key, MISSING) == self.condition_value: |
| 141 |
_remove_default_required_recurse(self, dct) |
| 142 |
|
| 143 |
|
| 144 |
def _no_additional_keys_check(self, dct): |
| 145 |
extra = sorted(set(dct) - set(self.keys)) |
| 146 |
if extra: |
| 147 |
extra_s = ', '.join(str(x) for x in extra) |
| 148 |
keys_s = ', '.join(str(x) for x in self.keys) |
| 149 |
raise ValidationError( |
| 150 |
f'Additional keys found: {extra_s}. ' |
| 151 |
f'Only these keys are allowed: {keys_s}', |
| 152 |
) |
| 153 |
|
| 154 |
|
| 155 |
def _warn_additional_keys_check(self, dct): |
| 156 |
extra = sorted(set(dct) - set(self.keys)) |
| 157 |
if extra: |
| 158 |
self.callback(extra, self.keys, dct) |
| 159 |
|
| 160 |
|
| 161 |
Required = collections.namedtuple('Required', ('key', 'check_fn')) |
| 162 |
Required.check = _check_required |
| 163 |
Required.apply_default = _dct_noop |
| 164 |
Required.remove_default = _dct_noop |
| 165 |
RequiredRecurse = collections.namedtuple('RequiredRecurse', ('key', 'schema')) |
| 166 |
RequiredRecurse.check = _check_required |
| 167 |
RequiredRecurse.check_fn = _check_fn_recurse |
| 168 |
RequiredRecurse.apply_default = _apply_default_required_recurse |
| 169 |
RequiredRecurse.remove_default = _remove_default_required_recurse |
| 170 |
Optional = collections.namedtuple('Optional', ('key', 'check_fn', 'default')) |
| 171 |
Optional.check = _check_optional |
| 172 |
Optional.apply_default = _apply_default_optional |
| 173 |
Optional.remove_default = _remove_default_optional |
| 174 |
OptionalRecurse = collections.namedtuple( |
| 175 |
'OptionalRecurse', ('key', 'schema', 'default'), |
| 176 |
) |
| 177 |
OptionalRecurse.check = _check_optional |
| 178 |
OptionalRecurse.check_fn = _check_fn_recurse |
| 179 |
OptionalRecurse.apply_default = _apply_default_optional_recurse |
| 180 |
OptionalRecurse.remove_default = _remove_default_optional_recurse |
| 181 |
OptionalNoDefault = collections.namedtuple( |
| 182 |
'OptionalNoDefault', ('key', 'check_fn'), |
| 183 |
) |
| 184 |
OptionalNoDefault.check = _check_optional |
| 185 |
OptionalNoDefault.apply_default = _dct_noop |
| 186 |
OptionalNoDefault.remove_default = _dct_noop |
| 187 |
Conditional = collections.namedtuple( |
| 188 |
'Conditional', |
| 189 |
('key', 'check_fn', 'condition_key', 'condition_value', 'ensure_absent'), |
| 190 |
) |
| 191 |
Conditional.__new__.__defaults__ = (False,) |
| 192 |
Conditional.check = _get_check_conditional(_check_required) |
| 193 |
Conditional.apply_default = _dct_noop |
| 194 |
Conditional.remove_default = _dct_noop |
| 195 |
ConditionalOptional = collections.namedtuple( |
| 196 |
'ConditionalOptional', |
| 197 |
( |
| 198 |
'key', 'check_fn', 'default', 'condition_key', 'condition_value', |
| 199 |
'ensure_absent', |
| 200 |
), |
| 201 |
) |
| 202 |
ConditionalOptional.__new__.__defaults__ = (False,) |
| 203 |
ConditionalOptional.check = _get_check_conditional(_check_optional) |
| 204 |
ConditionalOptional.apply_default = _apply_default_conditional_optional |
| 205 |
ConditionalOptional.remove_default = _remove_default_conditional_optional |
| 206 |
ConditionalRecurse = collections.namedtuple( |
| 207 |
'ConditionalRecurse', |
| 208 |
('key', 'schema', 'condition_key', 'condition_value', 'ensure_absent'), |
| 209 |
) |
| 210 |
ConditionalRecurse.__new__.__defaults__ = (False,) |
| 211 |
ConditionalRecurse.check = _get_check_conditional(_check_required) |
| 212 |
ConditionalRecurse.check_fn = _check_fn_recurse |
| 213 |
ConditionalRecurse.apply_default = _apply_default_conditional_recurse |
| 214 |
ConditionalRecurse.remove_default = _remove_default_conditional_recurse |
| 215 |
NoAdditionalKeys = collections.namedtuple('NoAdditionalKeys', ('keys',)) |
| 216 |
NoAdditionalKeys.check = _no_additional_keys_check |
| 217 |
NoAdditionalKeys.apply_default = _dct_noop |
| 218 |
NoAdditionalKeys.remove_default = _dct_noop |
| 219 |
WarnAdditionalKeys = collections.namedtuple( |
| 220 |
'WarnAdditionalKeys', ('keys', 'callback'), |
| 221 |
) |
| 222 |
WarnAdditionalKeys.check = _warn_additional_keys_check |
| 223 |
WarnAdditionalKeys.apply_default = _dct_noop |
| 224 |
WarnAdditionalKeys.remove_default = _dct_noop |
| 225 |
|
| 226 |
|
| 227 |
class Map(collections.namedtuple('Map', ('object_name', 'id_key', 'items'))): |
| 228 |
__slots__ = () |
| 229 |
|
| 230 |
def __new__(cls, object_name, id_key, *items): |
| 231 |
return super().__new__(cls, object_name, id_key, items) |
| 232 |
|
| 233 |
def check(self, v): |
| 234 |
if not isinstance(v, dict): |
| 235 |
raise ValidationError( |
| 236 |
f'Expected a {self.object_name} map but got a ' |
| 237 |
f'{type(v).__name__}', |
| 238 |
) |
| 239 |
if self.id_key is None: |
| 240 |
context = f'At {self.object_name}()' |
| 241 |
else: |
| 242 |
key_v_s = v.get(self.id_key, MISSING) |
| 243 |
context = f'At {self.object_name}({self.id_key}={key_v_s!r})' |
| 244 |
with validate_context(context): |
| 245 |
for item in self.items: |
| 246 |
item.check(v) |
| 247 |
|
| 248 |
def apply_defaults(self, v): |
| 249 |
ret = v.copy() |
| 250 |
for item in self.items: |
| 251 |
item.apply_default(ret) |
| 252 |
return ret |
| 253 |
|
| 254 |
def remove_defaults(self, v): |
| 255 |
ret = v.copy() |
| 256 |
for item in self.items: |
| 257 |
item.remove_default(ret) |
| 258 |
return ret |
| 259 |
|
| 260 |
|
| 261 |
class KeyValueMap( |
| 262 |
collections.namedtuple( |
| 263 |
'KeyValueMap', |
| 264 |
('object_name', 'check_key_fn', 'value_schema'), |
| 265 |
), |
| 266 |
): |
| 267 |
__slots__ = () |
| 268 |
|
| 269 |
def check(self, v): |
| 270 |
if not isinstance(v, dict): |
| 271 |
raise ValidationError( |
| 272 |
f'Expected a {self.object_name} map but got a ' |
| 273 |
f'{type(v).__name__}', |
| 274 |
) |
| 275 |
with validate_context(f'At {self.object_name}()'): |
| 276 |
for k, val in v.items(): |
| 277 |
with validate_context(f'For key: {k}'): |
| 278 |
self.check_key_fn(k) |
| 279 |
with validate_context(f'At key: {k}'): |
| 280 |
validate(val, self.value_schema) |
| 281 |
|
| 282 |
def apply_defaults(self, v): |
| 283 |
return { |
| 284 |
k: apply_defaults(val, self.value_schema) |
| 285 |
for k, val in v.items() |
| 286 |
} |
| 287 |
|
| 288 |
def remove_defaults(self, v): |
| 289 |
return { |
| 290 |
k: remove_defaults(val, self.value_schema) |
| 291 |
for k, val in v.items() |
| 292 |
} |
| 293 |
|
| 294 |
|
| 295 |
class Array(collections.namedtuple('Array', ('of', 'allow_empty'))): |
| 296 |
__slots__ = () |
| 297 |
|
| 298 |
def __new__(cls, of, allow_empty=True): |
| 299 |
return super().__new__(cls, of=of, allow_empty=allow_empty) |
| 300 |
|
| 301 |
def check(self, v): |
| 302 |
check_array(check_any)(v) |
| 303 |
if not self.allow_empty and not v: |
| 304 |
raise ValidationError( |
| 305 |
f"Expected at least 1 '{self.of.object_name}'", |
| 306 |
) |
| 307 |
for val in v: |
| 308 |
validate(val, self.of) |
| 309 |
|
| 310 |
def apply_defaults(self, v): |
| 311 |
return [apply_defaults(val, self.of) for val in v] |
| 312 |
|
| 313 |
def remove_defaults(self, v): |
| 314 |
return [remove_defaults(val, self.of) for val in v] |
| 315 |
|
| 316 |
|
| 317 |
class Not(collections.namedtuple('Not', ('val',))): |
| 318 |
__slots__ = () |
| 319 |
|
| 320 |
def describe_opposite(self): |
| 321 |
return f'is {self.val!r}' |
| 322 |
|
| 323 |
def __eq__(self, other): |
| 324 |
return other is not MISSING and other != self.val |
| 325 |
|
| 326 |
|
| 327 |
class NotIn(collections.namedtuple('NotIn', ('values',))): |
| 328 |
__slots__ = () |
| 329 |
|
| 330 |
def __new__(cls, *values): |
| 331 |
return super().__new__(cls, values=values) |
| 332 |
|
| 333 |
def describe_opposite(self): |
| 334 |
return f'is any of {self.values!r}' |
| 335 |
|
| 336 |
def __eq__(self, other): |
| 337 |
return other is not MISSING and other not in self.values |
| 338 |
|
| 339 |
|
| 340 |
class In(collections.namedtuple('In', ('values',))): |
| 341 |
__slots__ = () |
| 342 |
|
| 343 |
def __new__(cls, *values): |
| 344 |
return super().__new__(cls, values=values) |
| 345 |
|
| 346 |
def describe_opposite(self): |
| 347 |
return f'is not any of {self.values!r}' |
| 348 |
|
| 349 |
def __eq__(self, other): |
| 350 |
return other is not MISSING and other in self.values |
| 351 |
|
| 352 |
|
| 353 |
def check_any(_): |
| 354 |
pass |
| 355 |
|
| 356 |
|
| 357 |
def check_type(tp, typename=None): |
| 358 |
def check_type_fn(v): |
| 359 |
if not isinstance(v, tp): |
| 360 |
typename_s = typename or tp.__name__ |
| 361 |
raise ValidationError( |
| 362 |
f'Expected {typename_s} got {type(v).__name__}', |
| 363 |
) |
| 364 |
return check_type_fn |
| 365 |
|
| 366 |
|
| 367 |
check_bool = check_type(bool) |
| 368 |
check_bytes = check_type(bytes) |
| 369 |
check_int = check_type(int) |
| 370 |
check_string = check_type(str, typename='string') |
| 371 |
check_text = check_type(str, typename='text') |
| 372 |
|
| 373 |
|
| 374 |
def check_one_of(possible): |
| 375 |
def check_one_of_fn(v): |
| 376 |
if v not in possible: |
| 377 |
possible_s = ', '.join(str(x) for x in sorted(possible)) |
| 378 |
raise ValidationError( |
| 379 |
f'Expected one of {possible_s} but got: {v!r}', |
| 380 |
) |
| 381 |
return check_one_of_fn |
| 382 |
|
| 383 |
|
| 384 |
def check_regex(v): |
| 385 |
try: |
| 386 |
re.compile(v) |
| 387 |
except re.error: |
| 388 |
raise ValidationError(f'{v!r} is not a valid python regex') |
| 389 |
|
| 390 |
|
| 391 |
def check_array(inner_check): |
| 392 |
def check_array_fn(v): |
| 393 |
if not isinstance(v, (list, tuple)): |
| 394 |
raise ValidationError( |
| 395 |
f'Expected array but got {type(v).__name__!r}', |
| 396 |
) |
| 397 |
|
| 398 |
for i, val in enumerate(v): |
| 399 |
with validate_context(f'At index {i}'): |
| 400 |
inner_check(val) |
| 401 |
return check_array_fn |
| 402 |
|
| 403 |
|
| 404 |
def check_and(*fns): |
| 405 |
def check(v): |
| 406 |
for fn in fns: |
| 407 |
fn(v) |
| 408 |
return check |
| 409 |
|
| 410 |
|
| 411 |
def validate(v, schema): |
| 412 |
schema.check(v) |
| 413 |
return v |
| 414 |
|
| 415 |
|
| 416 |
def apply_defaults(v, schema): |
| 417 |
return schema.apply_defaults(v) |
| 418 |
|
| 419 |
|
| 420 |
def remove_defaults(v, schema): |
| 421 |
return schema.remove_defaults(v) |
| 422 |
|
| 423 |
|
| 424 |
def load_from_filename( |
| 425 |
filename, |
| 426 |
schema, |
| 427 |
load_strategy, |
| 428 |
exc_tp=ValidationError, |
| 429 |
*, |
| 430 |
display_filename=None, |
| 431 |
): |
| 432 |
display_filename = display_filename or filename |
| 433 |
with reraise_as(exc_tp): |
| 434 |
if not os.path.isfile(filename): |
| 435 |
raise ValidationError(f'{display_filename} is not a file') |
| 436 |
|
| 437 |
with validate_context(f'File {display_filename}'): |
| 438 |
try: |
| 439 |
with open(filename, encoding='utf-8') as f: |
| 440 |
contents = f.read() |
| 441 |
except UnicodeDecodeError as e: |
| 442 |
raise ValidationError(str(e)) |
| 443 |
|
| 444 |
try: |
| 445 |
data = load_strategy(contents) |
| 446 |
except Exception as e: |
| 447 |
raise ValidationError(str(e)) |
| 448 |
|
| 449 |
validate(data, schema) |
| 450 |
return apply_defaults(data, schema) |