From ed2b3f2afd7e329455ec0183af8d1ae07baa7714 Mon Sep 17 00:00:00 2001 From: Samuel Colvin Date: Wed, 8 Nov 2017 15:36:19 +0000 Subject: [PATCH] errors for invalid validator use --- HISTORY.rst | 4 ++++ pydantic/main.py | 6 ++++++ tests/test_validators.py | 20 ++++++++++++++++++++ 3 files changed, 30 insertions(+) diff --git a/HISTORY.rst b/HISTORY.rst index e73a58a..99b52aa 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -3,6 +3,10 @@ History ------- +v0.6.2 (2017-11-XX) +................... +* errors for invalid validator use + v0.6.1 (2017-11-08) ................... * prevent duplicate validators, #101 diff --git a/pydantic/main.py b/pydantic/main.py index 2144698..f5ea6a0 100644 --- a/pydantic/main.py +++ b/pydantic/main.py @@ -318,6 +318,12 @@ def validator(*fields, pre: bool=False, whole: bool=False, always: bool=False): :param whole: for complex objects (sets, lists etc.) whether to validate individual elements or the whole object :param always: whether this method and other validators should be called even if the value is missing """ + if not fields: + raise ConfigError('validator with no fields specified') + elif isinstance(fields[0], FunctionType): + raise ConfigError("validators should be used with fields and keyword arguments, not bare. " + "E.g. usage should be `@validator('', ...)`") + def dec(f): ref = f.__module__ + '.' + f.__qualname__ if ref in _FUNCS: diff --git a/tests/test_validators.py b/tests/test_validators.py index fb34820..0520c36 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -177,6 +177,26 @@ def test_duplicates(): '"tests.test_validators.test_duplicates..Model.duplicate_name"') +def test_use_bare(): + with pytest.raises(ConfigError): + class Model(BaseModel): + a: str + + @validator + def checker(cls, v): + return v + + +def test_use_no_fields(): + with pytest.raises(ConfigError): + class Model(BaseModel): + a: str + + @validator() + def checker(cls, v): + return v + + def test_validate_always(): check_calls = 0