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