Adds Aditional Validations in Enum #29
@@ -9,6 +9,16 @@ from enum import Enum
|
||||
class EnumTypeParser(GenericTypeParser):
|
||||
json_schema_type = "enum"
|
||||
|
||||
allowed_types: tuple[type] = (
|
||||
str,
|
||||
int,
|
||||
float,
|
||||
bool,
|
||||
list,
|
||||
set,
|
||||
type(None),
|
||||
)
|
||||
|
||||
def from_properties_impl(
|
||||
self, name, properties, **kwargs: Unpack[TypeParserOptions]
|
||||
):
|
||||
@@ -20,6 +30,13 @@ class EnumTypeParser(GenericTypeParser):
|
||||
if not isinstance(enum_values, list):
|
||||
raise ValueError(f"Enum type {name} must have 'enum' as a list of values.")
|
||||
|
||||
if any(
|
||||
not isinstance(value, self.allowed_types) for value in enum_values
|
||||
):
|
||||
raise ValueError(
|
||||
f"Enum type {name} must have 'enum' values of allowed types: {self.allowed_types}."
|
||||
)
|
||||
|
||||
# Create a new Enum type dynamically
|
||||
enum_type = Enum(name, {str(value).upper(): value for value in enum_values})
|
||||
parsed_properties = self.mappings_properties_builder(properties, **kwargs)
|
||||
|
||||
@@ -78,3 +78,13 @@ class TestEnumTypeParser(TestCase):
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
parser.from_properties_impl("TestEnum", schema)
|
||||
|
||||
def test_enum_type_parser_throws_invalid_enum_value(self):
|
||||
parser = EnumTypeParser()
|
||||
|
||||
schema = {
|
||||
"enum": ["value1", 42, dict()],
|
||||
}
|
||||
|
||||
with self.assertRaises(ValueError):
|
||||
parser.from_properties_impl("TestEnum", schema)
|
||||
|
||||
Reference in New Issue
Block a user