Skip to content

Commit

Permalink
Adding cucmber tests for scope-validation,api-versioning and backend-…
Browse files Browse the repository at this point in the history
…support
  • Loading branch information
O-sura committed Mar 28, 2024
1 parent eafb381 commit c7979b3
Show file tree
Hide file tree
Showing 23 changed files with 1,318 additions and 72 deletions.
65 changes: 64 additions & 1 deletion test/apim-apk-agent-test/cucumber-tests/CRs/artifacts.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -257,4 +257,67 @@ spec:
targetPort: 9002
protocol: TCP
selector:
app: graphql-faker
app: graphql-faker

---
apiVersion: v1
kind: Service
metadata:
name: backend
namespace: apk
spec:
ports:
- name: http
port: 80
targetPort: 80
selector:
app: httpbin
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: httpbin
namespace: apk
spec:
replicas: 1
selector:
matchLabels:
app: httpbin
template:
metadata:
labels:
app: httpbin
spec:
containers:
- image: docker.io/kennethreitz/httpbin:latest
imagePullPolicy: IfNotPresent
name: httpbin
ports:
- containerPort: 80
resources:
requests:
memory: "200Mi"
cpu: "300m"
limits:
memory: "200Mi"
cpu: "300m"
---
apiVersion: v1
kind: Secret
metadata:
name: backend-creds
namespace: apk
data:
username: YWRtaW4=
password: YWRtaW4=
type: Opaque
---
apiVersion: v1
kind: Secret
metadata:
name: backend-creds-1
namespace: apk
data:
username: ZHNmZHNmc2Rmc2Rm
password: YWRtaW4=
type: Opaque
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@
import org.wso2.apk.integration.utils.Constants;
import org.wso2.apk.integration.utils.Utils;
import org.wso2.apk.integration.utils.clients.SimpleHTTPClient;
import java.nio.file.Files;
import java.nio.charset.StandardCharsets;

import java.io.File;
import java.io.IOException;
Expand Down Expand Up @@ -83,17 +85,28 @@ public void iHaveTheDefinitionFile(String definitionFileName) throws IOException
definitionFile = new File(url.getPath());
}

@When("make the import API Creation request")
public void make_import_api_creation_request() throws Exception {
logger.info("OAS URL: " + OASURL);

// Create a MultipartEntityBuilder to build the request entity
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addTextBody("url", OASURL, ContentType.TEXT_PLAIN)
.addPart("additionalProperties", new FileBody(payloadFile));
@When("make the import API Creation request using OAS {string}")
public void make_import_api_creation_request(String definitionType) throws Exception {
MultipartEntityBuilder builder = null;
if(definitionType.equals("URL")){
logger.info("OAS URL: " + OASURL);
builder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addTextBody("url", OASURL, ContentType.TEXT_PLAIN)
.addPart("additionalProperties", new FileBody(payloadFile));

logger.info("Payload File: "+ new FileBody(payloadFile));
}
if(definitionType.equals("File")){
logger.info("OAS File: " + definitionFile.getName());
builder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
.addPart("file", new FileBody(definitionFile))
.addPart("additionalProperties", new FileBody(payloadFile));

logger.info("Payload File: "+ new FileBody(payloadFile));
}

logger.info("Payload File: "+ new FileBody(payloadFile));

Map<String, String> headers = new HashMap<>();
headers.put(Constants.REQUEST_HEADERS.AUTHORIZATION, "Bearer " + sharedContext.getPublisherAccessToken());
Expand Down Expand Up @@ -194,26 +207,44 @@ public void make_generate_keys_request() throws Exception {
String keyManagerUUID = sharedContext.getKeyManagerUUID();
logger.info("Key Manager UUID: " + keyManagerUUID);
logger.info("Application UUID: " + applicationUUID);
String payload = "{\"keyType\":\"PRODUCTION\",\"grantTypesToBeSupported\":[\"password\",\"client_credentials\"]," +
String payloadForProdKeys = "{\"keyType\":\"PRODUCTION\",\"grantTypesToBeSupported\":[\"password\",\"client_credentials\"]," +
"\"callbackUrl\":\"\",\"additionalProperties\":{\"application_access_token_expiry_time\":\"N/A\"," +
"\"user_access_token_expiry_time\":\"N/A\",\"refresh_token_expiry_time\":\"N/A\"," +
"\"id_token_expiry_time\":\"N/A\",\"pkceMandatory\":\"false\",\"pkceSupportPlain\":\"false\"," +
"\"bypassClientCredentials\":\"false\"},\"keyManager\":\"" + keyManagerUUID +"\"," +
"\"validityTime\":3600,\"scopes\":[\"default\"]}";


String payloadForSandboxKeys = "{\"keyType\":\"SANDBOX\",\"grantTypesToBeSupported\":[\"password\",\"client_credentials\"]," +
"\"callbackUrl\":\"\",\"additionalProperties\":{\"application_access_token_expiry_time\":\"N/A\"," +
"\"user_access_token_expiry_time\":\"N/A\",\"refresh_token_expiry_time\":\"N/A\"," +
"\"id_token_expiry_time\":\"N/A\",\"pkceMandatory\":\"false\",\"pkceSupportPlain\":\"false\"," +
"\"bypassClientCredentials\":\"false\"},\"keyManager\":\"" + keyManagerUUID +"\"," +
"\"validityTime\":3600,\"scopes\":[\"default\"]}";


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);

logger.info("Payload: " + payload);

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

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
sharedContext.setConsumerSecret(Utils.extractKeys(sharedContext.getResponseBody(), "consumerSecret"));
sharedContext.setConsumerKey(Utils.extractKeys(sharedContext.getResponseBody(), "consumerKey"));
sharedContext.setConsumerSecret(Utils.extractKeys(sharedContext.getResponseBody(), "consumerSecret"), "production");
sharedContext.setConsumerKey(Utils.extractKeys(sharedContext.getResponseBody(), "consumerKey"), "production");
sharedContext.setKeyMappingID(Utils.extractKeys(sharedContext.getResponseBody(), "keyMappingId"), "production");
Thread.sleep(3000);

HttpResponse response2 = sharedContext.getHttpClient().doPost(Utils.getGenerateKeysURL(applicationUUID),
headers, payloadForSandboxKeys, Constants.CONTENT_TYPES.APPLICATION_JSON);

sharedContext.setResponse(response2);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
sharedContext.setConsumerSecret(Utils.extractKeys(sharedContext.getResponseBody(), "consumerSecret"), "sandbox");
sharedContext.setConsumerKey(Utils.extractKeys(sharedContext.getResponseBody(), "consumerKey"), "sandbox");
sharedContext.setKeyMappingID(Utils.extractKeys(sharedContext.getResponseBody(), "keyMappingId"), "sandbox");
Thread.sleep(3000);
}

Expand All @@ -237,10 +268,10 @@ public void make_subscription_request() throws Exception {
Thread.sleep(3000);
}

@When("I get oauth keys for application")
public void get_oauth_keys_for_application() throws Exception {
@When("I get {string} oauth keys for application")
public void get_oauth_keys_for_application(String type) throws Exception {
String applicationUUID = sharedContext.getApplicationUUID();

String keyType = (type.equals("production")) ? "production" : "sandbox";
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);
Expand All @@ -250,18 +281,22 @@ public void get_oauth_keys_for_application() throws Exception {

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
sharedContext.setOauthKeyUUID(Utils.extractOAuthMappingID(sharedContext.getResponseBody()));
sharedContext.setOauthKeyUUID(Utils.extractOAuthMappingID(sharedContext.getResponseBody(), sharedContext.getKeyMappingID(keyType)));
Thread.sleep(3000);
}

@When("make the Access Token Generation request")
public void make_access_token_generation_request() throws Exception {
@When("make the Access Token Generation request for {string}")
public void make_access_token_generation_request(String type) throws Exception {
String applicationUUID = sharedContext.getApplicationUUID();
String oauthKeyUUID = sharedContext.getOauthKeyUUID();
String consumerKey = sharedContext.getConsumerKey();
String consumerSecret = sharedContext.getConsumerSecret();
logger.info("Oauth Key UUID: " + oauthKeyUUID);
String keyType = (type.equals("production")) ? "production" : "sandbox";
logger.info("Generating keys for: " + keyType);
String consumerKey = sharedContext.getConsumerKey(keyType);
String consumerSecret = sharedContext.getConsumerSecret(keyType);

logger.info("Application UUID: " + applicationUUID);
logger.info("Oauth Key UUID: " + oauthKeyUUID);

String payload = "{\"consumerSecret\":\"" + consumerSecret + "\",\"validityPeriod\":3600,\"revokeToken\":null," +
"\"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," +
Expand All @@ -285,10 +320,13 @@ public void make_access_token_generation_request() throws Exception {
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);
String keyType = "production"; //Use the same ternary logic above if both sandbox and production routes need to be tested
String consumerKey = sharedContext.getConsumerKey(keyType);
String consumerSecret = sharedContext.getConsumerSecret(keyType);

logger.info("Application UUID: " + applicationUUID);
logger.info("Oauth Key UUID: " + oauthKeyUUID);

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," +
Expand Down Expand Up @@ -355,8 +393,6 @@ public void makeAPIDeploymentFromOrganization(String organization) throws Except
Thread.sleep(3000);
}



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

Expand Down Expand Up @@ -398,7 +434,6 @@ public void makeAPIDeploymentFromOrganization(String organization) throws Except
// sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
// }

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

Expand Down Expand Up @@ -449,6 +484,21 @@ public void make_import_gqlapi_creation_request() throws Exception {
Thread.sleep(3000);
}

@Then("I update the GQL API settings")
public void make_update_gql_request() throws Exception {
String fileContent = new String(Files.readAllBytes(payloadFile.toPath()), StandardCharsets.UTF_8);
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().doPut(Utils.getAPIUnDeployerURL(sharedContext.getApiUUID()), headers, fileContent ,Constants.CONTENT_TYPES.APPLICATION_JSON);

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");
Expand Down Expand Up @@ -491,14 +541,39 @@ public void find_api_uuid_using_name(String apiName) throws Exception {

@When("I undeploy the selected API")
public void i_undeploy_the_api() throws Exception {
logger.info("API UUID to be deleted: " + sharedContext.getApiUUID());
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);
}

@When("I create the new version {string} of the same API with default version set to {string}")
public void create_new_version_of_the_api(String newVersion, String isDefaultVersion) throws Exception {
String apiUUID = sharedContext.getApiUUID();

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);

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

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

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

sharedContext.setResponse(response);
sharedContext.setResponseBody(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()));
sharedContext.setApiUUID(Utils.extractID(sharedContext.getResponseBody()));
Thread.sleep(3000);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,6 @@ 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
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,10 @@ public class SharedContext {
private String oauthKeyUUID;
private String consumerSecret;
private String consumerKey;
private String sandboxConsumerSecret;
private String sandboxConsumerKey;
private String prodKeyMappingID;
private String sandboxKeyMappingID;
private String apiAccessToken;
private Boolean definitionValidStatus;
private HashMap<String, Object> valueStore = new HashMap<>();
Expand Down Expand Up @@ -175,24 +179,49 @@ public void setOauthKeyUUID(String oauthKeyUUID) {
this.oauthKeyUUID = oauthKeyUUID;
}

public String getConsumerSecret() {

return consumerSecret;
public String getConsumerSecret(String keyType) {
if ("production".equals(keyType))
return consumerSecret;
else if ("sandbox".equals(keyType))
return sandboxConsumerSecret;
return "";
}

public void setConsumerSecret(String consumerSecret) {

this.consumerSecret = consumerSecret;
public void setConsumerSecret(String consumerSecret, String keyType) {
if ("production".equals(keyType))
this.consumerSecret = consumerSecret;
else if ("sandbox".equals(keyType))
this.sandboxConsumerSecret = consumerSecret;
}

public String getConsumerKey() {
public String getConsumerKey(String keyType) {
if ("production".equals(keyType))
return consumerKey;
else if ("sandbox".equals(keyType))
return sandboxConsumerKey;
return "";
}

return consumerKey;
public void setConsumerKey(String consumerKey, String keyType) {
if ("production".equals(keyType))
this.consumerKey = consumerKey;
else if ("sandbox".equals(keyType))
this.sandboxConsumerKey = consumerKey;
}

public void setConsumerKey(String consumerKey) {
public void setKeyMappingID(String keyMappingID, String keyType){
if ("production".equals(keyType))
this.prodKeyMappingID = keyMappingID;
else if ("sandbox".equals(keyType))
this.sandboxKeyMappingID = keyMappingID;
}

this.consumerKey = consumerKey;
public String getKeyMappingID(String keyType){
if ("production".equals(keyType))
return prodKeyMappingID;
else if ("sandbox".equals(keyType))
return sandboxKeyMappingID;
return "";
}

public String getApiAccessToken() {
Expand Down
Loading

0 comments on commit c7979b3

Please sign in to comment.