Skip to content
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

Diorcety fix fastapi #19822

Closed
wants to merge 5 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 @@ -50,6 +50,7 @@
import org.openapitools.codegen.CodegenOperation;
import org.openapitools.codegen.CodegenParameter;
import org.openapitools.codegen.CodegenProperty;
import org.openapitools.codegen.CodegenResponse;
import org.openapitools.codegen.DefaultCodegen;
import org.openapitools.codegen.GeneratorLanguage;
import org.openapitools.codegen.IJsonSchemaValidationProperties;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,8 @@ public String getTypeDeclaration(Schema p) {

@Override
public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List<ModelMap> allModels) {
super.postProcessOperationsWithModels(objs, allModels);

OperationMap operations = objs.getOperations();
// Set will make sure that no duplicated items are used.
Set<String> securityImports = new HashSet<>();
Expand Down
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{{#isString}}str{{/isString}}{{#isInteger}}int{{/isInteger}}{{#isLong}}int{{/isLong}}{{#isFloat}}float{{/isFloat}}{{#isDouble}}float{{/isDouble}}{{#isByteArray}}str{{/isByteArray}}{{#isBinary}}str{{/isBinary}}{{#isBoolean}}bool{{/isBoolean}}{{#isDate}}str{{/isDate}}{{#isDateTime}}str{{/isDateTime}}{{#isModel}}{{dataType}}{{/isModel}}{{#isContainer}}{{dataType}}{{/isContainer}}
{{{vendorExtensions.x-py-typing}}}
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package org.openapitools.codegen.python;

import com.google.common.collect.Sets;
import io.swagger.parser.OpenAPIParser;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.parser.core.models.ParseOptions;
import org.openapitools.codegen.*;
import org.openapitools.codegen.languages.PythonClientCodegen;
import org.openapitools.codegen.languages.PythonFastAPIServerCodegen;
import org.openapitools.codegen.languages.features.CXFServerFeatures;
import org.testng.Assert;
import org.testng.annotations.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

import static org.openapitools.codegen.TestUtils.assertFileContains;
import static org.openapitools.codegen.TestUtils.assertFileExists;

public class PythonFastAPIServerCodegenTest {

// Helper function, intended to reduce boilerplate
static private String generateFiles(DefaultCodegen codegen, String filePath) throws IOException {
final File output = Files.createTempDirectory("test").toFile().getCanonicalFile();
output.deleteOnExit();
final String outputPath = output.getAbsolutePath().replace('\\', '/');

codegen.setOutputDir(output.getAbsolutePath());
codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true");

final ClientOptInput input = new ClientOptInput();
final OpenAPI openAPI = new OpenAPIParser().readLocation(filePath, null, new ParseOptions()).getOpenAPI();
input.openAPI(openAPI);
input.config(codegen);

final DefaultGenerator generator = new DefaultGenerator();
final List<File> files = generator.opts(input).generate();

Assert.assertTrue(files.size() > 0);
return outputPath + "/";
}


@Test(description = "test containerType in parameters")
public void testContainerType() throws IOException {
final DefaultCodegen codegen = new PythonFastAPIServerCodegen();
final String outputPath = generateFiles(codegen, "src/test/resources/bugs/pr_18691.json");
final Path p = Paths.get(outputPath + "src/openapi_server/apis/default_api.py");

assertFileExists(p);
assertFileContains(p, "body: Optional[Dict[str, Any]] = Body(None, description=\"\"),");
}
}
24 changes: 24 additions & 0 deletions modules/openapi-generator/src/test/resources/bugs/pr_18691.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"openapi": "3.0.1",
"info": {
"title": "OpenAPI definition",
"version": "v0"
},
"paths": {
"/licensing/token/renew": {
"post": {
"description": "Manually ask license issuer for a new token. Available in Grafana Enterprise v7.4+.\n\nYou need to have a permission with action `licensing:update`.",
"operationId": "postRenewLicenseToken",
"requestBody": {
"content": {
"application/json": {
"schema": {
"type": "object"
}
}
}
}
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
)

from openapi_server.models.extra_models import TokenModel # noqa: F401
from pydantic import Field, StrictStr
from typing import Optional
from typing_extensions import Annotated


router = APIRouter()
Expand All @@ -43,8 +46,8 @@
response_model_by_alias=True,
)
async def fake_query_param_default(
has_default: str = Query('Hello World', description="has default value", alias="hasDefault"),
no_default: str = Query(None, description="no default value", alias="noDefault"),
has_default: Annotated[Optional[StrictStr], Field(description="has default value")] = Query('Hello World', description="has default value", alias="hasDefault"),
no_default: Annotated[Optional[StrictStr], Field(description="no default value")] = Query(None, description="no default value", alias="noDefault"),
) -> None:
""""""
if not BaseFakeApi.subclasses:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

from typing import ClassVar, Dict, List, Tuple # noqa: F401

from pydantic import Field, StrictStr
from typing import Optional
from typing_extensions import Annotated


class BaseFakeApi:
Expand All @@ -12,8 +15,8 @@ def __init_subclass__(cls, **kwargs):
BaseFakeApi.subclasses = BaseFakeApi.subclasses + (cls,)
async def fake_query_param_default(
self,
has_default: str,
no_default: str,
has_default: Annotated[Optional[StrictStr], Field(description="has default value")],
no_default: Annotated[Optional[StrictStr], Field(description="no default value")],
) -> None:
""""""
...
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
)

from openapi_server.models.extra_models import TokenModel # noqa: F401
from pydantic import Field, StrictBytes, StrictInt, StrictStr, field_validator
from typing import List, Optional, Tuple, Union
from typing_extensions import Annotated
from openapi_server.models.api_response import ApiResponse
from openapi_server.models.pet import Pet
from openapi_server.security_api import get_token_petstore_auth, get_token_api_key
Expand All @@ -45,7 +48,7 @@
response_model_by_alias=True,
)
async def add_pet(
pet: Pet = Body(None, description="Pet object that needs to be added to the store"),
pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")] = Body(None, description="Pet object that needs to be added to the store"),
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
Expand All @@ -66,8 +69,8 @@ async def add_pet(
response_model_by_alias=True,
)
async def delete_pet(
petId: int = Path(..., description="Pet id to delete"),
api_key: str = Header(None, description=""),
petId: Annotated[StrictInt, Field(description="Pet id to delete")] = Path(..., description="Pet id to delete"),
api_key: Optional[StrictStr] = Header(None, description=""),
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
Expand All @@ -89,7 +92,7 @@ async def delete_pet(
response_model_by_alias=True,
)
async def find_pets_by_status(
status: List[str] = Query(None, description="Status values that need to be considered for filter", alias="status"),
status: Annotated[List[StrictStr], Field(description="Status values that need to be considered for filter")] = Query(None, description="Status values that need to be considered for filter", alias="status"),
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["read:pets"]
),
Expand All @@ -111,7 +114,7 @@ async def find_pets_by_status(
response_model_by_alias=True,
)
async def find_pets_by_tags(
tags: List[str] = Query(None, description="Tags to filter by", alias="tags"),
tags: Annotated[List[StrictStr], Field(description="Tags to filter by")] = Query(None, description="Tags to filter by", alias="tags"),
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["read:pets"]
),
Expand All @@ -134,7 +137,7 @@ async def find_pets_by_tags(
response_model_by_alias=True,
)
async def get_pet_by_id(
petId: int = Path(..., description="ID of pet to return"),
petId: Annotated[StrictInt, Field(description="ID of pet to return")] = Path(..., description="ID of pet to return"),
token_api_key: TokenModel = Security(
get_token_api_key
),
Expand All @@ -158,7 +161,7 @@ async def get_pet_by_id(
response_model_by_alias=True,
)
async def update_pet(
pet: Pet = Body(None, description="Pet object that needs to be added to the store"),
pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")] = Body(None, description="Pet object that needs to be added to the store"),
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
Expand All @@ -179,9 +182,9 @@ async def update_pet(
response_model_by_alias=True,
)
async def update_pet_with_form(
petId: int = Path(..., description="ID of pet that needs to be updated"),
name: str = Form(None, description="Updated name of the pet"),
status: str = Form(None, description="Updated status of the pet"),
petId: Annotated[StrictInt, Field(description="ID of pet that needs to be updated")] = Path(..., description="ID of pet that needs to be updated"),
name: Annotated[Optional[StrictStr], Field(description="Updated name of the pet")] = Form(None, description="Updated name of the pet"),
status: Annotated[Optional[StrictStr], Field(description="Updated status of the pet")] = Form(None, description="Updated status of the pet"),
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
Expand All @@ -202,9 +205,9 @@ async def update_pet_with_form(
response_model_by_alias=True,
)
async def upload_file(
petId: int = Path(..., description="ID of pet to update"),
additional_metadata: str = Form(None, description="Additional data to pass to server"),
file: str = Form(None, description="file to upload"),
petId: Annotated[StrictInt, Field(description="ID of pet to update")] = Path(..., description="ID of pet to update"),
additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = Form(None, description="Additional data to pass to server"),
file: Annotated[Optional[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]]], Field(description="file to upload")] = Form(None, description="file to upload"),
token_petstore_auth: TokenModel = Security(
get_token_petstore_auth, scopes=["write:pets", "read:pets"]
),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

from typing import ClassVar, Dict, List, Tuple # noqa: F401

from pydantic import Field, StrictBytes, StrictInt, StrictStr, field_validator
from typing import List, Optional, Tuple, Union
from typing_extensions import Annotated
from openapi_server.models.api_response import ApiResponse
from openapi_server.models.pet import Pet
from openapi_server.security_api import get_token_petstore_auth, get_token_api_key
Expand All @@ -14,68 +17,68 @@ def __init_subclass__(cls, **kwargs):
BasePetApi.subclasses = BasePetApi.subclasses + (cls,)
async def add_pet(
self,
pet: Pet,
pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")],
) -> Pet:
""""""
...


async def delete_pet(
self,
petId: int,
api_key: str,
petId: Annotated[StrictInt, Field(description="Pet id to delete")],
api_key: Optional[StrictStr],
) -> None:
""""""
...


async def find_pets_by_status(
self,
status: List[str],
status: Annotated[List[StrictStr], Field(description="Status values that need to be considered for filter")],
) -> List[Pet]:
"""Multiple status values can be provided with comma separated strings"""
...


async def find_pets_by_tags(
self,
tags: List[str],
tags: Annotated[List[StrictStr], Field(description="Tags to filter by")],
) -> List[Pet]:
"""Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing."""
...


async def get_pet_by_id(
self,
petId: int,
petId: Annotated[StrictInt, Field(description="ID of pet to return")],
) -> Pet:
"""Returns a single pet"""
...


async def update_pet(
self,
pet: Pet,
pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")],
) -> Pet:
""""""
...


async def update_pet_with_form(
self,
petId: int,
name: str,
status: str,
petId: Annotated[StrictInt, Field(description="ID of pet that needs to be updated")],
name: Annotated[Optional[StrictStr], Field(description="Updated name of the pet")],
status: Annotated[Optional[StrictStr], Field(description="Updated status of the pet")],
) -> None:
""""""
...


async def upload_file(
self,
petId: int,
additional_metadata: str,
file: str,
petId: Annotated[StrictInt, Field(description="ID of pet to update")],
additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")],
file: Annotated[Optional[Union[StrictBytes, StrictStr, Tuple[StrictStr, StrictBytes]]], Field(description="file to upload")],
) -> ApiResponse:
""""""
...
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
)

from openapi_server.models.extra_models import TokenModel # noqa: F401
from pydantic import Field, StrictInt, StrictStr
from typing import Dict
from typing_extensions import Annotated
from openapi_server.models.order import Order
from openapi_server.security_api import get_token_api_key

Expand All @@ -44,7 +47,7 @@
response_model_by_alias=True,
)
async def delete_order(
orderId: str = Path(..., description="ID of the order that needs to be deleted"),
orderId: Annotated[StrictStr, Field(description="ID of the order that needs to be deleted")] = Path(..., description="ID of the order that needs to be deleted"),
) -> None:
"""For valid response try integer IDs with value &lt; 1000. Anything above 1000 or nonintegers will generate API errors"""
if not BaseStoreApi.subclasses:
Expand Down Expand Up @@ -84,7 +87,7 @@ async def get_inventory(
response_model_by_alias=True,
)
async def get_order_by_id(
orderId: int = Path(..., description="ID of pet that needs to be fetched", ge=1, le=5),
orderId: Annotated[int, Field(le=5, strict=True, ge=1, description="ID of pet that needs to be fetched")] = Path(..., description="ID of pet that needs to be fetched", ge=1, le=5),
) -> Order:
"""For valid response try integer IDs with value &lt;&#x3D; 5 or &gt; 10. Other values will generate exceptions"""
if not BaseStoreApi.subclasses:
Expand All @@ -103,7 +106,7 @@ async def get_order_by_id(
response_model_by_alias=True,
)
async def place_order(
order: Order = Body(None, description="order placed for purchasing the pet"),
order: Annotated[Order, Field(description="order placed for purchasing the pet")] = Body(None, description="order placed for purchasing the pet"),
) -> Order:
""""""
if not BaseStoreApi.subclasses:
Expand Down
Loading
Loading