Minor changes
[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 public 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     public 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     public 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     public 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     public 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     private String policiesUrl() {
147         return RIC_1_URL + "/A1-P/v1/policies";
148     }
149
150     private Gson gson() {
151         return SdncOscA1Client.gson;
152     }
153
154     private String createResponse(Object body) {
155         AdapterOutput output = ImmutableAdapterOutput.builder() //
156             .body(gson().toJson(body)) //
157             .httpStatus(200) //
158             .build();
159         return SdncJsonHelper.createOutputJsonString(output);
160     }
161
162     @Test
163     public void testGetPolicyIdentities() {
164
165         String policyIdsResp = createResponse(Arrays.asList(POLICY_1_ID, POLICY_2_ID));
166         whenAsyncPostThenReturn(Mono.just(policyIdsResp));
167
168         List<String> returned = clientUnderTest.getPolicyIdentities().block();
169         assertEquals(2, returned.size(), "");
170
171         ImmutableAdapterRequest expectedParams = ImmutableAdapterRequest.builder() //
172             .nearRtRicUrl(policiesUrl()) //
173             .build();
174         String expInput = SdncJsonHelper.createInputJsonString(expectedParams);
175         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_URL, expInput, CONTROLLER_USERNAME,
176             CONTROLLER_PASSWORD);
177
178     }
179
180     @Test
181     public void testGetValidPolicyType() {
182         String policyType = clientUnderTest.getPolicyTypeSchema("").block();
183         assertEquals("{}", policyType, "");
184     }
185
186     @Test
187     public void testPutPolicyValidResponse() {
188         whenPostReturnOkResponse();
189
190         String returned = clientUnderTest
191             .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
192             .block();
193         assertEquals("OK", returned, "");
194         final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
195         AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
196             .nearRtRicUrl(expUrl) //
197             .body(POLICY_JSON_VALID) //
198             .build();
199         String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams);
200
201         verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expInput, CONTROLLER_USERNAME, CONTROLLER_PASSWORD);
202     }
203
204     @Test
205     public void testPutPolicyRejected() {
206         final String policyJson = "{}";
207         AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
208             .body("NOK") //
209             .httpStatus(400) // ERROR
210             .build();
211
212         String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
213         whenAsyncPostThenReturn(Mono.just(resp));
214
215         Mono<String> returnedMono = clientUnderTest
216             .putPolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, policyJson, POLICY_TYPE_1_ID));
217         StepVerifier.create(returnedMono) //
218             .expectSubscription() //
219             .expectErrorMatches(t -> t instanceof WebClientResponseException) //
220             .verify();
221
222         final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
223         AdapterRequest expRequestParams = ImmutableAdapterRequest.builder() //
224             .nearRtRicUrl(expUrl) //
225             .body(policyJson) //
226             .build();
227         String expRequest = SdncJsonHelper.createInputJsonString(expRequestParams);
228         verify(asyncRestClientMock).postWithAuthHeader(PUT_A1_URL, expRequest, CONTROLLER_USERNAME,
229             CONTROLLER_PASSWORD);
230         StepVerifier.create(returnedMono)
231             .expectErrorMatches(throwable -> throwable instanceof WebClientResponseException).verify();
232     }
233
234     @Test
235     public void testDeletePolicy() {
236         whenPostReturnOkResponse();
237
238         String returned = clientUnderTest
239             .deletePolicy(A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID))
240             .block();
241         assertEquals("OK", returned, "");
242         final String expUrl = policiesUrl() + "/" + POLICY_1_ID;
243         AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
244             .nearRtRicUrl(expUrl) //
245             .build();
246         String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams);
247
248         verify(asyncRestClientMock).postWithAuthHeader(DELETE_A1_URL, expInput, CONTROLLER_USERNAME,
249             CONTROLLER_PASSWORD);
250     }
251
252     @Test
253     public void testGetStatus() {
254         whenPostReturnOkResponse();
255
256         Policy policy = A1ClientHelper.createPolicy(RIC_1_URL, POLICY_1_ID, POLICY_JSON_VALID, POLICY_TYPE_1_ID);
257
258         String returnedStatus = clientUnderTest.getPolicyStatus(policy).block();
259
260         assertEquals("OK", returnedStatus, "unexpected status");
261
262         final String expUrl = policiesUrl() + "/" + POLICY_1_ID + "/status";
263         AdapterRequest expectedInputParams = ImmutableAdapterRequest.builder() //
264             .nearRtRicUrl(expUrl) //
265             .build();
266         String expInput = SdncJsonHelper.createInputJsonString(expectedInputParams);
267
268         verify(asyncRestClientMock).postWithAuthHeader(GET_A1_POLICY_STATUS_URL, expInput, CONTROLLER_USERNAME,
269             CONTROLLER_PASSWORD);
270     }
271
272     @Test
273     public void testGetVersion() {
274         whenPostReturnOkResponse();
275         A1ProtocolType returnedVersion = clientUnderTest.getProtocolVersion().block();
276         assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion, "");
277
278         whenPostReturnOkResponseNoBody();
279         returnedVersion = clientUnderTest.getProtocolVersion().block();
280         assertEquals(A1ProtocolType.SDNC_OSC_STD_V1_1, returnedVersion, "");
281     }
282
283     private void whenPostReturnOkResponse() {
284         AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
285             .body("OK") //
286             .httpStatus(200) //
287             .build();
288
289         String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
290         whenAsyncPostThenReturn(Mono.just(resp));
291     }
292
293     private void whenPostReturnOkResponseNoBody() {
294         AdapterOutput adapterOutput = ImmutableAdapterOutput.builder() //
295             .httpStatus(200) //
296             .body(Optional.empty()) //
297             .build();
298
299         String resp = SdncJsonHelper.createOutputJsonString(adapterOutput);
300         whenAsyncPostThenReturn(Mono.just(resp));
301     }
302
303     private OngoingStubbing<Mono<String>> whenAsyncPostThenReturn(Mono<String> response) {
304         return when(asyncRestClientMock.postWithAuthHeader(anyString(), anyString(), anyString(), anyString()))
305             .thenReturn(response);
306     }
307 }