diff options
author | 2022-07-28 16:33:38 +0800 | |
---|---|---|
committer | 2022-08-08 02:11:59 +0000 | |
commit | 61f9c604018a27bf9438415aca03d05dc9974dcb (patch) | |
tree | e15678f9104d488c9c1c2cbf2a39dba59aa458fa /components/slice-analysis-ms/src/test | |
parent | 015b7529adc61181862c84a20ed7140a96e479dc (diff) |
feat:Enhance sliceanalysis MS to use DCAE SDK dmaap-client lib
Issue-ID: DCAEGEN2-3120
Signed-off-by: zhaoyh6 <zhaoyh6@asiainfo.com>
Change-Id: I946c7a4b49906cb402062235a97452fb7856c8f0
Diffstat (limited to 'components/slice-analysis-ms/src/test')
23 files changed, 1739 insertions, 532 deletions
diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/aai/AaiInterfaceServiceTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/aai/AaiInterfaceServiceTest.java index 31264e8c..04e2594e 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/aai/AaiInterfaceServiceTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/aai/AaiInterfaceServiceTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2021-2022 Wipro Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +24,7 @@ package org.onap.slice.analysis.ms.aai; import static org.junit.Assert.assertEquals; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; @@ -30,6 +32,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.commons.collections.MapUtils; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -37,9 +40,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.onap.slice.analysis.ms.models.Configuration; import org.onap.slice.analysis.ms.restclients.AaiRestClient; -import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.boot.test.context.SpringBootTest; @@ -50,7 +51,6 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(SpringRunner.class) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) -@PrepareForTest({AaiService.class, Configuration.class}) @SpringBootTest(classes = AaiInterfaceServiceTest.class) public class AaiInterfaceServiceTest { @@ -63,78 +63,53 @@ public class AaiInterfaceServiceTest { AaiRestClient restClient; @Test - public void fetchCurrentConfigurationOfSlice() { + public void fetchCurrentConfigurationOfSlice() throws IOException { configuration.setAaiUrl("http://aai:30233/aai/v21/business/customers/customer/"); - PowerMockito.mockStatic(AaiService.class); - PowerMockito.mockStatic(Configuration.class); - PowerMockito.when(Configuration.getInstance()).thenReturn(configuration); Map<String, Integer> responsemap = new HashMap<>(); responsemap.put("dLThptPerSlice", 60); responsemap.put("uLThptPerSlice", 54); - try { - String serviceInstance = - new String(Files.readAllBytes(Paths.get("src/test/resources/aaiDetailsList.json"))); - Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); - - } catch (Exception e) { - e.printStackTrace(); - - } + String serviceInstance = + new String(Files.readAllBytes(Paths.get("src/test/resources/aaiDetailsList.json"))); + Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); assertEquals(responsemap, aaiService.fetchCurrentConfigurationOfSlice("001-010000")); } @Test - public void fetchServiceProfile() { + public void fetchServiceProfile() throws IOException { Map<String, String> responseMap = new HashMap<String, String>(); responseMap.put("sNSSAI", "001-00110"); responseMap.put("ranNFNSSIId", "4b889f2b-8ee4-4ec7-881f-5b1af8a74039"); responseMap.put("sliceProfileId", "ab9af40f13f7219099333"); responseMap.put("globalSubscriberId", "5GCustomer"); responseMap.put("subscriptionServiceType", "5G"); - - try { - String serviceInstance = - new String(Files.readAllBytes(Paths.get("src/test/resources/aaiDetailsList.json"))); - Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); - - } catch (Exception e) { - e.printStackTrace(); - - } + String serviceInstance = + new String(Files.readAllBytes(Paths.get("src/test/resources/aaiDetailsList.json"))); + Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); assertEquals(responseMap, aaiService.fetchServiceDetails("001-00110")); } @Test - public void fetchSubscriberAndSubscriptionServiceTypeTest() throws Exception { + public void fetchSubscriberAndSubscriptionServiceTypeTest() throws IOException { configuration.setAaiUrl("http://aai:30233/aai/v21"); Map<String, String> expectedResponse = new HashMap<String, String>(); expectedResponse.put("globalSubscriberId", "5GCustomer"); expectedResponse.put("subscriptionServiceType", "5G"); - PowerMockito.mockStatic(AaiService.class); - PowerMockito.mockStatic(Configuration.class); - PowerMockito.when(Configuration.getInstance()).thenReturn(configuration); - try { - - String serviceInstance = - new String(Files.readAllBytes(Paths.get("src/test/resources/aaiDetailsList.json"))); - Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); - - } catch (Exception e) { - e.printStackTrace(); - } + String serviceInstance = + new String(Files.readAllBytes(Paths.get("src/test/resources/aaiDetailsList.json"))); + Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); Map<String, String> actualResponse = aaiService.fetchSubscriberAndSubscriptionServiceType(); assertEquals(expectedResponse, actualResponse); } @Test - public void fetchSliceProfilesOfAllotedResourceDataTest() throws Exception { + public void fetchSliceProfilesOfAllotedResourceDataTest() throws IOException { configuration.setAaiUrl("http://aai:30233/aai/v21"); List<String> allotedResourceList = new ArrayList<>(); allotedResourceList.add("530d188d-9087-49af-a44a-90c40e0c2d47"); @@ -142,27 +117,18 @@ public class AaiInterfaceServiceTest { expectedResponse.add("b2ae730f-1d5f-495a-8112-dac017a7348c"); expectedResponse.add("cad8fa36-2d55-4c12-a92e-1bd551517a0c"); expectedResponse.add("8d0d698e-77f4-4453-8c09-ae2cbe6a9a04"); - PowerMockito.mockStatic(AaiService.class); - PowerMockito.mockStatic(Configuration.class); - PowerMockito.when(Configuration.getInstance()).thenReturn(configuration); - - try { - String serviceInstance = - new String(Files.readAllBytes(Paths.get("src/test/resources/alloted-resource.json"))); - Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); + String serviceInstance = + new String(Files.readAllBytes(Paths.get("src/test/resources/alloted-resource.json"))); + Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); - } catch (Exception e) { - e.printStackTrace(); - - } List<String> actualResponse = aaiService.fetchSliceProfilesOfAllotedResourceData(allotedResourceList); assertEquals(expectedResponse, actualResponse); } @Test - public void fetchSnssaiOfSliceProfileTest() throws Exception { + public void fetchSnssaiOfSliceProfileTest() throws IOException { configuration.setAaiUrl("http://aai:30233/aai/v21"); List<String> sliceProfileList = new ArrayList<>(); sliceProfileList.add("b2ae730f-1d5f-495a-8112-dac017a7348c"); @@ -172,113 +138,101 @@ public class AaiInterfaceServiceTest { expectedResponse.add("01-06E442"); expectedResponse.add("01-B989BD"); - PowerMockito.mockStatic(AaiService.class); - PowerMockito.mockStatic(Configuration.class); - PowerMockito.when(Configuration.getInstance()).thenReturn(configuration); String serviceInstanceUrlAn = "b2ae730f-1d5f-495a-8112-dac017a7348c"; String serviceInstanceUrlCn = "cad8fa36-2d55-4c12-a92e-1bd551517a0c"; String serviceInstanceUrlTn = "8d0d698e-77f4-4453-8c09-ae2cbe6a9a04"; - try { - - String serviceInstanceAn = - new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_an_sa1.json"))); - Mockito.when(restClient.sendGetRequest(Mockito.contains(serviceInstanceUrlAn), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstanceAn, HttpStatus.OK)); + String serviceInstanceAn = + new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_an_sa1.json"))); + Mockito.when(restClient.sendGetRequest(Mockito.contains(serviceInstanceUrlAn), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstanceAn, HttpStatus.OK)); - String serviceInstanceCn = - new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_cn_sa1.json"))); - Mockito.when(restClient.sendGetRequest(Mockito.contains(serviceInstanceUrlCn), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstanceCn, HttpStatus.OK)); + String serviceInstanceCn = + new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_cn_sa1.json"))); + Mockito.when(restClient.sendGetRequest(Mockito.contains(serviceInstanceUrlCn), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstanceCn, HttpStatus.OK)); - String serviceInstanceTn = - new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_tn_sa1.json"))); - Mockito.when(restClient.sendGetRequest(Mockito.contains(serviceInstanceUrlTn), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstanceTn, HttpStatus.OK)); + String serviceInstanceTn = + new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_tn_sa1.json"))); + Mockito.when(restClient.sendGetRequest(Mockito.contains(serviceInstanceUrlTn), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstanceTn, HttpStatus.OK)); - } catch (Exception e) { - e.printStackTrace(); - - } List<String> actualResponse = aaiService.fetchSnssaiOfSliceProfile(sliceProfileList); assertEquals(expectedResponse, actualResponse); } @Test - public void getSnssaiListForNsiTest() throws Exception { + public void getSnssaiListForNsiTest() throws IOException { configuration.setAaiUrl("http://aai:30233/aai/v21"); List<String> expectedResponse = new ArrayList<>(); expectedResponse.add("01-06E442"); expectedResponse.add("01-B989BD"); - PowerMockito.mockStatic(AaiService.class); - PowerMockito.mockStatic(Configuration.class); - PowerMockito.when(Configuration.getInstance()).thenReturn(configuration); - - try { - - String allotedResource = - new String(Files.readAllBytes(Paths.get("src/test/resources/alloted-resource.json"))); - Mockito.when( - restClient.sendGetRequest(Mockito.contains("0835fd19-6726-4081-befb-cc8932c47767"), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(allotedResource, HttpStatus.OK)); - - String serviceInstance = new String(Files.readAllBytes(Paths.get("src/test/resources/nsi.json"))); - Mockito.when( - restClient.sendGetRequest(Mockito.contains("09cad94e-fbb8-4c70-9c4d-74ec75e97683"), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); - - String serviceInstanceAn = - new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_an_sa1.json"))); - Mockito.when( - restClient.sendGetRequest(Mockito.contains("b2ae730f-1d5f-495a-8112-dac017a7348c"), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstanceAn, HttpStatus.OK)); - - String serviceInstanceCn = - new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_cn_sa1.json"))); - Mockito.when( - restClient.sendGetRequest(Mockito.contains("cad8fa36-2d55-4c12-a92e-1bd551517a0c"), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstanceCn, HttpStatus.OK)); - - String serviceInstanceTn = - new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_tn_sa1.json"))); - Mockito.when( - restClient.sendGetRequest(Mockito.contains("8d0d698e-77f4-4453-8c09-ae2cbe6a9a04"), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstanceTn, HttpStatus.OK)); - - } catch (Exception e) { - e.printStackTrace(); - - } + + String allotedResource = + new String(Files.readAllBytes(Paths.get("src/test/resources/alloted-resource.json"))); + Mockito.when( + restClient.sendGetRequest(Mockito.contains("0835fd19-6726-4081-befb-cc8932c47767"), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(allotedResource, HttpStatus.OK)); + + String serviceInstance = new String(Files.readAllBytes(Paths.get("src/test/resources/nsi.json"))); + Mockito.when( + restClient.sendGetRequest(Mockito.contains("09cad94e-fbb8-4c70-9c4d-74ec75e97683"), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstance, HttpStatus.OK)); + + String serviceInstanceAn = + new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_an_sa1.json"))); + Mockito.when( + restClient.sendGetRequest(Mockito.contains("b2ae730f-1d5f-495a-8112-dac017a7348c"), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstanceAn, HttpStatus.OK)); + + String serviceInstanceCn = + new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_cn_sa1.json"))); + Mockito.when( + restClient.sendGetRequest(Mockito.contains("cad8fa36-2d55-4c12-a92e-1bd551517a0c"), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstanceCn, HttpStatus.OK)); + + String serviceInstanceTn = + new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_tn_sa1.json"))); + Mockito.when( + restClient.sendGetRequest(Mockito.contains("8d0d698e-77f4-4453-8c09-ae2cbe6a9a04"), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstanceTn, HttpStatus.OK)); + List<String> actualResponse = aaiService.getSnssaiList("09cad94e-fbb8-4c70-9c4d-74ec75e97683"); assertEquals(expectedResponse, actualResponse); } @Test - public void getSnssaiListForNssiTest() throws Exception { + public void getSnssaiListForNssiTest() throws IOException { configuration.setAaiUrl("http://aai:30233/aai/v21"); List<String> expectedResponse = new ArrayList<>(); expectedResponse.add("01-06E442"); - PowerMockito.mockStatic(AaiService.class); - PowerMockito.mockStatic(Configuration.class); - PowerMockito.when(Configuration.getInstance()).thenReturn(configuration); - try { - - String nssi = new String(Files.readAllBytes(Paths.get("src/test/resources/nssi.json"))); - Mockito.when( - restClient.sendGetRequest(Mockito.contains("50f418a6-804f-4453-bf70-21f0efaf6fcd"), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(nssi, HttpStatus.OK)); - - String serviceInstanceAn = - new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_an_sa1.json"))); - Mockito.when( - restClient.sendGetRequest(Mockito.contains("b2ae730f-1d5f-495a-8112-dac017a7348c"), Mockito.any())) - .thenReturn(new ResponseEntity<Object>(serviceInstanceAn, HttpStatus.OK)); - - } catch (Exception e) { - e.printStackTrace(); - - } + + String nssi = new String(Files.readAllBytes(Paths.get("src/test/resources/nssi.json"))); + Mockito.when( + restClient.sendGetRequest(Mockito.contains("50f418a6-804f-4453-bf70-21f0efaf6fcd"), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(nssi, HttpStatus.OK)); + + String serviceInstanceAn = + new String(Files.readAllBytes(Paths.get("src/test/resources/sliceprofile_an_sa1.json"))); + Mockito.when( + restClient.sendGetRequest(Mockito.contains("b2ae730f-1d5f-495a-8112-dac017a7348c"), Mockito.any())) + .thenReturn(new ResponseEntity<Object>(serviceInstanceAn, HttpStatus.OK)); + List<String> actualResponse = aaiService.getSnssaiList("50f418a6-804f-4453-bf70-21f0efaf6fcd"); assertEquals(expectedResponse, actualResponse); } + + @Test + public void fetchMaxBandwidthOfServiceTest() { + String data = "{" + + " \"network-policy\":[" + + " {" + + " \"max-bandwidth\":99" + + " }" + + " ]" + + "}"; + Mockito.when(restClient.sendGetRequest(Mockito.anyString(), Mockito.any())).thenReturn(new ResponseEntity<>(data, HttpStatus.OK)); + Map<String, Integer> map = aaiService.fetchMaxBandwidthOfService(""); + assertEquals(99, MapUtils.getIntValue(map, "maxBandwidth")); + } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/controller/ConfigFetchFromCbsTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/controller/ConfigFetchFromCbsTest.java new file mode 100644 index 00000000..84824547 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/controller/ConfigFetchFromCbsTest.java @@ -0,0 +1,77 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + + +package org.onap.slice.analysis.ms.controller; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.api.CbsClientFactory; +import org.onap.dcaegen2.services.sdk.rest.services.cbs.client.model.CbsClientConfiguration; +import org.onap.dcaegen2.services.sdk.rest.services.model.logging.ImmutableRequestDiagnosticContext; +import org.onap.dcaegen2.services.sdk.rest.services.model.logging.RequestDiagnosticContext; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.slf4j.LoggerFactory; +import org.slf4j.Logger; +import reactor.core.publisher.Mono; + +import java.time.Duration; + +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.when; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({LoggerFactory.class, + RequestDiagnosticContext.class, + CbsClientConfiguration.class, + ImmutableRequestDiagnosticContext.class, + CbsClientFactory.class}) +public class ConfigFetchFromCbsTest { + + @Test + public void getAppConfigTest() { + PowerMockito.mockStatic(LoggerFactory.class); + Logger log = PowerMockito.mock(Logger.class); + when(LoggerFactory.getLogger(ConfigFetchFromCbs.class)).thenReturn(log); + + PowerMockito.mockStatic(RequestDiagnosticContext.class); + ImmutableRequestDiagnosticContext diagnosticContext = PowerMockito.mock(ImmutableRequestDiagnosticContext.class); + when(RequestDiagnosticContext.create()).thenReturn(diagnosticContext); + + PowerMockito.mockStatic(CbsClientConfiguration.class); + CbsClientConfiguration cbsClientConfiguration = PowerMockito.mock(CbsClientConfiguration.class); + when(CbsClientConfiguration.fromEnvironment()).thenReturn(cbsClientConfiguration); + + PowerMockito.mockStatic(CbsClientFactory.class); + Mono mono = PowerMockito.mock(Mono.class); + when(CbsClientFactory.createCbsClient(cbsClientConfiguration)).thenReturn(mono); + + ConfigFetchFromCbs configFetchFromCbs = new ConfigFetchFromCbs(Duration.ofSeconds(60)); + ConfigFetchFromCbs spy = PowerMockito.spy(configFetchFromCbs); + Thread configFetchThread = new Thread(spy); + configFetchThread.start(); + Mockito.verify(spy, times(1)).run(); + + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/cps/CpsInterfaceServiceTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/cps/CpsInterfaceServiceTest.java index 0ae7d4f3..96b5fe2d 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/cps/CpsInterfaceServiceTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/cps/CpsInterfaceServiceTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2021-2022 Wipro Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,6 +24,7 @@ package org.onap.slice.analysis.ms.cps; import static org.junit.Assert.assertEquals; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; @@ -35,10 +37,8 @@ import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.onap.slice.analysis.ms.models.Configuration; import org.onap.slice.analysis.ms.restclients.CpsRestClient; import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.boot.test.context.SpringBootTest; @@ -49,7 +49,6 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(SpringRunner.class) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) -@PrepareForTest({CpsService.class, Configuration.class}) @SpringBootTest(classes = CpsInterfaceServiceTest.class) public class CpsInterfaceServiceTest { @InjectMocks @@ -59,52 +58,52 @@ public class CpsInterfaceServiceTest { CpsRestClient restClient; @Test - public void fetchCurrentConfigurationOfRICTest() { + public void fetchCurrentConfigurationOfRICTest() throws IOException { Map<String, Object> map = new HashMap<>(); map.put("dLThptPerSlice", 10); map.put("uLThptPerSlice", 10); map.put("maxNumberOfConns", 10); Map<String, Map<String, Object>> responseMap = new HashMap<>(); responseMap.put("11", map); - try { - String serviceInstance = new String(Files.readAllBytes(Paths.get("src/test/resources/sliceConfig.json"))); - Mockito.when(restClient.sendPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new ResponseEntity<>(serviceInstance, HttpStatus.OK)); - } catch (Exception e) { - e.printStackTrace(); - } + String serviceInstance = new String(Files.readAllBytes(Paths.get("src/test/resources/sliceConfig.json"))); + Mockito.when(restClient.sendPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<>(serviceInstance, HttpStatus.OK)); assertEquals(responseMap, cpsService.fetchCurrentConfigurationOfRIC("111-1111")); } @Test - public void fetchNetworkFunctionsOfSnssaiTest() { + public void fetchNetworkFunctionsOfSnssaiTest() throws IOException { List<String> responseList = new ArrayList<>(); responseList.add("22"); responseList.add("23"); - try { - String serviceInstance = new String(Files.readAllBytes(Paths.get("src/test/resources/DUList.json"))); - Mockito.when(restClient.sendPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new ResponseEntity<>(serviceInstance, HttpStatus.OK)); - } catch (Exception e) { - e.printStackTrace(); - } + String serviceInstance = new String(Files.readAllBytes(Paths.get("src/test/resources/DUList.json"))); + Mockito.when(restClient.sendPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<>(serviceInstance, HttpStatus.OK)); assertEquals(responseList, cpsService.fetchNetworkFunctionsOfSnssai("111-1111")); } @Test - public void fetchRICsOfSnssaiTest() { + public void fetchRICsOfSnssaiTest() throws IOException { Map<String, List<String>> responseMap = new HashMap<>(); List<String> cellslist = new ArrayList<>(); cellslist.add("1599"); cellslist.add("1598"); responseMap.put("11", cellslist); - try { - String serviceInstance = new String(Files.readAllBytes(Paths.get("src/test/resources/DUCellsList.json"))); - Mockito.when(restClient.sendPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.any())) - .thenReturn(new ResponseEntity<>(serviceInstance, HttpStatus.OK)); - } catch (Exception e) { - e.printStackTrace(); - } + String serviceInstance = new String(Files.readAllBytes(Paths.get("src/test/resources/DUCellsList.json"))); + Mockito.when(restClient.sendPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<>(serviceInstance, HttpStatus.OK)); assertEquals(responseMap, cpsService.fetchRICsOfSnssai("111-1111")); } + + @Test + public void fetchnrCellCUsOfSnssaiTest() throws IOException { + Map<String, List<String>> responseMap = new HashMap<>(); + List<String> cellslist = new ArrayList<>(); + cellslist.add("15199"); + responseMap.put("11", cellslist); + String serviceInstance = new String(Files.readAllBytes(Paths.get("src/test/resources/DUCellsList.json"))); + Mockito.when(restClient.sendPostRequest(Mockito.anyString(), Mockito.anyString(), Mockito.any())) + .thenReturn(new ResponseEntity<>(serviceInstance, HttpStatus.OK)); + assertEquals(responseMap, cpsService.fetchnrCellCUsOfSnssai("111-1111")); + } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/AaiEventNotificationCallbackTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/AaiEventNotificationCallbackTest.java index eb88d537..3b0c32fa 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/AaiEventNotificationCallbackTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/AaiEventNotificationCallbackTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2022 Huawei Canada Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -21,11 +22,18 @@ package org.onap.slice.analysis.ms.dmaap; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; +import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; +import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.Spy; +import org.onap.slice.analysis.ms.models.Configuration; +import org.onap.slice.analysis.ms.service.ccvpn.BandwidthEvaluator; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @@ -33,6 +41,9 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; +import static org.mockito.ArgumentMatchers.any; +import static org.powermock.api.mockito.PowerMockito.doNothing; + @RunWith(SpringRunner.class) @SpringBootTest(classes = VesNotificationCallbackTest.class) @@ -42,6 +53,45 @@ public class AaiEventNotificationCallbackTest { @InjectMocks AaiEventNotificationCallback aaiEventNotificationCallback; + @Mock + BandwidthEvaluator bandwidthEvaluator; + + @Before + public void initConfiguration() { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("sliceanalysisms.aaiNotif.targetAction", "UPDATE"); + jsonObject.addProperty("sliceanalysisms.aaiNotif.targetEntity", "service-instance"); + jsonObject.addProperty("sliceanalysisms.aaiNotif.targetSource", "UUI"); + jsonObject.addProperty("postgres.port", "1"); + jsonObject.addProperty("sliceanalysisms.pollingInterval", "1"); + jsonObject.addProperty("postgres.password", "1"); + jsonObject.addProperty("postgres.username", "1"); + jsonObject.addProperty("postgres.host", "1"); + jsonObject.addProperty("sliceanalysisms.cg", "1"); + jsonObject.addProperty("sliceanalysisms.cid", "1"); + jsonObject.addProperty("sliceanalysisms.configDb.service", "1"); + jsonObject.addProperty("sliceanalysisms.configDbEnabled", "1"); + jsonObject.addProperty("sliceanalysisms.pollingTimeout", "1"); + jsonObject.addProperty("sliceanalysisms.samples", "1"); + jsonObject.addProperty("sliceanalysisms.minPercentageChange", "1"); + jsonObject.addProperty("sliceanalysisms.initialDelaySeconds", "1"); + jsonObject.addProperty("sliceanalysisms.rannfnssiDetailsTemplateId", "1"); + jsonObject.addProperty("sliceanalysisms.desUrl", "1"); + jsonObject.addProperty("sliceanalysisms.pmDataDurationInWeeks", "1"); + jsonObject.addProperty("sliceanalysisms.pollingInterval", "1"); + jsonObject.addProperty("sliceanalysisms.vesNotifChangeIdentifier", "1"); + jsonObject.addProperty("sliceanalysisms.vesNotifChangeType", "1"); + jsonObject.addProperty("sliceanalysisms.vesNotifPollingInterval", "1"); + jsonObject.addProperty("sliceanalysisms.ccvpnEvalInterval", "1"); + jsonObject.addProperty("sliceanalysisms.ccvpnEvalThreshold", "1"); + jsonObject.addProperty("sliceanalysisms.ccvpnEvalPrecision", "1"); + jsonObject.addProperty("sliceanalysisms.ccvpnEvalPeriodicCheckOn", "1"); + jsonObject.addProperty("sliceanalysisms.ccvpnEvalOnDemandCheckOn", "1"); + Configuration configuration = Configuration.getInstance(); + configuration.updateConfigurationFromJsonObject(jsonObject); + doNothing().when(bandwidthEvaluator).post(any()); + } + @Test public void initTest() { aaiEventNotificationCallback.init(); @@ -49,14 +99,21 @@ public class AaiEventNotificationCallbackTest { } @Test - public void activateCallBackTest() { - String input = null; - try { - input = new String(Files.readAllBytes(Paths.get("src/test/resources/aaiEventDmaapMsg.json"))); - } catch (IOException e) { - e.printStackTrace(); - } + public void activateCallBackTest() throws IOException { + aaiEventNotificationCallback.init(); + String input = new String(Files.readAllBytes(Paths.get("src/test/resources/aaiEventDmaapMsg.json"))); aaiEventNotificationCallback.activateCallBack(input); Mockito.verify(aaiEventNotificationCallback, Mockito.atLeastOnce()).activateCallBack(Mockito.anyString()); } + @Test + public void activateCallBackArrayTest() throws IOException { + aaiEventNotificationCallback.init(); + String input = new String(Files.readAllBytes(Paths.get("src/test/resources/aaiEventDmaapMsg.json"))); + JsonArray jsonArray = new JsonArray(); + + JsonPrimitive jsonPrimitive = new JsonPrimitive(input); + jsonArray.add(jsonPrimitive); + aaiEventNotificationCallback.activateCallBack(jsonArray.toString()); + Mockito.verify(aaiEventNotificationCallback, Mockito.atLeastOnce()).activateCallBack(Mockito.anyString()); + } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/DmaapClientTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/DmaapClientTest.java index b74056db..7da9f95f 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/DmaapClientTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/DmaapClientTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,28 +23,23 @@ package org.onap.slice.analysis.ms.dmaap; -import static org.mockito.Mockito.when; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; -import com.att.nsa.cambria.client.CambriaTopicManager; import com.google.gson.Gson; import com.google.gson.JsonObject; import java.io.BufferedReader; import java.io.FileReader; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; -import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.onap.slice.analysis.ms.models.Configuration; +import org.powermock.api.mockito.PowerMockito; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; @@ -51,78 +47,43 @@ import org.springframework.test.context.junit4.SpringRunner; @SpringBootTest(classes = DmaapClientTest.class) public class DmaapClientTest { - @Mock - private CambriaTopicManager topicManager; - - @InjectMocks - DmaapClient client; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void getAllTopicsTest() { - Set<String> topics = new HashSet<String>(); - topics.add("topic1"); - topics.add("topic2"); - Configuration configuration = Configuration.getInstance(); - List<String> list = new ArrayList<String>(); - list.add("server"); - configuration.setDmaapServers(list); - configuration.setCg("cg"); - configuration.setCid("cid"); - configuration.setPollingInterval(30); - configuration.setPollingTimeout(100); - configuration.setConfigDbService("sdnrService"); - - try { - when(topicManager.getTopics()).thenReturn(topics); - - client=Mockito.mock(DmaapClient.class); - client.initClient(); - Mockito.verify(client).initClient(); - // Mockito.verifycreateAndConfigureTopics(); - - } catch (IOException e) { - e.printStackTrace(); - } - } - - @Test - public void startClientTest() { - try { - Configuration configuration = Configuration.getInstance(); - String configAllJson = readFromFile("src/test/resources/config_all.json"); - - JsonObject configAll = new Gson().fromJson(configAllJson, JsonObject.class); - - JsonObject config = configAll.getAsJsonObject("config"); - System.out.println(configuration); - configuration.updateConfigurationFromJsonObject(config); - DmaapClient client= new DmaapClient(); - client.initClient(); - //Mockito.verify(client).startClient(); - // Mockito.verifycreateAndConfigureTopics(); - - } catch ( Exception e) { - e.printStackTrace(); - } - } - - private static String readFromFile(String file) { - String content = ""; - try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { - content = bufferedReader.readLine(); - String temp; - while ((temp = bufferedReader.readLine()) != null) { - content = content.concat(temp); - } - content = content.trim(); - } catch (Exception e) { - content = null; - } - return content; - } + @InjectMocks + DmaapClient client; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void startClientTest() { + Configuration configuration = Configuration.getInstance(); + String configAllJson = readFromFile("src/test/resources/config_all.json"); + + JsonObject configAll = new Gson().fromJson(configAllJson, JsonObject.class); + + JsonObject config = configAll.getAsJsonObject("config"); + System.out.println(configuration); + configuration.updateConfigurationFromJsonObject(config); + MRTopicMonitor mrTopicMonitor = Mockito.mock(MRTopicMonitor.class); + DmaapClient spy = PowerMockito.spy(client); + doReturn(mrTopicMonitor).when(spy).getMRTopicMonitor(); + doNothing().when(mrTopicMonitor).start(); + spy.initClient(); + } + + private static String readFromFile(String file) { + String content = ""; + try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) { + content = bufferedReader.readLine(); + String temp; + while ((temp = bufferedReader.readLine()) != null) { + content = content.concat(temp); + } + content = content.trim(); + } catch (Exception e) { + content = null; + } + return content; + } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/IntelligentSlicingCallbackTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/IntelligentSlicingCallbackTest.java new file mode 100644 index 00000000..59daae09 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/IntelligentSlicingCallbackTest.java @@ -0,0 +1,56 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.dmaap; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.Spy; +import org.onap.slice.analysis.ms.service.MLMessageProcessor; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = IntelligentSlicingCallbackTest.class) +public class IntelligentSlicingCallbackTest { + + + @Spy + @InjectMocks + IntelligentSlicingCallback intelligentSlicingCallback; + + @Mock + private MLMessageProcessor mlMsMessageProcessor; + + @Test + public void activateCallBackTest() { + Mockito.doNothing().when(mlMsMessageProcessor).processMLMsg(Mockito.any()); + intelligentSlicingCallback.activateCallBack("{}"); + verify(mlMsMessageProcessor, times(1)).processMLMsg(any()); + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/MRTopicMonitorTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/MRTopicMonitorTest.java index ce920a0e..813bd463 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/MRTopicMonitorTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/MRTopicMonitorTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2022 Huawei Canada Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,19 +32,22 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.Spy; -import org.mockito.stubbing.Answer; import org.onap.slice.analysis.ms.models.Configuration; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.BufferedReader; import java.io.FileReader; -import java.util.Map; +import java.util.concurrent.Executors; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -@RunWith(SpringRunner.class) +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ Executors.class}) @SpringBootTest(classes = MRTopicMonitorTest.class) public class MRTopicMonitorTest { @@ -67,12 +71,6 @@ public class MRTopicMonitorTest { } @Test - public void start() { - mrTopicMonitor.start(); - Mockito.verify(mrTopicMonitor, Mockito.times(1)).start(); - } - - @Test public void run() { mrTopicMonitor.run(); Mockito.verify(mrTopicMonitor, Mockito.times(1)).run(); diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/MRTopicParamsTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/MRTopicParamsTest.java index a5066b17..2498306c 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/MRTopicParamsTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/MRTopicParamsTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2022 Huawei Canada Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -30,7 +31,16 @@ import com.openpojo.validation.rule.impl.SetterMustExistRule; import com.openpojo.validation.test.impl.GetterTester; import com.openpojo.validation.test.impl.SetterTester; import org.junit.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + public class MRTopicParamsTest { private static final String TEST_TOPIC = "test-topic"; @@ -93,4 +103,84 @@ public class MRTopicParamsTest { .build(); validator.validate(pojoclass); } + + @Test + public void initProperty() { + List<String> strings = new ArrayList<>(); + Map<String, String> map = new HashMap<>(); + MRTopicParams params = MRTopicParams.builder() + .topic(TEST_TOPIC) + .hostname(TEST_HOST) + .clientName(MY_CLIENT) + .consumerGroup(MY_CG) + .consumerInstance(MY_CI) + .apiSecret(MY_API_SEC) + .apiKey(MY_API_KEY) + .fetchLimit(MY_FETCH_LIMIT) + .fetchTimeout(MY_FETCH_TIMEOUT) + .password(MY_PASS) + .userName(MY_USERNAME) + .port(MY_PORT) + .servers(strings) + .additionalProps(map) + .effectiveTopic("") + .useHttps(true) + .allowSelfSignedCerts(true) + .managed(true) + .environment("") + .aftEnvironment("") + .partner("") + .latitude("") + .longitude("") + .partitionId("") + .basePath("") + .serializationProvider("") + .build(); + assertEquals(TEST_TOPIC, params.getTopic()); + assertEquals(TEST_HOST, params.getHostname()); + assertEquals(MY_CLIENT, params.getClientName()); + assertEquals(MY_CG, params.getConsumerGroup()); + assertEquals(MY_CI, params.getConsumerInstance()); + assertEquals(MY_API_SEC, params.getApiSecret()); + assertEquals(MY_API_KEY, params.getApiKey()); + assertEquals(MY_FETCH_LIMIT, params.getFetchLimit()); + assertEquals(MY_FETCH_TIMEOUT, params.getFetchTimeout()); + assertEquals(MY_PASS, params.getPassword()); + assertEquals(MY_USERNAME, params.getUserName()); + assertEquals(MY_PORT, params.getPort()); + assertEquals(strings, params.getServers()); + assertEquals(map, params.getAdditionalProps()); + assertEquals("", params.getEffectiveTopic()); + assertTrue(params.isUseHttps()); + assertTrue(params.isAllowSelfSignedCerts()); + assertTrue(params.isManaged()); + assertEquals("", params.getEnvironment()); + assertEquals("", params.getAftEnvironment()); + assertEquals("", params.getPartner()); + assertEquals("", params.getLongitude()); + assertEquals("", params.getPartitionId()); + assertEquals("", params.getBasePath()); + assertEquals("", params.getSerializationProvider()); + + assertTrue(params.isEnvironmentInvalid()); + assertTrue(params.isAftEnvironmentInvalid()); + assertTrue(params.isLatitudeInvalid()); + assertTrue(params.isLongitudeInvalid()); + assertTrue(params.isPartnerInvalid()); + assertTrue(params.isServersInvalid()); + assertTrue(params.isPartitionIdInvalid()); + assertTrue(params.isApiKeyValid()); + assertTrue(params.isApiSecretValid()); + assertTrue(params.isUserNameValid()); + assertTrue(params.isPasswordValid()); + assertTrue(params.isAdditionalPropsValid()); + assertFalse(params.isConsumerInstanceInvalid()); + assertFalse(params.isConsumerGroupInvalid()); + assertFalse(params.isClientNameInvalid()); + assertFalse(params.isTopicInvalid()); + assertFalse(params.isHostnameInvalid()); + assertFalse(params.isPortInvalid()); + } + + } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/NotificationConsumerTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/NotificationConsumerTest.java index 9aab22c2..5b8e5f25 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/NotificationConsumerTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/NotificationConsumerTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -23,44 +24,48 @@ package org.onap.slice.analysis.ms.dmaap; import static org.mockito.Mockito.when; -import java.util.ArrayList; -import java.util.List; - +import com.google.gson.JsonPrimitive; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterSubscriber; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.ImmutableMessageRouterSubscribeResponse; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterSubscribeRequest; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterSubscribeResponse; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; -import com.att.nsa.cambria.client.CambriaConsumer; +import reactor.core.publisher.Mono; @RunWith(SpringRunner.class) @SpringBootTest(classes = NotificationConsumerTest.class) public class NotificationConsumerTest { - - @Mock - CambriaConsumer cambriaConsumer; - - @Mock - NotificationCallback notificationCallback; + + @Mock + NotificationCallback notificationCallback; + + @Mock + MessageRouterSubscriber subscriber; + + @Mock + MessageRouterSubscribeRequest request; - @InjectMocks - NotificationConsumer notificationConsumer; + @InjectMocks + NotificationConsumer notificationConsumer; - @Test - public void testNotificationConsumer() { - try { - List<String> notifications = new ArrayList<>(); - notifications.add("notification1"); - when(cambriaConsumer.fetch()).thenReturn(notifications); - Mockito.doNothing().when(notificationCallback).activateCallBack(Mockito.anyString()); - notificationConsumer.run(); - - }catch(Exception e) { - e.printStackTrace(); - } - } + @Test + public void testNotificationConsumer() { + io.vavr.collection.List<String> expectedItems = io.vavr.collection.List.of("I", "like", "pizza"); + MessageRouterSubscribeResponse expectedResponse = ImmutableMessageRouterSubscribeResponse + .builder() + .items(expectedItems.map(JsonPrimitive::new)) + .build(); + Mono<MessageRouterSubscribeResponse> responses = Mono.just(expectedResponse); + when(subscriber.get(request)).thenReturn(responses); + Mockito.doNothing().when(notificationCallback).activateCallBack(Mockito.anyString()); + notificationConsumer.run(); + } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/NotificationProducerTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/NotificationProducerTest.java index 9dc51412..d39c0af6 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/NotificationProducerTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/NotificationProducerTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,42 +23,47 @@ package org.onap.slice.analysis.ms.dmaap; -import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -import com.att.nsa.cambria.client.CambriaBatchingPublisher; - -import java.io.IOException; - +import com.google.gson.JsonPrimitive; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; -import org.mockito.Mockito; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterPublisher; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.ImmutableMessageRouterPublishResponse; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterPublishRequest; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterPublishResponse; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; + +import java.io.IOException; @RunWith(SpringRunner.class) @SpringBootTest(classes = NotificationProducerTest.class) public class NotificationProducerTest { - @Mock - CambriaBatchingPublisher cambriaBatchingPublisher; - - @InjectMocks - NotificationProducer notificationProducer; + @Mock + MessageRouterPublisher publisher; - @Test - public void notificationProducerTest() { + @Mock + MessageRouterPublishRequest request; - try { + @InjectMocks + NotificationProducer notificationProducer; - when(cambriaBatchingPublisher.send(Mockito.anyString(), Mockito.anyString())).thenReturn(0); - int result = notificationProducer.sendNotification("msg"); - assertEquals(0, result); - } catch (IOException e) { - e.printStackTrace(); - } + @Test + public void notificationProducerTest() throws IOException { + io.vavr.collection.List<String> expectedItems = io.vavr.collection.List.of("I", "like", "pizza"); + MessageRouterPublishResponse expectedResponse = ImmutableMessageRouterPublishResponse + .builder().items(expectedItems.map(JsonPrimitive::new)) + .build(); + Flux<MessageRouterPublishResponse> responses = Flux.just(expectedResponse); +// Flux<JsonPrimitive> singleMessage = Flux.just("msg").map(JsonPrimitive::new); + when(publisher.put(any(), any())).thenReturn(responses); - } + notificationProducer.sendNotification("msg"); + } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/PolicyDmaapClientTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/PolicyDmaapClientTest.java index 3ff56ab1..26f691e3 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/PolicyDmaapClientTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/dmaap/PolicyDmaapClientTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,51 +23,50 @@ package org.onap.slice.analysis.ms.dmaap; -import static org.junit.Assert.assertTrue; - -import java.io.IOException; import java.util.HashMap; import java.util.Map; +import com.google.gson.JsonPrimitive; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterPublisher; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.ImmutableMessageRouterPublishResponse; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterPublishRequest; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterPublishResponse; import org.onap.slice.analysis.ms.models.Configuration; -import org.onap.slice.analysis.ms.utils.DmaapUtils; +import org.onap.slice.analysis.ms.utils.DcaeDmaapUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; +import reactor.core.publisher.Flux; -import com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaConsumer; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; -@RunWith(MockitoJUnitRunner.class) -@SpringBootTest(classes = PolicyDmaapClient.class) +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ DcaeDmaapUtil.class}) +@SpringBootTest(classes = PolicyDmaapClientTest.class) public class PolicyDmaapClientTest { @Mock Configuration configurationMock; - @Mock - DmaapUtils dmaapUtilsMock; - @InjectMocks PolicyDmaapClient policyDmaapClient; - @Mock - CambriaConsumer policyResponseCambriaConsumerMock; - - @Mock - CambriaBatchingPublisher cambriaBatchingPublisherMock; - - @Mock - NotificationProducer notificationProducerMock; - @Before public void setup() { - policyDmaapClient = new PolicyDmaapClient(dmaapUtilsMock, configurationMock); + policyDmaapClient = new PolicyDmaapClient(configurationMock); } @Test @@ -78,13 +78,21 @@ public class PolicyDmaapClientTest { dmaapInfo.put("dmaap_info", topics); streamsPublishes.put("CL_topic", dmaapInfo); Mockito.when(configurationMock.getStreamsPublishes()).thenReturn(streamsPublishes); - Mockito.when(dmaapUtilsMock.buildPublisher(configurationMock, "DCAE_CL_OUTPUT")).thenReturn(cambriaBatchingPublisherMock); - try { - Mockito.when(cambriaBatchingPublisherMock.send("", "hello")).thenReturn(0); - } catch (IOException e) { - e.printStackTrace(); - } - assertTrue(policyDmaapClient.sendNotificationToPolicy("hello")); - + + PowerMockito.mockStatic(DcaeDmaapUtil.class); + MessageRouterPublisher publisher = PowerMockito.mock(MessageRouterPublisher.class); + PowerMockito.when(DcaeDmaapUtil.buildPublisher()).thenReturn(publisher); + + MessageRouterPublishRequest request = PowerMockito.mock(MessageRouterPublishRequest.class); + PowerMockito.when(DcaeDmaapUtil.buildPublisherRequest(any(),any())).thenReturn(request); + + io.vavr.collection.List<String> expectedItems = io.vavr.collection.List.of("I", "like", "pizza"); + MessageRouterPublishResponse expectedResponse = ImmutableMessageRouterPublishResponse + .builder().items(expectedItems.map(JsonPrimitive::new)) + .build(); + Flux<MessageRouterPublishResponse> responses = Flux.just(expectedResponse); + when(publisher.put(any(), any())).thenReturn(responses); + + policyDmaapClient.sendNotificationToPolicy("msg"); } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/AggregatedConfigTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/AggregatedConfigTest.java new file mode 100644 index 00000000..c8d999ea --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/AggregatedConfigTest.java @@ -0,0 +1,75 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.models; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@SpringBootTest(classes = AggregatedConfigTest.class) +public class AggregatedConfigTest { + + @Test + public void AggregatedConfigTest() { + + AggregatedConfig aggregatedConfig = new AggregatedConfig(); + aggregatedConfig.setDLThptPerSlice(1); + aggregatedConfig.setULThptPerSlice(2); + aggregatedConfig.setMaxNumberOfConns(3); + + assertEquals(1, aggregatedConfig.getDLThptPerSlice()); + assertEquals(2, aggregatedConfig.getULThptPerSlice()); + assertEquals(3, aggregatedConfig.getMaxNumberOfConns()); + } + + @Test + public void RelationshipListEqualsTest() { + + + AggregatedConfig aggregatedConfig = new AggregatedConfig(); + aggregatedConfig.setDLThptPerSlice(1); + aggregatedConfig.setULThptPerSlice(2); + aggregatedConfig.setMaxNumberOfConns(3); + + + AggregatedConfig aggregatedConfig2 = new AggregatedConfig(); + aggregatedConfig2.setDLThptPerSlice(1); + aggregatedConfig2.setULThptPerSlice(2); + aggregatedConfig2.setMaxNumberOfConns(3); + + + assertTrue(aggregatedConfig2.equals(aggregatedConfig)); + assertTrue(StringUtils.isNotBlank(aggregatedConfig.toString())); + assertTrue(aggregatedConfig.hashCode() != 0); + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/SliceConfigDetailsTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/SliceConfigDetailsTest.java new file mode 100644 index 00000000..b843df5c --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/SliceConfigDetailsTest.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.models; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@SpringBootTest(classes = SliceConfigDetailsTest.class) +public class SliceConfigDetailsTest { + + @Test + public void SliceConfigDetailsTest() { + + AggregatedConfig aggregatedConfig = new AggregatedConfig(); + + SliceConfigDetails sliceConfigDetails = new SliceConfigDetails(); + sliceConfigDetails.setSliceIdentifiers("slice"); + sliceConfigDetails.setAggregatedConfig(aggregatedConfig); + + assertEquals("slice", sliceConfigDetails.getSliceIdentifiers()); + assertEquals(aggregatedConfig, sliceConfigDetails.getAggregatedConfig()); + } + + @Test + public void RelationshipListEqualsTest() { + + AggregatedConfig aggregatedConfig = new AggregatedConfig(); + + SliceConfigDetails sliceConfigDetails = new SliceConfigDetails(); + sliceConfigDetails.setSliceIdentifiers("slice"); + sliceConfigDetails.setAggregatedConfig(aggregatedConfig); + + SliceConfigDetails sliceConfigDetails2 = new SliceConfigDetails(); + sliceConfigDetails2.setSliceIdentifiers("slice"); + sliceConfigDetails2.setAggregatedConfig(aggregatedConfig); + + + assertTrue(sliceConfigDetails2.equals(sliceConfigDetails)); + assertTrue(StringUtils.isNotBlank(sliceConfigDetails.toString())); + assertTrue(sliceConfigDetails.hashCode() != 0); + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/SliceConfigRequestTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/SliceConfigRequestTest.java new file mode 100644 index 00000000..f688bb68 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/SliceConfigRequestTest.java @@ -0,0 +1,79 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.models; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@SpringBootTest(classes = SliceConfigRequestTest.class) +public class SliceConfigRequestTest { + + @Test + public void SliceConfigRequestTest() { + + List<String> sliceIdentifiers = new ArrayList<>(); + List<String> configParams = new ArrayList<>(); + + SliceConfigRequest sliceConfigRequest = new SliceConfigRequest(); + sliceConfigRequest.setConfigParams(configParams); + sliceConfigRequest.setSliceIdentifiers(sliceIdentifiers); + + + assertEquals(sliceIdentifiers, sliceConfigRequest.getSliceIdentifiers()); + assertEquals(configParams, sliceConfigRequest.getConfigParams()); + } + + @Test + public void SliceConfigRequestEqualsTest() { + + List<String> sliceIdentifiers = new ArrayList<>(); + List<String> configParams = new ArrayList<>(); + + SliceConfigRequest sliceConfigRequest = new SliceConfigRequest(); + sliceConfigRequest.setConfigParams(configParams); + sliceConfigRequest.setSliceIdentifiers(sliceIdentifiers); + + SliceConfigRequest sliceConfigRequest1 = new SliceConfigRequest(); + sliceConfigRequest1.setConfigParams(configParams); + sliceConfigRequest1.setSliceIdentifiers(sliceIdentifiers); + + + assertTrue(sliceConfigRequest1.equals(sliceConfigRequest)); + assertTrue(StringUtils.isNotBlank(sliceConfigRequest.toString())); + assertTrue(sliceConfigRequest.hashCode() != 0); + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/SliceConfigResponseTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/SliceConfigResponseTest.java new file mode 100644 index 00000000..78c42dae --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/SliceConfigResponseTest.java @@ -0,0 +1,73 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.models; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@SpringBootTest(classes = SliceConfigResponseTest.class) +public class SliceConfigResponseTest { + + @Test + public void SliceConfigResponseTest() { + + List<SliceConfigDetails> sliceConfigDetails = new ArrayList<>(); + + SliceConfigResponse sliceConfigResponse = new SliceConfigResponse(); + sliceConfigResponse.setSliceConfigDetails(sliceConfigDetails); + + + assertEquals(sliceConfigDetails, sliceConfigResponse.getSliceConfigDetails()); + } + + @Test + public void SliceConfigResponseEqualsTest() { + + List<SliceConfigDetails> sliceConfigDetails = new ArrayList<>(); + + SliceConfigResponse sliceConfigResponse = new SliceConfigResponse(); + sliceConfigResponse.setSliceConfigDetails(sliceConfigDetails); + + SliceConfigResponse sliceConfigResponse1 = new SliceConfigResponse(); + sliceConfigResponse1.setSliceConfigDetails(sliceConfigDetails); + + + assertTrue(sliceConfigResponse1.equals(sliceConfigResponse)); + assertTrue(StringUtils.isNotBlank(sliceConfigResponse.toString())); + assertTrue(sliceConfigResponse.hashCode() != 0); + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/aai/RelationshipListTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/aai/RelationshipListTest.java new file mode 100644 index 00000000..5e7640f6 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/aai/RelationshipListTest.java @@ -0,0 +1,113 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.models.aai; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonArray; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.google.gson.JsonObject; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@SpringBootTest(classes = RelationshipListTest.class) +public class RelationshipListTest { + + @Test + public void RelationshipListTest() throws JsonProcessingException { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("related-to", "related-to"); + jsonObject.addProperty("relationship-label", "relationship-label"); + jsonObject.addProperty("related-link", "related-link"); + + JsonArray relationshipData = new JsonArray(); + JsonObject relationshipDataObj = new JsonObject(); + relationshipDataObj.addProperty("a","1"); + relationshipData.add(relationshipDataObj); + JsonArray relatedToProperty = new JsonArray(); + JsonObject relatedToPropertyObj = new JsonObject(); + relatedToPropertyObj.addProperty("a","1"); + relatedToProperty.add(relatedToPropertyObj); + + jsonObject.add("relationship-data", relationshipData); + jsonObject.add("related-to-property", relatedToProperty); + + Relationship relationship = new ObjectMapper().readValue(jsonObject.toString(), Relationship.class); + + List<Relationship> relationships = new ArrayList<>(); + relationships.add(relationship); + + RelationshipList relationshipList = new RelationshipList(); + relationshipList.setRelationship(relationships); + + assertEquals(1, relationshipList.getRelationship().size()); + } + + @Test + public void RelationshipListEqualsTest() throws JsonProcessingException { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("related-to", "related-to"); + jsonObject.addProperty("relationship-label", "relationship-label"); + jsonObject.addProperty("related-link", "related-link"); + + JsonArray relationshipData = new JsonArray(); + JsonObject relationshipDataObj = new JsonObject(); + relationshipDataObj.addProperty("a","1"); + relationshipData.add(relationshipDataObj); + JsonArray relatedToProperty = new JsonArray(); + JsonObject relatedToPropertyObj = new JsonObject(); + relatedToPropertyObj.addProperty("a","1"); + relatedToProperty.add(relatedToPropertyObj); + + jsonObject.add("relationship-data", relationshipData); + jsonObject.add("related-to-property", relatedToProperty); + + Relationship relationship = new ObjectMapper().readValue(jsonObject.toString(), Relationship.class); + + List<Relationship> relationships = new ArrayList<>(); + relationships.add(relationship); + + RelationshipList relationshipList = new RelationshipList(); + relationshipList.setRelationship(relationships); + + RelationshipList relationshipList1 = new RelationshipList(); + relationshipList1.setRelationship(relationships); + + assertTrue(relationshipList1.equals(relationshipList)); + assertTrue(StringUtils.isNotBlank(relationshipList.toString())); + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/aai/RelationshipTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/aai/RelationshipTest.java new file mode 100644 index 00000000..3bd563bc --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/aai/RelationshipTest.java @@ -0,0 +1,100 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.models.aai; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.gson.JsonArray; +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import com.google.gson.JsonObject; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@SpringBootTest(classes = RelationshipTest.class) +public class RelationshipTest { + + @Test + public void RelationshipTest() throws JsonProcessingException { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("related-to", "related-to"); + jsonObject.addProperty("relationship-label", "relationship-label"); + jsonObject.addProperty("related-link", "related-link"); + + JsonArray relationshipData = new JsonArray(); + JsonObject relationshipDataObj = new JsonObject(); + relationshipDataObj.addProperty("a","1"); + relationshipData.add(relationshipDataObj); + JsonArray relatedToProperty = new JsonArray(); + JsonObject relatedToPropertyObj = new JsonObject(); + relatedToPropertyObj.addProperty("a","1"); + relatedToProperty.add(relatedToPropertyObj); + + jsonObject.add("relationship-data", relationshipData); + jsonObject.add("related-to-property", relatedToProperty); + + Relationship relationship = new ObjectMapper().readValue(jsonObject.toString(), Relationship.class); + assertEquals("related-to", relationship.getRelatedTo()); + assertEquals("relationship-label", relationship.getRelationshipLabel()); + assertEquals("related-link", relationship.getRelatedLink()); + assertEquals(1, relationship.getRelationshipData().size()); + assertEquals(1, relationship.getRelatedToProperty().size()); + } + + @Test + public void RelationshipEqualsTest() throws JsonProcessingException { + JsonObject jsonObject = new JsonObject(); + jsonObject.addProperty("related-to", "related-to"); + jsonObject.addProperty("relationship-label", "relationship-label"); + jsonObject.addProperty("related-link", "related-link"); + + JsonArray relationshipData = new JsonArray(); + JsonObject relationshipDataObj = new JsonObject(); + relationshipDataObj.addProperty("a","1"); + relationshipData.add(relationshipDataObj); + JsonArray relatedToProperty = new JsonArray(); + JsonObject relatedToPropertyObj = new JsonObject(); + relatedToPropertyObj.addProperty("a","1"); + relatedToProperty.add(relatedToPropertyObj); + + jsonObject.add("relationship-data", relationshipData); + jsonObject.add("related-to-property", relatedToProperty); + + Relationship relationship = new ObjectMapper().readValue(jsonObject.toString(), Relationship.class); + Relationship relationship1 = new ObjectMapper().readValue(jsonObject.toString(), Relationship.class); + + assertTrue(relationship1.equals(relationship)); + assertTrue(StringUtils.isNotBlank(relationship1.toString())); + + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/aai/ServiceInstanceTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/aai/ServiceInstanceTest.java new file mode 100644 index 00000000..3a550168 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/models/aai/ServiceInstanceTest.java @@ -0,0 +1,104 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.models.aai; + +import org.apache.commons.lang3.StringUtils; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@SpringBootTest(classes = ServiceInstanceTest.class) +public class ServiceInstanceTest { + + @Test + public void ServiceInstanceTest() { + + ServiceInstance serviceInstance = new ServiceInstance(); + serviceInstance.setServiceInstanceId("service-instance-id"); + serviceInstance.setServiceInstanceName("service-instance-name"); + serviceInstance.setServiceType("service-type"); + serviceInstance.setServiceRole("service-role"); + serviceInstance.setEnvironmentContext("environment-context"); + serviceInstance.setWorkloadContext("workload-context"); + serviceInstance.setOrchestrationStatus("orchestration-status"); + List<Relationship> relationships = new ArrayList<>(); + RelationshipList relationshipList = new RelationshipList(); + relationshipList.setRelationship(relationships); + serviceInstance.setRelationshipList(relationshipList); + + + assertEquals("service-instance-id", serviceInstance.getServiceInstanceId()); + assertEquals("service-instance-name", serviceInstance.getServiceInstanceName()); + assertEquals("service-type", serviceInstance.getServiceType()); + assertEquals("service-role", serviceInstance.getServiceRole()); + assertEquals("environment-context", serviceInstance.getEnvironmentContext()); + assertEquals("workload-context", serviceInstance.getWorkloadContext()); + assertEquals("orchestration-status", serviceInstance.getOrchestrationStatus()); + assertEquals(0, serviceInstance.getRelationshipList().getRelationship().size()); + } + + @Test + public void ServiceInstanceEqualsTest() { + + ServiceInstance serviceInstance = new ServiceInstance(); + serviceInstance.setServiceInstanceId("service-instance-id"); + serviceInstance.setServiceInstanceName("service-instance-name"); + serviceInstance.setServiceType("service-type"); + serviceInstance.setServiceRole("service-role"); + serviceInstance.setEnvironmentContext("environment-context"); + serviceInstance.setWorkloadContext("workload-context"); + serviceInstance.setOrchestrationStatus("orchestration-status"); + List<Relationship> relationships = new ArrayList<>(); + RelationshipList relationshipList = new RelationshipList(); + relationshipList.setRelationship(relationships); + serviceInstance.setRelationshipList(relationshipList); + + ServiceInstance serviceInstance1 = new ServiceInstance(); + serviceInstance1.setServiceInstanceId("service-instance-id"); + serviceInstance1.setServiceInstanceName("service-instance-name"); + serviceInstance1.setServiceType("service-type"); + serviceInstance1.setServiceRole("service-role"); + serviceInstance1.setEnvironmentContext("environment-context"); + serviceInstance1.setWorkloadContext("workload-context"); + serviceInstance1.setOrchestrationStatus("orchestration-status"); + List<Relationship> relationships1 = new ArrayList<>(); + RelationshipList relationshipList1 = new RelationshipList(); + relationshipList1.setRelationship(relationships1); + serviceInstance1.setRelationshipList(relationshipList1); + + assertTrue(serviceInstance1.equals(serviceInstance)); + assertTrue(StringUtils.isNotBlank(serviceInstance.toString())); + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/ConsumerThreadTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/ConsumerThreadTest.java new file mode 100644 index 00000000..6aaaed51 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/ConsumerThreadTest.java @@ -0,0 +1,135 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.service; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.slice.analysis.ms.configdb.IConfigDbService; +import org.onap.slice.analysis.ms.cps.CpsInterface; +import org.onap.slice.analysis.ms.models.Configuration; +import org.onap.slice.analysis.ms.utils.BeanUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.membermodification.MemberModifier; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.powermock.api.mockito.PowerMockito.doNothing; +import static org.powermock.api.mockito.PowerMockito.doReturn; +import static org.powermock.api.mockito.PowerMockito.doThrow; +import static org.powermock.api.mockito.PowerMockito.when; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ BeanUtil.class }) +@SpringBootTest(classes = ConsumerThreadTest.class) +public class ConsumerThreadTest { + + private ConsumerThread consumerThread; + @Mock + private PmDataQueue pmDataQueue; + @Mock + private IConfigDbService iConfigDbService; + @Mock + private CpsInterface cpsInterface; + + @Before + public void before() throws IllegalAccessException { + + PowerMockito.mockStatic(BeanUtil.class); + when(BeanUtil.getBean(PmDataQueue.class)).thenReturn(pmDataQueue); + + when(BeanUtil.getBean(IConfigDbService.class)).thenReturn(iConfigDbService); + + when(BeanUtil.getBean(CpsInterface.class)).thenReturn(cpsInterface); + + consumerThread = PowerMockito.spy(new ConsumerThread()); + + + + + MemberModifier.field(ConsumerThread.class, "cpsInterface") + .set(consumerThread , cpsInterface); + MemberModifier.field(ConsumerThread.class, "samples") + .set(consumerThread , 1); + } + + @Test + public void run1Test(){ + String snssai = "snssai"; + doReturn("snssai").when(pmDataQueue).getSnnsaiFromQueue(); + List<String> nfs = new ArrayList<>(); + when(iConfigDbService.fetchNetworkFunctionsOfSnssai(Mockito.any())).thenReturn(nfs); + when(pmDataQueue.checkSamplesInQueue(Mockito.any(), Mockito.anyInt())).thenReturn(true); + + + SnssaiSamplesProcessor snssaiSamplesProcessor = PowerMockito.mock(SnssaiSamplesProcessor.class); + when(BeanUtil.getBean(SnssaiSamplesProcessor.class)).thenReturn(snssaiSamplesProcessor); + Mockito.when(snssaiSamplesProcessor.processSamplesOfSnnsai(snssai, nfs)).thenReturn(false); + Mockito.doNothing().when(pmDataQueue).putSnssaiToQueue(snssai); + doThrow(new RuntimeException()).when(pmDataQueue).putSnssaiToQueue(snssai); + consumerThread.run(); + assertEquals(1,1); + } + + @Test + public void run2Test(){ + Configuration.getInstance().setConfigDbEnabled(false); + String snssai = "snssai"; + doReturn("snssai").when(pmDataQueue).getSnnsaiFromQueue(); + List<String> nfs = new ArrayList<>(); + when(iConfigDbService.fetchNetworkFunctionsOfSnssai(Mockito.any())).thenReturn(nfs); + when(pmDataQueue.checkSamplesInQueue(Mockito.any(), Mockito.anyInt())).thenReturn(true); + + when(cpsInterface.fetchNetworkFunctionsOfSnssai(snssai)).thenThrow(new RuntimeException()); + + SnssaiSamplesProcessor snssaiSamplesProcessor = PowerMockito.mock(SnssaiSamplesProcessor.class); + when(BeanUtil.getBean(SnssaiSamplesProcessor.class)).thenReturn(snssaiSamplesProcessor); + Mockito.when(snssaiSamplesProcessor.processSamplesOfSnnsai(snssai, nfs)).thenReturn(false); + Mockito.doNothing().when(pmDataQueue).putSnssaiToQueue(snssai); + doThrow(new RuntimeException()).when(pmDataQueue).putSnssaiToQueue(snssai); + consumerThread.run(); + assertEquals(1,1); + } + + @Test + public void checkForEnoughSamplesTest(){ + List<String> nfs = new ArrayList<>(); + nfs.add(""); + when(pmDataQueue.checkSamplesInQueue(Mockito.any(), Mockito.anyInt())).thenReturn(false); + doNothing().when(pmDataQueue).putSnssaiToQueue(Mockito.any()); + assertFalse(consumerThread.checkForEnoughSamples(nfs, "")); + + } +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/PmThreadTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/PmThreadTest.java new file mode 100644 index 00000000..6308a21c --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/PmThreadTest.java @@ -0,0 +1,115 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.service; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.onap.slice.analysis.ms.data.repository.PerformanceNotificationsRepository; +import org.onap.slice.analysis.ms.dmaap.NewPmNotification; +import org.onap.slice.analysis.ms.models.MeasurementObject; +import org.onap.slice.analysis.ms.utils.BeanUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.ArgumentMatchers.any; +import static org.powermock.api.mockito.PowerMockito.doNothing; +import static org.powermock.api.mockito.PowerMockito.doThrow; +import static org.powermock.api.mockito.PowerMockito.when; + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ BeanUtil.class }) +@SpringBootTest(classes = PmThreadTest.class) +public class PmThreadTest { + + private PmThread pmThread; + @Mock + private NewPmNotification newPmNotification; + @Mock + private PerformanceNotificationsRepository performanceNotificationsRepository; + @Mock + private IPmEventProcessor pmEventProcessor; + @Mock + private PmDataQueue pmDataQueue; + + @Before + public void before() throws IllegalAccessException { + + PowerMockito.mockStatic(BeanUtil.class); + when(BeanUtil.getBean(NewPmNotification.class)).thenReturn(newPmNotification); + + when(BeanUtil.getBean(PerformanceNotificationsRepository.class)).thenReturn(performanceNotificationsRepository); + + when(BeanUtil.getBean(PmDataQueue.class)).thenReturn(pmDataQueue); + + when(BeanUtil.getBean(IPmEventProcessor.class)).thenReturn(pmEventProcessor); + + pmThread = PowerMockito.spy(new PmThread()); + } + + @Test + public void runTest(){ + + when(newPmNotification.getNewNotif()).thenReturn(true); + + String pmNotificationString = "{" + + " \"event\":{" + + " \"commonEventHeader\":null," + + " \"perf3gppFields\":{" + + " \"perf3gppFieldsVersion\":\"\"," + + " \"measDataCollection\":{" + + " \"granularityPeriod\":1," + + " \"measuredEntityUserName\":\"measuredEntityUserName\"," + + " \"measuredEntityDn\":\"measuredEntityDn\"," + + " \"measuredEntitySoftwareVersion\":\"measuredEntitySoftwareVersion\"," + + " \"measInfoList\":[" + + "" + + " ]" + + " }" + + " }" + + " }" + + "}"; + when(performanceNotificationsRepository.getPerformanceNotificationFromQueue()).thenReturn(pmNotificationString); + + Map<String, List<MeasurementObject>> processedData = new HashMap<>(); + processedData.put("k", null); + when(pmEventProcessor.processEvent(any())).thenReturn(processedData); + doNothing().when(pmDataQueue).putDataToQueue(any(), any()); + doThrow(new RuntimeException()).when(pmDataQueue).putSnssaiToQueue(any()); + pmThread.run(); + Mockito.verify(pmDataQueue, Mockito.times(1)).putDataToQueue(any(), any()); + } + +} diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/SliceUtilizationTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/SliceUtilizationTest.java index 90202366..1de57060 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/SliceUtilizationTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/SliceUtilizationTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2022 Wipro Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,12 +23,12 @@ package org.onap.slice.analysis.ms.service; import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertTrue; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; +import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; @@ -49,13 +50,9 @@ import org.onap.slice.analysis.ms.models.Configuration; import org.onap.slice.analysis.ms.models.SliceConfigRequest; import org.onap.slice.analysis.ms.models.SliceConfigResponse; import org.onap.slice.analysis.ms.restclients.DesRestClient; -import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.modules.junit4.PowerMockRunnerDelegate; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -63,7 +60,6 @@ import org.springframework.test.context.junit4.SpringRunner; @RunWith(PowerMockRunner.class) @PowerMockRunnerDelegate(SpringRunner.class) -@PrepareForTest({SliceUtilization.class, Configuration.class}) @PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "org.xml.*", "javax.management.*"}) @SpringBootTest(classes = SliceUtilizationTest.class) public class SliceUtilizationTest { @@ -90,19 +86,10 @@ public class SliceUtilizationTest { } @Test - public void getPmDataTest() throws Exception { + public void getPmDataTest() throws IOException { configuration.setDesUrl("http://des:1681/datalake/v1/exposure/pm_data"); configuration.setPmDataDurationInWeeks(4); - PowerMockito.mockStatic(SliceUtilization.class); - PowerMockito.mockStatic(Configuration.class); - PowerMockito.when(Configuration.getInstance()).thenReturn(configuration); - String pmData = null; - try { - pmData = new String(Files.readAllBytes(Paths.get("src/test/resources/pm_data.json"))); - } catch (Exception e) { - e.printStackTrace(); - - } + String pmData = new String(Files.readAllBytes(Paths.get("src/test/resources/pm_data.json"))); Mockito.when(desRestClient.sendPostRequest(Mockito.any(), Mockito.any(), Mockito.any())) .thenReturn(new ResponseEntity<>(pmData, HttpStatus.OK)); JSONObject actualResponse = sliceUtilization.getPMData("001-1100"); @@ -111,30 +98,23 @@ public class SliceUtilizationTest { } @Test - public void calculateSliceUtilizationTest() throws Exception { + public void calculateSliceUtilizationTest() throws IOException { - PowerMockito.mockStatic(SliceUtilization.class); List<JSONObject> pmDataList = new ArrayList<>(); String pmData; - try { - pmData = new String(Files.readAllBytes(Paths.get("src/test/resources/pm_data.json"))); - JSONObject pmDataObj = new JSONObject(pmData); - pmDataList.add(pmDataObj); - pmDataList.add(pmDataObj); - pmDataList.add(pmDataObj); - } catch (Exception e) { - e.printStackTrace(); - - } + pmData = new String(Files.readAllBytes(Paths.get("src/test/resources/pm_data.json"))); + JSONObject pmDataObj = new JSONObject(pmData); + pmDataList.add(pmDataObj); + pmDataList.add(pmDataObj); + pmDataList.add(pmDataObj); AggregatedConfig actualResponse = sliceUtilization.calculateSliceUtilization(pmDataList); assertEquals(190857028, (int) actualResponse.getDLThptPerSlice()); assertEquals(119285978, (int) actualResponse.getULThptPerSlice()); } @Test - public void getSliceUtilizationDataTest() throws Exception { + public void getSliceUtilizationDataTest() throws IOException { - PowerMockito.mockStatic(SliceUtilization.class); SliceConfigRequest sliceConfigRequest = new SliceConfigRequest(); List<String> sliceIdentifiersList = new ArrayList<>(); sliceIdentifiersList.add("14559ead-f4fe-4c1c-a94c-8015fad3ea35"); @@ -150,21 +130,11 @@ public class SliceUtilizationTest { configuration.setDesUrl("http://des:1681/datalake/v1/exposure/pm_data"); configuration.setPmDataDurationInWeeks(4); - PowerMockito.mockStatic(SliceUtilization.class); - PowerMockito.mockStatic(Configuration.class); - PowerMockito.when(Configuration.getInstance()).thenReturn(configuration); + Mockito.when(aaiService.getSnssaiList(Mockito.any())).thenReturn(snssaiList); - try { - - Mockito.when(aaiService.getSnssaiList(Mockito.any())).thenReturn(snssaiList); - - String pmData = new String(Files.readAllBytes(Paths.get("src/test/resources/pm_data.json"))); - Mockito.when(desRestClient.sendPostRequest(Mockito.any(), Mockito.any(), Mockito.any())) - .thenReturn(new ResponseEntity<>(pmData, HttpStatus.OK)); - } catch (Exception e) { - e.printStackTrace(); - - } + String pmData = new String(Files.readAllBytes(Paths.get("src/test/resources/pm_data.json"))); + Mockito.when(desRestClient.sendPostRequest(Mockito.any(), Mockito.any(), Mockito.any())) + .thenReturn(new ResponseEntity<>(pmData, HttpStatus.OK)); SliceConfigResponse actualResponse = sliceUtilization.getSliceUtilizationData(sliceConfigRequest); String actualResponseString = objectMapper.writeValueAsString(actualResponse); SliceConfigResponse sliceConfigResponse = objectMapper diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/SnssaiSamplesProcessorTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/SnssaiSamplesProcessorTest.java index e8cc2145..edc4f43b 100644 --- a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/SnssaiSamplesProcessorTest.java +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/service/SnssaiSamplesProcessorTest.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2020 Wipro Limited. + * Copyright (C) 2022 CTC, Inc. * ============================================================================== * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -22,10 +23,18 @@ package org.onap.slice.analysis.ms.service; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.when; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -34,7 +43,15 @@ import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.onap.slice.analysis.ms.aai.AaiInterface; +import org.onap.slice.analysis.ms.configdb.IConfigDbService; +import org.onap.slice.analysis.ms.cps.CpsInterface; +import org.onap.slice.analysis.ms.models.Configuration; import org.onap.slice.analysis.ms.models.MeasurementObject; +import org.onap.slice.analysis.ms.models.SubCounter; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.util.ReflectionTestUtils; @@ -43,151 +60,226 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith(SpringRunner.class) +@PrepareForTest(SnssaiSamplesProcessor.class) @SpringBootTest(classes = SnssaiSamplesProcessorTest.class) public class SnssaiSamplesProcessorTest { - ObjectMapper obj = new ObjectMapper(); - - @InjectMocks - SnssaiSamplesProcessor snssaiSamplesProcessor; - - @Before - public void setup() { - Map<String, Map<String, Integer>> ricToThroughputMapping = new HashMap<>(); - Map<String, Integer> ric1 = new HashMap<>(); - Map<String, Integer> ric2 = new HashMap<>(); - ric1.put("dLThptPerSlice",50); - ric1.put("uLThptPerSlice",40); - ric2.put("dLThptPerSlice",50); - ric2.put("uLThptPerSlice",30); - ricToThroughputMapping.put("1", ric1); - ricToThroughputMapping.put("2", ric2); - ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToThroughputMapping", ricToThroughputMapping); - - Map<String, Map<String, Integer>> ricToPrbsMapping = null; - List<MeasurementObject> sliceMeasList = null; - Map<String, List<String>> ricToCellMapping = null; - Map<String, String> prbThroughputMapping = new HashMap<>(); - prbThroughputMapping = new HashMap<>(); - prbThroughputMapping.put("PrbUsedDl", "dLThptPerSlice"); - prbThroughputMapping.put("PrbUsedUl", "uLThptPerSlice"); - - try { - ricToPrbsMapping = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricToPrbMap.json"))), new TypeReference<Map<String, Map<String, Integer>>>(){}); - sliceMeasList = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/sliceMeasurementList.json"))), new TypeReference<List<MeasurementObject>>(){}); - ricToCellMapping = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricToCellMapping.json"))), new TypeReference<Map<String, List<String>>>(){}); - } - catch (IOException e) { - e.printStackTrace(); - } - ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToPrbsMapping", ricToPrbsMapping); - ReflectionTestUtils.setField(snssaiSamplesProcessor, "minPercentageChange", 6); - ReflectionTestUtils.setField(snssaiSamplesProcessor, "snssaiMeasurementList", sliceMeasList); - ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToCellMapping", ricToCellMapping); - ReflectionTestUtils.setField(snssaiSamplesProcessor, "prbThroughputMapping", prbThroughputMapping); - } - - @Test - public void computeSumTest() { - assertEquals(Integer.valueOf(100), snssaiSamplesProcessor.computeSum("PrbUsedDl")); - } - - @Test - public void updateConfigurationTest() { - Map<String, Map<String, Integer>> ricToThroughputMappingExp = new HashMap<>(); - Map<String, Integer> ric1 = new HashMap<>(); - Map<String, Integer> ric2 = new HashMap<>(); - ric1.put("dLThptPerSlice",50); - ric1.put("uLThptPerSlice",40); - ric2.put("dLThptPerSlice",50); - ric2.put("uLThptPerSlice",30); - ricToThroughputMappingExp.put("1", ric1); - ricToThroughputMappingExp.put("2", ric2); - snssaiSamplesProcessor.updateConfiguration(); - assertEquals(ricToThroughputMappingExp,ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); - } - - @Test - public void updateConfigurationTrueTest() { - Map<String, Map<String, Integer>> ricToThroughputMappingExp = new HashMap<>(); - Map<String, Integer> ric2 = new HashMap<>(); - ric2.put("dLThptPerSlice",50); - ric2.put("uLThptPerSlice",30); - ricToThroughputMappingExp.put("2", ric2); - - Map<String, Map<String, Integer>> ricToThroughputMapping = new HashMap<>(); - Map<String, Integer> ric1 = new HashMap<>(); - ric2 = new HashMap<>(); - ric2.put("dLThptPerSlice",50); - ric2.put("uLThptPerSlice",30); - ricToThroughputMapping.put("1", ric1); - ricToThroughputMapping.put("2", ric2); - ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToThroughputMapping", ricToThroughputMapping); - - snssaiSamplesProcessor.updateConfiguration(); - System.out.println(); - assertEquals(ricToThroughputMappingExp, ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); - } - - @Test - public void calculatePercentageChangeTest() { - Map<String, Map<String, Object>> ricConfiguration = null; - Map<String, Map<String, Integer>> exp = new HashMap<>(); - Map<String, Integer> ric1 = new HashMap<>(); - Map<String, Integer> ric2 = new HashMap<>(); - ric1.put("dLThptPerSlice", 50); - ric2.put("dLThptPerSlice", 50); - ric2.put("uLThptPerSlice", 30); - exp.put("1", ric1); - exp.put("2", ric2); - try { - ricConfiguration = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricConfiguration.json"))), new TypeReference<Map<String, Map<String, Object>>>(){}); - } - catch (IOException e) { - e.printStackTrace(); - } - snssaiSamplesProcessor.calculatePercentageChange(ricConfiguration, "uLThptPerSlice"); - assertEquals(exp,ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); - - ricConfiguration.get("2").put("dLThptPerSlice",60); - exp.get("1").remove("dLThptPerSlice"); - snssaiSamplesProcessor.calculatePercentageChange(ricConfiguration, "dLThptPerSlice"); - assertEquals(exp,ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); - } - - @Test - public void sumOfPrbsAcrossCellsTest() { - Map<String, Map<String, Integer>> ricToPrbsMapping = new HashMap<>(); - Map<String, Map<String, Integer>> ricToPrbsMappingExp = new HashMap<>(); - - ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToPrbsMapping", ricToPrbsMapping); - - try { - ricToPrbsMappingExp = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricToPrbOutput.json"))), new TypeReference<Map<String, Map<String, Integer>>>(){}); - } - catch (IOException e) { - e.printStackTrace(); - } + ObjectMapper obj = new ObjectMapper(); + + @InjectMocks + SnssaiSamplesProcessor snssaiSamplesProcessor; + @Mock + private PolicyService policyService; + + @Mock + private PmDataQueue pmDataQueue; + + @Mock + private AverageCalculator averageCalculator; + + @Mock + private IConfigDbService configDbService; + + @Mock + private AaiInterface aaiInterface; + + @Mock + private CpsInterface cpsInterface; + + @Before + public void setup() throws IOException { + Map<String, Map<String, Integer>> ricToThroughputMapping = new HashMap<>(); + Map<String, Integer> ric1 = new HashMap<>(); + Map<String, Integer> ric2 = new HashMap<>(); + ric1.put("dLThptPerSlice",50); + ric1.put("uLThptPerSlice",40); + ric2.put("dLThptPerSlice",50); + ric2.put("uLThptPerSlice",30); + ricToThroughputMapping.put("1", ric1); + ricToThroughputMapping.put("2", ric2); + ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToThroughputMapping", ricToThroughputMapping); + + Map<String, Map<String, Integer>> ricToPrbsMapping = null; + List<MeasurementObject> sliceMeasList = null; + Map<String, List<String>> ricToCellMapping = null; + Map<String, String> prbThroughputMapping = new HashMap<>(); + prbThroughputMapping = new HashMap<>(); + prbThroughputMapping.put("PrbUsedDl", "dLThptPerSlice"); + prbThroughputMapping.put("PrbUsedUl", "uLThptPerSlice"); + + ricToPrbsMapping = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricToPrbMap.json"))), new TypeReference<Map<String, Map<String, Integer>>>(){}); + sliceMeasList = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/sliceMeasurementList.json"))), new TypeReference<List<MeasurementObject>>(){}); + ricToCellMapping = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricToCellMapping.json"))), new TypeReference<Map<String, List<String>>>(){}); + ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToPrbsMapping", ricToPrbsMapping); + ReflectionTestUtils.setField(snssaiSamplesProcessor, "minPercentageChange", 6); + ReflectionTestUtils.setField(snssaiSamplesProcessor, "snssaiMeasurementList", sliceMeasList); + ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToCellMapping", ricToCellMapping); + ReflectionTestUtils.setField(snssaiSamplesProcessor, "prbThroughputMapping", prbThroughputMapping); + } + + + @Test + public void processSamplesOfSnnsaiTest() { + List<List<MeasurementObject>> samples = new ArrayList<>(); + when(pmDataQueue.getSamplesFromQueue(any(SubCounter.class),anyInt())).thenReturn(samples); + List<MeasurementObject> sample = new ArrayList<>(); + when(averageCalculator.findAverageOfSamples(samples)).thenReturn(sample); + + Map<String, List<String>> ricToCellMapping = new HashMap<>(); + when(configDbService.fetchRICsOfSnssai(any())).thenReturn(ricToCellMapping); + Map<String, Map<String, Object>> ricConfiguration = new HashMap<>(); + when(configDbService.fetchCurrentConfigurationOfRIC(any())).thenReturn(ricConfiguration); + Map<String, Integer> sliceConfiguration = new HashMap<>(); + when(configDbService.fetchCurrentConfigurationOfSlice(any())).thenReturn(sliceConfiguration); + Map<String, String> serviceDetails = new HashMap<>(); + when(configDbService.fetchServiceDetails(any())).thenReturn(serviceDetails); + + List<String> networkFunctions = new ArrayList<>(); + networkFunctions.add("nf1"); + SnssaiSamplesProcessor spy = PowerMockito.spy(snssaiSamplesProcessor); + doNothing().when(spy).sumOfPrbsAcrossCells(anyString()); + doReturn(1).when(spy).computeSum(any()); + doNothing().when(spy).computeThroughput(any(),anyInt(),any()); + doNothing().when(spy).calculatePercentageChange(any(),any()); + doNothing().when(spy).updateConfiguration(); + + Map<String, List<Map<String, Integer>>> map = new HashMap<>(); + doReturn(map).when(spy).getChangedRIConfigFormat(any()); + doNothing().when(policyService).sendOnsetMessageToPolicy(any(),any(), any()); + + spy.init(); + boolean b = spy.processSamplesOfSnnsai("", networkFunctions); + assertTrue(b); + + + } + @Test + public void processSamplesOfSnnsaiFalseTest() { + Configuration.getInstance().setConfigDbEnabled(false); + List<List<MeasurementObject>> samples = new ArrayList<>(); + when(pmDataQueue.getSamplesFromQueue(any(SubCounter.class),anyInt())).thenReturn(samples); + List<MeasurementObject> sample = new ArrayList<>(); + when(averageCalculator.findAverageOfSamples(samples)).thenReturn(sample); + + Map<String, List<String>> ricToCellMapping = new HashMap<>(); + when(cpsInterface.fetchRICsOfSnssai(any())).thenReturn(ricToCellMapping); + Map<String, Map<String, Object>> ricConfiguration = new HashMap<>(); + when(cpsInterface.fetchCurrentConfigurationOfRIC(any())).thenReturn(ricConfiguration); + Map<String, Integer> sliceConfiguration = new HashMap<>(); + when(aaiInterface.fetchCurrentConfigurationOfSlice(any())).thenReturn(sliceConfiguration); + Map<String, String> serviceDetails = new HashMap<>(); + when(aaiInterface.fetchServiceDetails(any())).thenReturn(serviceDetails); + + + List<String> networkFunctions = new ArrayList<>(); + networkFunctions.add("nf1"); + SnssaiSamplesProcessor spy = PowerMockito.spy(snssaiSamplesProcessor); + doNothing().when(spy).sumOfPrbsAcrossCells(anyString()); + doReturn(1).when(spy).computeSum(any()); + doNothing().when(spy).computeThroughput(any(),anyInt(),any()); + doNothing().when(spy).calculatePercentageChange(any(),any()); + doNothing().when(spy).updateConfiguration(); + + Map<String, List<Map<String, Integer>>> map = new HashMap<>(); + doReturn(map).when(spy).getChangedRIConfigFormat(any()); + doNothing().when(policyService).sendOnsetMessageToPolicy(any(),any(), any()); + + spy.init(); + boolean b = spy.processSamplesOfSnnsai("", networkFunctions); + assertTrue(b); + } + @Test + public void getChangedRIConfigFormatTest() { + Map<String, Map<String, Integer>> ricToThroughputMapping = new HashMap<>(); + Map<String, Integer> newConfigMap = new HashMap<>(); + ricToThroughputMapping.put("1", newConfigMap); + Map<String, List<Map<String, Integer>>> riConfigFormat = snssaiSamplesProcessor.getChangedRIConfigFormat(ricToThroughputMapping); + assertEquals(1, riConfigFormat.size()); + + } + + @Test + public void computeSumTest() { + assertEquals(Integer.valueOf(100), snssaiSamplesProcessor.computeSum("PrbUsedDl")); + } + + @Test + public void updateConfigurationTest() { + Map<String, Map<String, Integer>> ricToThroughputMappingExp = new HashMap<>(); + Map<String, Integer> ric1 = new HashMap<>(); + Map<String, Integer> ric2 = new HashMap<>(); + ric1.put("dLThptPerSlice",50); + ric1.put("uLThptPerSlice",40); + ric2.put("dLThptPerSlice",50); + ric2.put("uLThptPerSlice",30); + ricToThroughputMappingExp.put("1", ric1); + ricToThroughputMappingExp.put("2", ric2); + snssaiSamplesProcessor.updateConfiguration(); + assertEquals(ricToThroughputMappingExp,ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); + } + + @Test + public void updateConfigurationTrueTest() { + Map<String, Map<String, Integer>> ricToThroughputMappingExp = new HashMap<>(); + Map<String, Integer> ric2 = new HashMap<>(); + ric2.put("dLThptPerSlice",50); + ric2.put("uLThptPerSlice",30); + ricToThroughputMappingExp.put("2", ric2); + + Map<String, Map<String, Integer>> ricToThroughputMapping = new HashMap<>(); + Map<String, Integer> ric1 = new HashMap<>(); + ric2 = new HashMap<>(); + ric2.put("dLThptPerSlice",50); + ric2.put("uLThptPerSlice",30); + ricToThroughputMapping.put("1", ric1); + ricToThroughputMapping.put("2", ric2); + ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToThroughputMapping", ricToThroughputMapping); + + snssaiSamplesProcessor.updateConfiguration(); + System.out.println(); + assertEquals(ricToThroughputMappingExp, ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); + } + + @Test + public void calculatePercentageChangeTest() throws IOException { + Map<String, Map<String, Integer>> exp = new HashMap<>(); + Map<String, Integer> ric1 = new HashMap<>(); + Map<String, Integer> ric2 = new HashMap<>(); + ric1.put("dLThptPerSlice", 50); + ric2.put("dLThptPerSlice", 50); + ric2.put("uLThptPerSlice", 30); + exp.put("1", ric1); + exp.put("2", ric2); + Map<String, Map<String, Object>> ricConfiguration = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricConfiguration.json"))), new TypeReference<Map<String, Map<String, Object>>>(){}); + snssaiSamplesProcessor.calculatePercentageChange(ricConfiguration, "uLThptPerSlice"); + assertEquals(exp,ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); + + ricConfiguration.get("2").put("dLThptPerSlice",60); + exp.get("1").remove("dLThptPerSlice"); + snssaiSamplesProcessor.calculatePercentageChange(ricConfiguration, "dLThptPerSlice"); + assertEquals(exp,ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); + } + + @Test + public void sumOfPrbsAcrossCellsTest() throws IOException { + Map<String, Map<String, Integer>> ricToPrbsMapping = new HashMap<>(); + ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToPrbsMapping", ricToPrbsMapping); + + Map<String, Map<String, Integer>> ricToPrbsMappingExp = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricToPrbOutput.json"))), new TypeReference<Map<String, Map<String, Integer>>>(){}); snssaiSamplesProcessor.sumOfPrbsAcrossCells("PrbUsedDl"); assertEquals(ricToPrbsMappingExp, ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToPrbsMapping")); - } - - @Test - public void computeThroughputTest() { - Map<String, Map<String, Integer>> ricToThroughputMapping = new HashMap<>(); - ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToThroughputMapping", ricToThroughputMapping); - - Map<String, Map<String, Integer>> ricToThroughputMappingExp = new HashMap<>(); - try { - ricToThroughputMappingExp = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricToThroughputMappingOutput.json"))), new TypeReference<Map<String, Map<String, Integer>>>(){}); - } - catch (IOException e) { - e.printStackTrace(); - } - Map<String, Integer> sliceConfiguration = new HashMap<String, Integer>(); - sliceConfiguration.put("dLThptPerSlice",120); - sliceConfiguration.put("uLThptPerSlice",100); - snssaiSamplesProcessor.computeThroughput(sliceConfiguration, 100, "PrbUsedDl"); - snssaiSamplesProcessor.computeThroughput(sliceConfiguration, 70, "PrbUsedUl"); - assertEquals(ricToThroughputMappingExp, ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); - } + } + + @Test + public void computeThroughputTest() throws IOException { + Map<String, Map<String, Integer>> ricToThroughputMapping = new HashMap<>(); + ReflectionTestUtils.setField(snssaiSamplesProcessor, "ricToThroughputMapping", ricToThroughputMapping); + + Map<String, Map<String, Integer>> ricToThroughputMappingExp = obj.readValue(new String(Files.readAllBytes(Paths.get("src/test/resources/ricToThroughputMappingOutput.json"))), new TypeReference<Map<String, Map<String, Integer>>>(){}); + Map<String, Integer> sliceConfiguration = new HashMap<String, Integer>(); + sliceConfiguration.put("dLThptPerSlice",120); + sliceConfiguration.put("uLThptPerSlice",100); + snssaiSamplesProcessor.computeThroughput(sliceConfiguration, 100, "PrbUsedDl"); + snssaiSamplesProcessor.computeThroughput(sliceConfiguration, 70, "PrbUsedUl"); + assertEquals(ricToThroughputMappingExp, ReflectionTestUtils.getField(snssaiSamplesProcessor, "ricToThroughputMapping")); + } } diff --git a/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/utils/DcaeDmaapUtilTest.java b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/utils/DcaeDmaapUtilTest.java new file mode 100644 index 00000000..b77378a6 --- /dev/null +++ b/components/slice-analysis-ms/src/test/java/org/onap/slice/analysis/ms/utils/DcaeDmaapUtilTest.java @@ -0,0 +1,67 @@ +/******************************************************************************* + * ============LICENSE_START======================================================= + * slice-analysis-ms + * ================================================================================ + * Copyright (C) 2022 CTC, Inc. + * ============================================================================== + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + * + *******************************************************************************/ + +package org.onap.slice.analysis.ms.utils; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterPublisher; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterSubscriber; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterPublishRequest; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterSubscribeRequest; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.junit.Assert.assertNotNull; +import static org.onap.slice.analysis.ms.utils.DcaeDmaapUtil.buildPublisher; +import static org.onap.slice.analysis.ms.utils.DcaeDmaapUtil.buildPublisherRequest; +import static org.onap.slice.analysis.ms.utils.DcaeDmaapUtil.buildSubscriber; +import static org.onap.slice.analysis.ms.utils.DcaeDmaapUtil.buildSubscriberRequest; + +@RunWith(SpringRunner.class) +@SpringBootTest(classes = DcaeDmaapUtilTest.class) +public class DcaeDmaapUtilTest { + + @Test + public void buildSubscriberTest(){ + MessageRouterSubscriber subscriber = buildSubscriber(); + assertNotNull(subscriber); + } + + @Test + public void buildSubscriberRequestTest(){ + MessageRouterSubscribeRequest request = buildSubscriberRequest("name", "url"); + assertNotNull(request); + } + + @Test + public void buildPublisherTest(){ + MessageRouterPublisher publisher = buildPublisher(); + assertNotNull(publisher); + } + + @Test + public void buildPublisherRequestTest(){ + MessageRouterPublishRequest request = buildPublisherRequest("name", "url"); + assertNotNull(request); + } + +} |