Skip to content

Commit

Permalink
Don't ignore all exceptions during coercion for nullable fields
Browse files Browse the repository at this point in the history
Only ignore exceptions if a value for a nullable field is not null.
Previously all exceptions during custom coerction were ignored with nullable
fields. The developer and/or user most likely wants to know about
exceptions that happen during coercion - this leads to hard to debug
problems otherwise.

The purpose of the `e is not TypeError` condition was unclear. As far as I
know this condition can never be false (`e` is an instance of an exception,
not an exception class).

I think this is still in line with the original intent of this code, which
was to make common coercions like `float` work with nullable fields out
of the box: #269
  • Loading branch information
Nik Haldimann committed May 2, 2019
1 parent c4081a7 commit 7921688
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
9 changes: 9 additions & 0 deletions cerberus/tests/test_normalization.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,6 +170,15 @@ def test_nullables_dont_fail_coerce():
assert_normalized(document, document, schema)


def test_nullables_fail_coerce_on_non_null_values(validator):
schema = {'foo': {'coerce': lambda x: 1 / 0, 'nullable': True, 'type': 'integer'}}
document = {'foo': None}
assert_normalized(document, document, schema)

validator({'foo': 2}, schema)
assert errors.COERCION_FAILED in validator._errors


def test_normalized():
schema = {'amount': {'coerce': int}}
document = {'amount': '2'}
Expand Down
2 changes: 1 addition & 1 deletion cerberus/validator.py
Original file line number Diff line number Diff line change
Expand Up @@ -723,7 +723,7 @@ def __normalize_coerce(self, processor, field, value, nullable, error):
try:
return processor(value)
except Exception as e:
if not nullable and e is not TypeError:
if not nullable or value is not None:
self._error(field, error, str(e))
return value

Expand Down

0 comments on commit 7921688

Please sign in to comment.