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