Skip to content

Commit

Permalink
Adding cucumber tests for GraphQL API creation
Browse files Browse the repository at this point in the history
  • Loading branch information
O-sura committed Mar 20, 2024
1 parent 52a981d commit 2dcd2a3
Show file tree
Hide file tree
Showing 10 changed files with 1,200 additions and 62 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import com.google.common.io.Resources;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Given;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
Expand Down Expand Up @@ -152,24 +153,25 @@ public void make_a_change_lifecycle_request() throws Exception {
Thread.sleep(3000);
}

@When("make the Application Creation request")
public void make_application_creation_request() throws Exception {
@When("make the Application Creation request with the name {string}")
public void make_application_creation_request(String applicationName) throws Exception {
logger.info("Creating an application");
String payload = "{\"name\":\"PetstoreApp\",\"throttlingPolicy\":\"10PerMin\",\"description\":\"test app\",\"tokenType\":\"JWT\",\"groups\":null,\"attributes\":{}}";

String payload = "{\"name\":\"" + applicationName + "\",\"throttlingPolicy\":\"10PerMin\",\"description\":\"test app\",\"tokenType\":\"JWT\",\"groups\":null,\"attributes\":{}}";
Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getDevportalAccessToken());
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

HttpResponse response = sharedContext.getHttpClient().doPost(Utils.getApplicationCreateURL(),
headers, payload, Constants.CONTENT_TYPES.APPLICATION_JSON);

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
logger.info("Response: " + sharedContext.getResponseBody());
sharedContext.setApplicationUUID(Utils.extractApplicationID(sharedContext.getResponseBody()));
Thread.sleep(3000);
}


@When("I have a KeyManager")
public void i_have_a_key_manager() throws Exception {
Expand Down Expand Up @@ -221,7 +223,7 @@ public void make_subscription_request() throws Exception {
String apiUUID = sharedContext.getApiUUID();
logger.info("API UUID: " + apiUUID);
logger.info("Application UUID: " + applicationUUID);
String payload = "{\"apiId\":\"" + apiUUID + "\",\"applicationId\":\"" + applicationUUID + "\",\"throttlingPolicy\":\"Gold\"}";
String payload = "{\"apiId\":\"" + apiUUID + "\",\"applicationId\":\"" + applicationUUID + "\",\"throttlingPolicy\":\"Unlimited\"}";

Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getDevportalAccessToken());
Expand Down Expand Up @@ -261,7 +263,7 @@ public void make_access_token_generation_request() throws Exception {
logger.info("Oauth Key UUID: " + oauthKeyUUID);
logger.info("Application UUID: " + applicationUUID);
String payload = "{\"consumerSecret\":\"" + consumerSecret + "\",\"validityPeriod\":3600,\"revokeToken\":null," +
"\"scopes\":[\"write:pets\",\"read:pets\"],\"additionalProperties\":{\"id_token_expiry_time\":3600," +
"\"scopes\":[\"write:pets\",\"read:pets\",\"query:hero\"],\"additionalProperties\":{\"id_token_expiry_time\":3600," +
"\"application_access_token_expiry_time\":3600,\"user_access_token_expiry_time\":3600,\"bypassClientCredentials\":false," +
"\"pkceMandatory\":false,\"pkceSupportPlain\":false,\"refresh_token_expiry_time\":86400}}";

Expand All @@ -279,6 +281,33 @@ public void make_access_token_generation_request() throws Exception {
Thread.sleep(3000);
}

@When("I make Access Token Generation request without scopes")
public void make_access_token_generation_request_without_scopes() throws Exception {
String applicationUUID = sharedContext.getApplicationUUID();
String oauthKeyUUID = sharedContext.getOauthKeyUUID();
String consumerKey = sharedContext.getConsumerKey();
String consumerSecret = sharedContext.getConsumerSecret();
logger.info("Oauth Key UUID: " + oauthKeyUUID);
logger.info("Application UUID: " + applicationUUID);
String payload = "{\"consumerSecret\":\"" + consumerSecret + "\",\"validityPeriod\":3600,\"revokeToken\":null," +
"\"scopes\":[],\"additionalProperties\":{\"id_token_expiry_time\":3600," +
"\"application_access_token_expiry_time\":3600,\"user_access_token_expiry_time\":3600,\"bypassClientCredentials\":false," +
"\"pkceMandatory\":false,\"pkceSupportPlain\":false,\"refresh_token_expiry_time\":86400}}";

Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getDevportalAccessToken());
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

HttpResponse response = sharedContext.getHttpClient().doPost(Utils.getAccessTokenGenerationURL(applicationUUID, oauthKeyUUID),
headers, payload, Constants.CONTENT_TYPES.APPLICATION_JSON);

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
sharedContext.setApiAccessToken(Utils.extractKeys(sharedContext.getResponseBody(), "accessToken"));
logger.info("Access Token without scopes: " + sharedContext.getApiAccessToken());
Thread.sleep(3000);
}

@When("make the API Deployment request")
public void make_a_api_deployment_request() throws Exception {

Expand Down Expand Up @@ -328,44 +357,148 @@ public void makeAPIDeploymentFromOrganization(String organization) throws Except



@When("I undeploy the API whose ID is {string}")
public void i_undeploy_the_api_whose_id_is(String apiID) throws Exception {

// Create query parameters
List<NameValuePair> queryParams = new ArrayList<>();
queryParams.add(new BasicNameValuePair("apiId", apiID));

URI uri = new URIBuilder(Utils.getAPIUnDeployerURL()).addParameters(queryParams).build();

Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getPublisherAccessToken());
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

HttpResponse response = sharedContext.getHttpClient().doPost(uri.toString(), headers, "",
Constants.CONTENT_TYPES.APPLICATION_JSON);

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
}

@When("I undeploy the API whose ID is {string} and organization {string}")
public void undeployAPIByIdAndOrganization(String apiID,String organization) throws Exception {

// Create query parameters
List<NameValuePair> queryParams = new ArrayList<>();
queryParams.add(new BasicNameValuePair("apiId", apiID));

URI uri = new URIBuilder(Utils.getAPIUnDeployerURL()).addParameters(queryParams).build();

Map<String, String> headers = new HashMap<>();
Object header = sharedContext.getStoreValue(organization);
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + header);
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

HttpResponse response = sharedContext.getHttpClient().doPost(uri.toString(), headers, "",
Constants.CONTENT_TYPES.APPLICATION_JSON);

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
}
// @When("I undeploy the API whose ID is {string}")
// public void i_undeploy_the_api_whose_id_is(String apiID) throws Exception {

// // Create query parameters
// List<NameValuePair> queryParams = new ArrayList<>();
// queryParams.add(new BasicNameValuePair("apiId", apiID));

// URI uri = new URIBuilder(Utils.getAPIUnDeployerURL()).addParameters(queryParams).build();

// Map<String, String> headers = new HashMap<>();
// headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getPublisherAccessToken());
// headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

// HttpResponse response = sharedContext.getHttpClient().doPost(uri.toString(), headers, "",
// Constants.CONTENT_TYPES.APPLICATION_JSON);

// sharedContext.setResponse(response);
// sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
// }

// @When("I undeploy the API whose ID is {string} and organization {string}")
// public void undeployAPIByIdAndOrganization(String apiID,String organization) throws Exception {

// // Create query parameters
// List<NameValuePair> queryParams = new ArrayList<>();
// queryParams.add(new BasicNameValuePair("apiId", apiID));

// URI uri = new URIBuilder(Utils.getAPIUnDeployerURL()).addParameters(queryParams).build();

// Map<String, String> headers = new HashMap<>();
// Object header = sharedContext.getStoreValue(organization);
// headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + header);
// headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

// HttpResponse response = sharedContext.getHttpClient().doPost(uri.toString(), headers, "",
// Constants.CONTENT_TYPES.APPLICATION_JSON);

// sharedContext.setResponse(response);
// sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
// }

//New steps
@Given("a valid graphql definition file")
public void iHaveValidGraphQLDefinition() throws Exception {

// Create a MultipartEntityBuilder to build the request entity
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", new FileBody(definitionFile));

logger.info("Definition File: "+ new FileBody(definitionFile));

Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getPublisherAccessToken());
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_APIM_HOST);

HttpEntity multipartEntity = builder.build();

HttpResponse response = sharedContext.getHttpClient().doPostWithMultipart(Utils.getGQLSchemaValidatorURL(),
multipartEntity, headers);

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
sharedContext.setAPIDefinitionValidStatus(Utils.extractValidStatus(sharedContext.getResponseBody()));
Thread.sleep(3000);
}

@Then("I make the import GraphQLAPI Creation request")
public void make_import_gqlapi_creation_request() throws Exception {

// Create a MultipartEntityBuilder to build the request entity
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("additionalProperties", new FileBody(payloadFile))
.addPart("file", new FileBody(definitionFile));


Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getPublisherAccessToken());
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

HttpEntity multipartEntity = builder.build();

HttpResponse response = sharedContext.getHttpClient().doPostWithMultipart(Utils.getGQLImportAPIURL(),
multipartEntity, headers);

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
sharedContext.setApiUUID(Utils.extractID(sharedContext.getResponseBody()));
Thread.sleep(3000);
}

@Then("I delete the application {string} from devportal")
public void make_application_deletion_request(String applicationName) throws Exception {
logger.info("Fetching the applications");

Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getDevportalAccessToken());
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

List<NameValuePair> queryParams = new ArrayList<>();
queryParams.add(new BasicNameValuePair("query", applicationName));

URI uri = new URIBuilder(Utils.getApplicationCreateURL()).addParameters(queryParams).build();
HttpResponse appSearchResponse = sharedContext.getHttpClient().doGet(uri.toString(), headers);

sharedContext.setResponse(appSearchResponse);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
sharedContext.setApplicationUUID(Utils.extractApplicationUUID(sharedContext.getResponseBody()));
HttpResponse deleteResponse = sharedContext.getHttpClient().doDelete(Utils.getApplicationCreateURL() + "/" + sharedContext.getApplicationUUID(), headers);

sharedContext.setResponse(deleteResponse);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
Thread.sleep(3000);
}

@Then("I find the apiUUID of the API created with the name {string}")
public void find_api_uuid_using_name(String apiName) throws Exception {
logger.info("Fetching the APIs");

Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getPublisherAccessToken());
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

HttpResponse appSearchResponse = sharedContext.getHttpClient().doGet(Utils.getAPISearchEndpoint(apiName), headers);

sharedContext.setResponse(appSearchResponse);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
sharedContext.setApiUUID(Utils.extractAPIUUID(sharedContext.getResponseBody()));
Thread.sleep(3000);
}

@When("I undeploy the selected API")
public void i_undeploy_the_api() throws Exception {
Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getPublisherAccessToken());
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_API_HOST);

HttpResponse response = sharedContext.getHttpClient().doDelete(Utils.getAPIUnDeployerURL(sharedContext.getApiUUID()), headers);

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
Thread.sleep(3000);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,17 @@
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.testng.Assert;
import org.wso2.apk.integration.utils.Constants;
import org.wso2.apk.integration.utils.Utils;
import org.wso2.apk.integration.utils.clients.SimpleHTTPClient;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.ContentType;

import java.io.IOException;
import java.io.InputStream;
Expand Down Expand Up @@ -130,6 +134,8 @@ public void sendHttpRequest(String httpMethod, String url, String body) throws I
} else if (CurlOption.HttpMethod.POST.toString().toLowerCase().equals(httpMethod.toLowerCase())) {
sharedContext.setResponse(httpClient.doPost(url, sharedContext.getHeaders(), body, null));
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
logger.info("Post Response: " + sharedContext.getResponse());
logger.info("Post Response Body: " + sharedContext.getResponseBody());
} else if (CurlOption.HttpMethod.PUT.toString().toLowerCase().equals(httpMethod.toLowerCase())) {
sharedContext.setResponse(httpClient.doPut(url, sharedContext.getHeaders(), body, null));
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
Expand Down Expand Up @@ -347,7 +353,7 @@ public void iHaveValidPublisherAccessToken() throws Exception {
headers.put(Constants.REQUEST_HEADERS.HOST, Constants.DEFAULT_IDP_HOST);
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, basicAuthHeader);

HttpResponse httpResponse = httpClient.doPost(Utils.getTokenEndpointURL(), headers, "grant_type=password&username=admin&password=admin&scope=apim:api_view apim:api_create apim:api_publish",
HttpResponse httpResponse = httpClient.doPost(Utils.getTokenEndpointURL(), headers, "grant_type=password&username=admin&password=admin&scope=apim:api_view apim:api_create apim:api_publish apim:api_delete apim:api_manage apim:api_import_export",
Constants.CONTENT_TYPES.APPLICATION_X_WWW_FORM_URLENCODED);
logger.info("Response: " + httpResponse);
sharedContext.setPublisherAccessToken(Utils.extractToken(httpResponse));
Expand All @@ -370,6 +376,12 @@ public void iHaveValidDevportalAccessToken() throws Exception {
logger.info("Devportal Access Token: " + sharedContext.getDevportalAccessToken());
}

@Then("the response should be given as valid")
public void theResponseShouldBeGivenAs() throws IOException {
Boolean status = sharedContext.getDefinitionValidStatus();
Assert.assertEquals(true, status,"Actual definition validation status: "+ status);
}

// @Given("I have a valid subscription without api deploy permission")
// public void iHaveValidSubscriptionWithAPICreateScope() throws Exception {
//
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ public class SharedContext {
private String consumerSecret;
private String consumerKey;
private String apiAccessToken;
private Boolean definitionValidStatus;
private HashMap<String, Object> valueStore = new HashMap<>();
private HashMap<String, String> headers = new HashMap<>();

Expand Down Expand Up @@ -203,4 +204,12 @@ public void setApiAccessToken(String apiAccessToken) {

this.apiAccessToken = apiAccessToken;
}

public void setAPIDefinitionValidStatus(Boolean definitionValidStatus){
this.definitionValidStatus = definitionValidStatus;
}

public Boolean getDefinitionValidStatus(){
return definitionValidStatus;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class Constants {
public static final String SPACE_STRING = " ";
public static final String SUBSCRIPTION_BASIC_AUTH_TOKEN =
"Basic NDVmMWM1YzgtYTkyZS0xMWVkLWFmYTEtMDI0MmFjMTIwMDAyOjRmYmQ2MmVjLWE5MmUtMTFlZC1hZmExLTAyNDJhYzEyMDAwMg==";
public static final String DEFAULT_APIM_HOST = "apim.wso2.com";

public class REQUEST_HEADERS {

Expand Down
Loading

0 comments on commit 2dcd2a3

Please sign in to comment.