Skip to content

Commit

Permalink
fix: add default encoders for Enums and EnumMeta (#3193)
Browse files Browse the repository at this point in the history
* fix: add default encoders for Enums

* chore: revert linting change
  • Loading branch information
cofin authored Mar 12, 2024
1 parent d292aac commit bb6b48f
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions litestar/serialization/msgspec_hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions tests/unit/test_response/test_base_response.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from enum import Enum
from pathlib import PurePosixPath
from typing import Any, Optional

Expand Down Expand Up @@ -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"}

Expand All @@ -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:
Expand Down

0 comments on commit bb6b48f

Please sign in to comment.