Skip to content

Commit

Permalink
Merge pull request #1596 from ballerina-platform/improve-test-coverage
Browse files Browse the repository at this point in the history
Improve test coverage after restructuring
  • Loading branch information
TharmiganK authored Feb 1, 2024
2 parents 4608583 + 6e54819 commit b6f4475
Show file tree
Hide file tree
Showing 27 changed files with 921 additions and 55 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,10 @@
*
* @since 2.0.0
*/
public class ServiceToOpenAPIMapper {
public final class ServiceToOpenAPIMapper {

private ServiceToOpenAPIMapper() {
}

/**
* This method will generate openapi definition Map lists with ballerina code.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,6 @@
import io.ballerina.openapi.service.mapper.utils.MediaTypeUtils;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.headers.Header;
import io.swagger.v3.oas.models.media.ComposedSchema;
import io.swagger.v3.oas.models.media.Content;
import io.swagger.v3.oas.models.media.MediaType;
import io.swagger.v3.oas.models.media.Schema;
Expand Down Expand Up @@ -221,38 +220,18 @@ public void addApiResponse(ApiResponse apiResponse, String statusCode) {
}

private void updateExistingApiResponse(ApiResponse apiResponse, String statusCode) {
ApiResponse res = apiResponses.get(statusCode);
if (apiResponse.getContent() != null) {
Content content = res.getContent();
if (content == null) {
content = new Content();
}

updateApiResponseContentWithMediaType(apiResponse, content);
res.setContent(content);
}
apiResponses.put(statusCode, res);
}

private static void updateApiResponseContentWithMediaType(ApiResponse apiResponse, Content content) {
String mediaType = apiResponse.getContent().keySet().iterator().next();
Schema newSchema = apiResponse.getContent().values().iterator().next().getSchema();
if (content.containsKey(mediaType)) {
Schema<?> schema = content.get(mediaType).getSchema();
if (schema instanceof ComposedSchema && schema.getOneOf() != null) {
schema.getOneOf().add(newSchema);
content.put(mediaType, new MediaType().schema(schema));
ApiResponse existingRes = apiResponses.get(statusCode);
Content newContent = apiResponse.getContent();
if (Objects.nonNull(newContent)) {
Content content = existingRes.getContent();
if (Objects.isNull(content)) {
content = newContent;
} else {
ComposedSchema composedSchema = new ComposedSchema();
composedSchema.addOneOfItem(schema);
composedSchema.addOneOfItem(newSchema);
MediaType updatedMediaContent =
new MediaType().schema(composedSchema);
content.put(mediaType, updatedMediaContent);
content.put(newContent.keySet().iterator().next(), newContent.values().iterator().next());
}
} else {
content.put(mediaType, apiResponse.getContent().values().iterator().next());
existingRes.setContent(content);
}
apiResponses.put(statusCode, existingRes);
}

private void updateApiResponseContentWithMediaType(ApiResponse apiResponse, String mediaType,
Expand Down Expand Up @@ -297,7 +276,7 @@ private void addResponseMappingForSimpleType(TypeSymbol returnType, String defau
TypeSymbol bodyType = getBodyTypeFromStatusCodeResponse(returnType, semanticModel);
Map<String, Header> headersFromStatusCodeResponse = getHeadersFromStatusCodeResponse(returnType);
String statusCode = getResponseCode(returnType, defaultStatusCode, semanticModel);
headersMap.put(statusCode, headersFromStatusCodeResponse);
updateHeaderMap(statusCode, headersFromStatusCodeResponse);
createResponseMapping(bodyType, getResponseCode(returnType, defaultStatusCode, semanticModel));
} else {
ApiResponse apiResponse = new ApiResponse();
Expand Down Expand Up @@ -376,7 +355,7 @@ private void extractBasicMembers(UnionTypeSymbol unionTypeSymbol, String default
if (isHttpStatusCodeResponseType(semanticModel, directMemberType)) {
Map<String, Header> headersFromStatusCodeResponse = getHeadersFromStatusCodeResponse(directMemberType);
if (!headersFromStatusCodeResponse.isEmpty()) {
headersMap.put(code, headersFromStatusCodeResponse);
updateHeaderMap(code, headersFromStatusCodeResponse);
}
directMemberType = getBodyTypeFromStatusCodeResponse(directMemberType, semanticModel);
}
Expand All @@ -397,6 +376,14 @@ private void extractBasicMembers(UnionTypeSymbol unionTypeSymbol, String default
}
}

private void updateHeaderMap(String code, Map<String, Header> headers) {
if (headersMap.containsKey(code)) {
headersMap.get(code).putAll(headers);
} else {
headersMap.put(code, headers);
}
}

public static boolean isHttpStatusCodeResponseType(SemanticModel semanticModel, TypeSymbol typeSymbol) {
Optional<Symbol> optionalStatusCodeRecordSymbol = semanticModel.types().getTypeByName("ballerina", "http",
"", "StatusCodeResponse");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,6 @@ public static String getOpenApiFileName(String servicePath, String serviceName,
* Remove special characters from the given file name.
*/
public static String getNormalizedFileName(String openAPIFileName) {

String[] splitNames = openAPIFileName.split("[^a-zA-Z0-9]");
if (splitNames.length > 0) {
return Arrays.stream(splitNames)
Expand All @@ -365,12 +364,6 @@ public static String getNormalizedFileName(String openAPIFileName) {
return openAPIFileName;
}

public static boolean isHttpService(ModuleSymbol moduleSymbol) {
Optional<String> moduleNameOpt = moduleSymbol.getName();
return moduleNameOpt.isPresent() && Constants.HTTP.equals(moduleNameOpt.get())
&& Constants.BALLERINA.equals(moduleSymbol.id().orgName());
}

public static boolean containErrors(List<Diagnostic> diagnostics) {
return diagnostics != null && diagnostics.stream().anyMatch(diagnostic ->
diagnostic.diagnosticInfo().severity() == DiagnosticSeverity.ERROR);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ public void testForBuiltInSubTypes() throws IOException {
TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/built_in_sub_types_in_record.yaml");
}

@Test(description = "test for Ballerina table types")
public void testForTableType() throws IOException {
Path ballerinaFilePath = RES_DIR.resolve("data_type/table_types.bal");
TestUtils.compareWithGeneratedFile(ballerinaFilePath, "data_type/table_types.yaml");
}

@AfterMethod
public void cleanUp() {
TestUtils.deleteDirectory(this.tempDir);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ public type Hobby HobbyItemsString[];
@constraint:Array {length: 15}
public type School SchoolName[];

public type Modules string[];

@constraint:Array {maxLength: 5}
public type Subjects Modules;

public type Person record {
Hobby hobby?;
School school?;
Expand All @@ -31,6 +36,7 @@ public type Person record {
PersonFeeItemsNumber[] fee?;
# The maximum number of items in the response (as set in the query or by default).
PersonLimitItemsInteger[] 'limit?;
Subjects[] subjects?;
};

service /payloadV on new http:Listener(9090) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,15 @@ import ballerina/constraint;
}
public type Marks decimal;

@constraint:Number {
minValue: 3,
maxValue: 6
}
public type AdjustedMarks Marks;

public type School record {
Marks marks;
AdjustedMarks adjustedMarks;
};

service /payloadV on new http:Listener(9090) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,15 @@ import ballerina/constraint;
}
public type Position int;

@constraint:Int {
minValue: 50,
maxValue: 100
}
public type NewPosition Position;

public type Child record {
Position position;
NewPosition newPosition;
};

service /payloadV on new http:Listener(9090) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,23 @@ public type Person record {
decimal net?;
};

type Record record {
record {
@constraint:String {length: 10}
string name;
@constraint:Int {minValue: 18}
int age;
record {
@constraint:String {pattern: re `^[a-zA-Z0-9]+$`}
string username;
@constraint:String {minLength: 8}
string password;
} auth;
} user;
};

service /payloadV on new http:Listener(9090) {
resource function post pet(@http:Payload Person body) returns error? {
resource function post pet(@http:Payload Person body, Record rec) returns error? {
return;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,37 @@
import ballerina/http;
import ballerina/constraint;

annotation Annotation Annot on type;

type Annotation record {
string name;
};

@Annot {
name: "test"
}
type AnnotatedString string;

@constraint:String {
length: 10,
pattern: re `^[a-zA-Z0-9_]+$`
}
public type St_ID string;

@constraint:String {
minLength: 5
}
public type St_Roll_No St_ID;

public type StudentRecord record {
St_ID id;
St_Roll_No rollNo;
@constraint:String { pattern: re `^[a-zA-Z]+$`}
string name?;
};

service /payloadV on new http:Listener(9090) {
resource function post pet(@http:Payload StudentRecord body) returns error? {
resource function post pet(@http:Payload StudentRecord body, AnnotatedString annotStr) returns error? {
return;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import ballerina/http;
import ballerina/time;

type AppointmentTable table<Appointment> key(id);

public type Appointment record {|
readonly string id;
string description;
string doctorId;
time:Date date?;
|};

public type Pet record {|
string name;
readonly string tag;
decimal age;
AppointmentTable appointments?;
|};

table<Pet> key(tag) pets = table [
{name: "Tommy", tag: "dog", age: 2.5},
{
name: "Lucy",
tag: "cat",
age: 1.5,
appointments: table [
{id: "1", description: "Vaccination", doctorId: "1"},
{id: "2", description: "Checkup", doctorId: "2"}
]
}
];

service /payloadV on new http:Listener(9090) {

resource function get pets() returns table<Pet> {
return pets;
}

resource function get pets/[string tag]() returns Pet {
return pets.get(tag);
}

resource function get pets/[string tag]/appointments() returns AppointmentTable {
return pets.get(tag).appointments ?: table [];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import ballerina/http;
public type Pet record {
int id;
[int, string, decimal, float, User] address;
ReturnTypes? tuples;
TupleType? tupleSingle;
TupleType[]? tuples;
[int, decimal]? unionTuple;
};

Expand All @@ -12,10 +13,26 @@ public type User readonly & record {|
int age;
|};

public type ReturnTypes readonly & [int, decimal];
public type TupleType readonly & [int, decimal];

service /payloadV on new http:Listener(9090) {
resource function post .(@http:Payload Pet payload) {
resource function post path1(@http:Payload Pet payload) {

}

resource function post path2(@http:Payload TupleType payload) {

}

resource function post path3(@http:Payload TupleType[]? payload) {

}

resource function post path4(@http:Payload [int, decimal, string]? payload) {

}

resource function post path5(@http:Payload [int, decimal, string...] payload) {

}
}
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ components:
HobbyItemsString:
maxLength: 23
type: string
Modules:
type: array
items:
type: string
Person:
required:
- id
Expand Down Expand Up @@ -95,6 +99,10 @@ components:
query or by default).
items:
$ref: '#/components/schemas/PersonLimitItemsInteger'
subjects:
type: array
items:
$ref: '#/components/schemas/Subjects'
PersonDetailsItemsString:
minLength: 7
type: string
Expand All @@ -115,3 +123,7 @@ components:
SchoolName:
minLength: 5
type: string
Subjects:
maxItems: 5
allOf:
- $ref: '#/components/schemas/Modules'
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ paths:
$ref: '#/components/schemas/ErrorPayload'
components:
schemas:
AdjustedMarks:
maximum: 6.0
minimum: 3.0
allOf:
- $ref: '#/components/schemas/Marks'
ErrorPayload:
required:
- message
Expand Down Expand Up @@ -67,8 +72,11 @@ components:
format: double
School:
required:
- adjustedMarks
- marks
type: object
properties:
marks:
$ref: '#/components/schemas/Marks'
adjustedMarks:
$ref: '#/components/schemas/AdjustedMarks'
Loading

0 comments on commit b6f4475

Please sign in to comment.