Skip to content

Commit

Permalink
Merge pull request #832 from Kristinus/master
Browse files Browse the repository at this point in the history
Include Enum to NinjaJSONEncoder
  • Loading branch information
vitalik authored Aug 28, 2023
2 parents 5d4ceea + feac322 commit 8be35e4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
3 changes: 3 additions & 0 deletions ninja/responses.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from enum import Enum
from ipaddress import IPv4Address, IPv6Address
from typing import Any, FrozenSet

Expand All @@ -22,6 +23,8 @@ def default(self, o: Any) -> Any:
return o.model_dump()
if isinstance(o, (IPv4Address, IPv6Address)):
return str(o)
if isinstance(o, Enum):
return str(o)
return super().default(o)


Expand Down
13 changes: 13 additions & 0 deletions tests/test_response.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
from enum import Enum
from ipaddress import IPv4Address, IPv6Address
from typing import List, Union

Expand Down Expand Up @@ -30,6 +31,11 @@ def __init__(self, id, user_name, password):
self.password = password


class MyEnum(Enum):
first = "first"
second = "second"


def to_camel(string: str) -> str:
return "".join(word.capitalize() for word in string.split("_"))

Expand Down Expand Up @@ -157,3 +163,10 @@ def test_ipv6address_encoding():
response = Response(data)
response_data = json.loads(response.content)
assert response_data["ipv6"] == str(data["ipv6"])


def test_enum_encoding():
data = {"enum": MyEnum.first}
response = Response(data)
response_data = json.loads(response.content)
assert response_data["enum"] == str(data["enum"])

0 comments on commit 8be35e4

Please sign in to comment.