Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

None behaviour #803

Merged
merged 18 commits into from Sep 18, 2019
Merged
Changes from 1 commit
Commits
File filter...
Filter file types
Jump to…
Jump to file or symbol
Failed to load files and symbols.

Always

Just for now

fix validators on optional fields

  • Loading branch information
samuelcolvin committed Sep 16, 2019
commit 743c1886d14715081caed6314403ea5bec6eac44
@@ -313,7 +313,10 @@ def validate(

if v is None:
if self.allow_none:
return None, None
if self.post_validators:
return self._apply_validators(v, values, loc, cls, self.post_validators)
else:
return None, None
else:
return v, ErrorWrapper(NoneIsNotAllowedError(), loc=loc)

@@ -1285,6 +1285,26 @@ class Model(BaseModel):
assert Model(something={'foo': 'Bar'}).dict() == {'something': {'foo': 'Bar'}}


def test_optional_validator():
class Model(BaseModel):
something: Optional[str]

@validator('something', always=True)
def check_something(cls, v):
assert v is None or 'x' not in v, 'should not contain x'
return v

assert Model.schema() == {
'title': 'Model',
'type': 'object',
'properties': {'something': {'title': 'Something', 'type': 'string'}},
}

assert Model().dict() == {'something': None}
assert Model(something=None).dict() == {'something': None}
assert Model(something='hello').dict() == {'something': 'hello'}


def test_field_with_validator():
class Model(BaseModel):
something: Optional[int] = None
@@ -524,7 +524,7 @@ def check_a(cls, v):
return v or 'default value'

assert Model(a='y').a == 'y'
assert Model().a is None
assert Model().a == 'default value'


def test_validator_always_post_optional():
@@ -670,3 +670,20 @@ def check_a(cls, v):
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': f'invalid a{injected_by_pytest}', 'type': 'assertion_error'}
]


def test_optional_validator():
val_calls = []

class Model(BaseModel):
something: Optional[str]

@validator('something')
def check_something(cls, v):
val_calls.append(v)
return v

assert Model().dict() == {'something': None}
assert Model(something=None).dict() == {'something': None}
assert Model(something='hello').dict() == {'something': 'hello'}
assert val_calls == [None, 'hello']
ProTip! Use n and p to navigate between commits in a pull request.
You can’t perform that action at this time.