10000 change name and usage, start tests · ag-python/pydantic@0b509d3 · GitHub
[go: up one dir, main page]

Skip to content

Commit 0b509d3

Browse files
committed
change name and usage, start tests
1 parent 0451b33 commit 0b509d3

File tree

2 files changed

+29
-12
lines changed

2 files changed

+29
-12
lines changed

pydantic/decorator.py

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from functools import wraps
2-
from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Tuple, TypeVar, cast, get_type_hints
2+
from typing import TYPE_CHECKING, Any, Dict, List, Mapping, Tuple, Type, TypeVar, Union, cast, get_type_hints
33

44
from . import validator
55
from .errors import ConfigError
@@ -12,15 +12,16 @@
1212
from .typing import AnyCallable
1313

1414
Callable = TypeVar('Callable', bound=AnyCallable)
15+
ConfigType = Union[None, Type[Any], Dict[str, Any]]
1516

1617

17-
def validate_arguments(func: 'Callable' = None, **config_params: Any) -> 'Callable':
18+
def validate_arguments(func: 'Callable' = None, *, config: 'ConfigType' = None) -> 'Callable':
1819
"""
1920
Decorator to validate the arguments passed to a function.
2021
"""
2122

2223
def validate(_func: 'Callable') -> 'Callable':
23-
vd = ValidatedFunction(_func, **config_params)
24+
vd = ValidatedFunction(_func, config)
2425

2526
@wraps(_func)
2627
def wrapper_function(*args: Any, **kwargs: Any) -> Any:
@@ -43,7 +44,7 @@ def wrapper_function(*args: Any, **kwargs: Any) -> Any:
4344

4445

4546
class ValidatedFunction:
46-
def __init__(self, function: 'Callable', **config_params: Any):
47+
def __init__(self, function: 'Callable', config: 'ConfigType'):
4748
from inspect import signature, Parameter
4849

4950
parameters: Mapping[str, Parameter] = signature(function).parameters
@@ -107,7 +108,7 @@ def __init__(self, function: 'Callable', **config_params: Any):
107108
# same with kwargs
108109
fields[self.v_kwargs_name] = Dict[Any, Any], None
109110

110-
self.create_model(fields, takes_args, takes_kwargs, **config_params)
111+
self.create_model(fields, takes_args, takes_kwargs, config)
111112

112113
def call(self, *args: Any, **kwargs: Any) -> Any:
113114
values = self.build_values(args, kwargs)
@@ -177,16 +178,17 @@ def execute(self, m: BaseModel) -> Any:
177178
else:
178179
return self.raw_function(**d)
179180

180-
def create_model(self, fields: Dict[str, Any], takes_args: bool, takes_kwargs: bool, **config_params: Any) -> None:
181+
def create_model(self, fields: Dict[str, Any], takes_args: bool, takes_kwargs: bool, config: 'ConfigType') -> None:
181182
pos_args = len(self.arg_mapping)
182183

183-
if TYPE_CHECKING:
184+
class CustomConfig:
185+
pass
184186

185-
class CustomConfig:
186-
pass
187-
188-
else:
189-
CustomConfig = type('Config', (), config_params)
187+
if not TYPE_CHECKING:
188+
if isinstance(config, dict):
189+
CustomConfig = type('Config', (), config)
190+
elif config is not None:
191+
CustomConfig = config
190192

191193
class DecoratorBaseModel(BaseModel):
192194
@validator(self.v_args_name, check_fields=False, allow_reuse=True)

tests/test_decorator.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ def foo_bar(a: int, b: int):
7070
assert issubclass(foo_bar.model, BaseModel)
7171
assert foo_bar.model.__fields__.keys() == {'a', 'b', 'args', 'kwargs'}
7272
assert foo_bar.model.__name__ == 'FooBar'
73+
assert foo_bar.model.schema()['title'] == 'FooBar'
7374
# signature is slightly different on 3.6
7475
if sys.version_info >= (3, 7):
7576
assert repr(inspect.signature(foo_bar)) == '<Signature (a: int, b: int)>'
@@ -262,3 +263,17 @@ def foo(cls, a: int, b: int):
262263
{'loc': ('a',), 'msg': 'field required', 'type': 'value_error.missing'},
263264
{'loc': ('b',), 'msg': 'field required', 'type': 'value_error.missing'},
264265
]
266+
267+
268+
def test_config():
269+
@validate_arguments(config=dict(title='testing', fields={'b': 'bang'}))
270+
def foo(a: int, b: int):
271+
return f'{a}, {b}'
272+
273+
assert foo(1, 2) == '1, 2'
274+
assert foo(1, bang=2) == '1, 2'
275+
assert foo.model.schema()['title'] == 'testing'
276+
with pytest.raises(ValidationError) as exc_info:
277+
foo(1, b=2)
278+
279+
assert exc_info.value.errors() == ...

0 commit comments

Comments
 (0)
0