Skip to content

Commit

Permalink
Add: Introduce a StrEnum class for Models
Browse files Browse the repository at this point in the history
Allow to use a Enum class with str behavior for easier usage of models
with enum values in APIs.
  • Loading branch information
bjoernricks committed Nov 17, 2023
1 parent b1d96b0 commit 3073728
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
12 changes: 12 additions & 0 deletions pontos/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

from dataclasses import dataclass
from datetime import date, datetime
from enum import Enum
from inspect import isclass
from typing import Any, Dict, Type, Union, get_args, get_origin, get_type_hints

Expand All @@ -27,6 +28,7 @@
__all__ = (
"Model",
"ModelError",
"StrEnum",
"dotted_attributes",
)

Expand All @@ -37,6 +39,16 @@ class ModelError(PontosError):
"""


class StrEnum(str, Enum):
# Should be replaced by enum.StrEnum when we require Python >= 3.11
"""
An Enum that provides str like behavior
"""

def __str__(self) -> str:
return self.value


def dotted_attributes(obj: Any, data: Dict[str, Any]) -> Any:
"""
Set dotted attributes on an object
Expand Down
26 changes: 26 additions & 0 deletions tests/models/test_strenum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# SPDX-FileCopyrightText: 2023 Greenbone AG
#
# SPDX-License-Identifier: GPL-3.0-or-later

import unittest

from pontos.models import StrEnum


class FooEnum(StrEnum):
A = "a"
B = "b"


class StrEnumTestCase(unittest.TestCase):
def test_str(self):
self.assertEqual(str(FooEnum.A), "a")
self.assertEqual(str(FooEnum.B), "b")

def test_str_append(self):
self.assertEqual("say " + FooEnum.A, "say a")
self.assertEqual("say " + FooEnum.B, "say b")

def test_f_string(self):
self.assertEqual(f"say {FooEnum.A}", "say a")
self.assertEqual(f"say {FooEnum.B}", "say b")

0 comments on commit 3073728

Please sign in to comment.