Skip to content

Commit fef1426

Browse files
author
Naduni Pamudika
committed
Improve tests
1 parent a01db49 commit fef1426

File tree

12 files changed

+319
-99
lines changed

12 files changed

+319
-99
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
* Copyright (c) 2024, WSO2 LLC. (http://www.wso2.org) All Rights Reserved.
3+
*
4+
* WSO2 Inc. licenses this file to you under the Apache License,
5+
* Version 2.0 (the "License"); you may not use this file except
6+
* in compliance with the License.
7+
* You may obtain a copy of the License at
8+
*
9+
* http://www.apache.org/licenses/LICENSE-2.0
10+
*
11+
* Unless required by applicable law or agreed to in writing,
12+
* software distributed under the License is distributed on an
13+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
* KIND, either express or implied. See the License for the
15+
* specific language governing permissions and limitations
16+
* under the License.
17+
*/
18+
19+
package org.wso2.am.integration.test.utils;
20+
21+
import java.io.IOException;
22+
import java.net.Socket;
23+
24+
public class ServerPortsUtils {
25+
26+
public static String LOCALHOST = "localhost";
27+
public static final int httpPortLowerRange = 8080;
28+
public static final int httpPortUpperRange = 8099;
29+
public static final int httpsPortLowerRange = 9950;
30+
public static final int httpsPortUpperRange = 9999;
31+
32+
/**
33+
* Check whether give port is available
34+
*
35+
* @param port Port Number
36+
* @return status
37+
*/
38+
private static boolean isPortFree(int port, String host) {
39+
40+
Socket s = null;
41+
try {
42+
s = new Socket(host, port);
43+
// Something is using the port and has responded.
44+
return false;
45+
} catch (IOException e) {
46+
// Port available
47+
return true;
48+
} finally {
49+
if (s != null) {
50+
try {
51+
s.close();
52+
} catch (IOException e) {
53+
throw new RuntimeException("Unable to close connection ", e);
54+
}
55+
}
56+
}
57+
}
58+
59+
public static int getAvailableHttpPort(String host) {
60+
return getAvailablePort(httpPortLowerRange, httpPortUpperRange, host);
61+
}
62+
63+
public static int getAvailableHttpsPort(String host) {
64+
return getAvailablePort(httpsPortLowerRange, httpsPortUpperRange, host);
65+
}
66+
67+
/**
68+
* Find a free port to start backend WebSocket server in given port range
69+
*
70+
* @param lowerPortLimit from port number
71+
* @param upperPortLimit to port number
72+
* @return Available Port Number
73+
*/
74+
private static int getAvailablePort(int lowerPortLimit, int upperPortLimit, String host) {
75+
while (lowerPortLimit < upperPortLimit) {
76+
if (ServerPortsUtils.isPortFree(lowerPortLimit, host)) {
77+
return lowerPortLimit;
78+
}
79+
lowerPortLimit += 1;
80+
}
81+
return -1;
82+
}
83+
84+
}

modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/api/lifecycle/APIEndpointCertificateTestCase.java

+37-2
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,18 @@
4242
import org.wso2.am.integration.test.utils.base.APIMIntegrationConstants;
4343
import org.wso2.am.integration.test.utils.bean.APIRequest;
4444
import org.wso2.am.integration.test.utils.http.HttpRequestUtil;
45+
import org.wso2.carbon.automation.engine.context.AutomationContext;
4546
import org.wso2.carbon.automation.engine.context.TestUserMode;
4647
import org.wso2.carbon.automation.test.utils.http.client.HttpResponse;
48+
import org.wso2.carbon.integration.common.admin.client.LogViewerClient;
49+
import org.wso2.carbon.logging.view.data.xsd.LogEvent;
4750

4851
import java.io.File;
4952
import java.io.IOException;
5053
import java.net.InetAddress;
5154
import java.net.Socket;
5255
import java.net.URL;
56+
import java.rmi.RemoteException;
5357
import java.text.ParseException;
5458
import java.text.SimpleDateFormat;
5559
import java.util.ArrayList;
@@ -78,6 +82,7 @@ public class APIEndpointCertificateTestCase extends APIManagerLifecycleBaseTest
7882
String apiId;
7983
WireMockServer wireMockServer;
8084
private String accessToken;
85+
private LogViewerClient logViewerClient;
8186

8287
@Factory(dataProvider = "userModeDataProvider")
8388
public APIEndpointCertificateTestCase(TestUserMode userMode) {
@@ -137,6 +142,11 @@ public void initialize() throws Exception {
137142
accessToken = applicationKeyDTO.getToken().getAccessToken();
138143
waitForAPIDeploymentSync(user.getUserName(), apiRequest.getName(), apiRequest.getVersion(),
139144
APIMIntegrationConstants.IS_API_EXISTS);
145+
AutomationContext autoContext = new AutomationContext();
146+
logViewerClient = new LogViewerClient(autoContext.getContextUrls().getBackEndUrl(),
147+
autoContext.getSuperTenant().getTenantAdmin().getUserName(),
148+
autoContext.getSuperTenant().getTenantAdmin().getPassword());
149+
logViewerClient.clearLogs();
140150
}
141151

142152
@Test(groups = {"wso2.am"}, description = "Invoke API without inserting Endpoint Certificate")
@@ -263,7 +273,9 @@ public void testSearchEndpointCertificates() throws ApiException, ParseException
263273
"testSearchEndpointCertificates"})
264274
public void testInvokeAPI() throws ApiException, InterruptedException, XPathExpressionException, IOException {
265275

266-
Thread.sleep(60000); // Sleep to reload the transport
276+
// Thread.sleep(60000); // Sleep to reload the transport
277+
// Wait for SSLProfile with the uploaded certificate to be reloaded in Gateway
278+
waitForSSLProfileReload();
267279
Map<String, String> requestHeaders = new HashMap<>();
268280
requestHeaders.put("accept", "application/json");
269281
requestHeaders.put("Authorization", "Bearer " + accessToken);
@@ -282,7 +294,8 @@ public void testInvokeAPIAfterRemovingCertificate() throws InterruptedException,
282294
Assert.assertEquals(response.getStatusCode(), 200);
283295
response = restAPIPublisher.deleteEndpointCertificate("endpoint-2");
284296
Assert.assertEquals(response.getStatusCode(), 200);
285-
Thread.sleep(60500); // Sleep to reload the transport
297+
// Thread.sleep(60500); // Sleep to reload the transport
298+
waitForSSLProfileReload();
286299
Map<String, String> requestHeaders = new HashMap<>();
287300
requestHeaders.put("accept", "application/json");
288301
requestHeaders.put("Authorization", "Bearer " + accessToken);
@@ -320,6 +333,28 @@ private void startSecureEndpoint(int securedEndpointPort) {
320333
wireMockServer.start();
321334
}
322335

336+
private void waitForSSLProfileReload() throws RemoteException, InterruptedException {
337+
LogEvent[] logEvents = new LogEvent[0];
338+
Thread.sleep(60000);
339+
logEvents = logViewerClient.getAllRemoteSystemLogs();
340+
int retryAttempt = 0;
341+
boolean isSSProfileReloaded = false;
342+
while (retryAttempt < 5 && !isSSProfileReloaded) {
343+
for (LogEvent logEvent : logEvents) {
344+
if (logEvent.getMessage()
345+
.contains("PassThroughHttpSender reloading SSL Config")) {
346+
isSSProfileReloaded = true;
347+
log.info("SSLProfile has been reloaded successfully");
348+
logViewerClient.clearLogs();
349+
break;
350+
}
351+
}
352+
retryAttempt++;
353+
log.info("SSLProfile has not been reloaded. Retry attempt - " + retryAttempt);
354+
Thread.sleep(12000);
355+
}
356+
}
357+
323358
@AfterClass(alwaysRun = true)
324359
public void destroy() throws ApiException {
325360

modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/graphql/GraphqlSubscriptionTestCase.java

+8-7
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,6 @@
8989
import java.time.LocalDateTime;
9090
import java.util.ArrayList;
9191
import java.util.List;
92-
import java.util.concurrent.ExecutorService;
9392
import java.util.concurrent.Executors;
9493
import java.util.concurrent.TimeUnit;
9594

@@ -108,7 +107,6 @@ public class GraphqlSubscriptionTestCase extends APIMIntegrationBaseTest {
108107
private static final String GRAPHQL_API_NAME = "SnowtoothGraphQLSubAPI";
109108
private static final String GRAPHQL_API_CONTEXT = "snowtooth";
110109
private static final String GRAPHQL_API_VERSION = "1.0.0";
111-
private final ExecutorService executorService = Executors.newSingleThreadExecutor();
112110
private int webSocketServerPort;
113111
private String webSocketServerHost;
114112
private String graphqlApiId;
@@ -118,6 +116,7 @@ public class GraphqlSubscriptionTestCase extends APIMIntegrationBaseTest {
118116
String throttleAppId;
119117
String complexAppId;
120118
String depthAppId;
119+
Server server = null;
121120

122121
private enum AUTH_IN {
123122
HEADER,
@@ -623,8 +622,6 @@ private void invokeGraphQLSubscriptionSuccess(WebSocketClient client, String acc
623622
*/
624623
private void startGraphQLSubscriptionServer(final int serverPort) {
625624

626-
executorService.execute(() -> {
627-
628625
WebSocketHandler wsHandler = new WebSocketHandler() {
629626
@Override
630627
public void configure(WebSocketServletFactory factory) {
@@ -633,7 +630,7 @@ public void configure(WebSocketServletFactory factory) {
633630
}
634631
};
635632

636-
Server server = new Server(serverPort);
633+
server = new Server(serverPort);
637634
server.setHandler(wsHandler);
638635
try {
639636
server.start();
@@ -643,7 +640,6 @@ public void configure(WebSocketServletFactory factory) {
643640
log.error("Error while starting graphql backend server at port: " + serverPort, e);
644641
Assert.fail("Cannot start GraphQL WebSocket server");
645642
}
646-
});
647643
}
648644

649645
/**
@@ -1017,6 +1013,9 @@ private void testThrottling(String accessToken) throws Exception {
10171013
"Received response in not a Connection Ack response");
10181014
socket.setResponseMessage(null);
10191015
for (int count = 1; count <= limit; count++) {
1016+
if (count == limit) {
1017+
Thread.sleep(3000);
1018+
}
10201019
if (count == 1) {
10211020
//Send initial graphQL subscription request message
10221021
textMessage = "{\"id\":\"2\",\"type\":\"start\",\"payload\":{\"variables\":{},\"extensions\":{},"
@@ -1065,14 +1064,16 @@ private void testThrottling(String accessToken) throws Exception {
10651064

10661065
@AfterClass(alwaysRun = true)
10671066
public void destroy() throws Exception {
1067+
if (server != null) {
1068+
server.stop();
1069+
}
10681070
userManagementClient.deleteRole(GRAPHQL_ROLE);
10691071
userManagementClient.deleteUser(GRAPHQL_TEST_USER);
10701072
restAPIStore.deleteApplication(appJWTId);
10711073
restAPIStore.deleteApplication(complexAppId);
10721074
restAPIStore.deleteApplication(depthAppId);
10731075
restAPIStore.deleteApplication(throttleAppId);
10741076
undeployAndDeleteAPIRevisionsUsingRest(graphqlApiId, restAPIPublisher);
1075-
executorService.shutdownNow();
10761077
super.cleanUp();
10771078
}
10781079
}

modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/MandatoryPropertiesTestWithRestart.java

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
import org.apache.http.HttpStatus;
2121
import org.testng.Assert;
2222
import org.testng.annotations.AfterClass;
23-
import org.testng.annotations.BeforeClass;
23+
import org.testng.annotations.BeforeTest;
2424
import org.testng.annotations.DataProvider;
2525
import org.testng.annotations.Factory;
2626
import org.testng.annotations.Test;
@@ -67,7 +67,7 @@ public static Object[][] userModeDataProvider() {
6767
return new Object[][] { new Object[] { TestUserMode.SUPER_TENANT_ADMIN }};
6868
}
6969

70-
@BeforeClass(alwaysRun = true)
70+
@BeforeTest(alwaysRun = true)
7171
public void setEnvironment() throws Exception {
7272
super.init(userMode);
7373
superTenantKeyManagerContext = new AutomationContext(APIMIntegrationConstants.AM_PRODUCT_GROUP_NAME,

modules/integration/tests-integration/tests-backend/src/test/java/org/wso2/am/integration/tests/other/NotificationTestCase.java

+14-7
Original file line numberDiff line numberDiff line change
@@ -93,18 +93,24 @@ public void setEnvironment() throws Exception {
9393
super.init(userMode);
9494
storeURLHttp = "https://localhost:9943/";
9595

96-
}
97-
98-
@Test(groups = {"wso2.am"}, description = "Testing Notification Feature")
99-
public void notificationTestCase() throws Exception {
100-
10196
//Setting greenMail server
10297
ServerSetup setup = new ServerSetup(SMTP_TEST_PORT, "localhost", "smtp");
10398
greenMail = new GreenMail(setup);
10499
//Creating user in greenMail server
105100
greenMail.setUser(USER_EMAIL_ADDRESS, EMAIL_USERNAME, EMAIL_PASSWORD);
106-
greenMail.start();
107-
log.info("green mail server started ");
101+
try {
102+
greenMail.start();
103+
} catch (IllegalStateException e) {
104+
log.warn("There was a problem starting GreenMail server. Retrying in 10 seconds");
105+
Thread.sleep(10000);
106+
greenMail.start();
107+
}
108+
log.info("green mail server started");
109+
110+
}
111+
112+
@Test(groups = {"wso2.am"}, description = "Testing Notification Feature")
113+
public void notificationTestCase() throws Exception {
108114

109115
// Adding API
110116
String url = getGatewayURLNhttp() + "response";
@@ -212,6 +218,7 @@ public void destroy() throws Exception {
212218
undeployAndDeleteAPIRevisionsUsingRest(newApiId, restAPIPublisher);
213219
restAPIPublisher.deleteAPI(apiId);
214220
restAPIPublisher.deleteAPI(newApiId);
221+
greenMail.stop();
215222
}
216223

217224
@DataProvider

0 commit comments

Comments
 (0)