8000 fix int_validator not catching overflows by ojii · Pull Request #3112 · pydantic/pydantic · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/3112-ojii.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Catch overflow errors in `int_validator`
2 changes: 1 addition & 1 deletion pydantic/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def int_validator(v: Any) -> int:

try:
return int(v)
except (TypeError, ValueError):
except (TypeError, ValueError, OverflowError):
raise errors.IntegerError()
Comment on lines +128 to 129
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
except (TypeError, ValueError, OverflowError):
raise errors.IntegerError()
except (TypeError, ValueError):
raise errors.IntegerError()
except OverflowError:
raise errors.IntegerOverflowError()

I think this is meant.

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Then, like 144

-        return float(v)
+        rv = float(v)
+        if rv in (float("inf"), float("-inf")):
+            raise errors.FloatOverflowError()
+        if rv != rv:
+            raise errors.FloatNanError()
+        return rv

P.S. the weird line of code from https://stackoverflow.com/a/44154660/705086

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

floats are a separate case. I would say that float('inf') is a valid float, arguably so is float('nan').



Expand Down
12 changes: 12 additions & 0 deletions tests/test_validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,18 @@ class Model(BaseModel):
assert Model(a=4.5).a == 4


@pytest.mark.parametrize('value', [2.2250738585072011e308, float('nan'), float('inf')])
def test_int_overflow_validation(value):
class Model(BaseModel):
a: int

with pytest.raises(ValidationError) as exc_info:
Model(a=value)
assert exc_info.value.errors() == [
{'loc': ('a',), 'msg': 'value is not a valid integer', 'type': 'type_error.integer'}
]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can you add the case of passing float('inf') etc.



def test_frozenset_validation():
class Model(BaseModel):
a: frozenset
Expand Down
0