aboutsummaryrefslogtreecommitdiffstats
path: root/participant/participant-impl/participant-impl-simulator/src/test/java/org/onap/policy/clamp/acm/participant/simulator/endtoend/ParticipantSimulatorTest.java
blob: 4cf9f1e3c675e1ca2dced9e4d13d684e4aab11eb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2021-2022 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.clamp.acm.participant.simulator.endtoend;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.Invocation;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import org.glassfish.jersey.client.ClientProperties;
import org.glassfish.jersey.client.authentication.HttpAuthenticationFeature;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.onap.policy.clamp.acm.participant.intermediary.api.ParticipantIntermediaryApi;
import org.onap.policy.clamp.acm.participant.intermediary.comm.AutomationCompositionUpdateListener;
import org.onap.policy.clamp.acm.participant.intermediary.handler.ParticipantHandler;
import org.onap.policy.clamp.acm.participant.simulator.main.parameters.CommonTestData;
import org.onap.policy.clamp.acm.participant.simulator.main.rest.AbstractRestController;
import org.onap.policy.clamp.acm.participant.simulator.utils.TestListenerUtils;
import org.onap.policy.clamp.models.acm.concepts.AutomationComposition;
import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionElement;
import org.onap.policy.clamp.models.acm.concepts.AutomationCompositionOrderedState;
import org.onap.policy.clamp.models.acm.concepts.Participant;
import org.onap.policy.clamp.models.acm.concepts.ParticipantState;
import org.onap.policy.clamp.models.acm.messages.dmaap.participant.AutomationCompositionUpdate;
import org.onap.policy.clamp.models.acm.messages.rest.TypedSimpleResponse;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.gson.GsonMessageBodyHandler;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;

@ExtendWith(SpringExtension.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
@ActiveProfiles("test")
class ParticipantSimulatorTest {

    private static final String PARTICIPANTS_ENDPOINT = "participants";
    private static final String ELEMENTS_ENDPOINT = "elements";
    private static final CommInfrastructure INFRA = CommInfrastructure.NOOP;
    private static final String TOPIC = "my-topic";

    @Value("${spring.security.user.name}")
    private String user;

    @Value("${spring.security.user.password}")
    private String password;

    @LocalServerPort
    private int randomServerPort;

    @Autowired
    private ParticipantIntermediaryApi participantIntermediaryApi;

    @Autowired
    private ParticipantHandler participantHandler;

    private static final Object lockit = new Object();
    private boolean check = false;

    private void setUp() {
        synchronized (lockit) {
            if (!check) {
                check = true;
                AutomationCompositionUpdateListener acUpdateListener =
                    new AutomationCompositionUpdateListener(participantHandler);

                AutomationCompositionUpdate automationCompositionUpdateMsg =
                    TestListenerUtils.createAutomationCompositionUpdateMsg();
                acUpdateListener.onTopicEvent(INFRA, TOPIC, null, automationCompositionUpdateMsg);
            }
        }
    }

    @Test
    void testEndParticipantsSwagger() {
        testSwagger(PARTICIPANTS_ENDPOINT);
    }

    @Test
    void testElementsSwagger() {
        testSwagger(ELEMENTS_ENDPOINT);
    }

    @Test
    void testProducerYaml() {
        final Client client = ClientBuilder.newBuilder().build();

        client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
        client.register(GsonMessageBodyHandler.class);
        client.register(HttpAuthenticationFeature.basic(user, password));

        String path = getPath(PARTICIPANTS_ENDPOINT + "/org.onap.PM_CDS_Blueprint/1");
        final WebTarget webTarget = client.target(path);

        Response response = webTarget.request("application/yaml").get();

        assertThat(response.getStatus()).isEqualTo(200);
    }

    @Test
    void testQuery_Unauthorized() {
        String path = PARTICIPANTS_ENDPOINT + "/org.onap.PM_CDS_Blueprint/1";

        Response response = performRequest(path, true, null).get();
        assertThat(response.getStatus()).isEqualTo(200);

        // unauthorized call
        response = performRequest(path, false, null).get();
        assertThat(response.getStatus()).isEqualTo(401);
    }

    @Test
    void testQueryParticipants() {
        Participant participant = new Participant();
        ToscaConceptIdentifier participantId = CommonTestData.getParticipantId();
        participant.setDefinition(participantId);
        participant.setName(participantId.getName());
        participant.setVersion(participantId.getVersion());
        UUID uuid = UUID.randomUUID();

        // GET REST call for querying the participants
        Response response = performGet(
            PARTICIPANTS_ENDPOINT + "/" + participant.getKey().getName() + "/" + participant.getKey().getVersion(),
            uuid);
        checkResponseEntity(response, uuid);

        Participant[] returnValue = response.readEntity(Participant[].class);
        assertThat(returnValue).hasSize(1);
        // Verify the result of GET participants with what is stored
        assertEquals(participant.getDefinition(), returnValue[0].getDefinition());
    }

    @Test
    void testQueryAutomationCompositionElements() {
        setUp();
        UUID uuid = UUID.randomUUID();
        ToscaConceptIdentifier participantId = CommonTestData.getParticipantId();

        // GET REST call for querying the automationComposition elements
        Response response =
            performGet(ELEMENTS_ENDPOINT + "/" + participantId.getName() + "/" + participantId.getVersion(), uuid);
        checkResponseEntity(response, uuid);

        Map<?, ?> returnValue = response.readEntity(Map.class);
        // Verify the result of GET automation composition elements with what is stored
        assertThat(returnValue).isEmpty();
    }

    @Test
    void testUpdateParticipant() {
        setUp();
        List<Participant> participants = participantIntermediaryApi.getParticipants(
            CommonTestData.getParticipantId().getName(), CommonTestData.getParticipantId().getVersion());
        assertEquals(ParticipantState.UNKNOWN, participants.get(0).getParticipantState());
        // Change the state of the participant to PASSIVE from UNKNOWN
        participants.get(0).setParticipantState(ParticipantState.PASSIVE);
        UUID uuid = UUID.randomUUID();

        // PUT REST call for updating Participant
        Response response = performPut(PARTICIPANTS_ENDPOINT, Entity.json(participants.get(0)), uuid);
        checkResponseEntity(response, uuid);

        TypedSimpleResponse<Participant> resp = response.readEntity(new GenericType<>() {
        });
        assertNotNull(resp.getResponse());
        // Verify the response and state returned by PUT REST call for updating participants
        assertEquals(participants.get(0).getDefinition(), resp.getResponse().getDefinition());
        assertEquals(ParticipantState.PASSIVE, resp.getResponse().getParticipantState());
    }

    @Test
    void testUpdateAutomationCompositionElement() {
        setUp();
        AutomationComposition automationComposition = TestListenerUtils.createAutomationComposition();
        Map<UUID, AutomationCompositionElement> automationCompositionElements =
            participantIntermediaryApi.getAutomationCompositionElements(automationComposition.getDefinition().getName(),
                automationComposition.getDefinition().getVersion());

        UUID uuid = automationCompositionElements.keySet().iterator().next();
        AutomationCompositionElement automationCompositionElement = automationCompositionElements.get(uuid);

        automationCompositionElement.setOrderedState(AutomationCompositionOrderedState.PASSIVE);
        // PUT REST call for updating AutomationCompositionElement
        Response response = performPut(ELEMENTS_ENDPOINT, Entity.json(automationCompositionElement), uuid);
        checkResponseEntity(response, uuid);

        TypedSimpleResponse<AutomationCompositionElement> resp = response.readEntity(new GenericType<>() {
        });
        assertNotNull(resp.getResponse());
        // Verify the response and state returned by PUT REST call for updating participants
        assertEquals(automationCompositionElement.getDefinition(), resp.getResponse().getDefinition());
        assertEquals(AutomationCompositionOrderedState.PASSIVE, resp.getResponse().getOrderedState());
    }

    private String getPath(String path) {
        return "http://localhost:" + randomServerPort + "/onap/participantsim/v2/" + path;
    }

    void testSwagger(String endPoint) {
        final Client client = ClientBuilder.newBuilder().build();

        client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
        client.register(GsonMessageBodyHandler.class);
        client.register(HttpAuthenticationFeature.basic(user, password));

        final WebTarget webTarget = client.target(getPath("api-docs"));

        Response response = webTarget.request(MediaType.APPLICATION_JSON).get();

        assertThat(response.getStatus()).isEqualTo(200);
        assertTrue(response.readEntity(String.class).contains("/onap/participantsim/v2/" + endPoint));
    }

    private Invocation.Builder performRequest(String endpoint, boolean includeAuth, UUID uuid) {
        final Client client = ClientBuilder.newBuilder().build();

        client.property(ClientProperties.METAINF_SERVICES_LOOKUP_DISABLE, "true");
        client.register(GsonMessageBodyHandler.class);
        if (includeAuth) {
            client.register(HttpAuthenticationFeature.basic(user, password));
        }
        Invocation.Builder builder = client.target(getPath(endpoint)).request(MediaType.APPLICATION_JSON);
        if (uuid != null) {
            builder = builder.header(AbstractRestController.REQUEST_ID_NAME, uuid.toString());
        }
        return builder;
    }

    private Response performGet(String endpoint, UUID uuid) {
        return performRequest(endpoint, true, uuid).get();
    }

    private void checkResponseEntity(Response response, UUID uuid) {
        assertThat(response.getStatus()).isEqualTo(200);
        assertThat(getHeader(response.getHeaders(), AbstractRestController.VERSION_MINOR_NAME)).isEqualTo("0");
        assertThat(getHeader(response.getHeaders(), AbstractRestController.VERSION_PATCH_NAME)).isEqualTo("0");
        assertThat(getHeader(response.getHeaders(), AbstractRestController.VERSION_LATEST_NAME)).isEqualTo("1.0.0");
        assertThat(getHeader(response.getHeaders(), AbstractRestController.REQUEST_ID_NAME)).isEqualTo(uuid.toString());
    }

    private String getHeader(MultivaluedMap<String, Object> httpHeaders, String param) {
        List<Object> list = httpHeaders.get(param);
        assertThat(list).hasSize(1);
        assertThat(list.get(0)).isNotNull();
        return (String) list.get(0);
    }

    private Response performPut(String endpoint, final Entity<?> entity, UUID uuid) {
        return performRequest(endpoint, true, uuid).put(entity);
    }
}