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