08e9984784079100ec4ce1f30bac93adde39ee07
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2020 Nordix Foundation. All rights reserved.
6  * ======================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ========================LICENSE_END===================================
19  */
20
21 package org.onap.ccsdk.oran.a1policymanagementservice.clients;
22
23 import static org.junit.Assert.fail;
24 import static org.junit.jupiter.api.Assertions.assertEquals;
25 import static org.junit.jupiter.api.Assertions.assertThrows;
26 import static org.mockito.ArgumentMatchers.anyString;
27 import static org.mockito.Mockito.verify;
28 import static org.mockito.Mockito.when;
29
30 import com.google.gson.Gson;
31 import com.google.gson.JsonElement;
32
33 import java.io.File;
34 import java.io.IOException;
35 import java.net.URL;
36 import java.nio.file.Files;
37 import java.util.Arrays;
38 import java.util.List;
39 import java.util.Optional;
40
41 import org.junit.jupiter.api.BeforeEach;
42 import org.junit.jupiter.api.Test;
43 import org.junit.jupiter.api.extension.ExtendWith;
44 import org.mockito.Mock;
45 import org.mockito.junit.jupiter.MockitoExtension;
46 import org.mockito.stubbing.OngoingStubbing;
47 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1Client.A1ProtocolType;
48 import org.onap.ccsdk.oran.a1policymanagementservice.clients.ImmutableAdapterOutput.Builder;
49 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SdncOscA1Client.AdapterOutput;
50 import org.onap.ccsdk.oran.a1policymanagementservice.clients.SdncOscA1Client.AdapterRequest;
51 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ControllerConfig;
52 import org.onap.ccsdk.oran.a1policymanagementservice.configuration.ImmutableControllerConfig;
53 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
54 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Ric;
55 import org.springframework.http.HttpStatus;
56 import org.springframework.web.reactive.function.client.WebClientResponseException;
57
58 import reactor.core.publisher.Mono;
59 import reactor.test.StepVerifier;
60
61 @ExtendWith(MockitoExtension.class)
62 class SdncOscA1ClientTest {
63     private static final String CONTROLLER_USERNAME = "username";
64     private static final String CONTROLLER_PASSWORD = "password";
65     private static final String RIC_1_URL = "RicUrl";
66     private static final String GET_A1_POLICY_URL = "/A1-ADAPTER-API:getA1Policy";
67     private static final String PUT_A1_URL = "/A1-ADAPTER-API:putA1Policy";
68     private static final String DELETE_A1_URL = "/A1-ADAPTER-API:deleteA1Policy";
69     private static final String GET_A1_POLICY_STATUS_URL = "/A1-ADAPTER-API:getA1PolicyStatus";
70     private static final String POLICY_TYPE_1_ID = "type1";
71     private static final String POLICY_1_ID = "policy1";
72     private static final String POLICY_2_ID = "policy2";
73     private static final String POLICY_JSON_VALID = "{\"scope\":{\"ueId\":\"ue1\"}}";
74
75     SdncOscA1Client clientUnderTest;
76
77     @Mock
78     AsyncRestClient asyncRestClientMock;
79
80     private ControllerConfig controllerConfig() {
81         return ImmutableControllerConfig.builder() //
82             .name("name") //
83             .baseUrl("baseUrl") //
84             .password(CONTROLLER_PASSWORD) //
85             .userName(CONTROLLER_USERNAME) //
86             .build();
87     }
88
89     @BeforeEach
90     void init() {
91         Ric ric = A1ClientHelper.createRic(RIC_1_URL);
92
93         clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_STD_V1_1, ric.getConfig(), controllerConfig(),
94             asyncRestClientMock);
95     }
96
97     @Test
98     void createClientWithWrongProtocol_thenErrorIsThrown() {
99         AsyncRestClient asyncRestClient = new AsyncRestClient("", null);
100         assertThrows(IllegalArgumentException.class, () -> {
101             new SdncOscA1Client(A1ProtocolType.STD_V1_1, null, null, asyncRestClient);
102         });
103     }
104
105     @Test
106     void getPolicyTypeIdentities_STD() {
107         List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
108         assertEquals(1, policyTypeIds.size(), "should hardcoded to one");
109         assertEquals("", policyTypeIds.get(0), "should hardcoded to empty");
110     }
111
112     @Test
113     void getPolicyTypeIdentities_OSC() {
114         clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
115             A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
116             controllerConfig(), asyncRestClientMock);
117
118         String response = createOkResponseWithBody(Arrays.asList(POLICY_TYPE_1_ID));
119         whenAsyncPostThenReturn(Mono.just(response));
120
121         List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
122
123         assertEquals(1, policyTypeIds.size());
124         assertEquals(POLICY_TYPE_1_ID, policyTypeIds.get(0));
125
126         String expUrl = RIC_1_URL + "/a1-p/policytypes";
127         ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
128             .nearRtRicUrl(expUrl) //
129             .build();
130         String expInput = SdncJsonHelper.createInputJsonString(expectedParams);
131         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
132             CONTROLLER_PASSWORD);
133     }
134
135     @Test
136     void getTypeSchema_STD() {
137         String policyType = clientUnderTest.getPolicyTypeSchema("").block();
138
139         assertEquals("{}", policyType);
140     }
141
142     @Test
143     void getTypeSchema_OSC() throws IOException {
144         clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
145             A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
146             controllerConfig(), asyncRestClientMock);
147
148         String ricResponse = loadFile("test_osc_get_schema_response.json");
149         JsonElement elem = gson().fromJson(ricResponse, JsonElement.class);
150         String responseFromController = createOkResponseWithBody(elem);
151         whenAsyncPostThenReturn(Mono.just(responseFromController));
152
153         String response = clientUnderTest.getPolicyTypeSchema("policyTypeId").block();
154
155         JsonElement respJson = gson().fromJson(response, JsonElement.class);
156         assertEquals("policyTypeId", respJson.getAsJsonObject().get("title").getAsString(),
157             "title should be updated to contain policyType ID");
158     }
159
160     @Test
161     void parseJsonArrayOfString() {
162         // One integer and one string
163         String inputString = "[1, \"1\" ]";
164
165         List<String> result = SdncJsonHelper.parseJsonArrayOfString(inputString).collectList().block();
166         assertEquals(2, result.size());
167         assertEquals("1", result.get(0));
168         assertEquals("1", result.get(1));
169     }
170
171     @Test
172     void getPolicyIdentities_STD() {
173
174         String policyIdsResp = createOkResponseWithBody(Arrays.asList(POLICY_1_ID, POLICY_2_ID));
175         whenAsyncPostThenReturn(Mono.just(policyIdsResp));
176
177         List<String> returned = clientUnderTest.getPolicyIdentities().block();
178
179         assertEquals(2, returned.size());
180
181         ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
182             .nearRtRicUrl(policiesUrl()) //
183             .build();
184         String expInput = SdncJsonHelper.createInputJsonString(expectedParams);
185         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
186             CONTROLLER_PASSWORD);
187
188     }
189
190     @Test
191     void getPolicyIdentities_OSC() {
192         clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
193             A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
194             controllerConfig(), asyncRestClientMock);
195
196         String policytypeIdsResp = createOkResponseWithBody(Arrays.asList(POLICY_TYPE_1_ID));
197         String policyIdsResp = createOkResponseWithBody(Arrays.asList(POLICY_1_ID, POLICY_2_ID));
198         whenAsyncPostThenReturn(Mono.just(policytypeIdsResp)).thenReturn(Mono.just(policyIdsResp));
199
200         List<String> returned = clientUnderTest.getPolicyIdentities().block();
201
202         assertEquals(2, returned.size());
203
204         ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
205             .nearRtRicUrl(RIC_1_URL + "/a1-p/policytypes/type1/policies") //
206             .build();
207         String expInput = SdncJsonHelper.createInputJsonString(expectedParams);
208         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
209             CONTROLLER_PASSWORD);
210     }
211
212     @Test
213     void putPolicyValidResponse() {
214         whenPostReturnOkResponse();
215
216         String returned = clientUnderTest
217             .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
218             .block();
219
220         assertEquals("OK", returned);
221         final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
222         AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
223             .nearRtRicUrl(expUrl) //
224             .body(POLICY_JSON_VALID) //
225             .build();
226         String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams);
227
228         verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expInput, CONTROLLER_USERNAME, CONTROLLER_PASSWORD);
229     }
230
231     @Test
232     void putPolicyRejected() {
233         final String policyJson = "{}";
234         AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
235             .body("NOK") //
236             .httpStatus(HttpStatus.BAD_REQUEST.value()) // ERROR
237             .build();
238
239         String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
240         whenAsyncPostThenReturn(Mono.just(resp));
241
242         Mono<String> returnedMono = clientUnderTest
243             .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, policyJson, POLICY_TYPE_1_ID));
244         StepVerifier.create(returnedMono) //
245             .expectSubscription() //
246             .expectErrorMatches(t -> t instanceof WebClientResponseException) //
247             .verify();
248
249         final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
250         AdapterRequest expRequestParams = ImmutableAdapterRequest.builder() //
251             .nearRtRicUrl(expUrl) //
252             .body(policyJson) //
253             .build();
254         String expRequest = SdncJsonHelper.createInputJsonString(expRequestParams);
255         verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expRequest, CONTROLLER_USERNAME,
256             CONTROLLER_PASSWORD);
257         StepVerifier.create(returnedMono)
258             .expectErrorMatches(throwable -> throwable instanceof WebClientResponseException).verify();
259     }
260
261     @Test
262     void deletePolicy() {
263         whenPostReturnOkResponse();
264
265         String returned = clientUnderTest
266             .deletePolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
267             .block();
268
269         assertEquals("OK", returned);
270         final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
271         AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
272             .nearRtRicUrl(expUrl) //
273             .build();
274         String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams);
275
276         verify(asyncRestClientMock).postWithAuthHeader(DELETE_A1_URL, expInput, CONTROLLER_USERNAME,
277             CONTROLLER_PASSWORD);
278     }
279
280     @Test
281     void getStatus() {
282         whenPostReturnOkResponse();
283
284         Policy policy = A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID);
285
286         String returnedStatus = clientUnderTest.getPolicyStatus(policy).block();
287
288         assertEquals("OK", returnedStatus, "unexpected status");
289
290         final String expUrl = policiesUrl() + "/" + POLICY_1_ID + "/status";
291         AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
292             .nearRtRicUrl(expUrl) //
293             .build();
294         String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams);
295
296         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_STATUS_URL, expInput, CONTROLLER_USERNAME,
297             CONTROLLER_PASSWORD);
298     }
299
300     @Test
301     void getVersion_STD() {
302         whenPostReturnOkResponse();
303
304         A1ProtocolType returnedVersion = clientUnderTest.getProtocolVersion().block();
305
306         assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion);
307
308         whenPostReturnOkResponseNoBody();
309
310         returnedVersion = clientUnderTest.getProtocolVersion().block();
311
312         assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion);
313     }
314
315     @Test
316     void getVersion_OSC() {
317         clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
318             A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
319             controllerConfig(), asyncRestClientMock);
320
321         whenAsyncPostThenReturn(Mono.error(new Exception("Error"))).thenReturn(Mono.just(createOkResponseString(true)));
322
323         A1ProtocolType returnedVersion = clientUnderTest.getProtocolVersion().block();
324
325         assertEquals(A1ProtocolType.SDNC_OSC_OSC_V1, returnedVersion);
326     }
327
328     private String policiesUrl() {
329         return RIC_1_URL + "/A1-P/v1/policies";
330     }
331
332     private Gson gson() {
333         return SdncOscA1Client.gson;
334     }
335
336     private String loadFile(String fileName) throws IOException {
337         ClassLoader loader = Thread.currentThread().getContextClassLoader();
338         URL url = loader.getResource(fileName);
339         File file = new File(url.getFile());
340         return new String(Files.readAllBytes(file.toPath()));
341     }
342
343     private void whenPostReturnOkResponse() {
344         whenAsyncPostThenReturn(Mono.just(createOkResponseString(true)));
345     }
346
347     private void whenPostReturnOkResponseNoBody() {
348         whenAsyncPostThenReturn(Mono.just(createOkResponseString(false)));
349     }
350
351     private String createOkResponseWithBody(Object body) {
352         AdapterOutput output = ImmutableAdapterOutput.builder() //
353             .body(gson().toJson(body)) //
354             .httpStatus(HttpStatus.OK.value()) //
355             .build();
356         return SdncJsonHelper.createOutputJsonString(output);
357     }
358
359     private String createOkResponseString(boolean withBody) {
360         Builder responseBuilder = ImmutableAdapterOutput.builder().httpStatus(HttpStatus.OK.value());
361         if (withBody) {
362             responseBuilder.body(HttpStatus.OK.name());
363         } else {
364             responseBuilder.body(Optional.empty());
365         }
366         return SdncJsonHelper.createOutputJsonString(responseBuilder.build());
367     }
368
369     private OngoingStubbing<Mono<String>> whenAsyncPostThenReturn(Mono<String> response) {
370         return when(asyncRestClientMock.postWithAuthHeader(anyString(), anyString(), anyString(), anyString()))
371             .thenReturn(response);
372     }
373 }