14f51269ae5f6254d77fa0e6e7bb7cabffe5e10d
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021 Nordix Foundation.
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.clamp.controlloop.participant.simulator.endtoend;
22
23 import static org.assertj.core.api.Assertions.assertThat;
24 import static org.junit.jupiter.api.Assertions.assertEquals;
25 import static org.junit.jupiter.api.Assertions.assertNotNull;
26 import static org.junit.jupiter.api.Assertions.assertTrue;
27
28 import java.util.List;
29 import java.util.Map;
30 import java.util.UUID;
31 import javax.ws.rs.client.Client;
32 import javax.ws.rs.client.ClientBuilder;
33 import javax.ws.rs.client.Entity;
34 import javax.ws.rs.client.Invocation;
35 import javax.ws.rs.client.WebTarget;
36 import javax.ws.rs.core.GenericType;
37 import javax.ws.rs.core.MediaType;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Response;
40 import org.glassfish.jersey.client.ClientProperties;
41 import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
42 import org.junit.jupiter.api.Test;
43 import org.junit.jupiter.api.extension.ExtendWith;
44 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoop;
45 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopElement;
46 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ControlLoopOrderedState;
47 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.Participant;
48 import org.onap.policy.clamp.controlloop.models.controlloop.concepts.ParticipantState;
49 import org.onap.policy.clamp.controlloop.models.messages.dmaap.participant.ControlLoopUpdate;
50 import org.onap.policy.clamp.controlloop.models.messages.rest.TypedSimpleResponse;
51 import org.onap.policy.clamp.controlloop.participant.intermediary.api.ParticipantIntermediaryApi;
52 import org.onap.policy.clamp.controlloop.participant.intermediary.comm.ControlLoopUpdateListener;
53 import org.onap.policy.clamp.controlloop.participant.intermediary.handler.ParticipantHandler;
54 import org.onap.policy.clamp.controlloop.participant.simulator.main.parameters.CommonTestData;
55 import org.onap.policy.clamp.controlloop.participant.simulator.main.rest.AbstractRestController;
56 import org.onap.policy.clamp.controlloop.participant.simulator.main.rest.TestListenerUtils;
57 import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
58 import org.onap.policy.common.gson.GsonMessageBodyHandler;
59 import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
60 import org.springframework.beans.factory.annotation.Autowired;
61 import org.springframework.beans.factory.annotation.Value;
62 import org.springframework.boot.test.context.SpringBootTest;
63 import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
64 import org.springframework.boot.web.server.LocalServerPort;
65 import org.springframework.test.context.TestPropertySource;
66 import org.springframework.test.context.junit.jupiter.SpringExtension;
67
68 @ExtendWith(SpringExtension.class)
69 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
70 @TestPropertySource(locations = {"classpath:application_test.properties"})
71 class ParticipantSimulatorTest {
72
73     private static final String PARTICIPANTS_ENDPOINT = "participants";
74     private static final String ELEMENTS_ENDPOINT = "elements";
75     private static final CommInfrastructure INFRA = CommInfrastructure.NOOP;
76     private static final String TOPIC = "my-topic";
77
78     @Value("${spring.security.user.name}")
79     private String user;
80
81     @Value("${spring.security.user.password}")
82     private String password;
83
84     @LocalServerPort
85     private int randomServerPort;
86
87     @Autowired
88     private ParticipantIntermediaryApi participantIntermediaryApi;
89
90     @Autowired
91     private ParticipantHandler participantHandler;
92
93     private static final Object lockit = new Object();
94     private boolean check = false;
95
96     private void setUp() throws Exception {
97         synchronized (lockit) {
98             if (!check) {
99                 check = true;
100                 ControlLoopUpdateListener clUpdateListener = new ControlLoopUpdateListener(participantHandler);
101
102                 ControlLoopUpdate controlLoopUpdateMsg = TestListenerUtils.createControlLoopUpdateMsg();
103                 clUpdateListener.onTopicEvent(INFRA, TOPIC, null, controlLoopUpdateMsg);
104
105             }
106         }
107     }
108
109     private String getPath(String path) {
110         return "http://localhost:" + randomServerPort + "/onap/participantsim/v2/" + path;
111     }
112
113     void testSwagger(String endPoint) {
114         final Client client = ClientBuilder.newBuilder().build();
115
116         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
117         client.register(GsonMessageBodyHandler.class);
118         client.register(HttpAuthenticationFeature.basic(user, password));
119
120         final WebTarget webTarget = client.target(getPath("api-docs"));
121
122         Response response = webTarget.request(MediaType.APPLICATION_JSON).get();
123
124         assertThat(response.getStatus()).isEqualTo(200);
125         assertTrue(response.readEntity(String.class).contains("/onap/participantsim/v2/" + endPoint));
126     }
127
128     @Test
129     void testEndParticipatsSwagger() {
130         testSwagger(PARTICIPANTS_ENDPOINT);
131     }
132
133     @Test
134     void testElementsSwagger() {
135         testSwagger(ELEMENTS_ENDPOINT);
136     }
137
138     @Test
139     void testProducerYaml() {
140         final Client client = ClientBuilder.newBuilder().build();
141
142         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
143         client.register(GsonMessageBodyHandler.class);
144         client.register(HttpAuthenticationFeature.basic(user, password));
145
146         String path = getPath(PARTICIPANTS_ENDPOINT + "/org.onap.PM_CDS_Blueprint/1");
147         final WebTarget webTarget = client.target(path);
148
149         Response response = webTarget.request("application/yaml").get();
150
151         assertThat(response.getStatus()).isEqualTo(200);
152     }
153
154     @Test
155     void testQuery_Unauthorized() throws Exception {
156         String path = PARTICIPANTS_ENDPOINT + "/org.onap.PM_CDS_Blueprint/1";
157
158         Response response = performRequest(path, true, null).get();
159         assertThat(response.getStatus()).isEqualTo(200);
160
161         // unauthorized call
162         response = performRequest(path, false, null).get();
163         assertThat(response.getStatus()).isEqualTo(401);
164     }
165
166     private Invocation.Builder performRequest(String endpoint, boolean includeAuth, UUID uuid) {
167         final Client client = ClientBuilder.newBuilder().build();
168
169         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
170         client.register(GsonMessageBodyHandler.class);
171         if (includeAuth) {
172             client.register(HttpAuthenticationFeature.basic(user, password));
173         }
174         Invocation.Builder builder = client.target(getPath(endpoint)).request(MediaType.APPLICATION_JSON);
175         if (uuid != null) {
176             builder = builder.header(AbstractRestController.REQUEST_ID_NAME, uuid.toString());
177         }
178         return builder;
179     }
180
181     private Response performGet(String endpoint, UUID uuid) throws Exception {
182         return performRequest(endpoint, true, uuid).get();
183     }
184
185     @Test
186     void testQueryParticipants() throws Exception {
187         Participant participant = new Participant();
188         ToscaConceptIdentifier participantId = CommonTestData.getParticipantId();
189         participant.setDefinition(participantId);
190         participant.setName(participantId.getName());
191         participant.setVersion(participantId.getVersion());
192         UUID uuid = UUID.randomUUID();
193
194         // GET REST call for querying the participants
195         Response response = performGet(
196                 PARTICIPANTS_ENDPOINT + "/" + participant.getKey().getName() + "/" + participant.getKey().getVersion(),
197                 uuid);
198         checkResponseEntity(response, 200, uuid);
199
200         Participant[] returnValue = response.readEntity(Participant[].class);
201         assertThat(returnValue).hasSize(1);
202         // Verify the result of GET participants with what is stored
203         assertEquals(participant.getDefinition(), returnValue[0].getDefinition());
204     }
205
206     private <T> void checkResponseEntity(Response response, int status, UUID uuid) {
207         assertThat(response.getStatus()).isEqualTo(status);
208         assertThat(getHeader(response.getHeaders(), AbstractRestController.VERSION_MINOR_NAME)).isEqualTo("0");
209         assertThat(getHeader(response.getHeaders(), AbstractRestController.VERSION_PATCH_NAME)).isEqualTo("0");
210         assertThat(getHeader(response.getHeaders(), AbstractRestController.VERSION_LATEST_NAME)).isEqualTo("1.0.0");
211         assertThat(getHeader(response.getHeaders(), AbstractRestController.REQUEST_ID_NAME)).isEqualTo(uuid.toString());
212     }
213
214     private String getHeader(MultivaluedMap<String, Object> httpHeaders, String param) {
215         List<Object> list = httpHeaders.get(param);
216         assertThat(list).hasSize(1);
217         assertThat(list.get(0)).isNotNull();
218         return (String) list.get(0);
219     }
220
221     @Test
222     void testQueryControlLoopElements() throws Exception {
223         setUp();
224         UUID uuid = UUID.randomUUID();
225         ToscaConceptIdentifier participantId = CommonTestData.getParticipantId();
226
227         // GET REST call for querying the controlLoop elements
228         Response response =
229                 performGet(ELEMENTS_ENDPOINT + "/" + participantId.getName() + "/" + participantId.getVersion(), uuid);
230         checkResponseEntity(response, 200, uuid);
231
232         Map<?, ?> returnValue = response.readEntity(Map.class);
233         // Verify the result of GET controlloop elements with what is stored
234         assertThat(returnValue).isEmpty();
235     }
236
237     private Response performPut(String endpoint, final Entity<?> entity, UUID uuid) throws Exception {
238         return performRequest(endpoint, true, uuid).put(entity);
239     }
240
241     @Test
242     void testUpdateParticipant() throws Exception {
243         setUp();
244         List<Participant> participants = participantIntermediaryApi.getParticipants(
245                 CommonTestData.getParticipantId().getName(), CommonTestData.getParticipantId().getVersion());
246         assertEquals(ParticipantState.UNKNOWN, participants.get(0).getParticipantState());
247         // Change the state of the participant to PASSIVE from UNKNOWN
248         participants.get(0).setParticipantState(ParticipantState.PASSIVE);
249         UUID uuid = UUID.randomUUID();
250
251         // PUT REST call for updating Participant
252         Response response = performPut(PARTICIPANTS_ENDPOINT, Entity.json(participants.get(0)), uuid);
253         checkResponseEntity(response, 200, uuid);
254
255         TypedSimpleResponse<Participant> resp =
256                 response.readEntity(new GenericType<TypedSimpleResponse<Participant>>() {});
257         assertNotNull(resp.getResponse());
258         // Verify the response and state returned by PUT REST call for updating participants
259         assertEquals(participants.get(0).getDefinition(), resp.getResponse().getDefinition());
260         assertEquals(ParticipantState.PASSIVE, resp.getResponse().getParticipantState());
261     }
262
263     @Test
264     void testUpdateControlLoopElement() throws Exception {
265         setUp();
266         ControlLoop controlLoop = TestListenerUtils.createControlLoop();
267         Map<UUID, ControlLoopElement> controlLoopElements = participantIntermediaryApi.getControlLoopElements(
268                 controlLoop.getDefinition().getName(), controlLoop.getDefinition().getVersion());
269
270         UUID uuid = controlLoopElements.keySet().iterator().next();
271         ControlLoopElement controlLoopElement = controlLoopElements.get(uuid);
272
273         controlLoopElement.setOrderedState(ControlLoopOrderedState.PASSIVE);
274         // PUT REST call for updating ControlLoopElement
275         Response response = performPut(ELEMENTS_ENDPOINT, Entity.json(controlLoopElement), uuid);
276         checkResponseEntity(response, 200, uuid);
277
278         TypedSimpleResponse<ControlLoopElement> resp =
279                 response.readEntity(new GenericType<TypedSimpleResponse<ControlLoopElement>>() {});
280         assertNotNull(resp.getResponse());
281         // Verify the response and state returned by PUT REST call for updating participants
282         assertEquals(controlLoopElement.getDefinition(), resp.getResponse().getDefinition());
283         assertEquals(ControlLoopOrderedState.PASSIVE, resp.getResponse().getOrderedState());
284     }
285 }