Changed identifiers to concept identifiers
[policy/xacml-pdp.git] / applications / common / src / test / java / org / onap / policy / pdp / xacml / application / common / PolicyApiCallerTest.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved.
4  * Modifications Copyright (C) 2021 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
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
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.
17  *
18  * SPDX-License-Identifier: Apache-2.0
19  * ============LICENSE_END=========================================================
20  */
21
22 package org.onap.policy.pdp.xacml.application.common;
23
24 import static org.assertj.core.api.Assertions.assertThatThrownBy;
25 import static org.junit.Assert.assertEquals;
26 import static org.junit.Assert.assertNotNull;
27 import static org.junit.Assert.assertTrue;
28 import static org.mockito.Mockito.mock;
29 import static org.mockito.Mockito.when;
30
31 import java.io.IOException;
32 import java.util.Properties;
33 import java.util.UUID;
34 import javax.ws.rs.Consumes;
35 import javax.ws.rs.GET;
36 import javax.ws.rs.HeaderParam;
37 import javax.ws.rs.Path;
38 import javax.ws.rs.PathParam;
39 import javax.ws.rs.Produces;
40 import javax.ws.rs.core.Response;
41 import org.junit.AfterClass;
42 import org.junit.Before;
43 import org.junit.BeforeClass;
44 import org.junit.Test;
45 import org.onap.policy.common.endpoints.event.comm.bus.internal.BusTopicParams;
46 import org.onap.policy.common.endpoints.http.client.HttpClient;
47 import org.onap.policy.common.endpoints.http.client.HttpClientConfigException;
48 import org.onap.policy.common.endpoints.http.server.HttpServletServer;
49 import org.onap.policy.common.endpoints.http.server.HttpServletServerFactoryInstance;
50 import org.onap.policy.common.endpoints.parameters.RestServerParameters;
51 import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
52 import org.onap.policy.common.gson.GsonMessageBodyHandler;
53 import org.onap.policy.common.utils.network.NetworkUtil;
54 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
55 import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicyType;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 public class PolicyApiCallerTest {
60     private static final String MY_TYPE = "my-type";
61
62     private static final String MY_VERSION = "1.0.0";
63
64     private static final Logger logger = LoggerFactory.getLogger(PolicyApiCallerTest.class);
65
66     private static final String CLIENT_NAME = "policy-api";
67     private static final String NOT_A_TYPE = "other-type";
68     private static final String INVALID_TYPE = "invalid";
69     private static final String UNKNOWN_TYPE = "unknown";
70
71     private static int port;
72     private static RestServerParameters clientParams;
73
74     private PolicyApiCaller api;
75
76     /**
77      * Initializes {@link #clientParams} and starts a simple REST server to handle the
78      * test requests.
79      *
80      * @throws IOException if an error occurs
81      */
82     @BeforeClass
83     public static void setUpBeforeClass() throws Exception {
84         port = NetworkUtil.allocPort();
85
86         clientParams = mock(RestServerParameters.class);
87         when(clientParams.getHost()).thenReturn("localhost");
88         when(clientParams.getPort()).thenReturn(port);
89
90         Properties props = new Properties();
91         props.setProperty(PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES, CLIENT_NAME);
92
93         final String svcpfx =
94                         PolicyEndPointProperties.PROPERTY_HTTP_SERVER_SERVICES + "." + CLIENT_NAME;
95
96         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HOST_SUFFIX, clientParams.getHost());
97         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_PORT_SUFFIX,
98                         Integer.toString(clientParams.getPort()));
99         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_REST_CLASSES_SUFFIX,
100                         ApiRestController.class.getName());
101         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_MANAGED_SUFFIX, "true");
102         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX, "false");
103         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_AAF_SUFFIX, "false");
104         props.setProperty(svcpfx + PolicyEndPointProperties.PROPERTY_HTTP_SERIALIZATION_PROVIDER,
105                         GsonMessageBodyHandler.class.getName());
106
107         HttpServletServerFactoryInstance.getServerFactory().build(props).forEach(HttpServletServer::start);
108
109         assertTrue(NetworkUtil.isTcpPortOpen(clientParams.getHost(), clientParams.getPort(), 100, 100));
110     }
111
112     @AfterClass
113     public static void tearDownAfterClass() {
114         HttpServletServerFactoryInstance.getServerFactory().destroy();
115     }
116
117     /**
118      * Resets {@link #clientParams} and populates {@link #api}.
119      *
120      * @throws PolicyApiException if an error occurs
121      */
122     @Before
123     public void setUp() throws PolicyApiException {
124         when(clientParams.getPort()).thenReturn(port);
125
126         api = new PolicyApiCaller(clientParams);
127     }
128
129     @Test
130     public void testPolicyApi() {
131         assertThatThrownBy(() -> new PolicyApiCaller(clientParams) {
132             @Override
133             protected HttpClient makeClient(BusTopicParams busParams) throws HttpClientConfigException {
134                 throw new HttpClientConfigException("expected exception");
135             }
136         }).isInstanceOf(PolicyApiException.class);
137     }
138
139     @Test
140     public void testGetPolicyType() throws Exception {
141
142         assertNotNull(api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)));
143
144         assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(INVALID_TYPE, MY_VERSION)))
145                         .isInstanceOf(PolicyApiException.class);
146
147         assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(UNKNOWN_TYPE, MY_VERSION)))
148                         .isInstanceOf(NotFoundException.class);
149
150         assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(NOT_A_TYPE, MY_VERSION)))
151                         .isInstanceOf(PolicyApiException.class);
152
153         // connect to a port that has no server
154         when(clientParams.getPort()).thenReturn(NetworkUtil.allocPort());
155         api = new PolicyApiCaller(clientParams);
156
157         assertThatThrownBy(() -> api.getPolicyType(new ToscaConceptIdentifier(MY_TYPE, MY_VERSION)))
158                         .isInstanceOf(PolicyApiException.class);
159     }
160
161     /**
162      * Simple REST server to handle test requests.
163      */
164
165     @Path("/policy/api/v1")
166     @Produces({"application/json", "application/yaml"})
167     @Consumes({"application/json", "application/yaml"})
168     public static class ApiRestController {
169
170         /**
171          * Retrieves the specified version of a particular policy type.
172          *
173          * @param policyTypeId ID of desired policy type
174          * @param versionId version of desired policy type
175          * @param requestId optional request ID
176          *
177          * @return the Response object containing the results of the API operation
178          */
179         @GET
180         @Path("/policytypes/{policyTypeId}/versions/{versionId}")
181         public Response getSpecificVersionOfPolicyType(@PathParam("policyTypeId") String policyTypeId,
182                         @PathParam("versionId") String versionId, @HeaderParam("X-ONAP-RequestID") UUID requestId) {
183
184             assertEquals(MY_VERSION, versionId);
185
186             switch (policyTypeId) {
187                 case UNKNOWN_TYPE:
188                     logger.info("request for unknown policy type");
189                     return Response.status(Response.Status.NOT_FOUND).build();
190                 case INVALID_TYPE:
191                     logger.info("invalid request for policy type");
192                     return Response.status(Response.Status.BAD_REQUEST).build();
193                 case NOT_A_TYPE:
194                     logger.info("invalid request for policy type");
195                     return Response.status(Response.Status.OK).entity("string-type").build();
196                 default:
197                     logger.info("request for policy type={} version={}", policyTypeId, versionId);
198                     return Response.status(Response.Status.OK).entity(new ToscaPolicyType()).build();
199             }
200         }
201     }
202 }