Merge "Version Up & Removed unncessary properties"
[nonrtric.git] / policy-agent / src / test / java / org / oransc / policyagent / clients / SdncOscA1ClientTest.java
1 /*-
2  * ========================LICENSE_START=================================
3  * O-RAN-SC
4  * %%
5  * Copyright (C) 2020 Nordix Foundation
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.oransc.policyagent.clients;
22
23 import static org.junit.jupiter.api.Assertions.assertEquals;
24 import static org.mockito.ArgumentMatchers.anyString;
25 import static org.mockito.Mockito.mock;
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.BeforeEach;
41 import org.junit.jupiter.api.Test;
42 import org.junit.jupiter.api.extension.ExtendWith;
43 import org.mockito.junit.jupiter.MockitoExtension;
44 import org.mockito.stubbing.OngoingStubbing;
45 import org.oransc.policyagent.clients.A1Client.A1ProtocolType;
46 import org.oransc.policyagent.clients.SdncOscA1Client.AdapterOutput;
47 import org.oransc.policyagent.clients.SdncOscA1Client.AdapterRequest;
48 import org.oransc.policyagent.configuration.ControllerConfig;
49 import org.oransc.policyagent.configuration.ImmutableControllerConfig;
50 import org.oransc.policyagent.repository.Policy;
51 import org.oransc.policyagent.repository.Ric;
52 import org.springframework.web.reactive.function.client.WebClientResponseException;
53
54 import reactor.core.publisher.Mono;
55 import reactor.test.StepVerifier;
56
57 @ExtendWith(MockitoExtension.class)
58 class SdncOscA1ClientTest {
59     private static final String CONTROLLER_USERNAME = "username";
60     private static final String CONTROLLER_PASSWORD = "password";
61     private static final String RIC_1_URL = "RicUrl";
62     private static final String GET_A1_POLICY_URL = "/A1-ADAPTER-API:getA1Policy";
63     private static final String PUT_A1_URL = "/A1-ADAPTER-API:putA1Policy";
64     private static final String DELETE_A1_URL = "/A1-ADAPTER-API:deleteA1Policy";
65     private static final String GET_A1_POLICY_STATUS_URL = "/A1-ADAPTER-API:getA1PolicyStatus";
66     private static final String POLICY_TYPE_1_ID = "type1";
67     private static final String POLICY_1_ID = "policy1";
68     private static final String POLICY_2_ID = "policy2";
69     private static final String POLICY_JSON_VALID = "{\"scope\":{\"ueId\":\"ue1\"}}";
70
71     SdncOscA1Client clientUnderTest;
72
73     AsyncRestClient asyncRestClientMock;
74
75     private ControllerConfig controllerConfig() {
76         return ImmutableControllerConfig.builder() //
77             .name("name") //
78             .baseUrl("baseUrl") //
79             .password(CONTROLLER_PASSWORD) //
80             .userName(CONTROLLER_USERNAME) //
81             .build();
82     }
83
84     @BeforeEach
85     void init() {
86         asyncRestClientMock = mock(AsyncRestClient.class);
87         Ric ric = A1ClientHelper.createRic(RIC_1_URL);
88
89         clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_STD_V1_1, ric.getConfig(), controllerConfig(),
90             asyncRestClientMock);
91     }
92
93     @Test
94     void testGetPolicyTypeIdentities_STD() {
95         List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
96         assertEquals(1, policyTypeIds.size(), "should hardcoded to one");
97         assertEquals("", policyTypeIds.get(0), "should hardcoded to empty");
98     }
99
100     @Test
101     void testGetPolicyTypeIdentities_OSC() {
102         clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
103             A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
104             controllerConfig(), asyncRestClientMock);
105
106         String response = createResponse(Arrays.asList(POLICY_TYPE_1_ID));
107         whenAsyncPostThenReturn(Mono.just(response));
108
109         List<String> policyTypeIds = clientUnderTest.getPolicyTypeIdentities().block();
110         assertEquals(1, policyTypeIds.size(), "");
111         assertEquals(POLICY_TYPE_1_ID, policyTypeIds.get(0), "");
112
113         String expUrl = RIC_1_URL + "/a1-p/policytypes";
114         ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
115             .nearRtRicUrl(expUrl) //
116             .build();
117         String expInput = SdncJsonHelper.createInputJsonString(expectedParams);
118         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
119             CONTROLLER_PASSWORD);
120     }
121
122     private String loadFile(String fileName) throws IOException {
123         ClassLoader loader = Thread.currentThread().getContextClassLoader();
124         URL url = loader.getResource(fileName);
125         File file = new File(url.getFile());
126         return new String(Files.readAllBytes(file.toPath()));
127     }
128
129     @Test
130     void testGetTypeSchema_OSC() throws IOException {
131         clientUnderTest = new SdncOscA1Client(A1ProtocolType.SDNC_OSC_OSC_V1, //
132             A1ClientHelper.createRic(RIC_1_URL).getConfig(), //
133             controllerConfig(), asyncRestClientMock);
134
135         String ricResponse = loadFile("test_osc_get_schema_response.json");
136         JsonElement elem = gson().fromJson(ricResponse, JsonElement.class);
137         String responseFromController = createResponse(elem);
138         whenAsyncPostThenReturn(Mono.just(responseFromController));
139
140         String response = clientUnderTest.getPolicyTypeSchema("policyTypeId").block();
141         JsonElement respJson = gson().fromJson(response, JsonElement.class);
142         assertEquals("policyTypeId", respJson.getAsJsonObject().get("title").getAsString(),
143             "title should be updated to contain policyType ID");
144     }
145
146     @Test
147     void parseJsonArrayOfString() {
148         // One integer and one string
149         String inputString = "[1, \"1\" ]";
150
151         List<String> result = SdncJsonHelper.parseJsonArrayOfString(inputString).collectList().block();
152         assertEquals(2, result.size(), "");
153         assertEquals("1", result.get(0), "");
154         assertEquals("1", result.get(1), "");
155     }
156
157     private String policiesUrl() {
158         return RIC_1_URL + "/A1-P/v1/policies";
159     }
160
161     private Gson gson() {
162         return SdncOscA1Client.gson;
163     }
164
165     private String createResponse(Object body) {
166         AdapterOutput output = ImmutableAdapterOutput.builder() //
167             .body(gson().toJson(body)) //
168             .httpStatus(200) //
169             .build();
170         return SdncJsonHelper.createOutputJsonString(output);
171     }
172
173     @Test
174     void testGetPolicyIdentities() {
175
176         String policyIdsResp = createResponse(Arrays.asList(POLICY_1_ID, POLICY_2_ID));
177         whenAsyncPostThenReturn(Mono.just(policyIdsResp));
178
179         List<String> returned = clientUnderTest.getPolicyIdentities().block();
180         assertEquals(2, returned.size(), "");
181
182         ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
183             .nearRtRicUrl(policiesUrl()) //
184             .build();
185         String expInput = SdncJsonHelper.createInputJsonString(expectedParams);
186         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
187             CONTROLLER_PASSWORD);
188
189     }
190
191     @Test
192     void testGetValidPolicyType() {
193         String policyType = clientUnderTest.getPolicyTypeSchema("").block();
194         assertEquals("{}", policyType, "");
195     }
196
197     @Test
198     void testPutPolicyValidResponse() {
199         whenPostReturnOkResponse();
200
201         String returned = clientUnderTest
202             .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
203             .block();
204         assertEquals("OK", returned, "");
205         final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
206         AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
207             .nearRtRicUrl(expUrl) //
208             .body(POLICY_JSON_VALID) //
209             .build();
210         String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams);
211
212         verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expInput, CONTROLLER_USERNAME, CONTROLLER_PASSWORD);
213     }
214
215     @Test
216     void testPutPolicyRejected() {
217         final String policyJson = "{}";
218         AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
219             .body("NOK") //
220             .httpStatus(400) // ERROR
221             .build();
222
223         String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
224         whenAsyncPostThenReturn(Mono.just(resp));
225
226         Mono<String> returnedMono = clientUnderTest
227             .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, policyJson, POLICY_TYPE_1_ID));
228         StepVerifier.create(returnedMono) //
229             .expectSubscription() //
230             .expectErrorMatches(t -> t instanceof WebClientResponseException) //
231             .verify();
232
233         final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
234         AdapterRequest expRequestParams = ImmutableAdapterRequest.builder() //
235             .nearRtRicUrl(expUrl) //
236             .body(policyJson) //
237             .build();
238         String expRequest = SdncJsonHelper.createInputJsonString(expRequestParams);
239         verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expRequest, CONTROLLER_USERNAME,
240             CONTROLLER_PASSWORD);
241         StepVerifier.create(returnedMono)
242             .expectErrorMatches(throwable -> throwable instanceof WebClientResponseException).verify();
243     }
244
245     @Test
246     void testDeletePolicy() {
247         whenPostReturnOkResponse();
248
249         String returned = clientUnderTest
250             .deletePolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
251             .block();
252         assertEquals("OK", returned, "");
253         final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
254         AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
255             .nearRtRicUrl(expUrl) //
256             .build();
257         String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams);
258
259         verify(asyncRestClientMock).postWithAuthHeader(DELETE_A1_URL, expInput, CONTROLLER_USERNAME,
260             CONTROLLER_PASSWORD);
261     }
262
263     @Test
264     void testGetStatus() {
265         whenPostReturnOkResponse();
266
267         Policy policy = A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID);
268
269         String returnedStatus = clientUnderTest.getPolicyStatus(policy).block();
270
271         assertEquals("OK", returnedStatus, "unexpected status");
272
273         final String expUrl = policiesUrl() + "/" + POLICY_1_ID + "/status";
274         AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
275             .nearRtRicUrl(expUrl) //
276             .build();
277         String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams);
278
279         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_STATUS_URL, expInput, CONTROLLER_USERNAME,
280             CONTROLLER_PASSWORD);
281     }
282
283     @Test
284     void testGetVersion() {
285         whenPostReturnOkResponse();
286         A1ProtocolType returnedVersion = clientUnderTest.getProtocolVersion().block();
287         assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion, "");
288
289         whenPostReturnOkResponseNoBody();
290         returnedVersion = clientUnderTest.getProtocolVersion().block();
291         assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion, "");
292     }
293
294     private void whenPostReturnOkResponse() {
295         AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
296             .body("OK") //
297             .httpStatus(200) //
298             .build();
299
300         String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
301         whenAsyncPostThenReturn(Mono.just(resp));
302     }
303
304     private void whenPostReturnOkResponseNoBody() {
305         AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
306             .httpStatus(200) //
307             .body(Optional.empty()) //
308             .build();
309
310         String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
311         whenAsyncPostThenReturn(Mono.just(resp));
312     }
313
314     private OngoingStubbing<Mono<String>> whenAsyncPostThenReturn(Mono<String> response) {
315         return when(asyncRestClientMock.postWithAuthHeader(anyString(), anyString(), anyString(), anyString()))
316             .thenReturn(response);
317     }
318 }