Skip to content

Commit 5fceefe

Browse files
committedJan 27, 2023
:feat: Using fields in Pydantic models to leverage the alias feature
:feat: Cleaning names in parameters, in order for python to understand them. :feat: Added Regression test for #7. Also fixes #7
1 parent 89c5681 commit 5fceefe

File tree

8 files changed

+24937
-24
lines changed

8 files changed

+24937
-24
lines changed
 

‎noxfile.py

-9
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626
nox.needs_version = ">= 2021.6.6"
2727
nox.options.sessions = (
2828
"pre-commit",
29-
"safety",
3029
"mypy",
3130
"tests",
3231
"typeguard",
@@ -136,14 +135,6 @@ def precommit(session: Session) -> None:
136135
activate_virtualenv_in_precommit_hooks(session)
137136

138137

139-
@session(python=python_versions[0])
140-
def safety(session: Session) -> None:
141-
"""Scan dependencies for insecure packages."""
142-
requirements = session.poetry.export_requirements()
143-
session.install("safety")
144-
session.run("safety", "check", "--full-report", f"--file={requirements}")
145-
146-
147138
@session(python=python_versions)
148139
def mypy(session: Session) -> None:
149140
"""Type-check using mypy."""

‎pyproject.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "openapi-python-generator"
3-
version = "0.3.9"
3+
version = "0.3.10"
44
description = "Openapi Python Generator"
55
authors = ["Marco Müllner <muellnermarco@gmail.com>"]
66
license = "MIT"

‎src/openapi_python_generator/generate_data.py

+12-9
Original file line numberDiff line numberDiff line change
@@ -28,15 +28,18 @@ def write_code(path: Path, content) -> None:
2828
:param path: The path to the file.
2929
:param content: The content to write.
3030
"""
31-
with open(path, "w") as f:
32-
try:
33-
formatted_contend = black.format_file_contents(
34-
content, fast=False, mode=black.FileMode(line_length=120)
35-
)
36-
except NothingChanged:
37-
formatted_contend = content
38-
formatted_contend = isort.code(formatted_contend, line_length=120)
39-
f.write(formatted_contend)
31+
try:
32+
with open(path, "w") as f:
33+
try:
34+
formatted_contend = black.format_file_contents(
35+
content, fast=False, mode=black.FileMode(line_length=120)
36+
)
37+
except NothingChanged:
38+
formatted_contend = content
39+
formatted_contend = isort.code(formatted_contend, line_length=120)
40+
f.write(formatted_contend)
41+
except Exception as e:
42+
raise e
4043

4144

4245
def get_open_api(source: Union[str, Path]) -> OpenAPI:

‎src/openapi_python_generator/language_converters/python/service_generator.py

+30-3
Original file line numberDiff line numberDiff line change
@@ -106,13 +106,29 @@ def _generate_params_from_content(content: Union[Reference, Schema]):
106106
else:
107107
default_params += f"{converted_result}, "
108108

109+
operation_request_body_types = [
110+
"application/json",
111+
"text/plain",
112+
"multipart/form-data",
113+
]
114+
109115
if operation.requestBody is not None:
110116
if (
111117
isinstance(operation.requestBody, RequestBody)
112118
and isinstance(operation.requestBody.content, dict)
113-
and operation.requestBody.content.get("application/json") is not None
119+
and any(
120+
[
121+
operation.requestBody.content.get(i) is not None
122+
for i in operation_request_body_types
123+
]
124+
)
114125
):
115-
content = operation.requestBody.content.get("application/json")
126+
get_keyword = [
127+
i
128+
for i in operation_request_body_types
129+
if operation.requestBody.content.get(i) is not None
130+
][0]
131+
content = operation.requestBody.content.get(get_keyword)
116132
if content is not None and (
117133
isinstance(content.media_type_schema, Schema)
118134
or isinstance(content.media_type_schema, Reference)
@@ -128,6 +144,9 @@ def _generate_params_from_content(content: Union[Reference, Schema]):
128144
raise Exception(
129145
f"Unsupported request body type: {type(operation.requestBody)}"
130146
)
147+
# Replace - with _ in params
148+
params = params.replace("-", "_")
149+
default_params = default_params.replace("-", "_")
131150

132151
return params + default_params
133152

@@ -146,7 +165,9 @@ def generate_query_params(operation: Operation) -> List[str]:
146165
params = []
147166
for param in operation.parameters:
148167
if isinstance(param, Parameter) and param.param_in == "query":
149-
params.append(f"'{param.name}' : {param.name}")
168+
param_name_cleaned = param.name.replace("-", "_")
169+
170+
params.append(f"'{param.name}' : {param_name_cleaned}")
150171

151172
return params
152173

@@ -211,6 +232,12 @@ def generate_return_type(operation: Operation) -> OpReturnType:
211232
)
212233
else:
213234
raise Exception("Unknown media type schema type") # pragma: no cover
235+
elif media_type_schema is None:
236+
return OpReturnType(
237+
type=None,
238+
status_code=good_responses[0][0],
239+
complex_type=False,
240+
)
214241
else:
215242
raise Exception("Unknown media type schema type") # pragma: no cover
216243

‎src/openapi_python_generator/language_converters/python/templates/models.jinja2

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from typing import *
2-
from pydantic import BaseModel
2+
from pydantic import BaseModel, Field
33
{% for property in properties %}
44
{% if property.type.import_types is not none %}
55
{% for import_type in property.type.import_types %}
@@ -18,5 +18,5 @@ class {{ schema_name }}(BaseModel):
1818
"""
1919
{% for property in properties %}
2020

21-
{{ property.name }} : {{ property.type.converted_type }} {% if not property.required %} = {{ property.default }} {% endif %}
21+
{{ property.name | replace("@","")}} : {{ property.type.converted_type }} = Field(alias="{{ property.name }}" {% if not property.required %}, default = {{ property.default }} {% endif %})
2222
{% endfor %}

‎tests/regression/__init__.py

Whitespace-only changes.

‎tests/regression/test_issue_7.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import pytest
2+
from click.testing import CliRunner
3+
4+
from openapi_python_generator.common import HTTPLibrary
5+
6+
from tests.conftest import test_data_folder
7+
from tests.conftest import test_result_path
8+
from openapi_python_generator.__main__ import main
9+
10+
11+
@pytest.fixture
12+
def runner() -> CliRunner:
13+
"""Fixture for invoking command-line interfaces."""
14+
return CliRunner()
15+
16+
17+
@pytest.mark.parametrize(
18+
"library",
19+
[
20+
HTTPLibrary.httpx,
21+
HTTPLibrary.requests,
22+
],
23+
)
24+
25+
def test_issue_7(runner: CliRunner, model_data_with_cleanup, library) -> None:
26+
"""
27+
https://github.com/MarcoMuellner/openapi-python-generator/issues/7
28+
"""
29+
result = runner.invoke(
30+
main,
31+
[str(test_data_folder / "openapi_gitea_converted.json" ), str(test_result_path), "--library", library.value],
32+
)
33+
assert result.exit_code == 0
34+
pass

‎tests/test_data/openapi_gitea_converted.json

+24,858
Large diffs are not rendered by default.

0 commit comments

Comments
 (0)
Please sign in to comment.