Browse Source

[Fix] decimal_encoder function handle 'NaN' and 'Infinity' edge cases

Signed-off-by: Kent Huang <[email protected]>
pull/12935/head
Kent Huang 5 months ago
parent
commit
c02c16b0cb
  1. 3
      fastapi/encoders.py
  2. 15
      tests/test_jsonable_encoder.py

3
fastapi/encoders.py

@ -49,7 +49,8 @@ def decimal_encoder(dec_value: Decimal) -> Union[int, float]:
>>> decimal_encoder(Decimal("1"))
1
"""
if dec_value.as_tuple().exponent >= 0: # type: ignore[operator]
exponent = dec_value.as_tuple().exponent
if isinstance(exponent, int) and exponent >= 0: # type: ignore[operator]
return int(dec_value)
else:
return float(dec_value)

15
tests/test_jsonable_encoder.py

@ -3,6 +3,7 @@ from dataclasses import dataclass
from datetime import datetime, timezone
from decimal import Decimal
from enum import Enum
from math import isinf, isnan
from pathlib import PurePath, PurePosixPath, PureWindowsPath
from typing import Optional
@ -303,6 +304,20 @@ def test_decimal_encoder_int():
assert jsonable_encoder(data) == {"value": 2}
@needs_pydanticv2
def test_decimal_encoder_nan():
data = {"value": Decimal("NaN")}
assert isnan(jsonable_encoder(data)["value"])
@needs_pydanticv2
def test_decimal_encoder_infinity():
data = {"value": Decimal("Infinity")}
assert isinf(jsonable_encoder(data)["value"])
data = {"value": Decimal("-Infinity")}
assert isinf(jsonable_encoder(data)["value"])
def test_encode_deque_encodes_child_models():
class Model(BaseModel):
test: str

Loading…
Cancel
Save