Completed
Push — master ( a8a578...6c485c )
by Ramon
19s queued 10s
created

jsons._validation.get_validator()   A

Complexity

Conditions 1

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 12
rs 10
c 0
b 0
f 0
cc 1
nop 2
1
"""
2
PRIVATE MODULE: do not import (from) it directly.
3
4
This module contains functionality for validating objects.
5
"""
6
from typing import Union, Sequence, Callable
7
from jsons._cache import cached
8
from jsons.exceptions import ValidationError
9
from jsons._common_impl import StateHolder, get_class_name
10
from jsons._lizers_impl import _get_lizer
11
12
13
def set_validator(
14
        func: Callable[[type], bool],
15
        cls: Union[type, Sequence[type]],
16
        fork_inst: type = StateHolder) -> None:
17
    """
18
    Set a validator function for the given ``cls``. The function should accept
19
    an instance of the type it should validate and must return ``False`` or
20
    raise any exception in case of a validation failure.
21
    :param func: the function that takes an instance of type ``cls`` and
22
    returns a bool (``True`` if the validation was successful).
23
    :param cls: the type or types that ``func`` is able to validate.
24
    :param fork_inst: if given, it uses this fork of ``JsonSerializable``.
25
    :return: None.
26
    """
27
    if isinstance(cls, Sequence):
28
        for cls_ in cls:
29
            set_validator(func, cls_, fork_inst)
30
    cls_name = get_class_name(cls, fork_inst=fork_inst,
31
                              fully_qualified=True)
32
    fork_inst._validators[cls_name.lower()] = func
33
    fork_inst._classes_validators.append(cls)
34
35
36
@cached
37
def get_validator(
38
        cls: type,
39
        fork_inst: type = StateHolder) -> callable:
40
    """
41
    Return the validator function that would be used for the given ``cls``.
42
    :param cls: the type for which a deserializer is to be returned.
43
    :param fork_inst: if given, it uses this fork of ``JsonSerializable``.
44
    :return: a validator function.
45
    """
46
    return _get_lizer(cls, fork_inst._validators,
47
                      fork_inst._classes_validators, fork_inst)
48
49
50
def validate(
51
        obj: object,
52
        cls: type,
53
        fork_inst: type = StateHolder) -> None:
54
    """
55
    Validate the given ``obj`` with the validator that was registered for
56
    ``cls``. Raises a ``ValidationError`` if the validation failed.
57
    :param obj: the object that is to be validated.
58
    :param cls: the type of which the validator function was registered.
59
    :param fork_inst: if given, it uses this fork of ``JsonSerializable``.
60
    :return: None.
61
    """
62
    validator = get_validator(cls, fork_inst)
63
    result = True
64
    msg = 'Validation failed.'
65
    if validator:
66
        try:
67
            result = validator(obj)
68
        except Exception as err:
69
            if err.args:
70
                msg = err.args[0]
71
            result = False
72
    if not result:
73
        raise ValidationError(msg)
74