From 9e56f54efb422459dc8765caa1fd1a21ce583039 Mon Sep 17 00:00:00 2001 From: Jason Joy Atsu Winmorre <78548837+winmorre@users.noreply.github.com> Date: Tue, 22 Nov 2022 05:15:25 +0000 Subject: [PATCH] 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 --- rest_framework/fields.py | 5 ++++- tests/test_fields.py | 9 +++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 88d606b28..4bea5c419 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -919,7 +919,8 @@ class FloatField(Field): 'invalid': _('A valid number is required.'), '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}.'), - '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. @@ -945,6 +946,8 @@ class FloatField(Field): return float(data) except (TypeError, ValueError): self.fail('invalid') + except OverflowError: + self.fail('overflow') def to_representation(self, value): return float(value) diff --git a/tests/test_fields.py b/tests/test_fields.py index 3112fc2cc..bcdcf15d8 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1,4 +1,5 @@ import datetime +import math import os import re import uuid @@ -1072,6 +1073,14 @@ class TestMinMaxFloatField(FieldValues): 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): """ Valid and invalid values for `DecimalField`.