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