Skip to content

Commit

Permalink
Merge pull request #1466 from Tharsanan1/add-default-version-and-basi…
Browse files Browse the repository at this point in the history
…c-test

Add default version api and basic api tests
  • Loading branch information
Krishanx92 authored Jul 25, 2023
2 parents d3aeec3 + 128f177 commit 2141692
Show file tree
Hide file tree
Showing 23 changed files with 1,364 additions and 5 deletions.
77 changes: 77 additions & 0 deletions test/cucumber-tests/CRs/artifacts.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# --------------------------------------------------------------------
# Copyright (c) 2023, WSO2 LLC. (http://wso2.com) All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# -----------------------------------------------------------------------

apiVersion: v1
kind: Service
metadata:
name: backend
namespace: apk-integration-test
spec:
ports:
- name: http
port: 80
targetPort: 80
selector:
app: httpbin
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: httpbin
namespace: apk-integration-test
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-integration-test
data:
username: YWRtaW4=
password: YWRtaW4=
type: Opaque
---
apiVersion: v1
kind: Secret
metadata:
name: backend-creds-1
namespace: apk-integration-test
data:
username: ZHNmZHNmc2Rmc2Rm
password: YWRtaW4=
type: Opaque
2 changes: 2 additions & 0 deletions test/cucumber-tests/scripts/setup-hosts.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#!/usr/bin/env bash

kubectl apply -f ./CRs/artifacts.yaml
kubectl wait deployment/httpbin -n apk-integration-test --for=condition=available --timeout=600s
kubectl wait --timeout=5m -n apk-integration-test deployment/apk-test-setup-wso2-apk-adapter-deployment --for=condition=Available
kubectl wait --timeout=15m -n apk-integration-test deployment/apk-test-setup-wso2-apk-gateway-runtime-deployment --for=condition=Available
IP=$(kubectl get svc apk-test-setup-wso2-apk-router-service -n apk-integration-test --output jsonpath='{.status.loadBalancer.ingress[0].ip}')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,7 @@ public void make_a_deployment_request() throws Exception {
sharedContext.setResponse(response);
}

@Then("the response body should contain {string}")
public void theResponseBodyShouldContain(String expectedText) throws IOException {

Assert.assertTrue(SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse()).contains(expectedText));
}

@When("I undeploy the API whose ID is {string}")
public void i_undeploy_the_api_whose_id_is(String apiID) throws Exception {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,26 @@

package org.wso2.apk.integration.api;

import io.cucumber.core.options.CurlOption;
import io.cucumber.datatable.DataTable;
import io.cucumber.java.Before;
import io.cucumber.java.en.And;
import io.cucumber.java.en.Given;
import io.cucumber.java.en.Then;
import io.cucumber.java.en.When;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
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 java.io.IOException;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
Expand All @@ -36,6 +46,7 @@ public class BaseSteps {

private final SharedContext sharedContext;
private SimpleHTTPClient httpClient;
private static final int MAX_WAIT_FOR_NEXT_MINUTE_IN_SECONDS = 10;

public BaseSteps(SharedContext sharedContext) {

Expand All @@ -53,13 +64,91 @@ public void systemIsReady() {

}

@Then("the response body should contain {string}")
public void theResponseBodyShouldContain(String expectedText) throws IOException {
String body = SimpleHTTPClient.responseEntityBodyToString(sharedContext.getResponse());
Assert.assertTrue(body.contains(expectedText), "Actual response body: " + body);
}

@Then("the response status code should be {int}")
public void theResponseStatusCodeShouldBe(int expectedStatusCode) {

int actualStatusCode = sharedContext.getResponse().getStatusLine().getStatusCode();
Assert.assertEquals(actualStatusCode, expectedStatusCode);
}

@Then("I send {string} request to {string} with body {string}")
public void sendHttpRequest(String httpMethod, String url, String body) throws IOException {
if (sharedContext.getResponse() instanceof CloseableHttpResponse) {
((CloseableHttpResponse) sharedContext.getResponse()).close();
}
if (CurlOption.HttpMethod.GET.toString().toLowerCase().equals(httpMethod.toLowerCase())) {
sharedContext.setResponse(httpClient.doGet(url, sharedContext.getHeaders()));
} else if (CurlOption.HttpMethod.POST.toString().toLowerCase().equals(httpMethod.toLowerCase())) {
sharedContext.setResponse(httpClient.doPost(url, sharedContext.getHeaders(), body, null));
} else if (CurlOption.HttpMethod.PUT.toString().toLowerCase().equals(httpMethod.toLowerCase())) {
sharedContext.setResponse(httpClient.doPut(url, sharedContext.getHeaders(), body, null));
} else if (CurlOption.HttpMethod.DELETE.toString().toLowerCase().equals(httpMethod.toLowerCase())) {
sharedContext.setResponse(httpClient.doPut(url, sharedContext.getHeaders(), body, null));
}
}

@Then("I set headers")
public void setHeaders(DataTable dataTable) {
List<List<String>> rows = dataTable.asLists(String.class);
for (List<String> columns : rows) {
String key = columns.get(0);
String value = columns.get(1);
key = Utils.resolveVariables(key, sharedContext.getValueStore());
value = Utils.resolveVariables(value, sharedContext.getValueStore());
sharedContext.addHeader(key, value);
}
}

@Then("I eventually receive {int} response code, not accepting")
public void eventualSuccess(int statusCode, DataTable dataTable) throws IOException, InterruptedException {
List<Integer> nonAcceptableCodes = dataTable.asList(Integer.class);
if (sharedContext.getResponse().getStatusLine().getStatusCode() == statusCode) {
Assert.assertTrue(true);
} else {
HttpResponse httpResponse = httpClient.executeLastRequestForEventualConsistentResponse(statusCode,
nonAcceptableCodes);
sharedContext.setResponse(httpResponse);
Assert.assertEquals(httpResponse.getStatusLine().getStatusCode(), statusCode);
}
}

@Then("I wait for next minute")
public void waitForNextMinute() throws InterruptedException {
LocalDateTime now = LocalDateTime.now();
LocalDateTime nextMinute = now.plusMinutes(1).withSecond(0).withNano(0);
long secondsToWait = now.until(nextMinute, ChronoUnit.SECONDS);
if (secondsToWait > MAX_WAIT_FOR_NEXT_MINUTE_IN_SECONDS) {
return;
}
Thread.sleep((secondsToWait+1) * 1000);
}

@Then("the response headers contains key {string} and value {string} ")
public void containsHeader(String key, String value) {
key = Utils.resolveVariables(key, sharedContext.getValueStore());
value = Utils.resolveVariables(value, sharedContext.getValueStore());
HttpResponse response = sharedContext.getResponse();
if (response == null) {
Assert.fail("Response is null.");
}
Header header = response.getFirstHeader(key);
if (header == null) {
Assert.fail("Could not find a header with the given key: " + key);
}
if ("*".equals(value)) {
return; // Any value is acceptable
}
String actualValue = header.getValue();
Assert.assertEquals("Header with key found but value mismatched.", value, actualValue);
}


@Given("I have a valid subscription")
public void iHaveValidSubscription() throws Exception {

Expand All @@ -70,5 +159,6 @@ public void iHaveValidSubscription() throws Exception {
HttpResponse httpResponse = httpClient.doPost(Utils.getTokenEndpointURL(), headers, "grant_type=client_credentials",
Constants.CONTENT_TYPES.APPLICATION_X_WWW_FORM_URLENCODED);
sharedContext.setAccessToken(Utils.extractToken(httpResponse));
sharedContext.addStoreValue("accessToken", sharedContext.getAccessToken());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,19 @@
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class SharedContext {

private SimpleHTTPClient httpClient;
private String accessToken;
private HttpResponse response;
private HashMap<String, Object> valueStore = new HashMap<>();
private HashMap<String, String> headers = new HashMap<>();

public SimpleHTTPClient getHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
if (httpClient == null) {
httpClient = new SimpleHTTPClient();
Expand All @@ -55,4 +62,25 @@ public void setResponse(HttpResponse response) {

this.response = response;
}

public Object getStoreValue(String key) {
return valueStore.get(key);
}

public void addStoreValue(String key, Object value) {
valueStore.put(key, value);
}

public Map<String, Object> getValueStore() {
return Collections.unmodifiableMap(valueStore);
}

public Map<String, String> getHeaders() {
return Collections.unmodifiableMap(headers);
}

public void addHeader(String key, String value) {
headers.put(key, value);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,11 @@
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Utils {

Expand Down Expand Up @@ -86,4 +91,24 @@ public static String extractToken(HttpResponse response) throws IOException {
}
throw new IOException("Missing key [access_token] in the response from the OAuth server");
}

public static String resolveVariables(String input, Map<String, Object> valueStore) {
// Define the pattern to match variables like ${variableName}
Pattern pattern = Pattern.compile("\\$\\{([^}]*)\\}");
Matcher matcher = pattern.matcher(input);
StringBuffer resolvedString = new StringBuffer();

while (matcher.find()) {
String variableName = matcher.group(1);
String variableValue = valueStore.get(variableName).toString();

// Replace the variable with its value from the value store if it exists
// Otherwise, keep the variable placeholder as is in the string
String replacement = (variableValue != null) ? variableValue : matcher.group();
matcher.appendReplacement(resolvedString, Matcher.quoteReplacement(replacement));
}

matcher.appendTail(resolvedString);
return resolvedString.toString();
}
}
Loading

0 comments on commit 2141692

Please sign in to comment.