mirror of
https://github.com/openSUSE/osc.git
synced 2025-01-06 06:46:14 +01:00
Implement 'Enum' support in models
This commit is contained in:
parent
86e06a341f
commit
35433fc341
@ -13,6 +13,7 @@ import types
|
|||||||
from typing import get_type_hints
|
from typing import get_type_hints
|
||||||
|
|
||||||
# supported types
|
# supported types
|
||||||
|
from enum import Enum
|
||||||
from typing import Any
|
from typing import Any
|
||||||
from typing import Dict
|
from typing import Dict
|
||||||
from typing import List
|
from typing import List
|
||||||
@ -40,6 +41,7 @@ __all__ = (
|
|||||||
"Field",
|
"Field",
|
||||||
"NotSet",
|
"NotSet",
|
||||||
"FromParent",
|
"FromParent",
|
||||||
|
"Enum",
|
||||||
"Dict",
|
"Dict",
|
||||||
"List",
|
"List",
|
||||||
"NewType",
|
"NewType",
|
||||||
@ -176,6 +178,15 @@ class Field(property):
|
|||||||
valid_type = True
|
valid_type = True
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
if (
|
||||||
|
inspect.isclass(expected_type)
|
||||||
|
and issubclass(expected_type, Enum)
|
||||||
|
):
|
||||||
|
# test if the value is part of the enum
|
||||||
|
expected_type(value)
|
||||||
|
valid_type = True
|
||||||
|
continue
|
||||||
|
|
||||||
if not isinstance(value, origin_type):
|
if not isinstance(value, origin_type):
|
||||||
msg = f"Field '{self.name}' has type '{self.type}'. Cannot assign a value with type '{type(value).__name__}'."
|
msg = f"Field '{self.name}' has type '{self.type}'. Cannot assign a value with type '{type(value).__name__}'."
|
||||||
raise TypeError(msg)
|
raise TypeError(msg)
|
||||||
|
@ -195,6 +195,26 @@ class Test(unittest.TestCase):
|
|||||||
self.assertNotEqual(m.field, None)
|
self.assertNotEqual(m.field, None)
|
||||||
self.assertEqual(m.field.text, "text")
|
self.assertEqual(m.field.text, "text")
|
||||||
|
|
||||||
|
def test_enum(self):
|
||||||
|
class Numbers(Enum):
|
||||||
|
one = "one"
|
||||||
|
two = "two"
|
||||||
|
|
||||||
|
class TestModel(BaseModel):
|
||||||
|
field: Optional[Numbers] = Field(default=None)
|
||||||
|
|
||||||
|
m = TestModel()
|
||||||
|
field = m.__fields__["field"]
|
||||||
|
self.assertEqual(field.is_model, False)
|
||||||
|
self.assertEqual(field.is_optional, True)
|
||||||
|
self.assertEqual(field.origin_type, Numbers)
|
||||||
|
self.assertEqual(m.field, None)
|
||||||
|
|
||||||
|
m.field = "one"
|
||||||
|
self.assertEqual(m.field, "one")
|
||||||
|
|
||||||
|
self.assertRaises(ValueError, setattr, m, "field", "does-not-exist")
|
||||||
|
|
||||||
def test_parent(self):
|
def test_parent(self):
|
||||||
class ParentModel(BaseModel):
|
class ParentModel(BaseModel):
|
||||||
field: str = Field(default="text")
|
field: str = Field(default="text")
|
||||||
|
Loading…
Reference in New Issue
Block a user