f2b74ef31a917e1c111f958719184590f523219d
[ccsdk/oran.git] /
1 /*-
2  * ========================LICENSE_START=================================
3  * ONAP : ccsdk oran
4  * ======================================================================
5  * Copyright (C) 2024-2025 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.models.v3.PolicyTypeObject;
36 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policies;
37 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Policy;
38 import org.onap.ccsdk.oran.a1policymanagementservice.repository.PolicyType;
39 import org.onap.ccsdk.oran.a1policymanagementservice.repository.Rics;
40 import org.onap.ccsdk.oran.a1policymanagementservice.util.v3.Helper;
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.http.HttpStatus;
47 import org.springframework.http.ResponseEntity;
48 import org.springframework.test.context.ContextConfiguration;
49 import org.springframework.test.context.TestPropertySource;
50 import org.springframework.test.context.bean.override.mockito.MockitoBean;
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     @MockitoBean
92     private Helper helper;
93
94     @MockitoBean
95     private AuthorizationService authorizationService;
96
97     @Autowired
98     private Gson gson;
99
100     @AfterEach
101     public void clear() {
102         policies.clear();
103         rics.clear();
104     }
105
106     @AfterAll
107     static void clearTestDir() {
108         try {
109             FileSystemUtils.deleteRecursively(Path.of("/tmp/pmstestv3"));
110         } catch (Exception e) {
111             logger.warn("Could test directory : {}", e.getMessage());
112         }
113     }
114
115     @Test
116     void testPolicyAlreadyCreatedTrue() throws Exception{
117
118         String policyTypeName = "uri_type_123";
119         String nonRtRicId = "Ric_347";
120         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
121         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
122         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
123         when(helper.jsonSchemaValidation(any())).thenReturn(Boolean.TRUE);
124         when(helper.buildPolicy(any(),any(), any(), any(), any())).thenReturn(policy);
125         when(helper.isPolicyAlreadyCreated(any(), any())).thenReturn(Mono.error(new ServiceException
126                 ("Same policy content already created with policy ID: 122344-5674", HttpStatus.BAD_REQUEST)));
127         Mono<ResponseEntity<PolicyObjectInformation>> responseMono = policyService.createPolicyService(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), serverWebExchange);
128         testHelperTest.verifyMockError(responseMono, "Same policy content already created with policy ID: 122344-5674");
129     }
130
131     @Test
132     void testPolicyNotAuthorizedFail() throws IOException {
133
134         String policyTypeName = "uri_type_123";
135         String nonRtRicId = "Ric_347";
136         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
137         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
138         when(helper.jsonSchemaValidation(any())).thenReturn(Boolean.TRUE);
139         when(helper.isPolicyAlreadyCreated(any(), any())).thenReturn(Mono.just(Policy.builder().build()));
140         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.error(new ServiceException("Not authorized", HttpStatus.UNAUTHORIZED)));
141         Mono<ResponseEntity<PolicyObjectInformation>> responseMono = policyService.createPolicyService(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), serverWebExchange);
142         testHelperTest.verifyMockError(responseMono, "Not authorized");
143     }
144
145     @Test
146     void testDeletePolicySuccess() throws Exception {
147
148         String policyTypeName = "uri_type_123";
149         String nonRtRicId = "Ric_347";
150         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
151         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
152         policies.put(policy);
153         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
154         when(helper.checkRicStateIdle(any())).thenReturn(Mono.just(policy.getRic()));
155         when(helper.checkSupportedType(any(), any())).thenReturn(Mono.just(policy.getRic()));
156         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.just(policy));
157         Mono<ResponseEntity<Void>> responseMonoDelete = policyService.deletePolicyService(policy.getId(), serverWebExchange);
158         assert(policies.size() == 1);
159         testHelperTest.testSuccessResponse(responseMonoDelete, HttpStatus.NO_CONTENT, responseBody -> policies.size() == 0);
160     }
161
162     @Test
163     void testDeletePolicyThrowsException() {
164
165         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
166         assertThrows(EntityNotFoundException.class, () -> policyService.deletePolicyService("dummyPolicyID", serverWebExchange));
167     }
168
169     @Test
170     void testPutPolicy() throws Exception {
171
172         String policyTypeName = "uri_type_123";
173         String nonRtRicId = "Ric_347";
174         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
175         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
176         policies.put(policy);
177         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
178         PolicyObjectInformation updatedPolicyObjectInfo = testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName);
179         updatedPolicyObjectInfo.setPolicyObject(gson.fromJson(JsonParser.parseString("{\n" +
180                 "        \"scope\": {\n" +
181                 "            \"ueId\": \"ue6100\",\n" +
182                 "            \"qosId\": \"qos6100\"\n" +
183                 "        },\n" +
184                 "        \"qosObjectives\": {\n" +
185                 "            \"priorityLevel\": 6100.0\n" +
186                 "        }\n" +
187                 "    }").getAsJsonObject().toString(), Map.class));
188         Policy updatedPolicy = testHelperTest.buidTestPolicy(updatedPolicyObjectInfo, "122344-5674");
189         when(helper.buildPolicy(any(),any(), any(), any(), any())).thenReturn(updatedPolicy);
190         when(helper.checkRicStateIdle(any())).thenReturn(Mono.just(updatedPolicy.getRic()));
191         when(helper.checkSupportedType(any(), any())).thenReturn(Mono.just(updatedPolicy.getRic()));
192         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.just(updatedPolicy));
193         Mono<ResponseEntity<Object>> responseMono = policyService.putPolicyService(policy.getId(), updatedPolicyObjectInfo.getPolicyObject(), serverWebExchange);
194         testHelperTest.testSuccessResponse(responseMono, HttpStatus.OK, responseBody -> {
195             if (responseBody instanceof String returnPolicy)
196                 return returnPolicy.contains(updatedPolicy.getJson());
197             return false;
198         });
199     }
200
201     @ParameterizedTest
202     @CsvSource({
203             ", , ",
204             ", uri_type, ",
205             "Ric_347, uri_type,"
206     })
207     @DisplayName("testGetPolicyTypes & testGetPolicyTypesMatchedTypeName & testGetPolicyTypesMatchedTypeNameWithRic")
208     void testGetPolicyTypes(String nearRtRicID, String typeName, String compatibleWithVersion) throws Exception {
209
210         String policyTypeName = "uri_type_123";
211         String nonRtRicId = "Ric_347";
212         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
213         when(helper.toPolicyTypeInfoCollection(any(), any())).thenCallRealMethod();
214         Mono<ResponseEntity<Flux<PolicyTypeInformation>>> responseEntityMono =
215                 policyService.getPolicyTypesService(nearRtRicID, typeName, compatibleWithVersion);
216         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().count() == 1);
217     }
218
219     @Test
220     void testGetPolicyTypesEmpty() throws Exception {
221         when(helper.toPolicyTypeInfoCollection(any(), any())).thenCallRealMethod();
222         Mono<ResponseEntity<Flux<PolicyTypeInformation>>> responseEntityMono = policyService.getPolicyTypesService(null, null, null);
223         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().findAny().isEmpty());
224     }
225
226     @Test
227     void testGetPolicyTypesNoRic() {
228         assertThrows(EntityNotFoundException.class, () -> policyService.getPolicyTypesService("NoRic", "",""));
229     }
230
231     @Test
232     void testGetPolicyTypesNoMatchedTypeName() throws Exception {
233         String policyTypeName = "uri_type_123";
234         String nonRtRicId = "Ric_347";
235         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
236         when(helper.toPolicyTypeInfoCollection(any(), any())).thenCallRealMethod();
237         Mono<ResponseEntity<Flux<PolicyTypeInformation>>> responseEntityMono = policyService.getPolicyTypesService("", "noTypeName", null);
238         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().findAny().isEmpty());
239     }
240
241     @Test
242     void testGetPolicyTypesNoMatchedTypeNameWithRic() throws Exception {
243         String policyTypeName = "uri_type_123";
244         String nonRtRicId = "Ric_347";
245         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
246         when(helper.toPolicyTypeInfoCollection(any(), any())).thenCallRealMethod();
247         Mono<ResponseEntity<Flux<PolicyTypeInformation>>> responseEntityMono = policyService.getPolicyTypesService("Ric_347", "noTypeName", null);
248         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().findAny().isEmpty());
249     }
250
251     @Test
252     void testGetPolicyIds() throws Exception {
253         String policyTypeName = "uri_type_123";
254         String nonRtRicId = "Ric_347";
255         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
256         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
257         policies.put(policy);
258         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.just(policy));
259         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
260         Policy singlePolicy = policies.filterPolicies(null, null, null, null).iterator().next();
261         Collection<PolicyInformation> mockPolicyInfoCollection = new ArrayList<>();
262         mockPolicyInfoCollection.add(new PolicyInformation(singlePolicy.getId(), singlePolicy.getRic().getConfig().getRicId()));
263         when(helper.toFluxPolicyInformation(any())).thenReturn(Flux.fromIterable(mockPolicyInfoCollection));
264         Mono<ResponseEntity<Flux<PolicyInformation>>> responseEntityMono = policyService
265                 .getPolicyIdsService(null, null, null, null, serverWebExchange);
266         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> responseBody.toStream().count() == 1);
267     }
268
269     @Test
270     void testGetPolicyIdsNoRic() throws Exception {
271         testHelperTest.addPolicyType("uri_type_123", "Ric_347");
272         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
273         EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> policyService
274                 .getPolicyIdsService("uri_type_123", "noRic", "", "", serverWebExchange));
275         assertEquals("Near-RT RIC not found using ID: noRic", exception.getMessage());
276     }
277
278     @Test
279     void testGetPolicyIdsNoPolicyType() {
280         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
281         EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> policyService
282                 .getPolicyIdsService("noPolicyType", "noRic", "", "", serverWebExchange));
283         assertEquals("Policy type not found using ID: noPolicyType", exception.getMessage());
284     }
285
286     @Test
287     void testGetPolicyService() throws Exception {
288         String policyTypeName = "uri_type_123";
289         String nonRtRicId = "Ric_347";
290         testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
291         Policy policy = testHelperTest.buidTestPolicy(testHelperTest.policyObjectInfo(nonRtRicId, policyTypeName), "122344-5674");
292         policies.put(policy);
293         when(authorizationService.authCheck(any(), any(), any())).thenReturn(Mono.just(policy));
294         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
295         Mono<ResponseEntity<Object>> responseEntityMono = policyService.getPolicyService(policy.getId(), serverWebExchange);
296         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> {
297             if (responseBody instanceof String returnPolicy)
298                 return returnPolicy.contains(policy.getJson());
299             return false;
300         });
301     }
302
303     @Test
304     void testGetPolicyServiceNoPolicy() {
305         ServerWebExchange serverWebExchange = Mockito.mock(DefaultServerWebExchange.class);
306         EntityNotFoundException exception = assertThrows(EntityNotFoundException.class, () -> policyService
307                 .getPolicyService("NoPolicy", serverWebExchange));
308         assertEquals("Could not find policy: NoPolicy", exception.getMessage());
309     }
310
311     @Test
312     void testGetPolicyTypeService() throws Exception {
313         String policyTypeName = "uri_type_123";
314         String nonRtRicId = "Ric_347";
315         PolicyType addedPolicyType = testHelperTest.addPolicyType(policyTypeName, nonRtRicId);
316         Mono<ResponseEntity<PolicyTypeObject>> responseEntityMono = policyService.getPolicyTypeDefinitionService(policyTypeName);
317         testHelperTest.testSuccessResponse(responseEntityMono, HttpStatus.OK, responseBody -> {
318             try {
319                 Object expectedSchema = gson.fromJson(addedPolicyType.getSchema(), Object.class);
320                 return responseBody.getPolicySchema().equals(expectedSchema);
321             } catch (Exception e) {
322                 return false;
323             }
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 }