Skip to content

Commit

Permalink
Add integration tests for GraphQL API creation using SDL URL and Endp…
Browse files Browse the repository at this point in the history
…oint
  • Loading branch information
wso2-jenkins-bot authored and nisan-abeywickrama committed Feb 3, 2025
1 parent e34971d commit 8e5cae1
Show file tree
Hide file tree
Showing 4 changed files with 2,183 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2603,6 +2603,12 @@ paths:
type: string
description: Definition to uploads a file
format: binary
url:
type: string
description: Definition url
schema:
type: string
description: Definition schema
additionalProperties:
type: string
description: Additional attributes specified as a stringified JSON
Expand Down Expand Up @@ -2869,17 +2875,26 @@ paths:
summary: Validate a GraphQL SDL
description: |
This operation can be used to validate a graphQL definition and retrieve a summary.
parameters:
- name: useIntrospection
in: query
description: |
Specify whether to use Introspection to obtain the GraphQL Schema
schema:
type: boolean
default: false
requestBody:
content:
multipart/form-data:
schema:
required:
- file
properties:
file:
type: string
description: Definition to upload as a file
format: binary
url:
type: string
description: Definition to upload using url
required: true
responses:
200:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1241,15 +1241,31 @@ public ApiResponse<APIDTO> importOASDefinitionResponse(File file, String propert
public GraphQLValidationResponseDTO validateGraphqlSchemaDefinition(File schemaDefinition) throws ApiException {

ApiResponse<GraphQLValidationResponseDTO> response =
validationApi.validateGraphQLSchemaWithHttpInfo(schemaDefinition);
validationApi.validateGraphQLSchemaWithHttpInfo(false, schemaDefinition, null);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode());
return response.getData();
}

public GraphQLValidationResponseDTO validateGraphqlSchemaDefinitionByURL(String url, Boolean useIntrospection) throws ApiException {

ApiResponse<GraphQLValidationResponseDTO> response =
validationApi.validateGraphQLSchemaWithHttpInfo(useIntrospection, null, url);
Assert.assertEquals(HttpStatus.SC_OK, response.getStatusCode());
return response.getData();
}

public APIDTO importGraphqlSchemaDefinition(File file, String properties) throws ApiException {

ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importGraphQLSchemaWithHttpInfo(null, "GRAPHQL",
file, properties);
file, null, null, properties);
Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode());
return apiDtoApiResponse.getData();
}

public APIDTO importGraphqlSchemaDefinitionByURL(String url, String properties) throws ApiException {

ApiResponse<APIDTO> apiDtoApiResponse = apIsApi.importGraphQLSchemaWithHttpInfo(null, "GRAPHQL",
null, url, null, properties);
Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode());
return apiDtoApiResponse.getData();
}
Expand All @@ -1274,7 +1290,7 @@ public HttpResponse importGraphqlSchemaDefinitionWithInvalidContext(File file, S
HttpResponse response = null;
try {
apiDtoApiResponse = apIsApi.importGraphQLSchemaWithHttpInfo(null, "GRAPHQL",
file, properties);
file, null, null, properties);
Assert.assertEquals(HttpStatus.SC_CREATED, apiDtoApiResponse.getStatusCode());
} catch (ApiException e) {
if (e.getResponseBody().contains(APIMIntegrationConstants.API_CONTEXT_MALFORMED_ERROR)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
package org.wso2.am.integration.tests.graphql;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.tomakehurst.wiremock.WireMockServer;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.google.gson.Gson;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.io.IOUtils;
Expand Down Expand Up @@ -58,13 +60,20 @@
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.Socket;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ws.rs.core.Response;

import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static com.github.tomakehurst.wiremock.core.WireMockConfiguration.options;
import static org.testng.Assert.assertEquals;

@SetEnvironment(executionEnvironments = { ExecutionEnvironment.ALL })
Expand All @@ -78,18 +87,29 @@ public class GraphqlTestCase extends APIMIntegrationBaseTest {
private final String RESPONSE_DATA = "[{\"name\":\"Afrikaans\",\"code\":\"af\"},{\"name\":\"Amharic\",\"code\":\"am\"}," +
"{\"name\":\"Arabic\",\"code\":\"ar\"},{\"name\":\"Aymara\",\"code\":\"ay\"},{\"name\":\"Azerbaijani\"," +
"\"code\":\"az\"},{\"name\":\"Belarusian\",\"code\":\"be\"}]";
private static final String mockgraphQLAPIEndpoint = "/mock_graphql";
private static final String mockgraphQLAPIIntrospectionResource = "/introspection";
private static final String mockgraphQLAPISDLResource = "/sdl";
private static final String GRAPHQL_TEST_USER = "graphqluser";
private static final String GRAPHQL_TEST_USER_PASSWORD = "graphqlUser";
private static final String GRAPHQL_ROLE = "graphqlrole";
private static final long WAIT_TIME = 45 * 1000;

private String schemaDefinition;
private String graphqlAPIId;
private String graphqlAPISDLId;
private String graphqlAPIEndpointId;
private String testAppId1;
private String testAppId2;
private String testAppId3;
private String testAppId4;

private WireMockServer wireMockServer;
private int endpointPort;
private String endpointHost = "http://localhost";
private int lowerPortLimit = 9950;
private int upperPortLimit = 9999;

@Factory(dataProvider = "userModeDataProvider")
public GraphqlTestCase(TestUserMode userMode) {
this.userMode = userMode;
Expand Down Expand Up @@ -143,6 +163,7 @@ public void setEnvironment() throws Exception {
restAPIPublisher.changeAPILifeCycleStatus(graphqlAPIId, Constants.PUBLISHED);
waitForAPIDeploymentSync(user.getUserName(), GRAPHQL_API_NAME, API_VERSION_1_0_0,
APIMIntegrationConstants.IS_API_EXISTS);
startWiremockServer();
}

@Test(groups = {"wso2.am"}, description = "Create and publish GraphQL APIs by providing GraphQL schema with " +
Expand Down Expand Up @@ -227,6 +248,82 @@ public void testCreateAndPublishGraphQLAPIUsingSchemaWithMalformedContext() thro
Assert.assertEquals(response.getResponseCode(), 400, "Response Code miss matched when creating the API");
}

@Test(groups = { "wso2.am" }, description =
"Test GraphQL API creation using SDL URL")
public void testCreateGraphQLAPIUsingSDLURL() throws Exception {
String graphQLUrl = endpointHost + ":" + endpointPort + mockgraphQLAPIEndpoint + mockgraphQLAPISDLResource;
GraphQLValidationResponseDTO responseApiDto = restAPIPublisher.validateGraphqlSchemaDefinitionByURL(graphQLUrl, false);
GraphQLValidationResponseGraphQLInfoDTO graphQLInfo = responseApiDto.getGraphQLInfo();
String arrayToJson = new ObjectMapper().writeValueAsString(graphQLInfo.getOperations());
JSONArray operations = new JSONArray(arrayToJson);

ArrayList<String> environment = new ArrayList<String>();
environment.add(Constants.GATEWAY_ENVIRONMENT);

ArrayList<String> policies = new ArrayList<String>();
policies.add("Unlimited");

JSONObject additionalPropertiesObj = new JSONObject();
additionalPropertiesObj.put("name", GRAPHQL_API_NAME + "withSDL");
additionalPropertiesObj.put("context", API_CONTEXT + "_sdl");
additionalPropertiesObj.put("version", API_VERSION_1_0_0);

JSONObject url = new JSONObject();
url.put("url", END_POINT_URL);
JSONObject endpointConfig = new JSONObject();
endpointConfig.put("endpoint_type", "http");
endpointConfig.put("sandbox_endpoints", url);
endpointConfig.put("production_endpoints", url);
additionalPropertiesObj.put("endpointConfig", endpointConfig);
additionalPropertiesObj.put("policies", policies);
additionalPropertiesObj.put("operations", operations);

// create Graphql API
APIDTO apidto = restAPIPublisher.importGraphqlSchemaDefinitionByURL(graphQLUrl, additionalPropertiesObj.toString());
graphqlAPISDLId = apidto.getId();
HttpResponse createdApiResponse = restAPIPublisher.getAPI(graphqlAPISDLId);
assertEquals(Response.Status.OK.getStatusCode(), createdApiResponse.getResponseCode(),
GRAPHQL_API_NAME + "withSDL" + " API creation is failed");
}

@Test(groups = { "wso2.am" }, description =
"Test GraphQL API creation using Endpoint")
public void testCreateGraphQLAPIUsingEndpoint() throws Exception {
String graphQLEndpointURL = endpointHost + ":" + endpointPort + mockgraphQLAPIEndpoint + mockgraphQLAPIIntrospectionResource;
GraphQLValidationResponseDTO responseApiDto = restAPIPublisher.validateGraphqlSchemaDefinitionByURL(graphQLEndpointURL, true);
GraphQLValidationResponseGraphQLInfoDTO graphQLInfo = responseApiDto.getGraphQLInfo();
String arrayToJson = new ObjectMapper().writeValueAsString(graphQLInfo.getOperations());
JSONArray operations = new JSONArray(arrayToJson);

ArrayList<String> environment = new ArrayList<String>();
environment.add(Constants.GATEWAY_ENVIRONMENT);

ArrayList<String> policies = new ArrayList<String>();
policies.add("Unlimited");

JSONObject additionalPropertiesObj = new JSONObject();
additionalPropertiesObj.put("name", GRAPHQL_API_NAME + "withEndpoint");
additionalPropertiesObj.put("context", API_CONTEXT + "_endpoint");
additionalPropertiesObj.put("version", API_VERSION_1_0_0);

JSONObject url = new JSONObject();
url.put("url", graphQLEndpointURL);
JSONObject endpointConfig = new JSONObject();
endpointConfig.put("endpoint_type", "http");
endpointConfig.put("sandbox_endpoints", url);
endpointConfig.put("production_endpoints", url);
additionalPropertiesObj.put("endpointConfig", endpointConfig);
additionalPropertiesObj.put("policies", policies);
additionalPropertiesObj.put("operations", operations);

// create Graphql API
APIDTO apidto = restAPIPublisher.importGraphqlSchemaDefinitionByURL(null, additionalPropertiesObj.toString());
graphqlAPIEndpointId = apidto.getId();
HttpResponse createdApiResponse = restAPIPublisher.getAPI(graphqlAPIEndpointId);
assertEquals(Response.Status.OK.getStatusCode(), createdApiResponse.getResponseCode(),
GRAPHQL_API_NAME + "withEndpoint" + " API creation is failed");
}

@Test(groups = {"wso2.am"}, description = "test retrieve schemaDefinition at publisher")
public void testRetrieveSchemaDefinitionAtPublisher() throws Exception {
GraphQLSchemaDTO schema = restAPIPublisher.getGraphqlSchemaDefinition(graphqlAPIId);
Expand Down Expand Up @@ -483,6 +580,83 @@ public static Object[][] userModeDataProvider() {
};
}

private void startWiremockServer() throws Exception {

if (wireMockServer == null) {
String urlResponse;
String introspectionResponse;

ClassLoader classLoader = getClass().getClassLoader();
urlResponse = new String(Files.readAllBytes(Paths.get(classLoader.getResource("graphql/schema.graphql").toURI())));
introspectionResponse = new String(Files.readAllBytes(Paths.get(classLoader.getResource("graphql/schemaResponseFromIntrospection.json").toURI())));

endpointPort = getAvailablePort();
wireMockServer = new WireMockServer(options().port(endpointPort));

// SDL URL
wireMockServer.stubFor(WireMock.get(urlEqualTo(mockgraphQLAPIEndpoint + mockgraphQLAPISDLResource))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", "application/json").withBody(urlResponse)));

// Introspection endpoint
wireMockServer.stubFor(WireMock.post(urlEqualTo(mockgraphQLAPIEndpoint + mockgraphQLAPIIntrospectionResource))
.willReturn(aResponse().withStatus(200)
.withHeader("Content-Type", "application/json").withBody(introspectionResponse)));

wireMockServer.start();
log.info("Wiremock server started on port " + endpointPort);
}
}

private void stopWireMockServer() throws Exception {
if (wireMockServer != null) {
wireMockServer.stop();
}
}

/**
* Find a free port to start backend WebSocket server in given port range
*
* @return Available Port Number
*/
private int getAvailablePort() {

while (lowerPortLimit < upperPortLimit) {
if (isPortFree(lowerPortLimit)) {
return lowerPortLimit;
}
lowerPortLimit++;
}
return -1;
}

/**
* Check whether give port is available
*
* @param port Port Number
* @return status
*/
private boolean isPortFree(int port) {

Socket s = null;
try {
s = new Socket(endpointHost, port);
// something is using the port and has responded.
return false;
} catch (IOException e) {
// port available
return true;
} finally {
if (s != null) {
try {
s.close();
} catch (IOException e) {
throw new RuntimeException("Unable to close connection ", e);
}
}
}
}

@AfterClass(alwaysRun = true)
public void cleanUpArtifacts() throws Exception {
userManagementClient.deleteRole(GRAPHQL_ROLE);
Expand All @@ -493,6 +667,9 @@ public void cleanUpArtifacts() throws Exception {
restAPIStore.deleteApplication(testAppId4);
undeployAndDeleteAPIRevisionsUsingRest(graphqlAPIId, restAPIPublisher);
restAPIPublisher.deleteAPI(graphqlAPIId);
restAPIPublisher.deleteAPI(graphqlAPISDLId);
restAPIPublisher.deleteAPI(graphqlAPIEndpointId);
stopWireMockServer();
super.cleanUp();
}
}
Loading

0 comments on commit 8e5cae1

Please sign in to comment.