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