diff options
author | zhaoyh6 <zhaoyh6@asiainfo.com> | 2022-07-28 16:33:38 +0800 |
---|---|---|
committer | zhao yehua <zhaoyh6@asiainfo.com> | 2022-08-08 02:11:59 +0000 |
commit | 61f9c604018a27bf9438415aca03d05dc9974dcb (patch) | |
tree | e15678f9104d488c9c1c2cbf2a39dba59aa458fa /components | |
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')
37 files changed, 1986 insertions, 815 deletions
diff --git a/components/slice-analysis-ms/ChangeLog.md b/components/slice-analysis-ms/ChangeLog.md index 13209eda..08bc5b5d 100644 --- a/components/slice-analysis-ms/ChangeLog.md +++ b/components/slice-analysis-ms/ChangeLog.md @@ -4,6 +4,9 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). +## [1.1.4] - 2022/07/28 + - [DCAEGEN2-3120](https://jira.onap.org/browse/DCAEGEN2-3120) - Enhance sliceanalysis MS to use DCAE SDK dmaap-client lib + ## [1.1.3] - 2022/05/11 - [DCAEGEN2-3156](https://jira.onap.org/browse/DCAEGEN2-3156) - Fix bug in fetching PM data from DES diff --git a/components/slice-analysis-ms/pom.xml b/components/slice-analysis-ms/pom.xml index 21c62aab..f72f8d83 100644 --- a/components/slice-analysis-ms/pom.xml +++ b/components/slice-analysis-ms/pom.xml @@ -6,6 +6,7 @@ * ================================================================================ * Copyright (C) 2020-2022 Wipro Limited. * 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. @@ -34,7 +35,7 @@ </parent> <groupId>org.onap.dcaegen2.services.components</groupId> <artifactId>slice-analysis-ms</artifactId> - <version>1.1.3-SNAPSHOT</version> + <version>1.1.4-SNAPSHOT</version> <name>dcaegen2-services-slice-analysis-ms</name> <description>Network slice PM analyser</description> <packaging>jar</packaging> @@ -57,6 +58,11 @@ </sonar.coverage.jacoco.xmlReportPaths> </properties> <dependencies> + <dependency> + <groupId>com.google.code.gson</groupId> + <artifactId>gson</artifactId> + <version>2.9.0</version> + </dependency> <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-util --> <dependency> <groupId>org.apache.tomcat</groupId> @@ -110,6 +116,17 @@ <version>3.4</version> </dependency> <dependency> + <groupId>io.projectreactor</groupId> + <artifactId>reactor-core</artifactId> + <version>3.4.18</version> + </dependency> + <dependency> + <groupId>io.projectreactor</groupId> + <artifactId>reactor-test</artifactId> + <version>3.4.18</version> + <scope>test</scope> + </dependency> + <dependency> <groupId>org.onap.dmaap.messagerouter.dmaapclient</groupId> <artifactId>dmaapClient</artifactId> <version>1.1.12</version> @@ -135,6 +152,16 @@ <version>${sdk.version}</version> </dependency> <dependency> + <groupId>org.onap.dcaegen2.services.sdk.rest.services</groupId> + <artifactId>dmaap-client</artifactId> + <version>${sdk.version}</version> + </dependency> + <dependency> + <groupId>org.onap.dcaegen2.services.sdk.rest.services</groupId> + <artifactId>http-client</artifactId> + <version>${sdk.version}</version> + </dependency> + <dependency> <groupId>org.onap.dcaegen2.services.sdk.security.crypt</groupId> <artifactId>crypt-password</artifactId> <version>${sdk.version}</version> @@ -148,11 +175,6 @@ <scope>import</scope> </dependency> <dependency> - <groupId>com.att.nsa</groupId> - <artifactId>cambriaClient</artifactId> - <version>0.0.1</version> - </dependency> - <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> @@ -314,6 +336,30 @@ <version>1.18.22</version> <scope>provided</scope> </dependency> + <dependency> + <groupId>org.onap.dcaegen2.services.sdk.rest.services</groupId> + <artifactId>dmaap-client</artifactId> + <version>1.8.7</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>org.onap.dcaegen2.services.sdk.rest.services</groupId> + <artifactId>dmaap-client</artifactId> + <version>1.8.7</version> + <scope>compile</scope> + </dependency> + <dependency> + <groupId>io.projectreactor</groupId> + <artifactId>reactor-core</artifactId> + <version>3.4.18</version> + <scope>test</scope> + </dependency> + <dependency> + <groupId>io.projectreactor</groupId> + <artifactId>reactor-core</artifactId> + <version>3.4.18</version> + <scope>compile</scope> + </dependency> </dependencies> <build> <plugins> diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/AaiEventNotificationCallback.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/AaiEventNotificationCallback.java index 0259f130..9bff14a0 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/AaiEventNotificationCallback.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/AaiEventNotificationCallback.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. @@ -105,7 +106,7 @@ public class AaiEventNotificationCallback implements NotificationCallback { } JsonObject entity = jsonObject.get(ENTITY).getAsJsonObject(); JsonObject body = getNestedJsonObject(entity, aaiNotifTargetEntity); - logger.debug("AAI-EVENT entity object {}", body); + logger.info("AAI-EVENT entity object {}", body); if (body == null){ return; } diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/DmaapClient.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/DmaapClient.java index ad5941a4..6e4dbe18 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/DmaapClient.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/DmaapClient.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2020 Wipro Limited. * 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. @@ -29,15 +30,15 @@ import java.util.concurrent.TimeUnit; import javax.annotation.PostConstruct; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterSubscriber; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterSubscribeRequest; 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.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; -import com.att.nsa.cambria.client.CambriaConsumer; - /** * This class initializes and starts the dmaap client * to listen on application required dmaap events @@ -49,8 +50,6 @@ public class DmaapClient { private Configuration configuration; private static Logger log = LoggerFactory.getLogger(DmaapClient.class); - private DmaapUtils dmaapUtils; - @Autowired private IntelligentSlicingCallback intelligentSlicingCallback; @@ -66,7 +65,6 @@ public class DmaapClient { @PostConstruct public void initClient() { log.debug("initializing client"); - dmaapUtils = new DmaapUtils(); configuration = Configuration.getInstance(); if (log.isDebugEnabled()) { log.debug(configuration.toString()); @@ -85,39 +83,33 @@ public class DmaapClient { String pmTopicUrl = ((Map<String, String>) ((Map<String, Object>) streamSubscribes .get("performance_management_topic")).get("dmaap_info")).get("topic_url"); - String[] pmTopicSplit = pmTopicUrl.split("\\/"); - String pmTopic = pmTopicSplit[pmTopicSplit.length - 1]; - log.debug("pm topic : {}", pmTopic); String policyResponseTopicUrl = ((Map<String, String>) ((Map<String, Object>) streamSubscribes .get("dcae_cl_response_topic")).get("dmaap_info")).get("topic_url"); - String[] policyResponseTopicUrlSplit = policyResponseTopicUrl.split("\\/"); - String policyResponseTopic = policyResponseTopicUrlSplit[policyResponseTopicUrlSplit.length - 1]; - log.debug("policyResponse Topic : {}", policyResponseTopic); String intelligentSlicingTopicUrl = ((Map<String, String>) ((Map<String, Object>) streamSubscribes .get("intelligent_slicing_topic")).get("dmaap_info")).get("topic_url"); - String[] intelligentSlicingTopicSplit = intelligentSlicingTopicUrl.split("\\/"); - String intelligentSlicingTopic = intelligentSlicingTopicSplit[intelligentSlicingTopicSplit.length - 1]; - log.debug("intelligent slicing topic : {}", pmTopic); // Parsing ccvpn notification topic String ccvpnNotiTopicUrl = ((Map<String, String>) ((Map<String, Object>) streamSubscribes .get("ves_ccvpn_notification_topic")).get("dmaap_info")).get("topic_url"); - String[] ccvpnNotiTopicSplit = ccvpnNotiTopicUrl.split("\\/"); - String ccvpnNotiTopic = ccvpnNotiTopicSplit[ccvpnNotiTopicSplit.length - 1]; - log.debug("ccvpn notification topic : {}", ccvpnNotiTopic); - CambriaConsumer pmNotifCambriaConsumer = dmaapUtils.buildConsumer(configuration, pmTopic); - CambriaConsumer policyResponseCambriaConsumer = dmaapUtils.buildConsumer(configuration, policyResponseTopic); - CambriaConsumer intelligentSlicingCambriaConsumer = dmaapUtils.buildConsumer(configuration, intelligentSlicingTopic); - // Creating ccvpn notification cambriaconsumer - CambriaConsumer ccvpnNotiCambriaConsumer = dmaapUtils.buildConsumer(configuration, ccvpnNotiTopic); + MessageRouterSubscriber pmNotifSubscriber = DcaeDmaapUtil.buildSubscriber(); + MessageRouterSubscribeRequest pmNotifReqest = DcaeDmaapUtil.buildSubscriberRequest("performance_management_topic", pmTopicUrl); + + MessageRouterSubscriber policyNotifSubscriber = DcaeDmaapUtil.buildSubscriber(); + MessageRouterSubscribeRequest policyNotifReqest = DcaeDmaapUtil.buildSubscriberRequest("dcae_cl_response_topic", policyResponseTopicUrl); + + MessageRouterSubscriber intelligentSlicingSubscriber = DcaeDmaapUtil.buildSubscriber(); + MessageRouterSubscribeRequest intelligentSlicingReqest = DcaeDmaapUtil.buildSubscriberRequest("intelligent_slicing_topic", intelligentSlicingTopicUrl); + + MessageRouterSubscriber ccvpnNotiSubscriber = DcaeDmaapUtil.buildSubscriber(); + MessageRouterSubscribeRequest ccvpnNotiReqest = DcaeDmaapUtil.buildSubscriberRequest("ves_ccvpn_notification_topic", ccvpnNotiTopicUrl); ScheduledExecutorService executorPool; // create notification consumers for PM - NotificationConsumer pmNotificationConsumer = new NotificationConsumer(pmNotifCambriaConsumer, + NotificationConsumer pmNotificationConsumer = new NotificationConsumer(pmNotifSubscriber, pmNotifReqest, new PmNotificationCallback()); // start pm notification consumer threads executorPool = Executors.newScheduledThreadPool(10); @@ -125,7 +117,7 @@ public class DmaapClient { TimeUnit.SECONDS); // create notification consumers for Policy - NotificationConsumer policyNotificationConsumer = new NotificationConsumer(policyResponseCambriaConsumer, + NotificationConsumer policyNotificationConsumer = new NotificationConsumer(policyNotifSubscriber, policyNotifReqest, new PolicyNotificationCallback()); // start policy notification consumer threads executorPool = Executors.newScheduledThreadPool(10); @@ -133,7 +125,7 @@ public class DmaapClient { TimeUnit.SECONDS); // create notification consumers for ML MS - NotificationConsumer intelligentSlicingConsumer = new NotificationConsumer(intelligentSlicingCambriaConsumer, + NotificationConsumer intelligentSlicingConsumer = new NotificationConsumer(intelligentSlicingSubscriber, intelligentSlicingReqest, intelligentSlicingCallback); // start intelligent Slicing notification consumer threads executorPool = Executors.newScheduledThreadPool(10); @@ -141,15 +133,19 @@ public class DmaapClient { TimeUnit.SECONDS); // create notification consumers for ccvpn close-loop PM - NotificationConsumer ccvpnNotiConsumer = new NotificationConsumer(ccvpnNotiCambriaConsumer, + NotificationConsumer ccvpnNotiConsumer = new NotificationConsumer(ccvpnNotiSubscriber, ccvpnNotiReqest, vesNotificationCallback); executorPool = Executors.newScheduledThreadPool(1); executorPool.scheduleWithFixedDelay(ccvpnNotiConsumer, 0, configuration.getVesNotifPollingInterval(), TimeUnit.SECONDS); // start AAI-EVENT dmaap topic monitor - MRTopicMonitor mrTopicMonitor = new MRTopicMonitor(AAI_SUBSCRIBER, aaiEventNotificationCallback); + MRTopicMonitor mrTopicMonitor = getMRTopicMonitor(); mrTopicMonitor.start(); } + public MRTopicMonitor getMRTopicMonitor() { + return new MRTopicMonitor(AAI_SUBSCRIBER, aaiEventNotificationCallback); + } + } diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/MRTopicMonitor.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/MRTopicMonitor.java index aa1bc964..f3330dc3 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/MRTopicMonitor.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/MRTopicMonitor.java @@ -3,6 +3,7 @@ * ONAP * ================================================================================ * 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,23 +22,23 @@ package org.onap.slice.analysis.ms.dmaap; import com.google.gson.Gson; +import com.google.gson.JsonElement; import com.google.gson.JsonObject; +import io.vavr.collection.List; import lombok.Getter; import lombok.NonNull; -import org.onap.dmaap.mr.client.impl.MRConsumerImpl; -import org.onap.dmaap.mr.client.response.MRConsumerResponse; -import org.onap.dmaap.mr.test.clients.ProtocolTypeConstants; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterSubscriber; +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.onap.slice.analysis.ms.models.Configuration; -import org.onap.slice.analysis.ms.dmaap.MRTopicParams; +import org.onap.slice.analysis.ms.utils.DcaeDmaapUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; import java.io.IOException; -import java.net.MalformedURLException; -import java.util.ArrayList; import java.util.Map; -import java.util.Properties; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.Executors; @@ -92,11 +93,11 @@ public class MRTopicMonitor implements Runnable { while (running){ try { logger.debug("Topic: {} getting new msg...", name); - Iterable<String> dmaapMsgs = consumerWrapper.fetch(); - for (String msg : dmaapMsgs){ + List<JsonElement> dmaapMsgs = consumerWrapper.fetch(); + for (JsonElement msg : dmaapMsgs){ logger.debug("Received message: {}" + "\r\n and processing start", msg); - process(msg); + process(msg.toString()); } } catch (IOException | RuntimeException e){ logger.error("fetchMessage encountered error: {}", e); @@ -123,7 +124,7 @@ public class MRTopicMonitor implements Runnable { } } - private Iterable<String> fetch() throws IOException { + private List<JsonElement> fetch() throws IOException { return this.consumerWrapper.fetch(); } @@ -159,10 +160,8 @@ public class MRTopicMonitor implements Runnable { */ private final CountDownLatch closeCondition = new CountDownLatch(1); - /** - * MR Consumer. - */ - protected MRConsumerImpl consumer; + protected MessageRouterSubscriber subscriber; + protected MessageRouterSubscribeRequest request; /** * Constructs the object. @@ -188,42 +187,13 @@ public class MRTopicMonitor implements Runnable { } try{ - this.consumer = new MRConsumerImpl.MRConsumerImplBuilder() - .setHostPart(MRTopicParams.getServers()) - .setTopic(MRTopicParams.getTopic()) - .setConsumerGroup(MRTopicParams.getConsumerGroup()) - .setConsumerId(MRTopicParams.getConsumerInstance()) - .setTimeoutMs(MRTopicParams.getFetchTimeout()) - .setLimit(MRTopicParams.getFetchLimit()) - .setApiKey(MRTopicParams.getApiKey()) - .setApiSecret(MRTopicParams.getApiSecret()) - .createMRConsumerImpl(); - } catch (MalformedURLException e) { - throw new IllegalArgumentException("Illegal MrConsumer parameters"); - } - - - this.consumer.setUsername(MRTopicParams.getUserName()); - this.consumer.setPassword(MRTopicParams.getPassword()); - - if(MRTopicParams.isUserNameValid() && MRTopicParams.isPasswordValid()){ - this.consumer.setProtocolFlag(ProtocolTypeConstants.AAF_AUTH.getValue()); - } else { - this.consumer.setProtocolFlag(ProtocolTypeConstants.HTTPNOAUTH.getValue()); - } - - Properties props = new Properties(); - - if (MRTopicParams.isUseHttps()) { - props.setProperty(PROTOCOL_PROP, "https"); - this.consumer.setHost(MRTopicParams.getServers().get(0) + ":3905"); + this.subscriber = DcaeDmaapUtil.buildSubscriber(); + this.request = DcaeDmaapUtil.buildSubscriberRequest("aai_subscriber", MRTopicParams.getTopic()); - } else { - props.setProperty(PROTOCOL_PROP, "http"); - this.consumer.setHost(MRTopicParams.getServers().get(0) + ":3904"); + } catch (Exception e) { + throw new IllegalArgumentException("Illegal MrConsumer parameters"); } - this.consumer.setProps(props); } /** @@ -231,31 +201,12 @@ public class MRTopicMonitor implements Runnable { * @return * @throws IOException */ - public Iterable<String> fetch() throws IOException { - final MRConsumerResponse response = this.consumer.fetchWithReturnConsumerResponse(); - if (response == null) { - logger.warn("{}: DMaaP NULL response received", this); - - sleepAfterFetchFailure(); - return new ArrayList<>(); - } else { - logger.debug("DMaaP consumer received {} : {}", response.getResponseCode(), - response.getResponseMessage()); - - if (!"200".equals(response.getResponseCode())) { - - logger.error("DMaaP consumer received: {} : {}", response.getResponseCode(), - response.getResponseMessage()); + public List<JsonElement> fetch() throws IOException { + Mono<MessageRouterSubscribeResponse> responses = this.subscriber.get(this.request); + MessageRouterSubscribeResponse resp = responses.block(); + List<JsonElement> list = resp.items(); + return list; - sleepAfterFetchFailure(); - } - } - - if (response.getActualMessages() == null) { - return new ArrayList<>(); - } else { - return response.getActualMessages(); - } } /** @@ -280,7 +231,6 @@ public class MRTopicMonitor implements Runnable { */ public void close() { this.closeCondition.countDown(); - this.consumer.close(); } } } diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/MRTopicParams.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/MRTopicParams.java index e5aaa1e3..26f16baf 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/MRTopicParams.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/MRTopicParams.java @@ -3,9 +3,10 @@ * ONAP * ================================================================================ * Copyright (C) 2018 Samsung Electronics Co., Ltd. All rights reserved. - * Modifications Copyright (C) 2018-2019, 2021 AT&T Intellectual Property. All rights reserved. - * Modifications Copyright (C) 2019 Nordix Foundation. - * Modifications Copyright (C) 2022 Huawei Canada Limited. + * Copyright (C) 2018-2019, 2021 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2019 Nordix Foundation. + * 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. @@ -329,7 +330,7 @@ public class MRTopicParams { String[] pmTopicSplit = topicUrl.split("\\/"); topic = pmTopicSplit[pmTopicSplit.length - 1]; - this.params.topic = topic; + this.params.topic = topicUrl; this.params.servers = servers; this.params.consumerGroup = consumerGroup; this.params.consumerInstance = consumerInstance; diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/NotificationConsumer.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/NotificationConsumer.java index b605264c..b17eb182 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/NotificationConsumer.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/NotificationConsumer.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. @@ -21,10 +22,14 @@ package org.onap.slice.analysis.ms.dmaap; -import com.att.nsa.cambria.client.CambriaConsumer; - +import com.google.gson.JsonElement; +import io.vavr.collection.List; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterSubscriber; +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.slf4j.Logger; import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; /** * Consume Notifications from DMAAP events @@ -32,15 +37,17 @@ import org.slf4j.LoggerFactory; public class NotificationConsumer implements Runnable { private static Logger log = LoggerFactory.getLogger(NotificationConsumer.class); - private CambriaConsumer cambriaConsumer; private NotificationCallback notificationCallback; + private MessageRouterSubscriber subscriber; + private MessageRouterSubscribeRequest request; /** * Parameterized Constructor. */ - public NotificationConsumer(CambriaConsumer cambriaConsumer, NotificationCallback notificationCallback) { + public NotificationConsumer(MessageRouterSubscriber subscriber, MessageRouterSubscribeRequest request, NotificationCallback notificationCallback) { super(); - this.cambriaConsumer = cambriaConsumer; + this.subscriber = subscriber; + this.request = request; this.notificationCallback = notificationCallback; } @@ -50,9 +57,14 @@ public class NotificationConsumer implements Runnable { @Override public void run() { try { - Iterable<String> msgs = cambriaConsumer.fetch(); - for (String msg : msgs) { - log.debug(msg); + Mono<MessageRouterSubscribeResponse> responses = this.subscriber.get(this.request); + + MessageRouterSubscribeResponse resp = responses.block(); + log.debug(resp.toString()); + + List<JsonElement> list = resp.items(); + for(int i=0; i<list.size(); i++){ + String msg = list.get(i).toString(); notificationCallback.activateCallBack(msg); } } catch (Exception e) { diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/NotificationProducer.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/NotificationProducer.java index ce362019..55f24a65 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/NotificationProducer.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/NotificationProducer.java @@ -3,6 +3,7 @@ * slice-analysis-ms * ================================================================================ * Copyright (C) 2020-2021 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. @@ -21,7 +22,11 @@ package org.onap.slice.analysis.ms.dmaap; -import com.att.nsa.cambria.client.CambriaBatchingPublisher; +import com.google.gson.JsonPrimitive; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterPublisher; +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 reactor.core.publisher.Flux; import java.io.IOException; @@ -30,21 +35,25 @@ import java.io.IOException; */ public class NotificationProducer { - private CambriaBatchingPublisher cambriaBatchingPublisher; + private MessageRouterPublisher publisher; + private MessageRouterPublishRequest request; /** * Parameterized constructor. */ - public NotificationProducer(CambriaBatchingPublisher cambriaBatchingPublisher) { + public NotificationProducer(MessageRouterPublisher publisher, MessageRouterPublishRequest request) { super(); - this.cambriaBatchingPublisher = cambriaBatchingPublisher; + this.publisher = publisher; + this.request = request; } /** * sends notification to dmaap. */ - public int sendNotification(String msg) throws IOException { - return cambriaBatchingPublisher.send("", msg); + public void sendNotification(String msg) throws IOException { + Flux<JsonPrimitive> singleMessage = Flux.just(msg).map(JsonPrimitive::new); + Flux<MessageRouterPublishResponse> result = this.publisher.put(request, singleMessage); + result.then().block(); } } diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/PolicyDmaapClient.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/PolicyDmaapClient.java index 06604040..04ee151f 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/PolicyDmaapClient.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/dmaap/PolicyDmaapClient.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. @@ -21,24 +22,22 @@ package org.onap.slice.analysis.ms.dmaap; -import com.att.nsa.cambria.client.CambriaBatchingPublisher; import java.io.IOException; import java.util.Map; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.MessageRouterPublisher; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.MessageRouterPublishRequest; import org.onap.slice.analysis.ms.models.Configuration; -import org.onap.slice.analysis.ms.utils.DmaapUtils; +import org.onap.slice.analysis.ms.utils.DcaeDmaapUtil; /** * Client class to handle Policy interactions */ public class PolicyDmaapClient { - private DmaapUtils dmaapUtils; - private Configuration configuration; - public PolicyDmaapClient(DmaapUtils dmaapUtils, Configuration configuration) { - this.dmaapUtils = dmaapUtils; + public PolicyDmaapClient(Configuration configuration) { this.configuration = configuration; } @@ -50,14 +49,11 @@ public class PolicyDmaapClient { Map<String, Object> streamsPublishes = configuration.getStreamsPublishes(); String policyTopicUrl = ((Map<String, String>) ((Map<String, Object>) streamsPublishes.get("CL_topic")) .get("dmaap_info")).get("topic_url"); - String[] policyTopicSplit = policyTopicUrl.split("\\/"); - String policyTopic = policyTopicSplit[policyTopicSplit.length - 1]; - CambriaBatchingPublisher cambriaBatchingPublisher; try { + MessageRouterPublisher publisher = DcaeDmaapUtil.buildPublisher(); + MessageRouterPublishRequest request = DcaeDmaapUtil.buildPublisherRequest("CL_topic", policyTopicUrl); - cambriaBatchingPublisher = dmaapUtils.buildPublisher(configuration, policyTopic); - - NotificationProducer notificationProducer = new NotificationProducer(cambriaBatchingPublisher); + NotificationProducer notificationProducer = new NotificationProducer(publisher, request); notificationProducer.sendNotification(msg); } catch (IOException e) { return false; diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/PolicyService.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/PolicyService.java index 729fdc5a..24aeea61 100644 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/PolicyService.java +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/service/PolicyService.java @@ -4,6 +4,7 @@ * ================================================================================ * Copyright (C) 2020-2021 Wipro Limited. * 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. @@ -39,7 +40,6 @@ import org.onap.slice.analysis.ms.models.policy.Payload; import org.onap.slice.analysis.ms.models.policy.Sla; import org.onap.slice.analysis.ms.models.policy.TransportNetwork; import org.onap.slice.analysis.ms.service.ccvpn.RequestOwner; -import org.onap.slice.analysis.ms.utils.DmaapUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -61,7 +61,7 @@ public class PolicyService { @PostConstruct public void init() { Configuration configuration = Configuration.getInstance(); - policyDmaapClient = new PolicyDmaapClient(new DmaapUtils(), configuration); + policyDmaapClient = new PolicyDmaapClient(configuration); } protected <T> OnsetMessage formPolicyOnsetMessage(String snssai, AdditionalProperties<T> addProps, Map<String, String> serviceDetails) { diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/utils/DcaeDmaapUtil.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/utils/DcaeDmaapUtil.java new file mode 100644 index 00000000..9a5bf711 --- /dev/null +++ b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/utils/DcaeDmaapUtil.java @@ -0,0 +1,89 @@ +/******************************************************************************* + * ============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.onap.dcaegen2.services.sdk.model.streams.dmaap.ImmutableMessageRouterSink; +import org.onap.dcaegen2.services.sdk.model.streams.dmaap.ImmutableMessageRouterSource; +import org.onap.dcaegen2.services.sdk.model.streams.dmaap.MessageRouterSink; +import org.onap.dcaegen2.services.sdk.model.streams.dmaap.MessageRouterSource; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.ContentType; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.api.DmaapClientFactory; +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.ImmutableMessageRouterPublishRequest; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.ImmutableMessageRouterSubscribeRequest; +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.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.config.ImmutableDmaapConnectionPoolConfig; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.config.ImmutableMessageRouterSubscriberConfig; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.config.MessageRouterPublisherConfig; +import org.onap.dcaegen2.services.sdk.rest.services.dmaap.client.model.config.MessageRouterSubscriberConfig; +import org.onap.slice.analysis.ms.models.Configuration; + +public class DcaeDmaapUtil { + public static MessageRouterSubscriber buildSubscriber(){ + MessageRouterSubscriberConfig connectionPoolConfiguration = ImmutableMessageRouterSubscriberConfig.builder() + .connectionPoolConfig(ImmutableDmaapConnectionPoolConfig.builder() + .connectionPool(16) + .maxIdleTime(10) //in seconds + .maxLifeTime(20) //in seconds + .build()) + .build(); + + MessageRouterSubscriber cut = DmaapClientFactory.createMessageRouterSubscriber(connectionPoolConfiguration); + return cut; + } + + public static MessageRouterSubscribeRequest buildSubscriberRequest(String name, String topicUrl){ + MessageRouterSource sourceDefinition = ImmutableMessageRouterSource.builder() + .name(name) + .topicUrl(topicUrl) + .build(); + MessageRouterSubscribeRequest request = ImmutableMessageRouterSubscribeRequest.builder() + .consumerGroup("1") + .consumerId("1") + .sourceDefinition(sourceDefinition) + .build(); + + return request; + } + + public static MessageRouterPublisher buildPublisher(){ + MessageRouterPublisher pub = DmaapClientFactory + .createMessageRouterPublisher(MessageRouterPublisherConfig.createDefault()); + return pub; + } + + public static MessageRouterPublishRequest buildPublisherRequest(String name, String topicUrl){ + MessageRouterSink sinkDefinition = ImmutableMessageRouterSink.builder() + .name(name) + .topicUrl(topicUrl) + .build(); + MessageRouterPublishRequest request = ImmutableMessageRouterPublishRequest.builder() + .sinkDefinition(sinkDefinition) + .contentType(ContentType.TEXT_PLAIN) + .build(); + return request; + } + + +} diff --git a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/utils/DmaapUtils.java b/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/utils/DmaapUtils.java deleted file mode 100644 index 6e1cf912..00000000 --- a/components/slice-analysis-ms/src/main/java/org/onap/slice/analysis/ms/utils/DmaapUtils.java +++ /dev/null @@ -1,141 +0,0 @@ -/******************************************************************************* - * ============LICENSE_START======================================================= - * slice-analysis-ms - * ================================================================================ - * Copyright (C) 2020-2021 Wipro Limited. - * ============================================================================== - * 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 com.att.nsa.cambria.client.CambriaBatchingPublisher; -import com.att.nsa.cambria.client.CambriaClient; -import com.att.nsa.cambria.client.CambriaClientBuilders; -import com.att.nsa.cambria.client.CambriaClientBuilders.ConsumerBuilder; -import com.att.nsa.cambria.client.CambriaClientBuilders.PublisherBuilder; -import com.att.nsa.cambria.client.CambriaClientBuilders.TopicManagerBuilder; -import com.att.nsa.cambria.client.CambriaConsumer; -import com.att.nsa.cambria.client.CambriaTopicManager; - -import java.net.MalformedURLException; -import java.security.GeneralSecurityException; - -import org.onap.slice.analysis.ms.models.Configuration; - -/** - * Utility class to perform actions related to Dmaap - */ -public class DmaapUtils { - - /** - * Build publisher. - */ - public CambriaBatchingPublisher buildPublisher(Configuration config, String topic) { - try { - return builder(config, topic).build(); - } catch (MalformedURLException | GeneralSecurityException e) { - return null; - - } - } - - /** - * Build consumer. - */ - public CambriaConsumer buildConsumer(Configuration config, String topic) { - - try { - return builderConsumer(config, topic).build(); - } catch (MalformedURLException | GeneralSecurityException e) { - return null; - } - - } - - private static PublisherBuilder builder(Configuration config, String topic) { - if (config.isSecured()) { - return authenticatedBuilder(config, topic); - } else { - return unAuthenticatedBuilder(config, topic); - } - } - - private static PublisherBuilder authenticatedBuilder(Configuration config, String topic) { - return unAuthenticatedBuilder(config, topic).usingHttps().authenticatedByHttp(config.getAafUsername(), - config.getAafPassword()); - } - - private static PublisherBuilder unAuthenticatedBuilder(Configuration config, String topic) { - return new CambriaClientBuilders.PublisherBuilder().usingHosts(config.getDmaapServers()).onTopic(topic) - .logSendFailuresAfter(5); - } - - private static ConsumerBuilder builderConsumer(Configuration config, String topic) { - if (config.isSecured()) { - return authenticatedConsumerBuilder(config, topic); - } else { - return unAuthenticatedConsumerBuilder(config, topic); - } - } - - private static ConsumerBuilder unAuthenticatedConsumerBuilder(Configuration config, String topic) { - return new CambriaClientBuilders.ConsumerBuilder().usingHosts(config.getDmaapServers()).onTopic(topic) - .knownAs(config.getCg(), config.getCid()).withSocketTimeout(config.getPollingTimeout() * 1000); - } - - private static ConsumerBuilder authenticatedConsumerBuilder(Configuration config, String topic) { - return unAuthenticatedConsumerBuilder(config, topic).usingHttps().authenticatedByHttp(config.getAafUsername(), - config.getAafPassword()); - } - - /** - * Build cambriaClient. - */ - public CambriaTopicManager cambriaCLientBuilder(Configuration configuration) { - if (configuration.isSecured()) { - return authenticatedCambriaCLientBuilder(configuration); - } else { - return unAuthenticatedCambriaCLientBuilder(configuration); - - } - } - - private static CambriaTopicManager authenticatedCambriaCLientBuilder(Configuration config) { - try { - return buildCambriaClient(new TopicManagerBuilder().usingHosts(config.getDmaapServers()) - .authenticatedByHttp(config.getAafUsername(), config.getAafPassword())); - } catch (MalformedURLException | GeneralSecurityException e) { - return null; - } - } - - private static CambriaTopicManager unAuthenticatedCambriaCLientBuilder(Configuration config) { - try { - return buildCambriaClient(new TopicManagerBuilder().usingHosts(config.getDmaapServers())); - } catch (MalformedURLException | GeneralSecurityException e) { - return null; - - } - } - - @SuppressWarnings("unchecked") - private static <T extends CambriaClient> T buildCambriaClient( - CambriaClientBuilders.AbstractAuthenticatedManagerBuilder<? extends CambriaClient> client) - throws MalformedURLException, GeneralSecurityException { - return (T) client.build(); - } - -} diff --git a/components/slice-analysis-ms/src/main/resources/logback.xml b/components/slice-analysis-ms/src/main/resources/logback.xml index 6d8c6e22..aec15fbb 100644 --- a/components/slice-analysis-ms/src/main/resources/logback.xml +++ b/components/slice-analysis-ms/src/main/resources/logback.xml @@ -6,6 +6,7 @@ * ================================================================================ * Copyright (C) 2020 Wipro Limited. * 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. @@ -27,7 +28,7 @@ <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender"> <layout class="ch.qos.logback.classic.PatternLayout"> <Pattern> - %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n + %d{HH:mm:ss.SSS} [%t] %-5level %logger{36}:%line - %msg%n </Pattern> </layout> </appender> 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); + } + +} diff --git a/components/slice-analysis-ms/version.properties b/components/slice-analysis-ms/version.properties index 5844fb14..b536cee6 100644 --- a/components/slice-analysis-ms/version.properties +++ b/components/slice-analysis-ms/version.properties @@ -4,6 +4,7 @@ # ================================================================================ # Copyright (C) 2020-2021 Wipro Limited. # 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,7 +22,7 @@ ############################################################################### major=1 minor=1 -patch=3 +patch=4 base_version=${major}.${minor}.${patch} release_version=${base_version} snapshot_version=${base_version}-SNAPSHOT |