95c77a08085db2fcb95c758e98b9450b85e35fd3
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
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.service.v3;
22
23 import com.google.gson.Gson;
24 import com.google.gson.JsonParser;
25 import org.junit.jupiter.api.*;
26 import org.junit.jupiter.params.ParameterizedTest;
27 import org.junit.jupiter.params.provider.CsvSource;
28 import org.mockito.Mockito;
29 import org.onap.ccsdk.oran.a1policymanagementservice.config.TestConfig;
30 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.EntityNotFoundException;
31 import org.onap.ccsdk.oran.a1policymanagementservice.exceptions.ServiceException;
32 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyInformation;
33 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyObjectInformation;
34 import org.onap.ccsdk.oran.a1policymanagementservice.models.v3.PolicyTypeInformation;
35 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
36 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
37 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
38 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
39 import org.onap.ccsdk.oran.a1policymanagementservice.util.v3.Helper;
40 import org.onap.ccsdk.oran.a1policymanagementservice.utils.MockA1ClientFactory;
41 import org.onap.ccsdk.oran.a1policymanagementservice.utils.v3.TestHelperTest;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44 import org.springframework.beans.factory.annotation.Autowired;
45 import org.springframework.boot.test.context.SpringBootTest;
46 import org.springframework.boot.test.mock.mockito.MockBean;
47 import org.springframework.http.HttpStatus;
48 import org.springframework.http.ResponseEntity;
49 import org.springframework.test.context.ContextConfiguration;
50 import org.springframework.test.context.TestPropertySource;
51 import org.springframework.util.FileSystemUtils;
52 import org.springframework.web.server.ServerWebExchange;
53 import org.springframework.web.server.adapter.DefaultServerWebExchange;
54 import reactor.core.publisher.Flux;
55 import reactor.core.publisher.Mono;
56
57 import java.io.IOException;
58 import java.lang.invoke.MethodHandles;
59 import java.nio.file.Path;
60 import java.util.ArrayList;
61 import java.util.Collection;
62 import java.util.Map;
63
64 import static org.junit.jupiter.api.Assertions.assertEquals;
65 import static org.junit.jupiter.api.Assertions.assertThrows;
66 import static org.mockito.ArgumentMatchers.any;
67 import static org.mockito.Mockito.when;
68
69 @TestMethodOrder(MethodOrderer.MethodName.class)
70 @SpringBootTest
71 @ContextConfiguration(classes = TestConfig.class)
72 @TestPropertySource(properties = { //
73         "app.vardata-directory=/tmp/pmstestv3", //
74 })
75 class PolicyServiceTest {
76
77     private static final Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
78
79     @Autowired
80     private Policies policies;
81
82     @Autowired
83     private Rics rics;
84
85     @Autowired
86     private PolicyService policyService;
87
88     @Autowired
89     private TestHelperTest testHelperTest;
90
91     @MockBean
92     private Helper helper;
93
94     @MockBean
95     private AuthorizationService authorizationService;
96
97     @Autowired
98     private MockA1ClientFactory a1ClientFactory;
99
100     @Autowired
101     private Gson gson;
102
103     @AfterEach
104     public void clear() {
105         policies.clear();
106         rics.clear();
107     }
108
109     @AfterAll
110     static void clearTestDir() {
111         try {
112             FileSystemUtils.deleteRecursively(Path.of("/tmp/pmstestv3"));
113         } catch (Exception e) {
114             logger.warn("Could test directory : {}", e.getMessage());
115         }
116     }
117
118     @Test
119     void testPolicyAlreadyCreatedTrue() throws Exception{
120
121         String policyTypeName = "uri_type_123";
122         String nonRtRicId = "Ric_347";
123         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
124         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
125         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
126         when(helper.jsonSchemaValidation(any())).thenReturn(Boolean.TRUE);
127         when(helper.buildPolicy(any(),any(), any(), any())).thenReturn(policy);
128         when(helper.isPolicyAlreadyCreated(any(), any())).thenReturn(Mono.error(new ServiceException
129                 ("Same policy content already created with policy ID: 122344-5674", HttpStatus.BAD_REQUEST)));
130         Mono<ResponseEntity<PolicyObjectInformation>> responseMono = policyService.createPolicyService(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), serverWebExchange);
131         testHelperTest.verifyMockError(responseMono, "Same policy content already created with policy ID: 122344-5674");
132     }
133
134     @Test
135     void testPolicyNotAuthorizedFail() throws IOException {
136
137         String policyTypeName = "uri_type_123";
138         String nonRtRicId = "Ric_347";
139         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
140         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
141         when(helper.jsonSchemaValidation(any())).thenReturn(Boolean.TRUE);
142         when(helper.isPolicyAlreadyCreated(any(), any())).thenReturn(Mono.just(Policy.builder().build()));
143         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.error(new ServiceException("Not authorized", HttpStatus.UNAUTHORIZED)));
144         Mono<ResponseEntity<PolicyObjectInformation>> responseMono = policyService.createPolicyService(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), serverWebExchange);
145         testHelperTest.verifyMockError(responseMono, "Not authorized");
146     }
147
148     @Test
149     void testDeletePolicySuccess() throws Exception {
150
151         String policyTypeName = "uri_type_123";
152         String nonRtRicId = "Ric_347";
153         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
154         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
155         policies.put(policy);
156         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
157         when(helper.checkRicStateIdle(any())).thenReturn(Mono.just(policy.getRic()));
158         when(helper.checkSupportedType(any(), any())).thenReturn(Mono.just(policy.getRic()));
159         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.just(policy));
160         Mono<ResponseEntity<Void>> responseMonoDelete = policyService.deletePolicyService(policy.getId(), serverWebExchange);
161         assert(policies.size() == 1);
162         testHelperTest.testSuccessResponse(responseMonoDelete, HttpStatus.NO_CONTENT, responseBody -> policies.size() == 0);
163     }
164
165     @Test
166     void testDeletePolicyThrowsException() {
167
168         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
169         assertThrows(EntityNotFoundException.class, () -> policyService.deletePolicyService("dummyPolicyID", serverWebExchange));
170     }
171
172     @Test
173     void testPutPolicy() throws Exception {
174
175         String policyTypeName = "uri_type_123";
176         String nonRtRicId = "Ric_347";
177         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
178         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
179         policies.put(policy);
180         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
181         PolicyObjectInformation updatedPolicyObjectInfo = testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName);
182         updatedPolicyObjectInfo.setPolicyObject(gson.fromJson(JsonParser.parseString("{\n" +
183                 "        \"scope\": {\n" +
184                 "            \"ueId\": \"ue6100\",\n" +
185                 "            \"qosId\": \"qos6100\"\n" +
186                 "        },\n" +
187                 "        \"qosObjectives\": {\n" +
188                 "            \"priorityLevel\": 6100.0\n" +
189                 "        }\n" +
190                 "    }").getAsJsonObject().toString(), Map.class));
191         Policy updatedPolicy = testHelperTest.buidTestPolicy(updatedPolicyObjectInfo, "122344-5674");
192         when(helper.buildPolicy(any(),any(), any(), any())).thenReturn(updatedPolicy);
193         when(helper.checkRicStateIdle(any())).thenReturn(Mono.just(updatedPolicy.getRic()));
194         when(helper.checkSupportedType(any(), any())).thenReturn(Mono.just(updatedPolicy.getRic()));
195         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.just(updatedPolicy));
196         Mono<ResponseEntity<Object>> responseMono = policyService.putPolicyService(policy.getId(), updatedPolicyObjectInfo.getPolicyObject(), serverWebExchange);
197         testHelperTest.testSuccessResponse(responseMono, HttpStatus.OK, responseBody -> {
198             if (responseBody instanceof String returnPolicy)
199                 return returnPolicy.contains(updatedPolicy.getJson());
200             return false;
201         });
202     }
203
204     @ParameterizedTest
205     @CsvSource({
206             ", , ",
207             ", uri_type, ",
208             "Ric_347, uri_type,"
209     })
210     @DisplayName("testGetPolicyTypes & testGetPolicyTypesMatchedTypeName & testGetPolicyTypesMatchedTypeNameWithRic")
211     void testGetPolicyTypes(String nearRtRicID, String typeName, String compatibleWithVersion) throws Exception {
212
213         String policyTypeName = "uri_type_123";
214         String nonRtRicId = "Ric_347";
215         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
216         when(helper.toPolicyTypeInfoCollection(any(), any())).thenCallRealMethod();
217         Mono<ResponseEntity<Flux<PolicyTypeInformation>>> responseEntityMono =
218                 policyService.getPolicyTypesService(nearRtRicID, typeName, compatibleWithVersion);
219         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().count() == 1);
220     }
221
222     @Test
223     void testGetPolicyTypesEmpty() throws Exception {
224         when(helper.toPolicyTypeInfoCollection(any(), any())).thenCallRealMethod();
225         Mono<ResponseEntity<Flux<PolicyTypeInformation>>> responseEntityMono = policyService.getPolicyTypesService(null, null, null);
226         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().findAny().isEmpty());
227     }
228
229     @Test
230     void testGetPolicyTypesNoRic() {
231         assertThrows(EntityNotFoundException.class, () -> policyService.getPolicyTypesService("NoRic", "",""));
232     }
233
234     @Test
235     void testGetPolicyTypesNoMatchedTypeName() throws Exception {
236         String policyTypeName = "uri_type_123";
237         String nonRtRicId = "Ric_347";
238         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
239         when(helper.toPolicyTypeInfoCollection(any(), any())).thenCallRealMethod();
240         Mono<ResponseEntity<Flux<PolicyTypeInformation>>> responseEntityMono = policyService.getPolicyTypesService("", "noTypeName", null);
241         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().findAny().isEmpty());
242     }
243
244     @Test
245     void testGetPolicyTypesNoMatchedTypeNameWithRic() throws Exception {
246         String policyTypeName = "uri_type_123";
247         String nonRtRicId = "Ric_347";
248         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
249         when(helper.toPolicyTypeInfoCollection(any(), any())).thenCallRealMethod();
250         Mono<ResponseEntity<Flux<PolicyTypeInformation>>> responseEntityMono = policyService.getPolicyTypesService("Ric_347", "noTypeName", null);
251         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().findAny().isEmpty());
252     }
253
254     @Test
255     void testGetPolicyIds() throws Exception {
256         String policyTypeName = "uri_type_123";
257         String nonRtRicId = "Ric_347";
258         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
259         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
260         policies.put(policy);
261         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.just(policy));
262         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
263         Policy singlePolicy = policies.filterPolicies(null, null, null, null).iterator().next();
264         Collection<PolicyInformation> mockPolicyInfoCollection = new ArrayList<>();
265         mockPolicyInfoCollection.add(new PolicyInformation(singlePolicy.getId(), singlePolicy.getRic().getConfig().getRicId()));
266         when(helper.toFluxPolicyInformation(any())).thenReturn(Flux.fromIterable(mockPolicyInfoCollection));
267         Mono<ResponseEntity<Flux<PolicyInformation>>> responseEntityMono = policyService
268                 .getPolicyIdsService(null, null, null, null, serverWebExchange);
269         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().count() == 1);
270     }
271
272     @Test
273     void testGetPolicyIdsNoRic() throws Exception {
274         testHelperTest.addPolicyType("uri_type_123", "Ric_347");
275         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
276         EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> policyService
277                 .getPolicyIdsService("uri_type_123", "noRic", "", "", serverWebExchange));
278         assertEquals("Near-RT RIC not found using ID: noRic", exception.getMessage());
279     }
280
281     @Test
282     void testGetPolicyIdsNoPolicyType() {
283         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
284         EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> policyService
285                 .getPolicyIdsService("noPolicyType", "noRic", "", "", serverWebExchange));
286         assertEquals("Policy type not found using ID: noPolicyType", exception.getMessage());
287     }
288
289     @Test
290     void testGetPolicyService() throws Exception {
291         String policyTypeName = "uri_type_123";
292         String nonRtRicId = "Ric_347";
293         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
294         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
295         policies.put(policy);
296         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.just(policy));
297         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
298         Mono<ResponseEntity<Object>> responseEntityMono = policyService.getPolicyService(policy.getId(), serverWebExchange);
299         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> {
300             if (responseBody instanceof String returnPolicy)
301                 return returnPolicy.contains(policy.getJson());
302             return false;
303         });
304     }
305
306     @Test
307     void testGetPolicyServiceNoPolicy() {
308         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
309         EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> policyService
310                 .getPolicyService("NoPolicy", serverWebExchange));
311         assertEquals("Could not find policy: NoPolicy", exception.getMessage());
312     }
313
314     @Test
315     void testGetPolicyTypeService() throws Exception {
316         String policyTypeName = "uri_type_123";
317         String nonRtRicId = "Ric_347";
318         PolicyType addedPolicyType = testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
319         Mono<ResponseEntity<Object>> responseEntityMono = policyService.getPolicyTypeDefinitionService(policyTypeName);
320         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> {
321             if (responseBody instanceof String returnPolicyType)
322                 return returnPolicyType.contains(addedPolicyType.getSchema());
323             return false;
324         });
325     }
326
327     @Test
328     void testGetPolicyTypeServiceNoPolicyType() {
329         EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> policyService
330                 .getPolicyTypeDefinitionService("NoPolicyType"));
331         assertEquals("PolicyType not found with ID: NoPolicyType", exception.getMessage());
332     }
333 }