Skip to content

Handle bool enums better #923

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

Merged
merged 4 commits into from
Jan 4, 2024
Merged
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
11 changes: 11 additions & 0 deletions .changeset/do_not_stop_generation_for_invalid_enum_values.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
default: patch
---

# Do not stop generation for invalid enum values

This generator only supports `enum` values that are strings or integers.
Previously, this was handled at the parsing level, which would cause the generator to fail if there were any unsupported values in the document.
Now, the generator will correctly keep going, skipping only endpoints which contained unsupported values.

Thanks for reporting #922 @macmoritz!
13 changes: 13 additions & 0 deletions .changeset/generate_properties_for_some_boolean_enums.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
default: minor
---

# Generate properties for some boolean enums

If a schema has both `type = "boolean"` and `enum` defined, a normal boolean property will now be created.
Previously, the generator would error.

Note that the generate code _will not_ correctly limit the values to the enum values. To work around this, use the
OpenAPI 3.1 `const` instead of `enum` to generate Python `Literal` types.

Thanks for reporting #922 @macmoritz!
45 changes: 35 additions & 10 deletions end_to_end_tests/baseline_openapi_3.0.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@
},
"/bodies/json-like": {
"post": {
"tags": ["bodies"],
"tags": [
"bodies"
],
"description": "A content type that works like json but isn't application/json",
"operationId": "json-like",
"requestBody": {
Expand Down Expand Up @@ -799,11 +801,11 @@
}
}
}
},
"/tests/int_enum": {
},
"/enum/int": {
"post": {
"tags": [
"tests"
"enums"
],
"summary": "Int Enum",
"operationId": "int_enum_tests_int_enum_post",
Expand All @@ -825,14 +827,37 @@
"schema": {}
}
}
},
"422": {
"description": "Validation Error",
}
}
}
},
"/enum/bool": {
"post": {
"tags": [
"enums"
],
"summary": "Bool Enum",
"operationId": "bool_enum_tests_bool_enum_post",
"parameters": [
{
"required": true,
"schema": {
"type": "boolean",
"enum": [
true,
false
]
},
"name": "bool_enum",
"in": "query"
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
"schema": {}
}
}
}
Expand Down
39 changes: 31 additions & 8 deletions end_to_end_tests/baseline_openapi_3.1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -794,10 +794,10 @@ info:
}
}
},
"/tests/int_enum": {
"/enum/int": {
"post": {
"tags": [
"tests"
"enums"
],
"summary": "Int Enum",
"operationId": "int_enum_tests_int_enum_post",
Expand All @@ -819,14 +819,37 @@ info:
"schema": { }
}
}
},
"422": {
"description": "Validation Error",
}
}
}
},
"/enum/bool": {
"post": {
"tags": [
"enums"
],
"summary": "Bool Enum",
"operationId": "bool_enum_tests_bool_enum_post",
"parameters": [
{
"required": true,
"schema": {
"type": "boolean",
"enum": [
true,
false
]
},
"name": "bool_enum",
"in": "query"
}
],
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
"schema": { }
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from .bodies import BodiesEndpoints
from .default import DefaultEndpoints
from .defaults import DefaultsEndpoints
from .enums import EnumsEndpoints
from .location import LocationEndpoints
from .naming import NamingEndpoints
from .parameter_references import ParameterReferencesEndpoints
Expand All @@ -28,6 +29,10 @@ def tests(cls) -> Type[TestsEndpoints]:
def defaults(cls) -> Type[DefaultsEndpoints]:
return DefaultsEndpoints

@classmethod
def enums(cls) -> Type[EnumsEndpoints]:
return EnumsEndpoints

@classmethod
def responses(cls) -> Type[ResponsesEndpoints]:
return ResponsesEndpoints
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
""" Contains methods for accessing the API Endpoints """

import types

from . import bool_enum_tests_bool_enum_post, int_enum_tests_int_enum_post


class EnumsEndpoints:
@classmethod
def int_enum_tests_int_enum_post(cls) -> types.ModuleType:
"""
Int Enum
"""
return int_enum_tests_int_enum_post

@classmethod
def bool_enum_tests_bool_enum_post(cls) -> types.ModuleType:
"""
Bool Enum
"""
return bool_enum_tests_bool_enum_post
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
get_basic_list_of_integers,
get_basic_list_of_strings,
get_user_list,
int_enum_tests_int_enum_post,
json_body_tests_json_body_post,
no_response_tests_no_response_get,
octet_stream_tests_octet_stream_get,
Expand Down Expand Up @@ -132,13 +131,6 @@ def unsupported_content_tests_unsupported_content_get(cls) -> types.ModuleType:
"""
return unsupported_content_tests_unsupported_content_get

@classmethod
def int_enum_tests_int_enum_post(cls) -> types.ModuleType:
"""
Int Enum
"""
return int_enum_tests_int_enum_post

@classmethod
def test_inline_objects(cls) -> types.ModuleType:
"""
Expand Down
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
from http import HTTPStatus
from typing import Any, Dict, Optional, Union

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...types import UNSET, Response


def _get_kwargs(
*,
bool_enum: bool,
) -> Dict[str, Any]:
params: Dict[str, Any] = {}

params["bool_enum"] = bool_enum

params = {k: v for k, v in params.items() if v is not UNSET and v is not None}

_kwargs: Dict[str, Any] = {
"method": "post",
"url": "/enum/bool",
"params": params,
}

return _kwargs


def _parse_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Optional[Any]:
if response.status_code == HTTPStatus.OK:
return None
if client.raise_on_unexpected_status:
raise errors.UnexpectedStatus(response.status_code, response.content)
else:
return None


def _build_response(*, client: Union[AuthenticatedClient, Client], response: httpx.Response) -> Response[Any]:
return Response(
status_code=HTTPStatus(response.status_code),
content=response.content,
headers=response.headers,
parsed=_parse_response(client=client, response=response),
)


def sync_detailed(
*,
client: Union[AuthenticatedClient, Client],
bool_enum: bool,
) -> Response[Any]:
"""Bool Enum

Args:
bool_enum (bool):

Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.

Returns:
Response[Any]
"""

kwargs = _get_kwargs(
bool_enum=bool_enum,
)

response = client.get_httpx_client().request(
**kwargs,
)

return _build_response(client=client, response=response)


async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
bool_enum: bool,
) -> Response[Any]:
"""Bool Enum

Args:
bool_enum (bool):

Raises:
errors.UnexpectedStatus: If the server returns an undocumented status code and Client.raise_on_unexpected_status is True.
httpx.TimeoutException: If the request takes longer than Client.timeout.

Returns:
Response[Any]
"""

kwargs = _get_kwargs(
bool_enum=bool_enum,
)

response = await client.get_async_httpx_client().request(**kwargs)

return _build_response(client=client, response=response)
Loading