Browse Source

Merge e291fba055 into 1d434dec47

pull/12935/merge
Kent Huang 3 days ago
committed by GitHub
parent
commit
737ac486a1
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  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:
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