A1-PMS Add A1-Mediator Custom Adapter (Release I)
[nonrtric/plt/a1policymanagementservice.git] / add-src / test / java / org / onap / ccsdk / oran / a1policymanagementservice / clients / A1MediatorAdapterICCSDKTest.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  *  Copyright (C) 2024 OpenInfra Foundation Europe. 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.A1MediatorAdapterICCSDK.AdapterOutput;
48 import org.onap.ccsdk.oran.a1policymanagementservice.clients.A1MediatorAdapterICCSDK.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 A1MediatorAdapterICCSDKTest {
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     A1MediatorAdapterICCSDK 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 A1MediatorAdapterICCSDK(A1ProtocolType.STD_V1_1, null, asyncRestClient);
92         });
93     }
94
95     private Ric createRic(String url) {
96         RicConfig cfg = RicConfig.builder().ricId("ric") //
97                 .baseUrl(url) //
98                 .managedElementIds(new Vector<String>(Arrays.asList("kista_1", "kista_2"))) //
99                 .controllerConfig(controllerConfig()) //
100                 .build();
101         return new Ric(cfg);
102     }
103
104     private void testGetPolicyTypeIdentities(A1ProtocolType protocolType, String expUrl) {
105         clientUnderTest = new A1MediatorAdapterICCSDK(protocolType, //
106                 createRic(RIC_1_URL).getConfig(), //
107                 asyncRestClientMock);
108
109         String response = createOkResponseWithBody(Arrays.asList(POLICY_TYPE_1_ID));
110         whenAsyncPostThenReturn(Mono.just(response));
111
112         List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
113
114         assertEquals(1, policyTypeIds.size());
115         assertEquals(POLICY_TYPE_1_ID, policyTypeIds.get(0));
116
117         AdapterRequest expectedParams = new AdapterRequest(expUrl, null);
118
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     @DisplayName("test get Policy Type Identities A1MediatorAdapterICCSDK")
126     void getPolicyTypeIdentities_A1MediatorAdapterICCSDK() {
127         testGetPolicyTypeIdentities(A1ProtocolType.CUSTOM_PROTOCOL, RIC_1_URL + "/A1-P/v2/policytypes");
128     }
129
130     private void testGetTypeSchema(A1ProtocolType protocolType, String expUrl, String policyTypeId,
131             String getSchemaResponseFile) throws IOException {
132         clientUnderTest = new A1MediatorAdapterICCSDK(protocolType, //
133                 createRic(RIC_1_URL).getConfig(), //
134                 asyncRestClientMock);
135
136         String ricResponse = loadFile(getSchemaResponseFile);
137         JsonElement elem = gson().fromJson(ricResponse, JsonElement.class);
138         String responseFromController = createOkResponseWithBody(elem);
139         whenAsyncPostThenReturn(Mono.just(responseFromController));
140
141         String response = clientUnderTest.getPolicyTypeSchema(policyTypeId).block();
142
143         JsonElement respJson = gson().fromJson(response, JsonElement.class);
144         assertEquals(policyTypeId, respJson.getAsJsonObject().get("title").getAsString(),
145                 "title should be updated to contain policyType ID");
146
147         AdapterRequest expectedParams = new AdapterRequest(expUrl, null);
148
149         String expInput = A1AdapterJsonHelper.createInputJsonString(expectedParams);
150
151         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
152                 CONTROLLER_PASSWORD);
153     }
154
155     @Test
156     @DisplayName("test get Type Schema A1MediatorAdapterICCSDK")
157     void getTypeSchema_STD_V2() throws IOException {
158         String expUrl = RIC_1_URL + "/A1-P/v2/policytypes/policyTypeId";
159         testGetTypeSchema(A1ProtocolType.CUSTOM_PROTOCOL, expUrl, "policyTypeId",
160                 "test_osc_get_schema_response.json");
161     }
162
163     @Test
164     @DisplayName("test parse Json Array Of String")
165     void parseJsonArrayOfString() {
166         // One integer and one string
167         String inputString = "[1, \"1\" ]";
168
169         List<String> result = A1AdapterJsonHelper.parseJsonArrayOfString(inputString).collectList().block();
170         assertEquals(2, result.size());
171         assertEquals("1", result.get(0));
172         assertEquals("1", result.get(1));
173     }
174
175     private void getPolicyIdentities(A1ProtocolType protocolType, String... expUrls) {
176         clientUnderTest = new A1MediatorAdapterICCSDK(protocolType, //
177                 createRic(RIC_1_URL).getConfig(), //
178                 asyncRestClientMock);
179         String resp = createOkResponseWithBody(Arrays.asList("xxx"));
180         whenAsyncPostThenReturn(Mono.just(resp));
181
182         List<String> returned = clientUnderTest.getPolicyIdentities().block();
183
184         assertEquals(1, returned.size());
185         for (String expUrl : expUrls) {
186             AdapterRequest expectedParams = new AdapterRequest(expUrl, null);
187
188             String expInput = A1AdapterJsonHelper.createInputJsonString(expectedParams);
189             verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
190                     CONTROLLER_PASSWORD);
191         }
192     }
193
194     @Test
195     @DisplayName("test get Policy Identities A1MediatorAdapterICCSDK")
196     void getPolicyIdentities_STD_V2() {
197         String expUrlPolicies = RIC_1_URL + "/A1-P/v2/policytypes";
198         String expUrlInstances = RIC_1_URL + "/A1-P/v2/policytypes/xxx/policies";
199         getPolicyIdentities(A1ProtocolType.CUSTOM_PROTOCOL, expUrlPolicies, expUrlInstances);
200     }
201
202     private void putPolicy(A1ProtocolType protocolType, String expUrl) {
203         clientUnderTest = new A1MediatorAdapterICCSDK(protocolType, //
204                 createRic(RIC_1_URL).getConfig(), //
205                 asyncRestClientMock);
206
207         whenPostReturnOkResponse();
208
209         String returned = clientUnderTest
210                 .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
211                 .block();
212
213         assertEquals("OK", returned);
214         AdapterRequest expectedInputParams = new AdapterRequest(expUrl, POLICY_JSON_VALID);
215         String expInput = A1AdapterJsonHelper.createInputJsonString(expectedInputParams);
216
217         verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expInput, CONTROLLER_USERNAME, CONTROLLER_PASSWORD);
218
219     }
220
221     @Test
222     @DisplayName("test put Policy A1MediatorAdapterICCSDK")
223     void putPolicy_A1MediatorAdapterICCSDK() {
224         String expUrl =
225                 RIC_1_URL + "/A1-P/v2/policytypes/type1/policies/policy1?notificationDestination=https://test.com";
226         putPolicy(A1ProtocolType.CUSTOM_PROTOCOL, expUrl);
227     }
228
229     @Test
230     @DisplayName("test post Rejected")
231     void postRejected() {
232         clientUnderTest = new A1MediatorAdapterICCSDK(A1ProtocolType.CUSTOM_PROTOCOL, //
233                 createRic(RIC_1_URL).getConfig(), //
234                 asyncRestClientMock);
235
236         final String policyJson = "{}";
237         AdapterOutput adapterOutput = new AdapterOutput(HttpStatus.BAD_REQUEST.value(), "NOK");
238
239         String resp = A1AdapterJsonHelper.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         StepVerifier.create(returnedMono).expectErrorMatches(throwable -> {
250             return throwable instanceof WebClientResponseException;
251         }).verify();
252     }
253
254     private void deleteAllPolicies(A1ProtocolType protocolType, String expUrl) {
255         clientUnderTest = new A1MediatorAdapterICCSDK(protocolType, //
256                 createRic(RIC_1_URL).getConfig(), //
257                 asyncRestClientMock);
258         String resp = createOkResponseWithBody(Arrays.asList("xxx"));
259         whenAsyncPostThenReturn(Mono.just(resp));
260
261         clientUnderTest.deleteAllPolicies().blockLast();
262
263         AdapterRequest expectedParams = new AdapterRequest(expUrl, null);
264
265         String expInput = A1AdapterJsonHelper.createInputJsonString(expectedParams);
266         verify(asyncRestClientMock).postWithAuthHeader(DELETE_A1_URL, expInput, CONTROLLER_USERNAME,
267                 CONTROLLER_PASSWORD);
268     }
269
270     @Test
271     @DisplayName("test delete All Policies A1MediatorAdapterICCSDK")
272     void deleteAllPolicies_A1MediatorAdapterICCSDK() {
273         String expUrl1 = RIC_1_URL + "/A1-P/v2/policytypes/xxx/policies/xxx";
274         deleteAllPolicies(A1ProtocolType.CUSTOM_PROTOCOL, expUrl1);
275     }
276
277     @Test
278     @DisplayName("test Get Status")
279     void testGetStatus() {
280         clientUnderTest = new A1MediatorAdapterICCSDK(A1ProtocolType.CUSTOM_PROTOCOL, //
281                 createRic(RIC_1_URL).getConfig(), //
282                 asyncRestClientMock);
283         whenPostReturnOkResponse();
284
285         Policy policy = A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID);
286
287         String response = clientUnderTest.getPolicyStatus(policy).block();
288         assertEquals("OK", response);
289
290         String expUrl = RIC_1_URL + "/A1-P/v2/policytypes/type1/policies/policy1/status";
291         AdapterRequest expectedParams = new AdapterRequest(expUrl, null);
292
293         String expInput = A1AdapterJsonHelper.createInputJsonString(expectedParams);
294         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_STATUS_URL, expInput, CONTROLLER_USERNAME,
295                 CONTROLLER_PASSWORD);
296
297     }
298
299     private Gson gson() {
300         return A1MediatorAdapterICCSDK.gson;
301     }
302
303     private String loadFile(String fileName) throws IOException {
304         ClassLoader loader = Thread.currentThread().getContextClassLoader();
305         URL url = loader.getResource(fileName);
306         File file = new File(url.getFile());
307         return new String(Files.readAllBytes(file.toPath()));
308     }
309
310     private void whenPostReturnOkResponse() {
311         whenAsyncPostThenReturn(Mono.just(createOkResponseString(true)));
312     }
313
314     void whenPostReturnOkResponseNoBody() {
315         whenAsyncPostThenReturn(Mono.just(createOkResponseString(false)));
316     }
317
318     private String createOkResponseWithBody(Object body) {
319         AdapterOutput output = new AdapterOutput(HttpStatus.OK.value(), gson().toJson(body));
320         return A1AdapterJsonHelper.createOutputJsonString(output);
321     }
322
323     private String createOkResponseString(boolean withBody) {
324         String body = withBody ? HttpStatus.OK.name() : null;
325         AdapterOutput output = new AdapterOutput(HttpStatus.OK.value(), body);
326         return A1AdapterJsonHelper.createOutputJsonString(output);
327     }
328
329     private OngoingStubbing<Mono<String>> whenAsyncPostThenReturn(Mono<String> response) {
330         return when(asyncRestClientMock.postWithAuthHeader(anyString(), anyString(), anyString(), anyString()))
331                 .thenReturn(response);
332     }
333 }