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