Skip to content

Fix mixed case properties & params #972

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 7 commits into from
Feb 22, 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
10 changes: 10 additions & 0 deletions .changeset/allow_parameters_with_names_differing_only_by_case.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
default: patch
---

# Allow parameters with names differing only by case

If you have two parameters to an endpoint named `mixedCase` and `mixed_case`, previously, this was a conflict and the endpoint would not be generated.
Now, the generator will skip snake-casing the parameters and use the names as-is. Note that this means if neither of the parameters _was_ snake case, neither _will be_ in the generated code.

Fixes #922 reported by @macmoritz & @benedikt-bartscher.
32 changes: 32 additions & 0 deletions .changeset/fix_naming_conflicts_with_properties_in_models.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
default: patch
---

# Fix naming conflicts with properties in models with mixed casing

If you had an object with two properties, where the names differed only by case, conflicting properties would be generated in the model, which then failed the linting step (when using default config). For example, this:

```yaml
type: "object"
properties:
MixedCase:
type: "string"
mixedCase:
type: "string"
```

Would generate a class like this:

```python
class MyModel:
mixed_case: str
mixed_case: str
```

Now, neither of the properties will be forced into snake case, and the generated code will look like this:

```python
class MyModel:
MixedCase: str
mixedCase: str
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
---
default: major
---

# For custom templates, changed type of endpoint parameters

**This does not affect projects that are not using `--custom-template-path`**

The type of these properties on `Endpoint` has been changed from `Dict[str, Property]` to `List[Property]`:

- `path_parameters`
- `query_parameters`
- `header_parameters`
- `cookie_parameters`

If your templates are very close to the default templates, you can probably just remove `.values()` anywhere it appears.

The type of `iter_all_parameters()` is also different, you probably want `list_all_parameters()` instead.
7 changes: 7 additions & 0 deletions .changeset/updated_generated_config_for_ruff_v02.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
default: major
---

# Updated generated config for Ruff v0.2

This only affects projects using the `generate` command, not the `update` command. The `pyproject.toml` file generated which configures Ruff for linting and formatting has been updated to the 0.2 syntax, which means it will no longer work with Ruff 0.1.
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
default: major
---

# Updated naming strategy for conflicting properties

While fixing #922, some naming strategies were updated. These should mostly be backwards compatible, but there may be
some small differences in generated code. Make sure to check your diffs before pushing updates to consumers!
44 changes: 44 additions & 0 deletions end_to_end_tests/baseline_openapi_3.0.json
Original file line number Diff line number Diff line change
Expand Up @@ -1413,6 +1413,50 @@
}
}
},
"/naming/mixed-case": {
"get": {
"tags": ["naming"],
"operationId": "mixed_case",
"parameters": [
{
"name": "mixed_case",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "mixedCase",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"mixed_case": {
"type": "string"
},
"mixedCase": {
"type": "string"
}
}
}
}
}
}
}
}
},
"/parameter-references/{path_param}": {
"get": {
"tags": [
Expand Down
44 changes: 44 additions & 0 deletions end_to_end_tests/baseline_openapi_3.1.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1407,6 +1407,50 @@ info:
}
}
},
"/naming/mixed-case": {
"get": {
"tags": [ "naming" ],
"operationId": "mixed_case",
"parameters": [
{
"name": "mixed_case",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "mixedCase",
"in": "query",
"required": true,
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "Successful response",
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"mixed_case": {
"type": "string"
},
"mixedCase": {
"type": "string"
}
}
}
}
}
}
}
}
},
"/parameter-references/{path_param}": {
"get": {
"tags": [
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,14 @@

import types

from . import post_naming_property_conflict_with_import
from . import mixed_case, post_naming_property_conflict_with_import


class NamingEndpoints:
@classmethod
def post_naming_property_conflict_with_import(cls) -> types.ModuleType:
return post_naming_property_conflict_with_import

@classmethod
def mixed_case(cls) -> types.ModuleType:
return mixed_case
Original file line number Diff line number Diff line change
@@ -0,0 +1,169 @@
from http import HTTPStatus
from typing import Any, Dict, Optional, Union

import httpx

from ... import errors
from ...client import AuthenticatedClient, Client
from ...models.mixed_case_response_200 import MixedCaseResponse200
from ...types import UNSET, Response


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

params["mixed_case"] = mixed_case

params["mixedCase"] = mixedCase

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

_kwargs: Dict[str, Any] = {
"method": "get",
"url": "/naming/mixed-case",
"params": params,
}

return _kwargs


def _parse_response(
*, client: Union[AuthenticatedClient, Client], response: httpx.Response
) -> Optional[MixedCaseResponse200]:
if response.status_code == HTTPStatus.OK:
response_200 = MixedCaseResponse200.from_dict(response.json())

return response_200
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[MixedCaseResponse200]:
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],
mixed_case: str,
mixedCase: str,
) -> Response[MixedCaseResponse200]:
"""
Args:
mixed_case (str):
mixedCase (str):

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[MixedCaseResponse200]
"""

kwargs = _get_kwargs(
mixed_case=mixed_case,
mixedCase=mixedCase,
)

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

return _build_response(client=client, response=response)


def sync(
*,
client: Union[AuthenticatedClient, Client],
mixed_case: str,
mixedCase: str,
) -> Optional[MixedCaseResponse200]:
"""
Args:
mixed_case (str):
mixedCase (str):

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:
MixedCaseResponse200
"""

return sync_detailed(
client=client,
mixed_case=mixed_case,
mixedCase=mixedCase,
).parsed


async def asyncio_detailed(
*,
client: Union[AuthenticatedClient, Client],
mixed_case: str,
mixedCase: str,
) -> Response[MixedCaseResponse200]:
"""
Args:
mixed_case (str):
mixedCase (str):

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[MixedCaseResponse200]
"""

kwargs = _get_kwargs(
mixed_case=mixed_case,
mixedCase=mixedCase,
)

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

return _build_response(client=client, response=response)


async def asyncio(
*,
client: Union[AuthenticatedClient, Client],
mixed_case: str,
mixedCase: str,
) -> Optional[MixedCaseResponse200]:
"""
Args:
mixed_case (str):
mixedCase (str):

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:
MixedCaseResponse200
"""

return (
await asyncio_detailed(
client=client,
mixed_case=mixed_case,
mixedCase=mixedCase,
)
).parsed
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
from .http_validation_error import HTTPValidationError
from .import_ import Import
from .json_like_body import JsonLikeBody
from .mixed_case_response_200 import MixedCaseResponse200
from .model_from_all_of import ModelFromAllOf
from .model_name import ModelName
from .model_reference_with_periods import ModelReferenceWithPeriods
Expand Down Expand Up @@ -116,6 +117,7 @@
"HTTPValidationError",
"Import",
"JsonLikeBody",
"MixedCaseResponse200",
"ModelFromAllOf",
"ModelName",
"ModelReferenceWithPeriods",
Expand Down
Loading