From 98eff0cef58840bceeea4e3dfc418638a4739578 Mon Sep 17 00:00:00 2001 From: "T. Franzel" Date: Tue, 26 Dec 2023 22:40:49 +0100 Subject: [PATCH] coerse Decimal to float format explicitly #1134 this is to prevent accidental scientific notation and thus introducing !!float yaml tag that NOBODY likes. --- drf_spectacular/renderers.py | 2 +- tests/test_validators.py | 11 +++++++++++ tests/test_validators.yml | 14 ++++++++++++++ 3 files changed, 26 insertions(+), 1 deletion(-) diff --git a/drf_spectacular/renderers.py b/drf_spectacular/renderers.py index d3ee898c..1e4c0373 100644 --- a/drf_spectacular/renderers.py +++ b/drf_spectacular/renderers.py @@ -30,7 +30,7 @@ def multiline_str_representer(dumper, data): def decimal_representer(dumper, data): # prevent emitting "!! float" tags on fractionless decimals - value = str(data) + value = f'{data:f}' if '.' in value: return dumper.represent_scalar('tag:yaml.org,2002:float', value) else: diff --git a/tests/test_validators.py b/tests/test_validators.py index 0f244444..e330288d 100644 --- a/tests/test_validators.py +++ b/tests/test_validators.py @@ -1,5 +1,6 @@ import sys from datetime import timedelta +from decimal import Decimal from unittest import mock import pytest @@ -53,6 +54,16 @@ class XSerializer(serializers.Serializer): decimal_places=1, validators=[validators.DecimalValidator(max_digits=4, decimal_places=2)], ) + decimal_validator_decimal = serializers.DecimalField( + max_digits=9, + decimal_places=7, + validators=[validators.MinValueValidator(Decimal("0.0000000001"))] + ) + decimal_min_value_decimal = serializers.DecimalField( + decimal_places=2, + max_digits=5, + min_value=Decimal('0.000000000000000000000001'), + ) # The following only apply for `array` type: list_max_length = serializers.ListField(validators=[validators.MaxLengthValidator(200)]) diff --git a/tests/test_validators.yml b/tests/test_validators.yml index c68d8654..2754e259 100644 --- a/tests/test_validators.yml +++ b/tests/test_validators.yml @@ -126,6 +126,18 @@ components: minimum: -100 exclusiveMaximum: true exclusiveMinimum: true + decimal_validator_decimal: + type: number + format: double + maximum: 100 + minimum: 0.0000000001 + exclusiveMaximum: true + decimal_min_value_decimal: + type: number + format: double + maximum: 1000 + minimum: 0.000000000000000000000001 + exclusiveMaximum: true list_max_length: type: array items: {} @@ -183,6 +195,8 @@ components: - decimal_decimal - decimal_max_value - decimal_min_value + - decimal_min_value_decimal + - decimal_validator_decimal - dict_max_length - dict_min_length - file_extension