Skip to content

Commit 9e56f54

Browse files
winmorreauvipy
andauthored
FloatField will crash if the input is a number that is too big (#8725)
* FloatField will crash if the input is a number that is too big * Added Unit test for float field overflow error catch * Removed random import * Removed additional imported ValidationError * Update rest_framework/fields.py * Update tests/test_fields.py Co-authored-by: Asif Saif Uddin <[email protected]>
1 parent dc300aa commit 9e56f54

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-1
lines changed

rest_framework/fields.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -919,7 +919,8 @@ class FloatField(Field):
919919
'invalid': _('A valid number is required.'),
920920
'max_value': _('Ensure this value is less than or equal to {max_value}.'),
921921
'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
922-
'max_string_length': _('String value too large.')
922+
'max_string_length': _('String value too large.'),
923+
'overflow': _('Integer value too large to convert to float')
923924
}
924925
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
925926

@@ -945,6 +946,8 @@ def to_internal_value(self, data):
945946
return float(data)
946947
except (TypeError, ValueError):
947948
self.fail('invalid')
949+
except OverflowError:
950+
self.fail('overflow')
948951

949952
def to_representation(self, value):
950953
return float(value)

tests/test_fields.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import datetime
2+
import math
23
import os
34
import re
45
import uuid
@@ -1072,6 +1073,14 @@ class TestMinMaxFloatField(FieldValues):
10721073
field = serializers.FloatField(min_value=1, max_value=3)
10731074

10741075

1076+
class TestFloatFieldOverFlowError(TestCase):
1077+
def test_overflow_error_float_field(self):
1078+
field = serializers.FloatField()
1079+
with pytest.raises(serializers.ValidationError) as exec_info:
1080+
field.to_internal_value(data=math.factorial(171))
1081+
assert "Integer value too large to convert to float" in str(exec_info.value.detail)
1082+
1083+
10751084
class TestDecimalField(FieldValues):
10761085
"""
10771086
Valid and invalid values for `DecimalField`.

0 commit comments

Comments
 (0)