diff --git a/litestar/serialization/msgspec_hooks.py b/litestar/serialization/msgspec_hooks.py index 779f2e003e..7d4b0ecc39 100644 --- a/litestar/serialization/msgspec_hooks.py +++ b/litestar/serialization/msgspec_hooks.py @@ -3,6 +3,7 @@ from collections import deque from datetime import date, datetime, time from decimal import Decimal +from enum import Enum, EnumMeta from functools import partial from ipaddress import ( IPv4Address, @@ -52,6 +53,8 @@ deque: list, Decimal: lambda val: int(val) if val.as_tuple().exponent >= 0 else float(val), Pattern: lambda val: val.pattern, + Enum: lambda val: val.value if val else None, + EnumMeta: lambda val: None, # support subclasses of stdlib types, If no previous type matched, these will be # the last type in the mro, so we use this to (attempt to) convert a subclass into # its base class. # see https://github.com/jcrist/msgspec/issues/248 diff --git a/tests/unit/test_response/test_base_response.py b/tests/unit/test_response/test_base_response.py index 804da3f7be..ce05699a22 100644 --- a/tests/unit/test_response/test_base_response.py +++ b/tests/unit/test_response/test_base_response.py @@ -1,3 +1,4 @@ +from enum import Enum from pathlib import PurePosixPath from typing import Any, Optional @@ -187,6 +188,15 @@ def test_get_serializer() -> None: class Foo: pass + class Color(Enum): + RED = 1 + + class Size(str, Enum): + SMALL = "small" + + class AltSize(Enum): + OTHER = "another" + foo_encoder = {Foo: lambda f: "it's a foo"} path_encoder = {PurePosixPath: lambda p: "it's a path"} @@ -202,6 +212,9 @@ class FooResponse(Response): assert ( get_serializer(FooResponse(None, type_encoders={Foo: lambda f: "foo"}).response_type_encoders)(Foo()) == "foo" ) + assert get_serializer()(Color.RED) == Color.RED.value + assert get_serializer()(Size(Size.SMALL)) == "Size.SMALL" + assert get_serializer()(AltSize) is None def test_head_response_doesnt_support_content() -> None: