| 1 |
import warnings |
| 2 |
from collections import deque |
| 3 |
from dataclasses import dataclass |
| 4 |
from datetime import datetime, timezone |
| 5 |
from decimal import Decimal |
| 6 |
from enum import Enum |
| 7 |
from math import isinf, isnan |
| 8 |
from pathlib import PurePath, PurePosixPath, PureWindowsPath |
| 9 |
from typing import TypedDict |
| 10 |
|
| 11 |
import pytest |
| 12 |
from fastapi._compat import Undefined |
| 13 |
from fastapi.encoders import jsonable_encoder |
| 14 |
from fastapi.exceptions import PydanticV1NotSupportedError |
| 15 |
from pydantic import BaseModel, Field, ValidationError |
| 16 |
|
| 17 |
|
| 18 |
class Person: |
| 19 |
def __init__(self, name: str): |
| 20 |
self.name = name |
| 21 |
|
| 22 |
|
| 23 |
class Pet: |
| 24 |
def __init__(self, owner: Person, name: str): |
| 25 |
self.owner = owner |
| 26 |
self.name = name |
| 27 |
|
| 28 |
|
| 29 |
@dataclass |
| 30 |
class Item: |
| 31 |
name: str |
| 32 |
count: int |
| 33 |
|
| 34 |
|
| 35 |
class DictablePerson(Person): |
| 36 |
def __iter__(self): |
| 37 |
return ((k, v) for k, v in self.__dict__.items()) |
| 38 |
|
| 39 |
|
| 40 |
class DictablePet(Pet): |
| 41 |
def __iter__(self): |
| 42 |
return ((k, v) for k, v in self.__dict__.items()) |
| 43 |
|
| 44 |
|
| 45 |
class Unserializable: |
| 46 |
def __iter__(self): |
| 47 |
raise NotImplementedError() |
| 48 |
|
| 49 |
@property |
| 50 |
def __dict__(self): |
| 51 |
raise NotImplementedError() |
| 52 |
|
| 53 |
|
| 54 |
class RoleEnum(Enum): |
| 55 |
admin = "admin" |
| 56 |
normal = "normal" |
| 57 |
|
| 58 |
|
| 59 |
class ModelWithConfig(BaseModel): |
| 60 |
role: RoleEnum | None = None |
| 61 |
|
| 62 |
model_config = {"use_enum_values": True} |
| 63 |
|
| 64 |
|
| 65 |
class ModelWithAlias(BaseModel): |
| 66 |
foo: str = Field(alias="Foo") |
| 67 |
|
| 68 |
|
| 69 |
class ModelWithDefault(BaseModel): |
| 70 |
foo: str = ... # type: ignore |
| 71 |
bar: str = "bar" |
| 72 |
bla: str = "bla" |
| 73 |
|
| 74 |
|
| 75 |
def test_encode_dict(): |
| 76 |
pet = {"name": "Firulais", "owner": {"name": "Foo"}} |
| 77 |
assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} |
| 78 |
assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} |
| 79 |
assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} |
| 80 |
assert jsonable_encoder(pet, include={}) == {} |
| 81 |
assert jsonable_encoder(pet, exclude={}) == { |
| 82 |
"name": "Firulais", |
| 83 |
"owner": {"name": "Foo"}, |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
def test_encode_dict_include_exclude_list(): |
| 88 |
pet = {"name": "Firulais", "owner": {"name": "Foo"}} |
| 89 |
assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} |
| 90 |
assert jsonable_encoder(pet, include=["name"]) == {"name": "Firulais"} # ty: ignore[invalid-argument-type] |
| 91 |
assert jsonable_encoder(pet, exclude=["owner"]) == {"name": "Firulais"} # ty: ignore[invalid-argument-type] |
| 92 |
assert jsonable_encoder(pet, include=[]) == {} # ty: ignore[invalid-argument-type] |
| 93 |
assert jsonable_encoder(pet, exclude=[]) == { # ty: ignore[invalid-argument-type] |
| 94 |
"name": "Firulais", |
| 95 |
"owner": {"name": "Foo"}, |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
def test_encode_class(): |
| 100 |
person = Person(name="Foo") |
| 101 |
pet = Pet(owner=person, name="Firulais") |
| 102 |
assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} |
| 103 |
assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} |
| 104 |
assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} |
| 105 |
assert jsonable_encoder(pet, include={}) == {} |
| 106 |
assert jsonable_encoder(pet, exclude={}) == { |
| 107 |
"name": "Firulais", |
| 108 |
"owner": {"name": "Foo"}, |
| 109 |
} |
| 110 |
|
| 111 |
|
| 112 |
def test_encode_dictable(): |
| 113 |
person = DictablePerson(name="Foo") |
| 114 |
pet = DictablePet(owner=person, name="Firulais") |
| 115 |
assert jsonable_encoder(pet) == {"name": "Firulais", "owner": {"name": "Foo"}} |
| 116 |
assert jsonable_encoder(pet, include={"name"}) == {"name": "Firulais"} |
| 117 |
assert jsonable_encoder(pet, exclude={"owner"}) == {"name": "Firulais"} |
| 118 |
assert jsonable_encoder(pet, include={}) == {} |
| 119 |
assert jsonable_encoder(pet, exclude={}) == { |
| 120 |
"name": "Firulais", |
| 121 |
"owner": {"name": "Foo"}, |
| 122 |
} |
| 123 |
|
| 124 |
|
| 125 |
def test_encode_dataclass(): |
| 126 |
item = Item(name="foo", count=100) |
| 127 |
assert jsonable_encoder(item) == {"name": "foo", "count": 100} |
| 128 |
assert jsonable_encoder(item, include={"name"}) == {"name": "foo"} |
| 129 |
assert jsonable_encoder(item, exclude={"count"}) == {"name": "foo"} |
| 130 |
assert jsonable_encoder(item, include={}) == {} |
| 131 |
assert jsonable_encoder(item, exclude={}) == {"name": "foo", "count": 100} |
| 132 |
|
| 133 |
|
| 134 |
def test_encode_unsupported(): |
| 135 |
unserializable = Unserializable() |
| 136 |
with pytest.raises(ValueError): |
| 137 |
jsonable_encoder(unserializable) |
| 138 |
|
| 139 |
|
| 140 |
def test_encode_custom_json_encoders_model_pydanticv2(): |
| 141 |
from pydantic import field_serializer |
| 142 |
|
| 143 |
class ModelWithCustomEncoder(BaseModel): |
| 144 |
dt_field: datetime |
| 145 |
|
| 146 |
@field_serializer("dt_field") |
| 147 |
def serialize_dt_field(self, dt): |
| 148 |
return dt.replace(microsecond=0, tzinfo=timezone.utc).isoformat() |
| 149 |
|
| 150 |
class ModelWithCustomEncoderSubclass(ModelWithCustomEncoder): |
| 151 |
pass |
| 152 |
|
| 153 |
model = ModelWithCustomEncoder(dt_field=datetime(2019, 1, 1, 8)) |
| 154 |
assert jsonable_encoder(model) == {"dt_field": "2019-01-01T08:00:00+00:00"} |
| 155 |
subclass_model = ModelWithCustomEncoderSubclass(dt_field=datetime(2019, 1, 1, 8)) |
| 156 |
assert jsonable_encoder(subclass_model) == {"dt_field": "2019-01-01T08:00:00+00:00"} |
| 157 |
|
| 158 |
|
| 159 |
def test_json_encoder_error_with_pydanticv1(): |
| 160 |
with warnings.catch_warnings(): |
| 161 |
warnings.simplefilter("ignore", UserWarning) |
| 162 |
from pydantic import v1 |
| 163 |
|
| 164 |
class ModelV1(v1.BaseModel): |
| 165 |
name: str |
| 166 |
|
| 167 |
data = ModelV1(name="test") |
| 168 |
with pytest.raises(PydanticV1NotSupportedError): |
| 169 |
jsonable_encoder(data) |
| 170 |
|
| 171 |
|
| 172 |
def test_encode_model_with_config(): |
| 173 |
model = ModelWithConfig(role=RoleEnum.admin) |
| 174 |
assert jsonable_encoder(model) == {"role": "admin"} |
| 175 |
|
| 176 |
|
| 177 |
def test_encode_model_with_alias_raises(): |
| 178 |
with pytest.raises(ValidationError): |
| 179 |
ModelWithAlias(foo="Bar") # ty: ignore[missing-argument, unknown-argument] |
| 180 |
|
| 181 |
|
| 182 |
def test_encode_model_with_alias(): |
| 183 |
model = ModelWithAlias(Foo="Bar") |
| 184 |
assert jsonable_encoder(model) == {"Foo": "Bar"} |
| 185 |
|
| 186 |
|
| 187 |
def test_encode_model_with_default(): |
| 188 |
model = ModelWithDefault(foo="foo", bar="bar") |
| 189 |
assert jsonable_encoder(model) == {"foo": "foo", "bar": "bar", "bla": "bla"} |
| 190 |
assert jsonable_encoder(model, exclude_unset=True) == {"foo": "foo", "bar": "bar"} |
| 191 |
assert jsonable_encoder(model, exclude_defaults=True) == {"foo": "foo"} |
| 192 |
assert jsonable_encoder(model, exclude_unset=True, exclude_defaults=True) == { |
| 193 |
"foo": "foo" |
| 194 |
} |
| 195 |
assert jsonable_encoder(model, include={"foo"}) == {"foo": "foo"} |
| 196 |
assert jsonable_encoder(model, exclude={"bla"}) == {"foo": "foo", "bar": "bar"} |
| 197 |
assert jsonable_encoder(model, include={}) == {} |
| 198 |
assert jsonable_encoder(model, exclude={}) == { |
| 199 |
"foo": "foo", |
| 200 |
"bar": "bar", |
| 201 |
"bla": "bla", |
| 202 |
} |
| 203 |
|
| 204 |
|
| 205 |
def test_encode_model_with_default_in_dict_and_list(): |
| 206 |
model = ModelWithDefault(foo="foo", bar="bar") |
| 207 |
assert jsonable_encoder([model], exclude_defaults=True) == [{"foo": "foo"}] |
| 208 |
assert jsonable_encoder({"key": model}, exclude_defaults=True) == { |
| 209 |
"key": {"foo": "foo"} |
| 210 |
} |
| 211 |
assert jsonable_encoder({"key": [model]}, exclude_defaults=True) == { |
| 212 |
"key": [{"foo": "foo"}] |
| 213 |
} |
| 214 |
assert jsonable_encoder({"key": model}) == { |
| 215 |
"key": {"foo": "foo", "bar": "bar", "bla": "bla"} |
| 216 |
} |
| 217 |
|
| 218 |
|
| 219 |
def test_custom_encoders(): |
| 220 |
class safe_datetime(datetime): |
| 221 |
pass |
| 222 |
|
| 223 |
class MyDict(TypedDict): |
| 224 |
dt_field: safe_datetime |
| 225 |
|
| 226 |
instance = MyDict(dt_field=safe_datetime.now()) |
| 227 |
|
| 228 |
encoded_instance = jsonable_encoder( |
| 229 |
instance, custom_encoder={safe_datetime: lambda o: o.strftime("%H:%M:%S")} |
| 230 |
) |
| 231 |
assert encoded_instance["dt_field"] == instance["dt_field"].strftime("%H:%M:%S") |
| 232 |
|
| 233 |
encoded_instance = jsonable_encoder( |
| 234 |
instance, custom_encoder={datetime: lambda o: o.strftime("%H:%M:%S")} |
| 235 |
) |
| 236 |
assert encoded_instance["dt_field"] == instance["dt_field"].strftime("%H:%M:%S") |
| 237 |
|
| 238 |
encoded_instance2 = jsonable_encoder(instance) |
| 239 |
assert encoded_instance2["dt_field"] == instance["dt_field"].isoformat() |
| 240 |
|
| 241 |
|
| 242 |
def test_custom_enum_encoders(): |
| 243 |
def custom_enum_encoder(v: Enum): |
| 244 |
return v.value.lower() |
| 245 |
|
| 246 |
class MyEnum(Enum): |
| 247 |
ENUM_VAL_1 = "ENUM_VAL_1" |
| 248 |
|
| 249 |
instance = MyEnum.ENUM_VAL_1 |
| 250 |
|
| 251 |
encoded_instance = jsonable_encoder( |
| 252 |
instance, custom_encoder={MyEnum: custom_enum_encoder} |
| 253 |
) |
| 254 |
assert encoded_instance == custom_enum_encoder(instance) |
| 255 |
|
| 256 |
|
| 257 |
def test_encode_model_with_pure_path(): |
| 258 |
class ModelWithPath(BaseModel): |
| 259 |
path: PurePath |
| 260 |
|
| 261 |
model_config = {"arbitrary_types_allowed": True} |
| 262 |
|
| 263 |
test_path = PurePath("/foo", "bar") |
| 264 |
obj = ModelWithPath(path=test_path) |
| 265 |
assert jsonable_encoder(obj) == {"path": str(test_path)} |
| 266 |
|
| 267 |
|
| 268 |
def test_encode_model_with_pure_posix_path(): |
| 269 |
class ModelWithPath(BaseModel): |
| 270 |
path: PurePosixPath |
| 271 |
|
| 272 |
model_config = {"arbitrary_types_allowed": True} |
| 273 |
|
| 274 |
obj = ModelWithPath(path=PurePosixPath("/foo", "bar")) |
| 275 |
assert jsonable_encoder(obj) == {"path": "/foo/bar"} |
| 276 |
|
| 277 |
|
| 278 |
def test_encode_model_with_pure_windows_path(): |
| 279 |
class ModelWithPath(BaseModel): |
| 280 |
path: PureWindowsPath |
| 281 |
|
| 282 |
model_config = {"arbitrary_types_allowed": True} |
| 283 |
|
| 284 |
obj = ModelWithPath(path=PureWindowsPath("/foo", "bar")) |
| 285 |
assert jsonable_encoder(obj) == {"path": "\\foo\\bar"} |
| 286 |
|
| 287 |
|
| 288 |
def test_encode_pure_path(): |
| 289 |
test_path = PurePath("/foo", "bar") |
| 290 |
|
| 291 |
assert jsonable_encoder({"path": test_path}) == {"path": str(test_path)} |
| 292 |
|
| 293 |
|
| 294 |
def test_decimal_encoder_float(): |
| 295 |
data = {"value": Decimal(1.23)} |
| 296 |
assert jsonable_encoder(data) == {"value": 1.23} |
| 297 |
|
| 298 |
|
| 299 |
def test_decimal_encoder_int(): |
| 300 |
data = {"value": Decimal(2)} |
| 301 |
assert jsonable_encoder(data) == {"value": 2} |
| 302 |
|
| 303 |
|
| 304 |
def test_decimal_encoder_nan(): |
| 305 |
data = {"value": Decimal("NaN")} |
| 306 |
assert isnan(jsonable_encoder(data)["value"]) |
| 307 |
|
| 308 |
|
| 309 |
def test_decimal_encoder_infinity(): |
| 310 |
data = {"value": Decimal("Infinity")} |
| 311 |
assert isinf(jsonable_encoder(data)["value"]) |
| 312 |
data = {"value": Decimal("-Infinity")} |
| 313 |
assert isinf(jsonable_encoder(data)["value"]) |
| 314 |
|
| 315 |
|
| 316 |
def test_encode_deque_encodes_child_models(): |
| 317 |
class Model(BaseModel): |
| 318 |
test: str |
| 319 |
|
| 320 |
dq = deque([Model(test="test")]) |
| 321 |
|
| 322 |
assert jsonable_encoder(dq)[0]["test"] == "test" |
| 323 |
|
| 324 |
|
| 325 |
def test_encode_pydantic_undefined(): |
| 326 |
data = {"value": Undefined} |
| 327 |
assert jsonable_encoder(data) == {"value": None} |
| 328 |
|
| 329 |
|
| 330 |
@pytest.mark.filterwarnings("ignore::DeprecationWarning") |
| 331 |
@pytest.mark.parametrize( |
| 332 |
"module_path", |
| 333 |
[ |
| 334 |
pytest.param("pydantic.color"), |
| 335 |
pytest.param("pydantic_extra_types.color"), |
| 336 |
], |
| 337 |
) |
| 338 |
def test_encode_color(module_path): |
| 339 |
try: |
| 340 |
Color = __import__(module_path, fromlist=["Color"]).Color |
| 341 |
except ImportError: # pragma: no cover |
| 342 |
pytest.skip(f"{module_path} not available") |
| 343 |
|
| 344 |
data = {"color": Color("blue")} |
| 345 |
assert jsonable_encoder(data) == {"color": "blue"} |