diff options
author | beili.zhou <beili.zhou@amdocs.com> | 2017-08-11 22:55:57 -0400 |
---|---|---|
committer | beili.zhou <beili.zhou@amdocs.com> | 2017-08-14 13:33:58 -0400 |
commit | 891e97b2d53b644b88eb14e2b0cb91d4b3acf930 (patch) | |
tree | fc1e3dbfec2bc70bade1bb8e1cab1e44290e71a4 /appc-oam/appc-oam-bundle | |
parent | 9adb43f6b764ca4766c43fbdb8afe351f43a24ee (diff) |
OAM operations 3 - JUnit tests
OAM operations changes are large, need to be broken down to multiple
submission based on size and compilability. This is the third (last) set
which covers JUnit test cases.
Includes these user stories: APPC-39/41/43/44/45/46/52/77.
Issue Id: APPC-38
Change-Id: I2df5e6b371d05030fb18bdd48155e4bb23034997
Signed-off-by: beili.zhou <beili.zhou@amdocs.com>
Diffstat (limited to 'appc-oam/appc-oam-bundle')
10 files changed, 1693 insertions, 0 deletions
diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/AppcOamTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/AppcOamTest.java new file mode 100644 index 000000000..5eb37af24 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/AppcOamTest.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.oam; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.AppcState; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.GetAppcStateOutput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.MaintenanceModeInput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.MaintenanceModeOutput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.RestartInput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.RestartOutput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.StartOutput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.StopInput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.StopOutput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.status.Status; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.openecomp.appc.oam.processor.OamMmodeProcessor; +import org.openecomp.appc.oam.processor.OamRestartProcessor; +import org.openecomp.appc.oam.processor.OamStartProcessor; +import org.openecomp.appc.oam.processor.OamStopProcessor; +import org.openecomp.appc.oam.util.OperationHelper; +import org.openecomp.appc.oam.util.StateHelper; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.spy; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({AppcOam.class, FrameworkUtil.class, Executors.class}) +public class AppcOamTest { + + private AppcOam appcOam; + private CommonHeader mockCommonHeader = mock(CommonHeader.class); + private Status mockStatus = mock(Status.class); + private OperationHelper mockOperationHelper = mock(OperationHelper.class); + private StateHelper mockStateHelper = mock(StateHelper.class); + + @Before + public void setUp() throws Exception { + appcOam = spy(new AppcOam(null, null, null)); + + Whitebox.setInternalState(appcOam, "stateHelper", mockStateHelper); + Whitebox.setInternalState(appcOam, "operationHelper", mockOperationHelper); + } + + @Test + public void testMaintenanceMode() throws Exception { + // mock processor creation + OamMmodeProcessor mockProcessor = mock(OamMmodeProcessor.class); + PowerMockito.mockStatic(OamMmodeProcessor.class); + PowerMockito.whenNew(OamMmodeProcessor.class).withAnyArguments().thenReturn(mockProcessor); + // mock input + MaintenanceModeInput mockInput = mock(MaintenanceModeInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + // mock processor result + Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); + + Future<RpcResult<MaintenanceModeOutput>> response = appcOam.maintenanceMode(mockInput); + + Assert.assertEquals("Should have common header", mockCommonHeader, + response.get().getResult().getCommonHeader()); + Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); + } + + @Test + public void testStart() throws Exception { + // mock processor creation + OamStartProcessor mockProcessor = mock(OamStartProcessor.class); + PowerMockito.mockStatic(OamStartProcessor.class); + PowerMockito.whenNew(OamStartProcessor.class).withAnyArguments().thenReturn(mockProcessor); + // mock input + StartInput mockInput = mock(StartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + // mock processor result + Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); + + Future<RpcResult<StartOutput>> response = appcOam.start(mockInput); + + Assert.assertEquals("Should have common header", mockCommonHeader, + response.get().getResult().getCommonHeader()); + Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); + } + + @Test + public void testStop() throws Exception { + // mock processor creation + OamStopProcessor mockProcessor = mock(OamStopProcessor.class); + PowerMockito.mockStatic(OamStopProcessor.class); + PowerMockito.whenNew(OamStopProcessor.class).withAnyArguments().thenReturn(mockProcessor); + // mock input + StopInput mockInput = mock(StopInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + // mock processor result + Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); + + Future<RpcResult<StopOutput>> response = appcOam.stop(mockInput); + + Assert.assertEquals("Should have common header", mockCommonHeader, + response.get().getResult().getCommonHeader()); + Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); + } + + @Test + public void testRestart() throws Exception { + // mock processor creation + OamRestartProcessor mockProcessor = mock(OamRestartProcessor.class); + PowerMockito.mockStatic(OamRestartProcessor.class); + PowerMockito.whenNew(OamRestartProcessor.class).withAnyArguments().thenReturn(mockProcessor); + // mock input + RestartInput mockInput = mock(RestartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + // mock processor result + Mockito.doReturn(mockStatus).when(mockProcessor).processRequest(mockInput); + + Future<RpcResult<RestartOutput>> response = appcOam.restart(mockInput); + + Assert.assertEquals("Should have common header", mockCommonHeader, + response.get().getResult().getCommonHeader()); + Assert.assertEquals("Should have status", mockStatus, response.get().getResult().getStatus()); + } + + @Test + public void testGetAppcState() throws Exception { + AppcState appcState = AppcState.Started; + Mockito.doReturn(appcState).when(mockStateHelper).getCurrentOamYangState(); + + Future<RpcResult<GetAppcStateOutput>> state = appcOam.getAppcState(); + Assert.assertEquals("Should return the same state", + appcState, state.get().getResult().getState()); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/messageadapter/MessageAdapterTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/messageadapter/MessageAdapterTest.java new file mode 100644 index 000000000..ff60923fb --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/messageadapter/MessageAdapterTest.java @@ -0,0 +1,115 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.oam.messageadapter; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.appc.adapter.message.MessageAdapterFactory; +import org.openecomp.appc.adapter.message.Producer; + +import org.mockito.Mockito; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.HashSet; + +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({MessageAdapter.class, FrameworkUtil.class}) +public class MessageAdapterTest { + + private Producer fakeProducer; + + private MessageAdapter messageAdapter; + + + @Before + public final void setup() throws Exception { + fakeProducer = mock(Producer.class); + messageAdapter = new MessageAdapter(); + } + + @Test + public void testGetProducerReturnsNull() throws Exception { + MessageAdapter maSpy = Mockito.spy(messageAdapter); + Mockito.doNothing().when(maSpy).createProducer(); + + Producer producer = maSpy.getProducer(); + Assert.assertTrue("getProducer() did not return null", producer == null); + Producer mySpyProducer = Whitebox.getInternalState(maSpy, "producer"); + Assert.assertTrue("MessageAdapter producer is not null", mySpyProducer == null); + Mockito.verify(maSpy, Mockito.times(1)).createProducer(); + } + + @Test + public void testGetProducerWithExistingProducer() throws Exception { + MessageAdapter maSpy = Mockito.spy(messageAdapter); + Whitebox.setInternalState(maSpy, "producer", fakeProducer); + + Producer producer = maSpy.getProducer(); + Assert.assertTrue("getProducer() returned null", producer == fakeProducer); + Mockito.verify(maSpy, Mockito.times(0)).createProducer(); + } + + @Test + public void testGetProducerWithCreateProducer() throws Exception { + MessageAdapter maSpy = Mockito.spy(messageAdapter); + Whitebox.setInternalState(maSpy, "producer", (Object) null); + HashSet<String> pool = new HashSet<>(); + Whitebox.setInternalState(maSpy, "pool", pool); + + // Prepare all mocks + mockStatic(FrameworkUtil.class); + Bundle maBundle = mock(Bundle.class); + PowerMockito.when(FrameworkUtil.getBundle(MessageAdapter.class)).thenReturn(maBundle); + + BundleContext maBundleContext = mock(BundleContext.class); + Mockito.when(maBundle.getBundleContext()).thenReturn(maBundleContext); + + ServiceReference svcRef = mock(ServiceReference.class); + Mockito.when(maBundleContext.getServiceReference(MessageAdapterFactory.class.getName())).thenReturn(svcRef); + + MessageAdapterFactory maFactory = mock(MessageAdapterFactory.class); + Mockito.when(maBundleContext.getService(svcRef)).thenReturn(maFactory); + Mockito.when(maFactory.createProducer(pool, (String) null, null, null)).thenReturn(fakeProducer); + + Producer producer = maSpy.getProducer(); + Assert.assertTrue("getProducer() result does not match", producer == fakeProducer); + Producer mySpyProducer = Whitebox.getInternalState(maSpy, "producer"); + Assert.assertTrue("MessageAdapter producer does not match",mySpyProducer == fakeProducer); + Mockito.verify(maSpy, Mockito.times(1)).createProducer(); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseActionRunnableTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseActionRunnableTest.java new file mode 100644 index 000000000..5fd51ef11 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseActionRunnableTest.java @@ -0,0 +1,243 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.openecomp.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.common.header.CommonHeader; +import org.openecomp.appc.configuration.Configuration; +import org.openecomp.appc.i18n.Msg; +import org.openecomp.appc.oam.AppcOam; +import org.openecomp.appc.oam.OAMCommandStatus; +import org.openecomp.appc.oam.util.AsyncTaskHelper; +import org.openecomp.appc.oam.util.ConfigurationHelper; +import org.openecomp.appc.oam.util.OperationHelper; +import org.openecomp.appc.oam.util.StateHelper; +import org.openecomp.appc.statemachine.impl.readers.AppcOamStates; +import org.powermock.reflect.Whitebox; + +import java.util.Date; + +import static org.mockito.Matchers.any; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; + +public class BaseActionRunnableTest { + private AppcOam.RPC testRpc = AppcOam.RPC.maintenance_mode; + private AppcOamStates targetState = AppcOamStates.MaintenanceMode; + + private class TestProcessor extends BaseProcessor { + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelperIn for property reading + * @param stateHelperIn for APP-C OAM state checking + * @param asyncTaskHelperIn for scheduling async task + * @param operationHelperIn for operational helper + */ + TestProcessor(EELFLogger eelfLogger, + ConfigurationHelper configurationHelperIn, + StateHelper stateHelperIn, + AsyncTaskHelper asyncTaskHelperIn, + OperationHelper operationHelperIn) { + super(eelfLogger, configurationHelperIn, stateHelperIn, asyncTaskHelperIn, operationHelperIn); + + // must set rpc and auditMsg + rpc = testRpc; + auditMsg = Msg.OAM_OPERATION_STARTING; + startTime = new Date(); + } + } + + class TestAbc extends BaseActionRunnable { + boolean doActionResult; + + TestAbc(BaseProcessor parent) { + super(parent); + + actionName = "testing"; + auditMsg = Msg.OAM_OPERATION_MAINTENANCE_MODE; + finalState = targetState; + } + + @Override + boolean doAction() { + return doActionResult; + } + } + + private TestAbc testBaseAcionRunnable; + private BaseProcessor testProcessor; + private StateHelper mockStateHelper = mock(StateHelper.class); + private OperationHelper mockOperHelper = mock(OperationHelper.class); + private ConfigurationHelper mockConfigHelper = mock(ConfigurationHelper.class); + private Configuration mockConfig = mock(Configuration.class); + + @SuppressWarnings("ResultOfMethodCallIgnored") + @Before + public void setUp() throws Exception { + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + + Mockito.doReturn(mockConfig).when(mockConfigHelper).getConfig(); + Mockito.doReturn(10).when(mockConfig).getIntegerProperty(any(), anyInt()); + + testProcessor = spy( + new TestProcessor(mockLogger, mockConfigHelper, mockStateHelper, null, mockOperHelper)); + testBaseAcionRunnable = spy(new TestAbc(testProcessor)); + + Whitebox.setInternalState(testBaseAcionRunnable, "commonHeader", mock(CommonHeader.class)); + } + + @Test + public void testSetTimeoutValues() throws Exception { + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); + testBaseAcionRunnable.setTimeoutValues(); + Assert.assertEquals("Should set timeoutMs", 10 * 1000, testBaseAcionRunnable.timeoutMs); + Assert.assertTrue("Should set start time MS", testBaseAcionRunnable.startTimeMs != 0); + Assert.assertTrue("Should do check", testBaseAcionRunnable.doTimeoutChecking); + + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); + int timeoutSeconds = 20; + Whitebox.setInternalState(testProcessor, "timeoutSeconds", timeoutSeconds); + testBaseAcionRunnable.setTimeoutValues(); + Assert.assertEquals("Should set timeoutMs", timeoutSeconds * 1000, testBaseAcionRunnable.timeoutMs); + Assert.assertTrue("Should set start time MS", testBaseAcionRunnable.startTimeMs != 0); + Assert.assertTrue("Should do check", testBaseAcionRunnable.doTimeoutChecking); + + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 0); + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); + + timeoutSeconds = 0; + Whitebox.setInternalState(testProcessor, "timeoutSeconds", timeoutSeconds); + Mockito.doReturn(0).when(mockConfig).getIntegerProperty( + testBaseAcionRunnable.OAM_OPERATION_TIMEOUT_SECOND, testBaseAcionRunnable.DEFAULT_OAM_OPERATION_TIMEOUT); + testBaseAcionRunnable.setTimeoutValues(); + Assert.assertEquals("Should set timeoutMs", timeoutSeconds * 1000, testBaseAcionRunnable.timeoutMs); + Assert.assertTrue("Should not set start time MS", testBaseAcionRunnable.startTimeMs == 0); + Assert.assertFalse("Should not do check", testBaseAcionRunnable.doTimeoutChecking); + } + @Test + public void testRun() throws Exception { + // test doAction failed + Whitebox.setInternalState(testBaseAcionRunnable, "doActionResult", false); + testBaseAcionRunnable.run(); + Assert.assertFalse("isWaiting should still be false", + Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); + + // test doAction success + Whitebox.setInternalState(testBaseAcionRunnable, "doActionResult", true); + + // with checkState return true + Mockito.doReturn(targetState).when(mockStateHelper).getBundlesState(); + testBaseAcionRunnable.run(); + Assert.assertFalse("isWaiting should still be false", + Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); + + // with checkState return false + Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getBundlesState(); + testBaseAcionRunnable.run(); + Assert.assertTrue("isWaiting should still be true", + Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); + + // should stay + testBaseAcionRunnable.run(); + Mockito.verify(testBaseAcionRunnable, times(1)).keepWaiting(); + } + + @Test + public void testSetAbortStatus() throws Exception { + testBaseAcionRunnable.setAbortStatus(); + Assert.assertEquals("Should return reject code", OAMCommandStatus.REJECTED.getResponseCode(), + testBaseAcionRunnable.status.getCode().intValue()); + Assert.assertTrue("Should set abort message", + testBaseAcionRunnable.status.getMessage().endsWith( + String.format(testBaseAcionRunnable.ABORT_MESSAGE_FORMAT, testRpc.name()))); + } + + @Test + public void testCheckState() throws Exception { + Mockito.doReturn(targetState).when(mockStateHelper).getBundlesState(); + Assert.assertTrue("Should return true", testBaseAcionRunnable.checkState()); + + Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getBundlesState(); + Assert.assertFalse("Should return false", testBaseAcionRunnable.checkState()); + } + + @Test + public void testPostAction() throws Exception { + Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getCurrentOamState(); + // set status to avoid NPE when using status + testBaseAcionRunnable.setAbortStatus(); + + // test no parameter + testBaseAcionRunnable.postAction(null); + Mockito.verify(mockOperHelper, times(1)).sendNotificationMessage(any(), any(), any()); + Mockito.verify(mockStateHelper, times(0)).setState(any()); + Mockito.verify(testProcessor, times(1)).cancelAsyncTask(); + + // test with parameter + testBaseAcionRunnable.postAction(AppcOamStates.Error); + Mockito.verify(mockOperHelper, times(2)).sendNotificationMessage(any(), any(), any()); + Mockito.verify(mockStateHelper, times(1)).setState(any()); + Mockito.verify(testProcessor, times(2)).cancelAsyncTask(); + } + + @Test + public void testIsTimeout() throws Exception { + String parentName = "testing"; + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", false); + Assert.assertFalse("Should not be timeout", testBaseAcionRunnable.isTimeout(parentName)); + + Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getCurrentOamState(); + Whitebox.setInternalState(testBaseAcionRunnable, "doTimeoutChecking", true); + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", System.currentTimeMillis() + 100); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 2); + Assert.assertFalse("Should not be timeout", testBaseAcionRunnable.isTimeout(parentName)); + + long timeoutMs = 1; + Whitebox.setInternalState(testBaseAcionRunnable, "timeoutMs", timeoutMs); + Whitebox.setInternalState(testBaseAcionRunnable, "startTimeMs", 2); + Assert.assertTrue("Should be timeout", testBaseAcionRunnable.isTimeout(parentName)); + Mockito.verify(testBaseAcionRunnable, times(1)).postAction(any()); + Assert.assertEquals("Should return timeout code", OAMCommandStatus.TIMEOUT.getResponseCode(), + testBaseAcionRunnable.status.getCode().intValue()); + Assert.assertTrue("Should set timeout message", + testBaseAcionRunnable.status.getMessage().endsWith( + String.format(testBaseAcionRunnable.TIMEOUT_MESSAGE_FORMAT, testRpc.name(), timeoutMs))); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseCommonTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseCommonTest.java new file mode 100644 index 000000000..4e1025781 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseCommonTest.java @@ -0,0 +1,124 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.openecomp.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.status.Status; +import org.openecomp.appc.exceptions.InvalidInputException; +import org.openecomp.appc.exceptions.InvalidStateException; +import org.openecomp.appc.oam.AppcOam; +import org.openecomp.appc.oam.OAMCommandStatus; +import org.openecomp.appc.oam.util.ConfigurationHelper; +import org.openecomp.appc.oam.util.OperationHelper; +import org.openecomp.appc.oam.util.StateHelper; +import org.openecomp.appc.statemachine.impl.readers.AppcOamStates; +import org.powermock.reflect.Whitebox; + +import static org.mockito.Mockito.mock; + +public class BaseCommonTest { + private class TestAbc extends BaseCommon { + + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelperIn for property reading + * @param stateHelperIn for APP-C OAM state checking + * @param operationHelperIn for operational helper + */ + TestAbc(EELFLogger eelfLogger, + ConfigurationHelper configurationHelperIn, + StateHelper stateHelperIn, + OperationHelper operationHelperIn) { + super(eelfLogger, configurationHelperIn, stateHelperIn, operationHelperIn); + } + } + + private TestAbc testBaseCommon; + private ConfigurationHelper mockConfigHelper = mock(ConfigurationHelper.class); + private StateHelper mockStateHelper = mock(StateHelper.class); + + @Before + public void setUp() throws Exception { + testBaseCommon = new TestAbc(null, mockConfigHelper, mockStateHelper, null); + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + Whitebox.setInternalState(testBaseCommon, "logger", mockLogger); + } + + @Test + public void testSetStatus() throws Exception { + OAMCommandStatus oamCommandStatus = OAMCommandStatus.ACCEPTED; + testBaseCommon.setStatus(oamCommandStatus); + Status status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + Assert.assertEquals("Should have message", oamCommandStatus.getResponseMessage(), status.getMessage()); + } + + @Test + public void testSetStatusWithParams() throws Exception { + String message = "testing"; + OAMCommandStatus oamCommandStatus = OAMCommandStatus.REJECTED; + testBaseCommon.setStatus(oamCommandStatus, message); + Status status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + Assert.assertTrue("Should have message", status.getMessage().endsWith(message)); + } + + @Test + public void testSetErrorStatus() throws Exception { + Mockito.doReturn("testName").when(mockConfigHelper).getAppcName(); + Mockito.doReturn(AppcOamStates.Started).when(mockStateHelper).getCurrentOamState(); + Whitebox.setInternalState(testBaseCommon, "rpc", AppcOam.RPC.maintenance_mode); + + String exceptionMessage = "testing"; + + OAMCommandStatus oamCommandStatus = OAMCommandStatus.INVALID_PARAMETER; + Throwable t = new InvalidInputException(exceptionMessage); + testBaseCommon.setErrorStatus(t); + Status status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + + oamCommandStatus = OAMCommandStatus.REJECTED; + t = new InvalidStateException(exceptionMessage); + testBaseCommon.setErrorStatus(t); + status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + + oamCommandStatus = OAMCommandStatus.UNEXPECTED_ERROR; + t = new NullPointerException(exceptionMessage); + testBaseCommon.setErrorStatus(t); + status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + } + +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseProcessorTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseProcessorTest.java new file mode 100644 index 000000000..7a023e162 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/processor/BaseProcessorTest.java @@ -0,0 +1,198 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + + +package org.openecomp.appc.oam.processor; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.status.Status; +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.appc.exceptions.InvalidInputException; +import org.openecomp.appc.exceptions.InvalidStateException; +import org.openecomp.appc.i18n.Msg; +import org.openecomp.appc.oam.AppcOam; +import org.openecomp.appc.oam.OAMCommandStatus; +import org.openecomp.appc.oam.util.AsyncTaskHelper; +import org.openecomp.appc.oam.util.ConfigurationHelper; +import org.openecomp.appc.oam.util.OperationHelper; +import org.openecomp.appc.oam.util.StateHelper; +import org.openecomp.appc.statemachine.impl.readers.AppcOamStates; +import org.powermock.reflect.Whitebox; + +import java.util.concurrent.Future; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; + +@SuppressWarnings("ResultOfMethodCallIgnored") +public class BaseProcessorTest { + private AppcOam.RPC testRpc = AppcOam.RPC.start; + private AppcOamStates currentState = AppcOamStates.Stopped; + + private class TestAbc extends BaseProcessor { + + /** + * Constructor + * + * @param eelfLogger for logging + * @param configurationHelperIn for property reading + * @param stateHelperIn for APP-C OAM state checking + * @param asyncTaskHelperIn for scheduling async task + * @param operationHelperIn for operational helper + */ + TestAbc(EELFLogger eelfLogger, + ConfigurationHelper configurationHelperIn, + StateHelper stateHelperIn, + AsyncTaskHelper asyncTaskHelperIn, + OperationHelper operationHelperIn) { + super(eelfLogger, configurationHelperIn, stateHelperIn, asyncTaskHelperIn, operationHelperIn); + + // must set rpc and auditMsg + rpc = testRpc; + auditMsg = Msg.OAM_OPERATION_STARTING; + } + } + + private TestAbc testBaseProcessor; + private ConfigurationHelper mockConfigHelper = mock(ConfigurationHelper.class); + private StateHelper mockStateHelper = mock(StateHelper.class); + private AsyncTaskHelper mockTaskHelper = mock(AsyncTaskHelper.class); + private OperationHelper mockOperHelper = mock(OperationHelper.class); + + private StartInput mockInput = mock(StartInput.class); + private CommonHeader mockCommonHeader = mock(CommonHeader.class); + + @Before + public void setUp() throws Exception { + Mockito.doReturn(mockCommonHeader).when(mockOperHelper).getCommonHeader(mockInput); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + + testBaseProcessor = spy( + new TestAbc(null, mockConfigHelper, mockStateHelper, mockTaskHelper, mockOperHelper)); + + Whitebox.setInternalState(testBaseProcessor, "commonHeader", mockCommonHeader); + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + Whitebox.setInternalState(testBaseProcessor, "logger", mockLogger); + } + + @Test + public void testProcessRequestError() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + Mockito.doThrow(new InvalidInputException("test")).when(mockOperHelper).isInputValid(mockInput); + Status status = testBaseProcessor.processRequest(mockInput); + Assert.assertEquals("Should return reject", + OAMCommandStatus.INVALID_PARAMETER.getResponseCode(), status.getCode().intValue()); + } + + @Test + public void testProcessRequest() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + Mockito.doReturn(AppcOamStates.Starting).when(mockOperHelper).getNextState(any(), any()); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Status status = testBaseProcessor.processRequest(mockInput); + Assert.assertEquals("Should return success", + OAMCommandStatus.ACCEPTED.getResponseCode(), status.getCode().intValue()); + } + + @Test(expected = InvalidInputException.class) + public void testPreProcessWithInvalidInput() throws Exception { + Mockito.doThrow(new InvalidInputException("test")).when(mockOperHelper).isInputValid(mockInput); + testBaseProcessor.preProcess(mockInput); + } + + @Test(expected = InvalidStateException.class) + public void testPreProcessWithInvalidState() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + Mockito.doThrow(new InvalidStateException("test")) + .when(mockOperHelper).getNextState(testRpc.getAppcOperation(), currentState); + testBaseProcessor.preProcess(mockInput); + } + + @Test(expected = APPCException.class) + public void testPreProcessWithAppcException() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + Mockito.doThrow(new APPCException("test")) + .when(mockOperHelper).getNextState(testRpc.getAppcOperation(), currentState); + testBaseProcessor.preProcess(mockInput); + } + + @Test + public void testPreProcess() throws Exception { + Mockito.doReturn(currentState).when(mockStateHelper).getCurrentOamState(); + AppcOamStates nextState = AppcOamStates.Starting; + Mockito.doReturn(nextState) + .when(mockOperHelper).getNextState(testRpc.getAppcOperation(), currentState); + testBaseProcessor.preProcess(mockInput); + Mockito.verify(mockOperHelper, times(1)).isInputValid(mockInput); + Mockito.verify(mockOperHelper, times(1)).getNextState(testRpc.getAppcOperation(), currentState); + Mockito.verify(mockStateHelper, times(1)).setState(nextState); + } + + @Test + public void testScheduleAsyncTask() throws Exception { + // test no runnable + testBaseProcessor.scheduleAsyncTask(); + Mockito.verify(mockTaskHelper, times(0)).scheduleAsyncTask(any(), any()); + + // test runnable + Runnable runnable = () -> { + // do nothing + }; + Whitebox.setInternalState(testBaseProcessor, "runnable", runnable); + testBaseProcessor.scheduleAsyncTask(); + Mockito.verify(mockTaskHelper, times(1)).scheduleAsyncTask(testRpc, runnable); + } + + @Test + public void isSameAsyncTask() throws Exception { + Future<?> mockTask1 = mock(Future.class); + Whitebox.setInternalState(testBaseProcessor, "scheduledRunnable", mockTask1); + Mockito.doReturn(mockTask1).when(mockTaskHelper).getCurrentAsyncTask(); + Assert.assertTrue("Shoudl be the same", testBaseProcessor.isSameAsyncTask()); + + Future<?> mockTask2 = mock(Future.class); + Mockito.doReturn(mockTask2).when(mockTaskHelper).getCurrentAsyncTask(); + Assert.assertFalse("Shoudl not be the same", testBaseProcessor.isSameAsyncTask()); + } + + @Test + public void cancleAsyncTask() throws Exception { + Future<?> mockTask = mock(Future.class); + Whitebox.setInternalState(testBaseProcessor, "scheduledRunnable", mockTask); + testBaseProcessor.cancelAsyncTask(); + Mockito.verify(mockTaskHelper, times(1)).cancelAsyncTask(mockTask); + Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "scheduledRunnable") == null); + } + +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/AsyncTaskHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/AsyncTaskHelperTest.java new file mode 100644 index 000000000..d080b735b --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/AsyncTaskHelperTest.java @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.appc.oam.AppcOam; +import org.powermock.reflect.Whitebox; + +import java.util.Arrays; +import java.util.concurrent.Future; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; + +public class AsyncTaskHelperTest { + private AsyncTaskHelper asyncTaskHelper; + private ScheduledExecutorService mockScheduler = mock(ScheduledExecutorService.class); + + @Before + public void setUp() throws Exception { + asyncTaskHelper = new AsyncTaskHelper(null); + + Whitebox.setInternalState(asyncTaskHelper, "scheduledExecutorService", mockScheduler); + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + Whitebox.setInternalState(asyncTaskHelper, "logger", mockLogger); + } + + @Test + public void testClose() throws Exception { + asyncTaskHelper.close(); + Mockito.verify(mockScheduler, times(1)).shutdown(); + } + + @Test + public void testGetCurrentAsyncTask() throws Exception { + Future<?> mockTask = mock(Future.class); + Whitebox.setInternalState(asyncTaskHelper, "backgroundOamTask", mockTask); + Assert.assertEquals("Should return mock task", mockTask, asyncTaskHelper.getCurrentAsyncTask()); + } + + @Test + public void testScheduleAsyncTaskWithMmod() throws Exception { + Runnable mockRunnable = mock(Runnable.class); + + // test maintance mode + ScheduledFuture<?> mockTask0 = mock(ScheduledFuture.class); + Whitebox.setInternalState(asyncTaskHelper, "backgroundOamTask", mockTask0); + + ScheduledFuture<?> mockTask1 = mock(ScheduledFuture.class); + Mockito.doReturn(mockTask1).when(mockScheduler).scheduleWithFixedDelay( + mockRunnable, asyncTaskHelper.MMODE_TASK_DELAY, asyncTaskHelper.MMODE_TASK_DELAY, TimeUnit.MILLISECONDS); + asyncTaskHelper.scheduleAsyncTask(AppcOam.RPC.maintenance_mode, mockRunnable); + Mockito.verify(mockTask0, times(1)).cancel(true); + Assert.assertEquals(mockTask1, asyncTaskHelper.scheduleAsyncTask(AppcOam.RPC.maintenance_mode, mockRunnable)); + Assert.assertEquals("Should set backgroundOamTask", mockTask1, asyncTaskHelper.getCurrentAsyncTask()); + } + + @Test + public void testScheduleAsyncTaskWithStart() throws Exception { + for (AppcOam.RPC rpc : Arrays.asList(AppcOam.RPC.start, AppcOam.RPC.stop, AppcOam.RPC.restart)) { + runTest(rpc); + } + } + + private void runTest(AppcOam.RPC rpc) { + Runnable mockRunnable = mock(Runnable.class); + ScheduledFuture<?> mockTask0 = mock(ScheduledFuture.class); + Whitebox.setInternalState(asyncTaskHelper, "backgroundOamTask", mockTask0); + + ScheduledFuture<?> mockTask2 = mock(ScheduledFuture.class); + Mockito.doReturn(mockTask2).when(mockScheduler).scheduleWithFixedDelay( + mockRunnable, asyncTaskHelper.COMMON_INITIAL_DELAY, asyncTaskHelper.COMMON_INTERVAL, TimeUnit.MILLISECONDS); + asyncTaskHelper.scheduleAsyncTask(rpc, mockRunnable); + Mockito.verify(mockTask0, times(1)).cancel(true); + Assert.assertEquals(mockTask2, asyncTaskHelper.scheduleAsyncTask(rpc, mockRunnable)); + Assert.assertEquals("Should set backgroundOamTask", mockTask2, asyncTaskHelper.getCurrentAsyncTask()); + } + + @Test + public void testCancelAsyncTask() throws Exception { + Future<?> mockTask = mock(Future.class); + Whitebox.setInternalState(asyncTaskHelper, "backgroundOamTask", mockTask); + asyncTaskHelper.cancelAsyncTask(mockTask); + Mockito.verify(mockTask, times(1)).cancel(false); + Assert.assertTrue("Should have reset backgroundOamTask", + asyncTaskHelper.getCurrentAsyncTask() == null); + + + Whitebox.setInternalState(asyncTaskHelper, "backgroundOamTask", mockTask); + Future<?> mockTask2 = mock(Future.class); + asyncTaskHelper.cancelAsyncTask(mockTask2); + Mockito.verify(mockTask2, times(1)).cancel(false); + Assert.assertEquals("Should not reset backgroundOamTask", mockTask, asyncTaskHelper.getCurrentAsyncTask()); + } + +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/BundleHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/BundleHelperTest.java new file mode 100644 index 000000000..2edc285f0 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/BundleHelperTest.java @@ -0,0 +1,180 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.apache.commons.lang.ArrayUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.openecomp.appc.configuration.Configuration; +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.appc.oam.AppcOam; +import org.openecomp.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.membermodification.MemberMatcher; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.mockStatic; +import static org.powermock.api.mockito.PowerMockito.spy; + +@SuppressWarnings("ResultOfMethodCallIgnored") +@RunWith(PowerMockRunner.class) +@PrepareForTest({BundleHelper.class, FrameworkUtil.class}) +public class BundleHelperTest { + private BundleHelper bundleHelper; + private AsyncTaskHelper mockTaskHelper = mock(AsyncTaskHelper.class); + + @Before + public void setUp() throws Exception { + bundleHelper = spy(new BundleHelper(null, null, null)); + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + Whitebox.setInternalState(bundleHelper, "logger", mockLogger); + } + + @Test + public void testBundleOperations() throws Exception { + // spy mocked bundle for calls to method statr or stop. + // Note: the time of method calls are accumulated in this test method. + Bundle mockBundle = spy(Mockito.mock(Bundle.class)); + Map<String, Bundle> mapFromGetAppcLcmBundles = new HashMap<>(); + mapFromGetAppcLcmBundles.put("BundleString", mockBundle); + + PowerMockito.doReturn(mapFromGetAppcLcmBundles).when(bundleHelper, MemberMatcher.method( + BundleHelper.class, "getAppcLcmBundles")).withNoArguments(); + + StateHelper mockStateHelper = mock(StateHelper.class); + Whitebox.setInternalState(bundleHelper, "stateHelper", mockStateHelper); + + AppcOamStates appcOamStates = AppcOamStates.Stopped; + Mockito.doReturn(appcOamStates).when(mockStateHelper).getState(); + + // test start + Mockito.doReturn(true).when(mockStateHelper).isSameState(appcOamStates); + boolean result = bundleHelper.bundleOperations(AppcOam.RPC.start, new HashMap<>(), mockTaskHelper); + Assert.assertTrue("Should be completed", result); + Mockito.verify(mockTaskHelper, times(1)).submitBundleLcOperation(any()); + + // test start aborted + Mockito.doReturn(false).when(mockStateHelper).isSameState(appcOamStates); + result = bundleHelper.bundleOperations(AppcOam.RPC.start, new HashMap<>(), mockTaskHelper); + Assert.assertFalse("Should be abort", result); + Mockito.verify(mockTaskHelper, times(1)).submitBundleLcOperation(any()); + + // test stop + result = bundleHelper.bundleOperations(AppcOam.RPC.stop, new HashMap<>(), mockTaskHelper); + Assert.assertTrue("Should be completed", result); + Mockito.verify(mockTaskHelper, times(2)).submitBundleLcOperation(any()); + } + + @Test(expected = APPCException.class) + public void testBundleOperationsRpcException() throws Exception { + bundleHelper.bundleOperations(AppcOam.RPC.maintenance_mode, new HashMap<>(), mockTaskHelper); + } + + @Test + public void testGetBundleList() throws Exception { + mockStatic(FrameworkUtil.class); + Bundle myBundle = mock(Bundle.class); + PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle); + + // test bundle context is null + Mockito.when(myBundle.getBundleContext()).thenReturn(null); + Assert.assertTrue("Should return null", bundleHelper.getBundleList() == null); + + BundleContext myBundleContext = mock(BundleContext.class); + Mockito.when(myBundle.getBundleContext()).thenReturn(myBundleContext); + + // test bundle list is empty + Bundle[] bundleArray = {}; + Mockito.when(myBundleContext.getBundles()).thenReturn(bundleArray); + Bundle[] results = bundleHelper.getBundleList(); + Assert.assertTrue("Should not be null", results != null); + Assert.assertTrue("Should not have any element", results.length == 0); + + // test bundle list has at one bundle + bundleArray = new Bundle[] { myBundle }; + Mockito.when(myBundleContext.getBundles()).thenReturn(bundleArray); + results = bundleHelper.getBundleList(); + Assert.assertTrue("Should not be null", results != null); + Assert.assertTrue("Should have one element", results.length == 1); + Assert.assertEquals("Should be the mock bundle", myBundle, results[0]); + } + + @Test + public void testReadPropsFromPropListName() throws Exception { + // mock configuarion helper + ConfigurationHelper configurationHelper = new ConfigurationHelper(null); + EELFLogger fakeLogger = mock(EELFLogger.class); + Whitebox.setInternalState(configurationHelper, "logger", fakeLogger); + Configuration fakeConf = mock(Configuration.class); + Whitebox.setInternalState(configurationHelper, "configuration", fakeConf); + + Whitebox.setInternalState(bundleHelper, "configurationHelper", configurationHelper); + + String propKey = "testing"; + // Property does not exist + Mockito.doReturn(null).when(fakeConf).getProperty(propKey); + String[] propResult = bundleHelper.readPropsFromPropListName(propKey); + Assert.assertArrayEquals("PropertyResult should be empty string array", + ArrayUtils.EMPTY_STRING_ARRAY, propResult); + // Property has one entry + String propValue1 = "1234"; + String propValue2 = "5678"; + Mockito.doReturn(propValue1).when(fakeConf).getProperty(propKey); + Mockito.doReturn(propValue2).when(fakeConf).getProperty(propValue1); + propResult = bundleHelper.readPropsFromPropListName(propKey); + Assert.assertTrue("PropertyResult should have only one element", propResult.length == 1); + Assert.assertEquals("PropertyResult should martch propertyValue", propValue2, propResult[0]); + // Property has two entries + propValue1 = "1234\n,4321"; + String propValue3 = "8765"; + Mockito.doReturn(propValue1).when(fakeConf).getProperty(propKey); + Mockito.doReturn(propValue2).when(fakeConf).getProperty(propValue1); + Mockito.doReturn(propValue3).when(fakeConf).getProperty("4321"); + propResult = bundleHelper.readPropsFromPropListName(propKey); + Assert.assertTrue("PropertyResult should have two elements", propResult.length == 2); + List propResultList = Arrays.asList(propResult); + Assert.assertTrue("PropertyResult should have propertyValue2", propResultList.contains(propValue2)); + Assert.assertTrue("PropertyResult should have propertyValue2", propResultList.contains(propValue3)); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/ConfigurationHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/ConfigurationHelperTest.java new file mode 100644 index 000000000..a489aa05e --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/ConfigurationHelperTest.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.apache.commons.lang3.ArrayUtils; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.appc.configuration.Configuration; +import org.powermock.reflect.Whitebox; + +import static org.mockito.Mockito.mock; + +public class ConfigurationHelperTest { + private ConfigurationHelper configurationHelper; + + private Configuration mockConf; + private Configuration origConf; + + @Before + public void setUp() throws Exception { + mockConf = mock(Configuration.class); + + configurationHelper = new ConfigurationHelper(null); + + // to avoid operation on logger fail, mock up the logger + EELFLogger fakeLogger = mock(EELFLogger.class); + Whitebox.setInternalState(configurationHelper, "logger", fakeLogger); + } + + private void setMockConf() { + origConf = Whitebox.getInternalState(configurationHelper, "configuration"); + Whitebox.setInternalState(configurationHelper, "configuration", mockConf); + } + + private void resetOrigConfig() { + Whitebox.setInternalState(configurationHelper, "configuration", origConf); + origConf = null; + } + + @Test + public void getAppcName() throws Exception { + // test with existing properties file + Assert.assertEquals("Should return value(APPC).", "APPC", configurationHelper.getAppcName()); + + // test with mockup + setMockConf(); + + String propValue = "testing"; + Mockito.doReturn(propValue).when(mockConf).getProperty(ConfigurationHelper.PROP_KEY_APPC_NAME); + Assert.assertEquals(String.format("Should return value(%s).", propValue), propValue, + configurationHelper.getAppcName()); + + resetOrigConfig(); + } + + @Test + public void isMetricEnabled() throws Exception { + // test with mockup + setMockConf(); + + Mockito.doReturn(false).when(mockConf).getBooleanProperty( + ConfigurationHelper.PROP_KEY_METRIC_STATE, false); + Assert.assertFalse("Should return false", configurationHelper.isMetricEnabled()); + + Mockito.doReturn(true).when(mockConf).getBooleanProperty( + ConfigurationHelper.PROP_KEY_METRIC_STATE, false); + Assert.assertTrue("Should return true", configurationHelper.isMetricEnabled()); + } + + @Test + public void testReadPropertyNotStop() throws Exception { + String[] str = configurationHelper.readProperty("appc.OAM.AppcBundlesToNotStop"); + Assert.assertTrue(str.length > 0); + Assert.assertTrue(str[0].equals(".*appc.oam.*")); + } + + @Test + public void testReadPropertyStop() throws Exception { + String[] str = configurationHelper.readProperty("appc.OAM.AppcBundlesToStop"); + Assert.assertTrue(str.length > 0); + Assert.assertTrue(str[0].equals(".*appc.*")); + } + + @Test + public void testReadPropertyWithMockup() throws Exception { + setMockConf(); + + String propKey = "testing"; + // Property does not exist + Mockito.doReturn(null).when(mockConf).getProperty(propKey); + String[] propResult = configurationHelper.readProperty(propKey); + Assert.assertArrayEquals("PropertyResult should be empty string array", + ArrayUtils.EMPTY_STRING_ARRAY, propResult); + // Property has one entry + String propValue = "1234"; + Mockito.doReturn(propValue).when(mockConf).getProperty(propKey); + propResult = configurationHelper.readProperty(propKey); + Assert.assertTrue("PropertyResult should have only one element", propResult.length == 1); + Assert.assertEquals("PropertyResult should martch propertyValue", propValue, propResult[0]); + + resetOrigConfig(); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/OperationHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/OperationHelperTest.java new file mode 100644 index 000000000..e335ad830 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/OperationHelperTest.java @@ -0,0 +1,240 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.oam.util; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.MaintenanceModeInput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.StopInput; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.common.header.common.header.Flags; +import org.openecomp.appc.exceptions.APPCException; +import org.openecomp.appc.exceptions.InvalidInputException; +import org.openecomp.appc.exceptions.InvalidStateException; +import org.openecomp.appc.lifecyclemanager.LifecycleManager; +import org.openecomp.appc.lifecyclemanager.objects.LifecycleException; +import org.openecomp.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.openecomp.appc.oam.AppcOam; +import org.openecomp.appc.statemachine.impl.readers.AppcOamMetaDataReader; +import org.openecomp.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +import org.osgi.framework.BundleContext; +import org.osgi.framework.FrameworkUtil; +import org.osgi.framework.ServiceReference; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({FrameworkUtil.class}) +public class OperationHelperTest { + private OperationHelper operationHelper; + private LifecycleManager lifecycleManager = mock(LifecycleManager.class); + private CommonHeader mockCommonHeader = mock(CommonHeader.class); + + @Rule + public ExpectedException expectedException = ExpectedException.none(); + + @Before + public void setUp() throws Exception { + operationHelper = new OperationHelper(); + Whitebox.setInternalState(operationHelper, "lifecycleMgr", lifecycleManager); + } + + @Test + public void testIsInputValidWithMissingInput() throws Exception { + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.MISSING_COMMON_HEADER_MESSAGE); + + operationHelper.isInputValid(null); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidWithMissingCommonHeader() throws Exception { + StartInput mockInput = mock(StartInput.class); + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.MISSING_COMMON_HEADER_MESSAGE); + + operationHelper.isInputValid(mockInput); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidWithMissingOid() throws Exception { + StartInput mockInput = mock(StartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Mockito.doReturn(null).when(mockCommonHeader).getOriginatorId(); + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.MISSING_FIELD_MESSAGE); + + operationHelper.isInputValid(mockInput); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidWithMissingRid() throws Exception { + StartInput mockInput = mock(StartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Mockito.doReturn("originalId").when(mockCommonHeader).getOriginatorId(); + Mockito.doReturn(null).when(mockCommonHeader).getRequestId(); + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.MISSING_FIELD_MESSAGE); + + operationHelper.isInputValid(mockInput); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidWithMmodeFlags() throws Exception { + MaintenanceModeInput mockInput = mock(MaintenanceModeInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Mockito.doReturn("originalId").when(mockCommonHeader).getOriginatorId(); + Mockito.doReturn("requestId").when(mockCommonHeader).getRequestId(); + Mockito.doReturn(mock(Flags.class)).when(mockCommonHeader).getFlags(); + expectedException.expect(InvalidInputException.class); + expectedException.expectMessage(operationHelper.NOT_SUPPORT_FLAG); + + operationHelper.isInputValid(mockInput); + expectedException = ExpectedException.none(); + } + + @Test + public void testIsInputValidPass() throws Exception { + StartInput mockInput = mock(StartInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput).getCommonHeader(); + Mockito.doReturn("originalId").when(mockCommonHeader).getOriginatorId(); + Mockito.doReturn("requestId").when(mockCommonHeader).getRequestId(); + + //with Flags + Mockito.doReturn(mock(Flags.class)).when(mockCommonHeader).getFlags(); + operationHelper.isInputValid(mockInput); + + //without Flags + Mockito.doReturn(null).when(mockCommonHeader).getFlags(); + operationHelper.isInputValid(mockInput); + + // MaintenanceMode without Flags + MaintenanceModeInput mockInput1 = mock(MaintenanceModeInput.class); + Mockito.doReturn(mockCommonHeader).when(mockInput1).getCommonHeader(); + operationHelper.isInputValid(mockInput1); + } + + @Test + public void testGetCommonHeader() throws Exception { + CommonHeader commonHeader = mock(CommonHeader.class); + // for StartInput + StartInput startInput = mock(StartInput.class); + Mockito.doReturn(commonHeader).when(startInput).getCommonHeader(); + Assert.assertEquals("Should return startInput commonHeader", commonHeader, + operationHelper.getCommonHeader(startInput)); + + // for StopInput + StopInput stopInput = mock(StopInput.class); + Mockito.doReturn(commonHeader).when(stopInput).getCommonHeader(); + Assert.assertEquals("Should return stopInput commonHeader", commonHeader, + operationHelper.getCommonHeader(stopInput)); + + // for MaintenanceModeInput + MaintenanceModeInput mmInput = mock(MaintenanceModeInput.class); + Mockito.doReturn(commonHeader).when(mmInput).getCommonHeader(); + Assert.assertEquals("Should return MaintenanceModeInput commonHeader", commonHeader, + operationHelper.getCommonHeader(mmInput)); + + // unsupported type + Assert.assertTrue("should return null", + operationHelper.getCommonHeader(new Object()) == null); + } + + @SuppressWarnings("unchecked") + @Test + public void testGetService() throws Exception { + Class<OperationHelper> operationHelperClass = OperationHelper.class; + String className = operationHelperClass.getName(); + String exceptionMsg = String.format(operationHelper.NO_SERVICE_REF_FORMAT, className); + + mockStatic(FrameworkUtil.class); + Bundle bundle = mock(Bundle.class); + PowerMockito.when(FrameworkUtil.getBundle(operationHelperClass)).thenReturn(bundle); + + // No bundle context + Mockito.when(bundle.getBundleContext()).thenReturn(null); + expectedException.expect(APPCException.class); + expectedException.expectMessage(exceptionMsg); + operationHelper.getService(operationHelperClass); + + // No service reference + BundleContext bundleContext = mock(BundleContext.class); + Mockito.when(bundle.getBundleContext()).thenReturn(bundleContext); + Mockito.when(bundleContext.getServiceReference(className)).thenReturn(null); + expectedException.expect(APPCException.class); + expectedException.expectMessage(exceptionMsg); + operationHelper.getService(operationHelperClass); + + // Success path + ServiceReference svcRef = mock(ServiceReference.class); + Mockito.when(bundleContext.getServiceReference(className)).thenReturn(svcRef); + expectedException = ExpectedException.none(); + Assert.assertTrue("should not be null", operationHelper.getService(operationHelperClass) != null); + } + + @Test + public void testGetNextState() throws Exception { + AppcOamMetaDataReader.AppcOperation operation = AppcOamMetaDataReader.AppcOperation.Start; + AppcOamStates currentState = AppcOamStates.Stopped; + String exceptionMsg = String.format(AppcOam.INVALID_STATE_MESSAGE_FORMAT, operation, "APPC", currentState); + + // got LifecycleException + Mockito.doThrow(LifecycleException.class).when(lifecycleManager) + .getNextState("APPC", operation.name(), currentState.name()); + expectedException.expect(InvalidStateException.class); + expectedException.expectMessage(exceptionMsg); + operationHelper.getNextState(operation, currentState); + + // got NoTransitionDefinedException + Mockito.doThrow(NoTransitionDefinedException.class).when(lifecycleManager) + .getNextState("APPC", operation.name(), currentState.name()); + expectedException.expect(InvalidStateException.class); + expectedException.expectMessage(exceptionMsg); + operationHelper.getNextState(operation, currentState); + + // Success path + expectedException = ExpectedException.none(); + Mockito.doReturn("starting").when(lifecycleManager) + .getNextState("APPC", operation.name(), currentState.name()); + Assert.assertEquals("Should return proper Starting state", AppcOamStates.Starting, + operationHelper.getNextState(operation, currentState)); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/StateHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/StateHelperTest.java new file mode 100644 index 000000000..3dfb52bbe --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/openecomp/appc/oam/util/StateHelperTest.java @@ -0,0 +1,173 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP : APPC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Copyright (C) 2017 Amdocs + * ============================================================================= + * 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. + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.opendaylight.yang.gen.v1.org.openecomp.appc.oam.rev170303.AppcState; +import org.openecomp.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +import java.util.HashMap; +import java.util.Map; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({StateHelper.class}) +public class StateHelperTest { + private StateHelper stateHelper; + + @Before + public void setUp() throws Exception { + stateHelper = PowerMockito.spy(new StateHelper(null, null)); + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + Whitebox.setInternalState(stateHelper, "logger", mockLogger); + } + + @Test + public void testSetState() throws Exception { + AppcOamStates appcOamStates = AppcOamStates.Started; + stateHelper.setState(appcOamStates); + Assert.assertEquals("Should have the new value", appcOamStates, + Whitebox.getInternalState(stateHelper, "appcOamCurrentState")); + // reest to default value + stateHelper.setState(AppcOamStates.Unknown); + } + + @Test + public void testGetState() throws Exception { + AppcOamStates appcOamStates = stateHelper.getState(); + Assert.assertEquals("Should have the class value", appcOamStates, + Whitebox.getInternalState(stateHelper, "appcOamCurrentState")); + } + + @Test + public void testIsSameState() throws Exception { + AppcOamStates classValue = Whitebox.getInternalState(stateHelper, "appcOamCurrentState"); + for (AppcOamStates appcOamStates : AppcOamStates.values()) { + boolean isSame = stateHelper.isSameState(appcOamStates); + if (appcOamStates == classValue) { + Assert.assertTrue("Should be the same", isSame); + } else { + Assert.assertFalse("Should not be the same", isSame); + } + } + } + + @Test + public void testGetCurrentOamState() throws Exception { + AppcOamStates mockResult = AppcOamStates.Started; + // mock getBundlesState, as we are testin it separately + PowerMockito.doReturn(mockResult).when(stateHelper, "getBundlesState"); + + Whitebox.setInternalState(stateHelper, "appcOamCurrentState", AppcOamStates.Unknown); + Assert.assertEquals("Should call deriveStatte and return mockeResult", + mockResult, stateHelper.getCurrentOamState()); + Mockito.verify(stateHelper, times(1)).getBundlesState(); + + + Whitebox.setInternalState(stateHelper, "appcOamCurrentState", AppcOamStates.Unknown); + Assert.assertEquals("Should call deriveStatte and return mockeResult", + mockResult, stateHelper.getCurrentOamState()); + Mockito.verify(stateHelper, times(2)).getBundlesState(); + + Whitebox.setInternalState(stateHelper, "appcOamCurrentState", mockResult); + Assert.assertEquals("Should just return mockeResult", mockResult, stateHelper.getCurrentOamState()); + Mockito.verify(stateHelper, times(2)).getBundlesState(); + } + + @Test + public void testGetCurrentOamYangState() throws Exception { + Map<AppcOamStates, AppcState> stateMap = new HashMap<AppcOamStates, AppcState>() { + { + put(AppcOamStates.EnteringMaintenanceMode, AppcState.EnteringMaintenanceMode); + put(AppcOamStates.MaintenanceMode, AppcState.MaintenanceMode); + put(AppcOamStates.Instantiated, AppcState.Instantiated); + put(AppcOamStates.NotInstantiated, AppcState.NotInstantiated); + put(AppcOamStates.Restarting, AppcState.Restarting); + put(AppcOamStates.Started, AppcState.Started); + put(AppcOamStates.Starting, AppcState.Starting); + put(AppcOamStates.Stopped, AppcState.Stopped); + put(AppcOamStates.Stopping, AppcState.Stopping); + put(AppcOamStates.Error, AppcState.Error); + put(AppcOamStates.Unknown, AppcState.Unknown); + } + }; + for (Map.Entry<AppcOamStates, AppcState> aEntry : stateMap.entrySet()) { + AppcOamStates aState = aEntry.getKey(); + AppcState appcState = aEntry.getValue(); + + PowerMockito.doReturn(aState).when(stateHelper, "getCurrentOamState"); + + AppcState resultState = stateHelper.getCurrentOamYangState(); + Assert.assertEquals( + String.format("%s state, returned(%s),should return(%s) state", aState, resultState, appcState), + appcState, resultState); + + } + } + + @Test + public void testGetBundlesState() throws Exception { + BundleHelper mockBundlerHelper = mock(BundleHelper.class); + PowerMockito.whenNew(BundleHelper.class).withAnyArguments().thenReturn(mockBundlerHelper); + + // test null bundle map + Mockito.when(mockBundlerHelper.getAppcLcmBundles()).thenReturn(null); + Assert.assertEquals("Should return unknown state", AppcOamStates.Unknown, stateHelper.getBundlesState()); + + // tet empty bundle map + Map<String, Bundle> bundleMap = new HashMap<>(); + Mockito.when(mockBundlerHelper.getAppcLcmBundles()).thenReturn(bundleMap); + Assert.assertEquals("Should return unknown state", AppcOamStates.Unknown, stateHelper.getBundlesState()); + + Bundle mockBundle1 = mock(Bundle.class); + Bundle mockBundle2 = mock(Bundle.class); + bundleMap.put("1", mockBundle1); + bundleMap.put("2", mockBundle2); + Mockito.when(mockBundlerHelper.getAppcLcmBundles()).thenReturn(bundleMap); + + // test bundles have differnt states + Mockito.doReturn(Bundle.RESOLVED).when(mockBundle1).getState(); + Mockito.doReturn(Bundle.ACTIVE).when(mockBundle2).getState(); + Assert.assertEquals("Should return lower state", AppcOamStates.Stopped, stateHelper.getBundlesState()); + + // test bundles have the same state + Mockito.doReturn(Bundle.ACTIVE).when(mockBundle1).getState(); + Assert.assertEquals("Should return the state", AppcOamStates.Started, stateHelper.getBundlesState()); + } +} |