Skip to content

fix: Allow None in enum properties #512

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
from ...client import Client
from ...models.a_model import AModel
from ...models.an_enum import AnEnum
from ...models.an_enum_with_null import AnEnumWithNull
from ...models.an_enum_with_only_null import AnEnumWithOnlyNull
from ...models.http_validation_error import HTTPValidationError
from ...types import UNSET, Response

Expand All @@ -14,6 +16,8 @@ def _get_kwargs(
*,
client: Client,
an_enum_value: List[AnEnum],
an_enum_value_with_null: List[Optional[AnEnumWithNull]],
an_enum_value_with_only_null: List[AnEnumWithOnlyNull],
some_date: Union[datetime.date, datetime.datetime],
) -> Dict[str, Any]:
url = "{}/tests/".format(client.base_url)
Expand All @@ -27,13 +31,29 @@ def _get_kwargs(

json_an_enum_value.append(an_enum_value_item)

json_an_enum_value_with_null = []
for an_enum_value_with_null_item_data in an_enum_value_with_null:
an_enum_value_with_null_item = (
an_enum_value_with_null_item_data.value if an_enum_value_with_null_item_data else None
)

json_an_enum_value_with_null.append(an_enum_value_with_null_item)

json_an_enum_value_with_only_null = []
for an_enum_value_with_only_null_item_data in an_enum_value_with_only_null:
an_enum_value_with_only_null_item = an_enum_value_with_only_null_item_data.value

json_an_enum_value_with_only_null.append(an_enum_value_with_only_null_item)

if isinstance(some_date, datetime.date):
json_some_date = some_date.isoformat()
else:
json_some_date = some_date.isoformat()

params: Dict[str, Any] = {
"an_enum_value": json_an_enum_value,
"an_enum_value_with_null": json_an_enum_value_with_null,
"an_enum_value_with_only_null": json_an_enum_value_with_only_null,
"some_date": json_some_date,
}
params = {k: v for k, v in params.items() if v is not UNSET and v is not None}
Expand Down Expand Up @@ -82,11 +102,15 @@ def sync_detailed(
*,
client: Client,
an_enum_value: List[AnEnum],
an_enum_value_with_null: List[Optional[AnEnumWithNull]],
an_enum_value_with_only_null: List[AnEnumWithOnlyNull],
some_date: Union[datetime.date, datetime.datetime],
) -> Response[Union[HTTPValidationError, List[AModel]]]:
kwargs = _get_kwargs(
client=client,
an_enum_value=an_enum_value,
an_enum_value_with_null=an_enum_value_with_null,
an_enum_value_with_only_null=an_enum_value_with_only_null,
some_date=some_date,
)

Expand All @@ -101,13 +125,17 @@ def sync(
*,
client: Client,
an_enum_value: List[AnEnum],
an_enum_value_with_null: List[Optional[AnEnumWithNull]],
an_enum_value_with_only_null: List[AnEnumWithOnlyNull],
some_date: Union[datetime.date, datetime.datetime],
) -> Optional[Union[HTTPValidationError, List[AModel]]]:
"""Get a list of things"""

return sync_detailed(
client=client,
an_enum_value=an_enum_value,
an_enum_value_with_null=an_enum_value_with_null,
an_enum_value_with_only_null=an_enum_value_with_only_null,
some_date=some_date,
).parsed

Expand All @@ -116,11 +144,15 @@ async def asyncio_detailed(
*,
client: Client,
an_enum_value: List[AnEnum],
an_enum_value_with_null: List[Optional[AnEnumWithNull]],
an_enum_value_with_only_null: List[AnEnumWithOnlyNull],
some_date: Union[datetime.date, datetime.datetime],
) -> Response[Union[HTTPValidationError, List[AModel]]]:
kwargs = _get_kwargs(
client=client,
an_enum_value=an_enum_value,
an_enum_value_with_null=an_enum_value_with_null,
an_enum_value_with_only_null=an_enum_value_with_only_null,
some_date=some_date,
)

Expand All @@ -134,6 +166,8 @@ async def asyncio(
*,
client: Client,
an_enum_value: List[AnEnum],
an_enum_value_with_null: List[Optional[AnEnumWithNull]],
an_enum_value_with_only_null: List[AnEnumWithOnlyNull],
some_date: Union[datetime.date, datetime.datetime],
) -> Optional[Union[HTTPValidationError, List[AModel]]]:
"""Get a list of things"""
Expand All @@ -142,6 +176,8 @@ async def asyncio(
await asyncio_detailed(
client=client,
an_enum_value=an_enum_value,
an_enum_value_with_null=an_enum_value_with_null,
an_enum_value_with_only_null=an_enum_value_with_only_null,
some_date=some_date,
)
).parsed
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
from .all_of_sub_model_type_enum import AllOfSubModelTypeEnum
from .an_all_of_enum import AnAllOfEnum
from .an_enum import AnEnum
from .an_enum_with_null import AnEnumWithNull
from .an_enum_with_only_null import AnEnumWithOnlyNull
from .an_int_enum import AnIntEnum
from .another_all_of_sub_model import AnotherAllOfSubModel
from .another_all_of_sub_model_type import AnotherAllOfSubModelType
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from enum import Enum


class AnEnumWithNull(str, Enum):
FIRST_VALUE = "FIRST_VALUE"
SECOND_VALUE = "SECOND_VALUE"

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

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from enum import Enum


class AnEnumWithOnlyNull(Enum):
VALUE_0 = None

def __str__(self) -> str:
return str(self.value)
40 changes: 40 additions & 0 deletions end_to_end_tests/openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,30 @@
"name": "an_enum_value",
"in": "query"
},
{
"required": true,
"schema": {
"title": "An Enum Value With Null And String Values",
"type": "array",
"items": {
"$ref": "#/components/schemas/AnEnumWithNull"
}
},
"name": "an_enum_value_with_null",
"in": "query"
},
{
"required": true,
"schema": {
"title": "An Enum Value With Only Null Values",
"type": "array",
"items": {
"$ref": "#/components/schemas/AnEnumWithOnlyNull"
}
},
"name": "an_enum_value_with_only_null",
"in": "query"
},
{
"required": true,
"schema": {
Expand Down Expand Up @@ -1164,6 +1188,22 @@
],
"description": "For testing Enums in all the ways they can be used "
},
"AnEnumWithNull": {
"title": "AnEnumWithNull",
"enum": [
"FIRST_VALUE",
"SECOND_VALUE",
null
],
"description": "For testing Enums with mixed string / null values "
},
"AnEnumWithOnlyNull": {
"title": "AnEnumWithOnlyNull",
"enum": [
null
],
"description": "For testing Enums with only null values "
},
"AnAllOfEnum": {
"title": "AnAllOfEnum",
"enum": [
Expand Down
4 changes: 4 additions & 0 deletions openapi_python_client/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ def _build_models(self) -> None:
models_dir.mkdir()
models_init = models_dir / "__init__.py"
imports = []
NoneType = type(None)

model_template = self.env.get_template("model.py.jinja")
for model in self.openapi.models:
Expand All @@ -234,11 +235,14 @@ def _build_models(self) -> None:

# Generate enums
str_enum_template = self.env.get_template("str_enum.py.jinja")
null_enum_template = self.env.get_template("null_enum.py.jinja")
int_enum_template = self.env.get_template("int_enum.py.jinja")
for enum in self.openapi.enums:
module_path = models_dir / f"{enum.class_info.module_name}.py"
if enum.value_type is int:
module_path.write_text(int_enum_template.render(enum=enum), encoding=self.file_encoding)
elif enum.value_type is NoneType:
module_path.write_text(null_enum_template.render(enum=enum), encoding=self.file_encoding)
else:
module_path.write_text(str_enum_template.render(enum=enum), encoding=self.file_encoding)
imports.append(import_string_from_class(enum.class_info))
Expand Down
10 changes: 9 additions & 1 deletion openapi_python_client/parser/properties/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ def build_enum_property(
name: str,
required: bool,
schemas: Schemas,
enum: Union[List[str], List[int]],
enum: Union[List[Optional[str]], List[Optional[int]]],
parent_name: Optional[str],
config: Config,
) -> Tuple[Union[EnumProperty, PropertyError], Schemas]:
Expand Down Expand Up @@ -332,6 +332,14 @@ def build_enum_property(
schemas,
)

# Remove None from str / int list, if present, and mark property as nullable
# If list only has None, with no str or int, make special None enum instead
keys_to_remove = [key for key, value in values.items() if value is None]
if keys_to_remove and len(keys_to_remove) < len(values.items()):
data.nullable = True
for key in keys_to_remove:
values.pop(key)

for value in values.values():
value_type = type(value)
break
Expand Down
9 changes: 5 additions & 4 deletions openapi_python_client/parser/properties/enum_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from .property import Property
from .schemas import Class

ValueType = Union[str, int]
ValueType = Union[str, int, None]


@attr.s(auto_attribs=True, frozen=True)
Expand Down Expand Up @@ -41,8 +41,8 @@ def get_imports(self, *, prefix: str) -> Set[str]:
return imports

@staticmethod
def values_from_list(values: Union[List[str], List[int]]) -> Dict[str, ValueType]:
"""Convert a list of values into dict of {name: value}"""
def values_from_list(values: Union[List[Optional[str]], List[Optional[int]]]) -> Dict[str, ValueType]:
"""Convert a list of values into dict of {name: value}, where value can sometimes be None"""
output: Dict[str, ValueType] = {}

for i, value in enumerate(values):
Expand All @@ -60,5 +60,6 @@ def values_from_list(values: Union[List[str], List[int]]) -> Dict[str, ValueType
if key in output:
raise ValueError(f"Duplicate key {key} in Enum")
sanitized_key = utils.snake_case(key).upper()
output[sanitized_key] = utils.remove_string_escapes(value)
output[sanitized_key] = utils.remove_string_escapes(value) if isinstance(value, str) else value
# If value is the string "null", this becomes Python's None instead of a str, so must special-case it
return output
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class Schema(BaseModel):
maxProperties: Optional[int] = Field(default=None, ge=0)
minProperties: Optional[int] = Field(default=None, ge=0)
required: Optional[List[str]] = Field(default=None, min_items=1)
enum: Union[None, List[StrictInt], List[StrictStr]] = Field(default=None, min_items=1)
enum: Union[None, List[Optional[StrictInt]], List[Optional[StrictStr]]] = Field(default=None, min_items=1)
type: Optional[DataType] = Field(default=None)
allOf: Optional[List[Union[Reference, "Schema"]]] = None
oneOf: List[Union[Reference, "Schema"]] = []
Expand Down
9 changes: 9 additions & 0 deletions openapi_python_client/templates/null_enum.py.jinja
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from enum import Enum

class {{ enum.class_info.name }}(Enum):
{% for key, value in enum.values.items() %}
{{ key }} = {{ value }}
{% endfor %}

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