2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019 Nordix Foundation.
4 * Modifications Copyright (C) 2019, 2021 AT&T Intellectual Property.
5 * Modifications Copyright (C) 2021-2022 Bell Canada. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * SPDX-License-Identifier: Apache-2.0
20 * ============LICENSE_END=========================================================
23 package org.onap.policy.pap.main.rest;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertTrue;
29 import java.io.FileOutputStream;
30 import java.nio.charset.StandardCharsets;
31 import java.security.SecureRandom;
32 import java.util.concurrent.atomic.AtomicBoolean;
33 import java.util.function.Function;
34 import javax.net.ssl.SSLContext;
35 import javax.ws.rs.client.Client;
36 import javax.ws.rs.client.ClientBuilder;
37 import javax.ws.rs.client.Invocation;
38 import javax.ws.rs.client.WebTarget;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.Response;
41 import org.glassfish.jersey.client.ClientProperties;
42 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
43 import org.junit.After;
44 import org.junit.Before;
45 import org.junit.BeforeClass;
46 import org.junit.runner.RunWith;
47 import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
49 import org.onap.policy.common.gson.GsonMessageBodyHandler;
50 import org.onap.policy.common.utils.network.NetworkUtil;
51 import org.onap.policy.common.utils.security.SelfSignedKeyStore;
52 import org.onap.policy.common.utils.services.Registry;
53 import org.onap.policy.pap.main.PolicyPapApplication;
54 import org.onap.policy.pap.main.parameters.CommonTestData;
55 import org.onap.policy.pap.main.startstop.PapActivator;
56 import org.powermock.reflect.Whitebox;
57 import org.springframework.beans.factory.annotation.Autowired;
58 import org.springframework.boot.test.context.SpringBootTest;
59 import org.springframework.boot.web.server.LocalServerPort;
60 import org.springframework.test.annotation.DirtiesContext;
61 import org.springframework.test.annotation.DirtiesContext.ClassMode;
62 import org.springframework.test.context.DynamicPropertyRegistry;
63 import org.springframework.test.context.DynamicPropertySource;
64 import org.springframework.test.context.junit4.SpringRunner;
67 * Class to perform unit test of {@link PapRestControllerV1}.
69 * @author Ram Krishna Verma (ram.krishna.verma@est.tech)
71 @RunWith(SpringRunner.class)
72 @SpringBootTest(classes = PolicyPapApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
73 properties = {"db.initialize=false"})
74 @DirtiesContext(classMode = ClassMode.AFTER_CLASS)
75 public abstract class CommonPapRestServer {
77 protected static final String CONFIG_FILE = "src/test/resources/parameters/TestConfigParams.json";
79 public static final String NOT_ALIVE = "not alive";
80 public static final String ALIVE = "alive";
81 public static final String SELF = NetworkUtil.getHostname();
82 public static final String NAME = "Policy PAP";
83 public static final String ENDPOINT_PREFIX = "policy/pap/v1/";
85 private static SelfSignedKeyStore keystore;
87 private boolean activatorWasAlive;
88 protected String httpsPrefix;
94 private PapActivator papActivator;
97 * Allocates a new db url, writes a config file.
99 * @throws Exception if an error occurs
102 public static void setUpBeforeClass() throws Exception {
103 keystore = new SelfSignedKeyStore();
104 CommonTestData.newDb();
107 HttpServletServerFactoryInstance.getServerFactory().destroy();
108 TopicEndpointManager.getManager().shutdown();
109 Registry.newRegistry();
112 @DynamicPropertySource
113 static void registerPgProperties(DynamicPropertyRegistry registry) {
114 registry.add("spring.datasource.url", () -> "jdbc:h2:mem:testdb" + CommonTestData.dbNum);
115 registry.add("server.ssl.enabled", () -> "true");
116 registry.add("server.ssl.key-store", () -> keystore.getKeystoreName());
117 registry.add("server.ssl.key-store-password", () -> SelfSignedKeyStore.KEYSTORE_PASSWORD);
123 * @throws Exception if an error occurs
126 public void setUp() throws Exception {
127 httpsPrefix = "https://localhost:" + port + "/";
128 activatorWasAlive = papActivator.isAlive();
132 * Restores the activator's "alive" state.
135 public void tearDown() {
136 markActivator(activatorWasAlive);
140 * Verifies that an endpoint appears within the swagger response.
142 * @param endpoint the endpoint of interest
143 * @throws Exception if an error occurs
145 protected void testSwagger(final String endpoint) throws Exception {
146 final Invocation.Builder invocationBuilder = sendFqeRequest(httpsPrefix + "v2/api-docs", true);
147 final String resp = invocationBuilder.get(String.class);
148 assertTrue(resp.contains(ENDPOINT_PREFIX + endpoint));
152 * Makes a parameter configuration file.
154 * @throws Exception if an error occurs
156 private static void makeConfigFile() throws Exception {
157 String json = new CommonTestData().getPapParameterGroupAsString(6969);
159 File file = new File(CONFIG_FILE);
162 try (FileOutputStream output = new FileOutputStream(file)) {
163 output.write(json.getBytes(StandardCharsets.UTF_8));
168 * Mark the activator as dead, but leave its REST server running.
170 protected void markActivatorDead() {
171 markActivator(false);
174 private void markActivator(boolean wasAlive) {
175 Object manager = Whitebox.getInternalState(papActivator, "serviceManager");
176 AtomicBoolean running = Whitebox.getInternalState(manager, "running");
177 running.set(wasAlive);
181 * Verifies that unauthorized requests fail.
183 * @param endpoint the target end point
184 * @param sender function that sends the requests to the target
185 * @throws Exception if an error occurs
187 protected void checkUnauthRequest(final String endpoint, Function<Invocation.Builder, Response> sender)
189 assertEquals(Response.Status.UNAUTHORIZED.getStatusCode(),
190 sender.apply(sendNoAuthRequest(endpoint)).getStatus());
194 * Sends a request to an endpoint.
196 * @param endpoint the target endpoint
197 * @return a request builder
198 * @throws Exception if an error occurs
200 protected Invocation.Builder sendRequest(final String endpoint) throws Exception {
201 return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, true);
205 * Sends a request to an endpoint, without any authorization header.
207 * @param endpoint the target endpoint
208 * @return a request builder
209 * @throws Exception if an error occurs
211 protected Invocation.Builder sendNoAuthRequest(final String endpoint) throws Exception {
212 return sendFqeRequest(httpsPrefix + ENDPOINT_PREFIX + endpoint, false);
216 * Sends a request to a fully qualified endpoint.
218 * @param fullyQualifiedEndpoint the fully qualified target endpoint
219 * @param includeAuth if authorization header should be included
220 * @return a request builder
221 * @throws Exception if an error occurs
223 protected Invocation.Builder sendFqeRequest(final String fullyQualifiedEndpoint, boolean includeAuth)
225 final SSLContext sc = SSLContext.getInstance("TLSv1.2");
226 sc.init(null, NetworkUtil.getAlwaysTrustingManager(), new SecureRandom());
227 final ClientBuilder clientBuilder =
228 ClientBuilder.newBuilder().sslContext(sc).hostnameVerifier((host, session) -> true);
229 final Client client = clientBuilder.build();
231 client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
232 client.register(GsonMessageBodyHandler.class);
235 final HttpAuthenticationFeature feature = HttpAuthenticationFeature.basic("policyadmin", "zb!XztG34");
236 client.register(feature);
239 final WebTarget webTarget = client.target(fullyQualifiedEndpoint);
241 return webTarget.request(MediaType.APPLICATION_JSON);