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