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 <auvipy@gmail.com>
This commit is contained in:
Jason Joy Atsu Winmorre 2022-11-22 05:15:25 +00:00 committed by GitHub
parent dc300aa4e0
commit 9e56f54efb
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 1 deletions

View File

@ -919,7 +919,8 @@ class FloatField(Field):
'invalid': _('A valid number is required.'), 'invalid': _('A valid number is required.'),
'max_value': _('Ensure this value is less than or equal to {max_value}.'), 'max_value': _('Ensure this value is less than or equal to {max_value}.'),
'min_value': _('Ensure this value is greater than or equal to {min_value}.'), 'min_value': _('Ensure this value is greater than or equal to {min_value}.'),
'max_string_length': _('String value too large.') 'max_string_length': _('String value too large.'),
'overflow': _('Integer value too large to convert to float')
} }
MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs. MAX_STRING_LENGTH = 1000 # Guard against malicious string inputs.
@ -945,6 +946,8 @@ class FloatField(Field):
return float(data) return float(data)
except (TypeError, ValueError): except (TypeError, ValueError):
self.fail('invalid') self.fail('invalid')
except OverflowError:
self.fail('overflow')
def to_representation(self, value): def to_representation(self, value):
return float(value) return float(value)

View File

@ -1,4 +1,5 @@
import datetime import datetime
import math
import os import os
import re import re
import uuid import uuid
@ -1072,6 +1073,14 @@ class TestMinMaxFloatField(FieldValues):
field = serializers.FloatField(min_value=1, max_value=3) field = serializers.FloatField(min_value=1, max_value=3)
class TestFloatFieldOverFlowError(TestCase):
def test_overflow_error_float_field(self):
field = serializers.FloatField()
with pytest.raises(serializers.ValidationError) as exec_info:
field.to_internal_value(data=math.factorial(171))
assert "Integer value too large to convert to float" in str(exec_info.value.detail)
class TestDecimalField(FieldValues): class TestDecimalField(FieldValues):
""" """
Valid and invalid values for `DecimalField`. Valid and invalid values for `DecimalField`.