4cf9f1e3c675e1ca2dced9e4d13d684e4aab11eb
[policy/clamp.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2021-2022 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.acm.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.acm.participant.intermediary.api.ParticipantIntermediaryApi;
45 import org.onap.policy.clamp.acm.participant.intermediary.comm.AutomationCompositionUpdateListener;
46 import org.onap.policy.clamp.acm.participant.intermediary.handler.ParticipantHandler;
47 import org.onap.policy.clamp.acm.participant.simulator.main.parameters.CommonTestData;
48 import org.onap.policy.clamp.acm.participant.simulator.main.rest.AbstractRestController;
49 import org.onap.policy.clamp.acm.participant.simulator.utils.TestListenerUtils;
50 import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
51 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
52 import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionOrderedState;
53 import org.onap.policy.clamp.models.acm.concepts.Participant;
54 import org.onap.policy.clamp.models.acm.concepts.ParticipantState;
55 import org.onap.policy.clamp.models.acm.messages.dmaap.participant.AutomationCompositionUpdate;
56 import org.onap.policy.clamp.models.acm.messages.rest.TypedSimpleResponse;
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.ActiveProfiles;
66 import org.springframework.test.context.junit.jupiter.SpringExtension;
67
68 @ExtendWith(SpringExtension.class)
69 @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
70 @ActiveProfiles("test")
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() {
97         synchronized (lockit) {
98             if (!check) {
99                 check = true;
100                 AutomationCompositionUpdateListener acUpdateListener =
101                     new AutomationCompositionUpdateListener(participantHandler);
102
103                 AutomationCompositionUpdate automationCompositionUpdateMsg =
104                     TestListenerUtils.createAutomationCompositionUpdateMsg();
105                 acUpdateListener.onTopicEvent(INFRA, TOPIC, null, automationCompositionUpdateMsg);
106             }
107         }
108     }
109
110     @Test
111     void testEndParticipantsSwagger() {
112         testSwagger(PARTICIPANTS_ENDPOINT);
113     }
114
115     @Test
116     void testElementsSwagger() {
117         testSwagger(ELEMENTS_ENDPOINT);
118     }
119
120     @Test
121     void testProducerYaml() {
122         final Client client = ClientBuilder.newBuilder().build();
123
124         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
125         client.register(GsonMessageBodyHandler.class);
126         client.register(HttpAuthenticationFeature.basic(user, password));
127
128         String path = getPath(PARTICIPANTS_ENDPOINT + "/org.onap.PM_CDS_Blueprint/1");
129         final WebTarget webTarget = client.target(path);
130
131         Response response = webTarget.request("application/yaml").get();
132
133         assertThat(response.getStatus()).isEqualTo(200);
134     }
135
136     @Test
137     void testQuery_Unauthorized() {
138         String path = PARTICIPANTS_ENDPOINT + "/org.onap.PM_CDS_Blueprint/1";
139
140         Response response = performRequest(path, true, null).get();
141         assertThat(response.getStatus()).isEqualTo(200);
142
143         // unauthorized call
144         response = performRequest(path, false, null).get();
145         assertThat(response.getStatus()).isEqualTo(401);
146     }
147
148     @Test
149     void testQueryParticipants() {
150         Participant participant = new Participant();
151         ToscaConceptIdentifier participantId = CommonTestData.getParticipantId();
152         participant.setDefinition(participantId);
153         participant.setName(participantId.getName());
154         participant.setVersion(participantId.getVersion());
155         UUID uuid = UUID.randomUUID();
156
157         // GET REST call for querying the participants
158         Response response = performGet(
159             PARTICIPANTS_ENDPOINT + "/" + participant.getKey().getName() + "/" + participant.getKey().getVersion(),
160             uuid);
161         checkResponseEntity(response, uuid);
162
163         Participant[] returnValue = response.readEntity(Participant[].class);
164         assertThat(returnValue).hasSize(1);
165         // Verify the result of GET participants with what is stored
166         assertEquals(participant.getDefinition(), returnValue[0].getDefinition());
167     }
168
169     @Test
170     void testQueryAutomationCompositionElements() {
171         setUp();
172         UUID uuid = UUID.randomUUID();
173         ToscaConceptIdentifier participantId = CommonTestData.getParticipantId();
174
175         // GET REST call for querying the automationComposition elements
176         Response response =
177             performGet(ELEMENTS_ENDPOINT + "/" + participantId.getName() + "/" + participantId.getVersion(), uuid);
178         checkResponseEntity(response, uuid);
179
180         Map<?, ?> returnValue = response.readEntity(Map.class);
181         // Verify the result of GET automation composition elements with what is stored
182         assertThat(returnValue).isEmpty();
183     }
184
185     @Test
186     void testUpdateParticipant() {
187         setUp();
188         List<Participant> participants = participantIntermediaryApi.getParticipants(
189             CommonTestData.getParticipantId().getName(), CommonTestData.getParticipantId().getVersion());
190         assertEquals(ParticipantState.UNKNOWN, participants.get(0).getParticipantState());
191         // Change the state of the participant to PASSIVE from UNKNOWN
192         participants.get(0).setParticipantState(ParticipantState.PASSIVE);
193         UUID uuid = UUID.randomUUID();
194
195         // PUT REST call for updating Participant
196         Response response = performPut(PARTICIPANTS_ENDPOINT, Entity.json(participants.get(0)), uuid);
197         checkResponseEntity(response, uuid);
198
199         TypedSimpleResponse<Participant> resp = response.readEntity(new GenericType<>() {
200         });
201         assertNotNull(resp.getResponse());
202         // Verify the response and state returned by PUT REST call for updating participants
203         assertEquals(participants.get(0).getDefinition(), resp.getResponse().getDefinition());
204         assertEquals(ParticipantState.PASSIVE, resp.getResponse().getParticipantState());
205     }
206
207     @Test
208     void testUpdateAutomationCompositionElement() {
209         setUp();
210         AutomationComposition automationComposition = TestListenerUtils.createAutomationComposition();
211         Map<UUID, AutomationCompositionElement> automationCompositionElements =
212             participantIntermediaryApi.getAutomationCompositionElements(automationComposition.getDefinition().getName(),
213                 automationComposition.getDefinition().getVersion());
214
215         UUID uuid = automationCompositionElements.keySet().iterator().next();
216         AutomationCompositionElement automationCompositionElement = automationCompositionElements.get(uuid);
217
218         automationCompositionElement.setOrderedState(AutomationCompositionOrderedState.PASSIVE);
219         // PUT REST call for updating AutomationCompositionElement
220         Response response = performPut(ELEMENTS_ENDPOINT, Entity.json(automationCompositionElement), uuid);
221         checkResponseEntity(response, uuid);
222
223         TypedSimpleResponse<AutomationCompositionElement> resp = response.readEntity(new GenericType<>() {
224         });
225         assertNotNull(resp.getResponse());
226         // Verify the response and state returned by PUT REST call for updating participants
227         assertEquals(automationCompositionElement.getDefinition(), resp.getResponse().getDefinition());
228         assertEquals(AutomationCompositionOrderedState.PASSIVE, resp.getResponse().getOrderedState());
229     }
230
231     private String getPath(String path) {
232         return "http://localhost:" + randomServerPort + "/onap/participantsim/v2/" + path;
233     }
234
235     void testSwagger(String endPoint) {
236         final Client client = ClientBuilder.newBuilder().build();
237
238         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
239         client.register(GsonMessageBodyHandler.class);
240         client.register(HttpAuthenticationFeature.basic(user, password));
241
242         final WebTarget webTarget = client.target(getPath("api-docs"));
243
244         Response response = webTarget.request(MediaType.APPLICATION_JSON).get();
245
246         assertThat(response.getStatus()).isEqualTo(200);
247         assertTrue(response.readEntity(String.class).contains("/onap/participantsim/v2/" + endPoint));
248     }
249
250     private Invocation.Builder performRequest(String endpoint, boolean includeAuth, UUID uuid) {
251         final Client client = ClientBuilder.newBuilder().build();
252
253         client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
254         client.register(GsonMessageBodyHandler.class);
255         if (includeAuth) {
256             client.register(HttpAuthenticationFeature.basic(user, password));
257         }
258         Invocation.Builder builder = client.target(getPath(endpoint)).request(MediaType.APPLICATION_JSON);
259         if (uuid != null) {
260             builder = builder.header(AbstractRestController.REQUEST_ID_NAME, uuid.toString());
261         }
262         return builder;
263     }
264
265     private Response performGet(String endpoint, UUID uuid) {
266         return performRequest(endpoint, true, uuid).get();
267     }
268
269     private void checkResponseEntity(Response response, UUID uuid) {
270         assertThat(response.getStatus()).isEqualTo(200);
271         assertThat(getHeader(response.getHeaders(), AbstractRestController.VERSION_MINOR_NAME)).isEqualTo("0");
272         assertThat(getHeader(response.getHeaders(), AbstractRestController.VERSION_PATCH_NAME)).isEqualTo("0");
273         assertThat(getHeader(response.getHeaders(), AbstractRestController.VERSION_LATEST_NAME)).isEqualTo("1.0.0");
274         assertThat(getHeader(response.getHeaders(), AbstractRestController.REQUEST_ID_NAME)).isEqualTo(uuid.toString());
275     }
276
277     private String getHeader(MultivaluedMap<String, Object> httpHeaders, String param) {
278         List<Object> list = httpHeaders.get(param);
279         assertThat(list).hasSize(1);
280         assertThat(list.get(0)).isNotNull();
281         return (String) list.get(0);
282     }
283
284     private Response performPut(String endpoint, final Entity<?> entity, UUID uuid) {
285         return performRequest(endpoint, true, uuid).put(entity);
286     }
287 }