Skip to content

Commit

Permalink
Merge pull request #1697 from lnash94/record-name-revert
Browse files Browse the repository at this point in the history
[master] Fix for removing `getValidName()` usage in record Name generation for OAS to Ballerina service/client
  • Loading branch information
lnash94 authored Apr 30, 2024
2 parents c260728 + 70c92f3 commit 3a5d5d7
Show file tree
Hide file tree
Showing 79 changed files with 687 additions and 692 deletions.
7 changes: 4 additions & 3 deletions .github/workflows/pull-request.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,10 @@ jobs:
packagePAT: ${{ secrets.GITHUB_TOKEN }}
run: |
./gradlew build codeCoverageReport --stacktrace --scan --console=plain --no-daemon
- name: Generate Codecov Report
if: github.event_name == 'pull_request'
uses: codecov/codecov-action@v1
# - name: Generate Codecov Report
# if: github.event_name == 'pull_request'
# uses: codecov/codecov-action@v1
# todo: uncomment this block when the issue with the code coverage report is resolved

windows-build:

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public void getReturnTypeTests() throws IOException, BallerinaOpenApiException {
TypeHandler.createInstance(response, false);
FunctionReturnTypeGeneratorImp functionReturnType = new FunctionReturnTypeGeneratorImp(
response.getPaths().get("/products").getGet(), response, "get");
assertEquals(functionReturnType.getReturnType().get().type().toString(), "Inline_response_200|error");
assertEquals(functionReturnType.getReturnType().get().type().toString(), "inline_response_200|error");
}

@Test(description = "Tests for returnType")
Expand All @@ -55,7 +55,7 @@ public void getReturnTypeForAllOf() throws IOException, BallerinaOpenApiExceptio
TypeHandler.createInstance(response, false);
Operation post = response.getPaths().get("/users/{userId}/meetings").getPost();
FunctionReturnTypeGeneratorImp functionReturnType = new FunctionReturnTypeGeneratorImp(post, response, "post");
assertEquals(functionReturnType.getReturnType().get().type().toString(), "Inline_response_201|error");
assertEquals(functionReturnType.getReturnType().get().type().toString(), "inline_response_201|error");
}

@Test(description = "Tests for the object response without property")
Expand All @@ -79,7 +79,7 @@ public void getReturnTypeForMapSchema() throws IOException, BallerinaOpenApiExce
FunctionReturnTypeGeneratorImp functionReturnType = new FunctionReturnTypeGeneratorImp(get, response, "get");

String returnType = functionReturnType.getReturnType().get().type().toString();
Assert.assertEquals(returnType, "Inline_response_200|error");
Assert.assertEquals(returnType, "inline_response_200|error");
}

@Test(description = "Tests for the object response without property and without additional properties")
Expand All @@ -101,7 +101,7 @@ public void getReturnTypeForMapSchemaWithOutAdditionalProperties() throws IOExce
Operation get = response.getPaths().get("/products").getGet();
FunctionReturnTypeGeneratorImp functionReturnType = new FunctionReturnTypeGeneratorImp(get, response, "get");
String returnType = functionReturnType.getReturnType().get().type().toString();
Assert.assertEquals(returnType, "Inline_response_200|error");
Assert.assertEquals(returnType, "inline_response_200|error");
}
// 1. nested allof
// 2. allof with reference
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ public void checkDiagnosticIssuesWithResourceFunctions(String yamlFile) throws I
Assert.assertFalse(hasErrors);
}

//todo
@Test(description = "Test OpenAPI 3.1 definition to ballerina client source code generation with remote functions",
dataProvider = "fileProviderForOpenAPI31DiagnosticCheck", enabled = false)
public void checkDiagnosticIssuesWithRemoteFunctionsOpenAPIV31(String yamlFile) throws IOException,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,9 @@ public Object[][] dataProviderForFunctionBody() {
{"client/swagger/multipart_formdata_custom.yaml", "/pets", "{string resourcePath = string `/pets`;\n" +
"http:Request request = new;\n" +
"map<Encoding> encodingMap = {\"profileImage\": {contentType: \"image/png\", headers: " +
"{\"X-Custom-Header\": xCustomHeader}}, \"id\":{headers: {\"X-Custom-Header\": " +
"xCustomHeader}}, \"address\": {headers:{\"X-Address-Header\":xAddressHeader}}, \"name\":" +
"{\"X-Custom-Header\": X\\-Custom\\-Header}}, \"id\":{headers: {\"X-Custom-Header\": " +
"X\\-Custom\\-Header}}, \"address\": {headers:{\"X-Address-Header\":X\\-Address\\-Header}}, " +
"\"name\":" +
"{contentType:\"text/plain\"}};\n" +
"mime:Entity[] bodyParts = check createBodyParts(payload, encodingMap);\n" +
"request.setBodyParts(bodyParts);\n" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public void testFunctionSignatureNodeForMultipartCustomHeader() throws IOExcepti

RequiredParameterNode param01 = (RequiredParameterNode) parameters.get(0);
Assert.assertEquals(param01.paramName().orElseThrow().text(), "payload");
Assert.assertEquals(param01.typeName().toString(), "Pets_body");
Assert.assertEquals(param01.typeName().toString(), "pets_body");

RequiredParameterNode param02 = (RequiredParameterNode) parameters.get(1);
Assert.assertEquals(param02.paramName().orElseThrow().text(), "X\\-Address\\-Header");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ public void getReturnTypeForMapSchema() throws IOException, BallerinaOpenApiExce
FunctionReturnTypeGeneratorImp functionReturnType = new FunctionReturnTypeGeneratorImp(
openapi.getPaths().get("/products").getGet(), openapi, "get");
String returnType = functionReturnType.getReturnType().get().type().toString();
Assert.assertEquals(returnType, "Inline_response_200|error");
Assert.assertEquals(returnType, "inline_response_200|error");
}

@Test(description = "Tests for the object response without property and without additional properties")
Expand All @@ -118,7 +118,7 @@ public void getReturnTypeForMapSchemaWithOutAdditionalProperties() throws IOExce
FunctionReturnTypeGeneratorImp functionReturnType = new FunctionReturnTypeGeneratorImp(
openapi.getPaths().get("/products").getGet(), openapi, "get");
String returnType = functionReturnType.getReturnType().get().type().toString();
Assert.assertEquals(returnType, "Inline_response_200|error");
Assert.assertEquals(returnType, "inline_response_200|error");
}

@Test(description = "Tests for the response with no schema")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ public void getReturnTypeOneOfArray() throws IOException, BallerinaOpenApiExcept
FunctionReturnTypeGeneratorImp functionReturnType = new FunctionReturnTypeGeneratorImp(
openapi.getPaths().get("/pet").getGet(), openapi, "get");
Assert.assertEquals(functionReturnType.getReturnType().get().type().toString(),
"Inline_response_2XX|error");
"inline_response_2XX|error");
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
import io.ballerina.openapi.core.generators.common.GeneratorUtils;
import io.ballerina.openapi.core.generators.common.TypeHandler;
import io.ballerina.openapi.core.generators.common.exception.BallerinaOpenApiException;
import io.ballerina.openapi.core.generators.type.BallerinaTypesGenerator;
import io.ballerina.openapi.core.generators.type.exception.OASTypeGenException;
import io.ballerina.projects.DocumentId;
import io.ballerina.projects.Module;
Expand All @@ -36,10 +35,8 @@
import io.ballerina.projects.ProjectKind;
import io.ballerina.projects.directory.ProjectLoader;
import io.ballerina.tools.diagnostics.Diagnostic;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.SpecVersion;
import io.swagger.v3.oas.models.media.Schema;
import org.ballerinalang.formatter.core.Formatter;
import org.ballerinalang.formatter.core.FormatterException;
import org.testng.Assert;
Expand All @@ -51,11 +48,9 @@
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand Down Expand Up @@ -84,9 +79,6 @@ public static List<Diagnostic> getDiagnostics(SyntaxTree syntaxTree, OpenAPI ope
List<TypeDefinitionNode> preGeneratedTypeDefinitionNodes = new LinkedList<>();
preGeneratedTypeDefinitionNodes.addAll(ballerinaClientGenerator.
getBallerinaAuthConfigGenerator().getAuthRelatedTypeDefinitionNodes());
// preGeneratedTypeDefinitionNodes.addAll(ballerinaClientGenerator.getTypeDefinitionNodeList());
BallerinaTypesGenerator ballerinaSchemaGenerator = new BallerinaTypesGenerator(
openAPI, false);
TypeHandler.createInstance(openAPI, false);
SyntaxTree schemaSyntax = TypeHandler.getInstance().generateTypeSyntaxTree();
SyntaxTree utilSyntaxTree = ballerinaClientGenerator.getBallerinaUtilGenerator().generateUtilSyntaxTree();
Expand Down Expand Up @@ -250,20 +242,6 @@ public static OpenAPI normalizeOpenAPI(Path openAPIPath, boolean isClient, SpecV
GeneratorUtils.validateOperationIds(openAPIPaths.entrySet());
}
GeneratorUtils.validateRequestBody(openAPIPaths.entrySet());

if (openAPI.getComponents() != null) {
// Refactor schema name with valid name
Components components = openAPI.getComponents();
Map<String, Schema> componentsSchemas = components.getSchemas();
if (componentsSchemas != null) {
Map<String, Schema> refacSchema = new HashMap<>();
for (Map.Entry<String, Schema> schemaEntry : componentsSchemas.entrySet()) {
String name = GeneratorUtils.getValidName(schemaEntry.getKey(), true);
refacSchema.put(name, schemaEntry.getValue());
}
openAPI.getComponents().setSchemas(refacSchema);
}
}
return openAPI;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@

import static io.ballerina.openapi.TestUtils.FILTER;
import static io.ballerina.openapi.core.generators.common.GeneratorUtils.extractReferenceType;
import static io.ballerina.openapi.core.generators.common.GeneratorUtils.getValidName;
import static io.ballerina.openapi.generators.common.GeneratorTestUtils
.compareGeneratedSyntaxTreeWithExpectedSyntaxTree;

Expand Down Expand Up @@ -74,16 +73,8 @@ public static void testForReferenceLinkValid() throws BallerinaOpenApiException
Assert.assertEquals(GeneratorUtils.extractReferenceType("#/components/schemas/Pet.-id"), "Pet.-id");
Assert.assertEquals(GeneratorUtils.extractReferenceType("#/components/schemas/Pet."), "Pet.");
Assert.assertEquals(GeneratorUtils.extractReferenceType("#/components/schemas/200"), "200");
Assert.assertEquals(getValidName(GeneratorUtils.extractReferenceType("#/components/schemas/worker"),
true), "Worker");
Assert.assertEquals(getValidName(GeneratorUtils.extractReferenceType("#/components/schemas/worker abc"),
true), "WorkerAbc");
}

@Test(description = "Generate the readable function, record name removing special characters")
public static void testGenerateReadableName() {
Assert.assertEquals(getValidName("endpoint-remove-shows-user", true),
"EndpointRemoveShowsUser");
Assert.assertEquals(GeneratorUtils.extractReferenceType("#/components/schemas/worker"), "worker");
Assert.assertEquals(GeneratorUtils.extractReferenceType("#/components/schemas/worker abc"), "worker abc");
}

@Test(description = "Set record name with removing special Characters")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ public class TestConstants {
" string appid;\n" +
" # API key to authorize requests.\n" +
" @display {label: \"\", kind: \"password\"}\n" +
" string apiXKey;\n" +
" string API\\-X\\-Key;\n" +
"|};";

public static final String API_KEY_ASSIGNMENT = "self.apiKeyConfig = apiKeyConfig.cloneReadOnly();";
Expand All @@ -156,7 +156,7 @@ public class TestConstants {
" string appid;\n" +
" # API key to authorize POST requests.\n" +
" @display {label: \"\", kind: \"password\"}\n" +
" string xApiKey;\n" +
" string X\\-API\\-Key;\n" +
"|};";
public static final String MULTI_LINE_API_KEY_DESC = "# Provides API key configurations needed when " +
"communicating with a remote HTTP endpoint.\n" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,8 @@ public Object[][] singleFileProviderForDiagnosticCheck() {
{"ballerinax_connector_tests/files.com.yaml"},
{"ballerinax_connector_tests/openweathermap.yaml"},
{"ballerinax_connector_tests/soundcloud.yaml"},
{"ballerinax_connector_tests/stripe.yaml"},
{"ballerinax_connector_tests/vimeo.yaml"},
{"ballerinax_connector_tests/stripe.yaml"}, // this yaml was modified to schema names with camel case
{"ballerinax_connector_tests/vimeo.yaml"}, // modified to yaml for error schema into Error
// todo : 209 status code is not supported in
// Ballerina. Generate `http:Response` at the moment.
{"ballerinax_connector_tests/ynab.yaml"},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public isolated client class Client {
self.clientEp = httpEp;
return;
}

# Add a new pet to the store
#
# + payload - Pet object that needs to be added to the store
Expand All @@ -57,6 +58,7 @@ public isolated client class Client {
request.setPayload(jsonBody, "application/json");
return self.clientEp->post(resourcePath, request);
}

# Create user
#
# + request - Created user object
Expand All @@ -66,6 +68,7 @@ public isolated client class Client {
// TODO: Update the request as needed;
return self.clientEp->post(resourcePath, request);
}

# Creates list of users with given input array
#
# + request - List of user object
Expand All @@ -75,6 +78,7 @@ public isolated client class Client {
// TODO: Update the request as needed;
return self.clientEp->post(resourcePath, request);
}

# Creates list of users with given input array
#
# + request - List of user object
Expand All @@ -84,6 +88,7 @@ public isolated client class Client {
// TODO: Update the request as needed;
return self.clientEp->post(resourcePath, request);
}

# Delete purchase order by ID
#
# + orderId - ID of the order that needs to be deleted
Expand All @@ -92,6 +97,7 @@ public isolated client class Client {
string resourcePath = string `/store/order/${getEncodedUri(orderId)}`;
return self.clientEp->delete(resourcePath);
}

# Deletes a pet
#
# + petId - Pet id to delete
Expand All @@ -102,6 +108,7 @@ public isolated client class Client {
map<string|string[]> httpHeaders = getMapForHeaders(headerValues);
return self.clientEp->delete(resourcePath, headers = httpHeaders);
}

# Delete user
#
# + username - The name that needs to be deleted
Expand All @@ -110,6 +117,7 @@ public isolated client class Client {
string resourcePath = string `/user/${getEncodedUri(username)}`;
return self.clientEp->delete(resourcePath);
}

# Finds Pets by status
#
# + status - Status values that need to be considered for filter
Expand All @@ -121,6 +129,7 @@ public isolated client class Client {
resourcePath = resourcePath + check getPathForQueryParam(queryParam, queryParamEncoding);
return self.clientEp->get(resourcePath);
}

# Finds Pets by tags
#
# + tags - Tags to filter by
Expand All @@ -135,6 +144,7 @@ public isolated client class Client {
resourcePath = resourcePath + check getPathForQueryParam(queryParam, queryParamEncoding);
return self.clientEp->get(resourcePath);
}

# Returns pet inventories by status
#
# + return - successful operation
Expand All @@ -147,6 +157,7 @@ public isolated client class Client {
map<string|string[]> httpHeaders = getMapForHeaders(headerValues);
return self.clientEp->get(resourcePath, httpHeaders);
}

# Find purchase order by ID
#
# + orderId - ID of pet that needs to be fetched
Expand All @@ -155,6 +166,7 @@ public isolated client class Client {
string resourcePath = string `/store/order/${getEncodedUri(orderId)}`;
return self.clientEp->get(resourcePath);
}

# Find pet by ID
#
# + petId - ID of pet to return
Expand All @@ -168,6 +180,7 @@ public isolated client class Client {
map<string|string[]> httpHeaders = getMapForHeaders(headerValues);
return self.clientEp->get(resourcePath, httpHeaders);
}

# Get user by user name
#
# + username - The name that needs to be fetched. Use user1 for testing.
Expand All @@ -176,6 +189,7 @@ public isolated client class Client {
string resourcePath = string `/user/${getEncodedUri(username)}`;
return self.clientEp->get(resourcePath);
}

# Logs user into the system
#
# + username - The user name for login
Expand All @@ -187,13 +201,15 @@ public isolated client class Client {
resourcePath = resourcePath + check getPathForQueryParam(queryParam);
return self.clientEp->get(resourcePath);
}

# Logs out current logged in user session
#
# + return - successful operation
remote isolated function logoutUser() returns http:Response|error {
string resourcePath = string `/user/logout`;
return self.clientEp->get(resourcePath);
}

# Place an order for a pet
#
# + request - order placed for purchasing the pet
Expand All @@ -203,6 +219,7 @@ public isolated client class Client {
// TODO: Update the request as needed;
return self.clientEp->post(resourcePath, request);
}

# Update an existing pet
#
# + payload - Pet object that needs to be added to the store
Expand All @@ -214,17 +231,19 @@ public isolated client class Client {
request.setPayload(jsonBody, "application/json");
return self.clientEp->put(resourcePath, request);
}

# Updates a pet in the store with form data
#
# + petId - ID of pet that needs to be updated
# + return - Invalid input
remote isolated function updatePetWithForm(int petId, Pet_petId_body payload) returns http:Response|error {
remote isolated function updatePetWithForm(int petId, pet_petId_body payload) returns http:Response|error {
string resourcePath = string `/pet/${getEncodedUri(petId)}`;
http:Request request = new;
string encodedRequestBody = createFormURLEncodedRequestBody(payload);
request.setPayload(encodedRequestBody, "application/x-www-form-urlencoded");
return self.clientEp->post(resourcePath, request);
}

# Updated user
#
# + username - name that need to be updated
Expand All @@ -235,11 +254,12 @@ public isolated client class Client {
// TODO: Update the request as needed;
return self.clientEp->put(resourcePath, request);
}

# uploads an image
#
# + petId - ID of pet to update
# + return - successful operation
remote isolated function uploadFile(int petId, PetId_uploadImage_body payload) returns ApiResponse|error {
remote isolated function uploadFile(int petId, petId_uploadImage_body payload) returns ApiResponse|error {
string resourcePath = string `/pet/${getEncodedUri(petId)}/uploadImage`;
http:Request request = new;
mime:Entity[] bodyParts = check createBodyParts(payload);
Expand Down
Loading

0 comments on commit 3a5d5d7

Please sign in to comment.