|
14 | 14 |
|
15 | 15 | from __future__ import annotations |
16 | 16 | import json |
17 | | -from enum import Enum |
18 | | -from typing_extensions import Self |
| 17 | +import pprint |
| 18 | +from pydantic import BaseModel, ConfigDict, Field, StrictStr, ValidationError, field_validator |
| 19 | +from typing import Any, List, Optional |
| 20 | +from petstore_api.models.enum_string1 import EnumString1 |
| 21 | +from petstore_api.models.enum_string2 import EnumString2 |
| 22 | +from pydantic import StrictStr, Field |
| 23 | +from typing import Union, List, Set, Optional, Dict |
| 24 | +from typing_extensions import Literal, Self |
19 | 25 |
|
| 26 | +ONEOFENUMSTRING_ONE_OF_SCHEMAS = ["EnumString1", "EnumString2"] |
20 | 27 |
|
21 | | -class OneOfEnumString(str, Enum): |
| 28 | +class OneOfEnumString(BaseModel): |
22 | 29 | """ |
23 | 30 | oneOf enum strings |
24 | 31 | """ |
| 32 | + # data type: EnumString1 |
| 33 | + oneof_schema_1_validator: Optional[EnumString1] = None |
| 34 | + # data type: EnumString2 |
| 35 | + oneof_schema_2_validator: Optional[EnumString2] = None |
| 36 | + actual_instance: Optional[Union[EnumString1, EnumString2]] = None |
| 37 | + one_of_schemas: Set[str] = { "EnumString1", "EnumString2" } |
25 | 38 |
|
26 | | - """ |
27 | | - allowed enum values |
28 | | - """ |
29 | | - A = 'a' |
30 | | - B = 'b' |
31 | | - C = 'c' |
32 | | - D = 'd' |
| 39 | + model_config = ConfigDict( |
| 40 | + validate_assignment=True, |
| 41 | + protected_namespaces=(), |
| 42 | + ) |
| 43 | + |
| 44 | + |
| 45 | + def __init__(self, *args, **kwargs) -> None: |
| 46 | + if args: |
| 47 | + if len(args) > 1: |
| 48 | + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") |
| 49 | + if kwargs: |
| 50 | + raise ValueError("If a position argument is used, keyword arguments cannot be used.") |
| 51 | + super().__init__(actual_instance=args[0]) |
| 52 | + else: |
| 53 | + super().__init__(**kwargs) |
| 54 | + |
| 55 | + @field_validator('actual_instance') |
| 56 | + def actual_instance_must_validate_oneof(cls, v): |
| 57 | + instance = OneOfEnumString.model_construct() |
| 58 | + error_messages = [] |
| 59 | + match = 0 |
| 60 | + # validate data type: EnumString1 |
| 61 | + if not isinstance(v, EnumString1): |
| 62 | + error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString1`") |
| 63 | + else: |
| 64 | + match += 1 |
| 65 | + # validate data type: EnumString2 |
| 66 | + if not isinstance(v, EnumString2): |
| 67 | + error_messages.append(f"Error! Input type `{type(v)}` is not `EnumString2`") |
| 68 | + else: |
| 69 | + match += 1 |
| 70 | + if match > 1: |
| 71 | + # more than 1 match |
| 72 | + raise ValueError("Multiple matches found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) |
| 73 | + elif match == 0: |
| 74 | + # no match |
| 75 | + raise ValueError("No match found when setting `actual_instance` in OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) |
| 76 | + else: |
| 77 | + return v |
| 78 | + |
| 79 | + @classmethod |
| 80 | + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: |
| 81 | + return cls.from_json(json.dumps(obj)) |
33 | 82 |
|
34 | 83 | @classmethod |
35 | 84 | def from_json(cls, json_str: str) -> Self: |
36 | | - """Create an instance of OneOfEnumString from a JSON string""" |
37 | | - return cls(json.loads(json_str)) |
| 85 | + """Returns the object represented by the json string""" |
| 86 | + instance = cls.model_construct() |
| 87 | + error_messages = [] |
| 88 | + match = 0 |
| 89 | + |
| 90 | + # deserialize data into EnumString1 |
| 91 | + try: |
| 92 | + instance.actual_instance = EnumString1.from_json(json_str) |
| 93 | + match += 1 |
| 94 | + except (ValidationError, ValueError) as e: |
| 95 | + error_messages.append(str(e)) |
| 96 | + # deserialize data into EnumString2 |
| 97 | + try: |
| 98 | + instance.actual_instance = EnumString2.from_json(json_str) |
| 99 | + match += 1 |
| 100 | + except (ValidationError, ValueError) as e: |
| 101 | + error_messages.append(str(e)) |
| 102 | + |
| 103 | + if match > 1: |
| 104 | + # more than 1 match |
| 105 | + raise ValueError("Multiple matches found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) |
| 106 | + elif match == 0: |
| 107 | + # no match |
| 108 | + raise ValueError("No match found when deserializing the JSON string into OneOfEnumString with oneOf schemas: EnumString1, EnumString2. Details: " + ", ".join(error_messages)) |
| 109 | + else: |
| 110 | + return instance |
| 111 | + |
| 112 | + def to_json(self) -> str: |
| 113 | + """Returns the JSON representation of the actual instance""" |
| 114 | + if self.actual_instance is None: |
| 115 | + return "null" |
| 116 | + |
| 117 | + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): |
| 118 | + return self.actual_instance.to_json() |
| 119 | + else: |
| 120 | + return json.dumps(self.actual_instance) |
| 121 | + |
| 122 | + def to_dict(self) -> Optional[Union[Dict[str, Any], EnumString1, EnumString2]]: |
| 123 | + """Returns the dict representation of the actual instance""" |
| 124 | + if self.actual_instance is None: |
| 125 | + return None |
| 126 | + |
| 127 | + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): |
| 128 | + return self.actual_instance.to_dict() |
| 129 | + else: |
| 130 | + # primitive type |
| 131 | + return self.actual_instance |
| 132 | + |
| 133 | + def to_str(self) -> str: |
| 134 | + """Returns the string representation of the actual instance""" |
| 135 | + return pprint.pformat(self.model_dump()) |
38 | 136 |
|
39 | 137 |
|
0 commit comments