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