1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
|
import pytest
from pydantic_core import SchemaValidator, ValidationError
from pydantic_core import core_schema as cs
def func():
return 42
class Foo:
pass
class CallableClass:
def __call__(self, *args, **kwargs):
pass
def test_callable():
v = SchemaValidator(cs.callable_schema())
assert v.validate_python(func) == func
assert v.isinstance_python(func) is True
with pytest.raises(ValidationError) as exc_info:
v.validate_python(42)
assert exc_info.value.errors(include_url=False) == [
{'type': 'callable_type', 'loc': (), 'msg': 'Input should be callable', 'input': 42}
]
@pytest.mark.parametrize(
'input_value,expected',
[
(func, True),
(lambda: 42, True),
(lambda x: 2 * 42, True),
(dict, True),
(Foo, True),
(Foo(), False),
(4, False),
('ddd', False),
([], False),
((1,), False),
(CallableClass, True),
(CallableClass(), True),
],
)
def test_callable_cases(input_value, expected):
v = SchemaValidator(cs.callable_schema())
assert v.isinstance_python(input_value) == expected
def test_repr():
v = SchemaValidator(cs.union_schema(choices=[cs.int_schema(), cs.callable_schema()]))
assert v.isinstance_python(4) is True
assert v.isinstance_python(func) is True
assert v.isinstance_python('foo') is False
with pytest.raises(ValidationError, match=r'callable\s+Input should be callable'):
v.validate_python('foo')
|