marshmallow-code / marshmallow-code/marshmallow
Incorrect Integer validation for Floats
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 7.2k
- Forks
- 738
- Avg merge
- 1d 23h
- Merged PRs (30d)
- 7
Description
When supplying a float value to a schema whose field is registered as `Integer`, Marshmallow will implicitly cast the given float to an integer, without raising errors, even when attempting to force strictness.
e.g.: a given value of 0.15 will be silently cast to 0, of type `int`.
This behaviour comes from the definition of the constructor for the Integer field. Line 707 in `fields.py`:
```
# override Number
def __init__(self, strict=False, **kwargs):
self.strict = strict
super(Integer, self).__init__(**kwargs)
```
`strict=False` is the culprit.
This comes into effect when we format the value:
```
# override Number
def _format_num(self, value):
if self.strict and isinstance(value, numbers.Number): # this condition will never be satisfied!
if not isinstance(value, numbers.Integral):
self.fail('invalid')
return super(Integer, self)._format_num(value)
```
Cannot seem to stop this by setting the strictness via the schema object either.
Expected output would be: `ValidationError: {'your_value': [u'Not a valid integer.']`}
Thoughts?
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start in fields.py at the Integer constructor and _format_num method described in the issue. Reproduce deserialization of a float such as 0.15 with strictness enabled, then verify that the invalid value raises the expected ValidationError instead of being cast to an integer.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- backend
- Issue type
- Bug
- Difficulty
- 2/5
- Estimated time
- 1-3 hours
- Activity status
- Stale
- Clarity
- Clearly specified
- Newbie friendliness
- 58/100