2 * ============LICENSE_START=======================================================
3 * Copyright (C) 2019, 2021 AT&T Intellectual Property. All rights reserved.
4 * Modifications Copyright (C) 2021, 2023-2024 Nordix Foundation.
5 * ================================================================================
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * SPDX-License-Identifier: Apache-2.0
19 * ============LICENSE_END=========================================================
22 package org.onap.policy.pdp.xacml.application.common;
24 import static org.assertj.core.api.Assertions.assertThatThrownBy;
25 import static org.junit.jupiter.api.Assertions.assertEquals;
26 import static org.junit.jupiter.api.Assertions.assertNotNull;
27 import static org.junit.jupiter.api.Assertions.assertTrue;
28 import static org.mockito.Mockito.mock;
29 import static org.mockito.Mockito.when;
31 import jakarta.ws.rs.Consumes;
32 import jakarta.ws.rs.GET;
33 import jakarta.ws.rs.HeaderParam;
34 import jakarta.ws.rs.Path;
35 import jakarta.ws.rs.PathParam;
36 import jakarta.ws.rs.Produces;
37 import jakarta.ws.rs.core.Response;
38 import java.io.IOException;
39 import java.util.Properties;
40 import java.util.UUID;
41 import org.junit.jupiter.api.AfterAll;
42 import org.junit.jupiter.api.BeforeAll;
43 import org.junit.jupiter.api.BeforeEach;
44 import org.junit.jupiter.api.Test;
45 import org.onap.policy.common.endpoints.http.client.HttpClient;
46 import org.onap.policy.common.endpoints.http.client.HttpClientFactoryInstance;
47 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
49 import org.onap.policy.common.endpoints.parameters.RestClientParameters;
50 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
51 import org.onap.policy.common.gson.GsonMessageBodyHandler;
52 import org.onap.policy.common.utils.network.NetworkUtil;
53 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 class PolicyApiCallerTest {
59 private static final String MY_TYPE = "my-type";
61 private static final String MY_VERSION = "1.0.0";
63 private static final Logger logger = LoggerFactory.getLogger(PolicyApiCallerTest.class);
65 private static final String CLIENT_NAME = "policy-api";
66 private static final String NOT_A_TYPE = "other-type";
67 private static final String INVALID_TYPE = "invalid";
68 private static final String UNKNOWN_TYPE = "unknown";
70 private static int port;
71 private static RestClientParameters clientParams;
73 private static HttpClient apiClient;
75 private PolicyApiCaller api;
78 * Initializes {@link #clientParams} and starts a simple REST server to handle the
81 * @throws IOException if an error occurs
84 static void setUpBeforeClass() throws Exception {
85 port = NetworkUtil.allocPort();
87 clientParams = mock(RestClientParameters.class);
88 when(clientParams.getClientName()).thenReturn("apiClient");
89 when(clientParams.getHostname()).thenReturn("localhost");
90 when(clientParams.getPort()).thenReturn(port);
92 Properties props = new Properties();
93 props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
96 PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
98 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHostname());
99 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
100 Integer.toString(clientParams.getPort()));
101 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
102 ApiRestController.class.getName());
103 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
104 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
105 props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
106 GsonMessageBodyHandler.class.getName());
108 HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
109 apiClient = HttpClientFactoryInstance.getClientFactory().build(clientParams);
111 assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHostname(), clientParams.getPort(), 100, 100));
115 static void tearDownAfterClass() {
116 HttpServletServerFactoryInstance.getServerFactory().destroy();
120 * Resets {@link #clientParams} and populates {@link #api}.
122 * @throws PolicyApiException if an error occurs
125 void setUp() throws PolicyApiException {
126 when(clientParams.getPort()).thenReturn(port);
128 api = new PolicyApiCaller(apiClient);
132 void testGetPolicyType() throws Exception {
134 assertNotNull(api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)));
136 assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(INVALID_TYPE, MY_VERSION)))
137 .isInstanceOf(PolicyApiException.class);
139 assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(UNKNOWN_TYPE, MY_VERSION)))
140 .isInstanceOf(NotFoundException.class);
142 assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(NOT_A_TYPE, MY_VERSION)))
143 .isInstanceOf(PolicyApiException.class);
145 // connect to a port that has no server
146 RestClientParameters params2 = mock(RestClientParameters.class);
147 when(params2.getClientName()).thenReturn("apiClient");
148 when(params2.getHostname()).thenReturn("localhost");
149 when(params2.getPort()).thenReturn(NetworkUtil.allocPort());
151 HttpClient apiClient2 = HttpClientFactoryInstance.getClientFactory().build(params2);
152 api = new PolicyApiCaller(apiClient2);
154 assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)))
155 .isInstanceOf(PolicyApiException.class);
159 * Simple REST server to handle test requests.
162 @Path("/policy/api/v1")
163 @Produces({"application/json", "application/yaml"})
164 @Consumes({"application/json", "application/yaml"})
165 public static class ApiRestController {
168 * Retrieves the specified version of a particular policy type.
170 * @param policyTypeId ID of desired policy type
171 * @param versionId version of desired policy type
172 * @param requestId optional request ID
173 * @return the Response object containing the results of the API operation
176 @Path("/policytypes/{policyTypeId}/versions/{versionId}")
177 public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
178 @PathParam("versionId") String versionId,
179 @HeaderParam("X-ONAP-RequestID") UUID requestId) {
181 assertEquals(MY_VERSION, versionId);
183 return switch (policyTypeId) {
184 case UNKNOWN_TYPE -> {
185 logger.info("request for unknown policy type");
186 yield Response.status(Response.Status.NOT_FOUND).build();
188 case INVALID_TYPE -> {
189 logger.info("invalid request for policy type");
190 yield Response.status(Response.Status.BAD_REQUEST).build();
193 logger.info("invalid request for policy type");
194 yield Response.status(Response.Status.OK).entity("string-type").build();
197 logger.info("request for policy type={} version={}", policyTypeId, versionId);
198 yield Response.status(Response.Status.OK).entity(new ToscaPolicyType()).build();