diff options
author | Patrick Brady <pb071s@att.com> | 2017-12-13 11:19:06 -0800 |
---|---|---|
committer | Patrick Brady <pb071s@att.com> | 2017-12-13 11:19:17 -0800 |
commit | 781b1a6df324419c846c84ea983c18fc8362bfd3 (patch) | |
tree | 580008010dd50ca32db2ef6dc2e36628cf8c2b5b /appc-oam/appc-oam-bundle/src/test/java/org/onap | |
parent | 161df8a94bb3b0c34ed16fd4fdba078bd1eeef9a (diff) |
Third part of onap rename
This part of the commit changes the folder structure on all other
folders of appc.
Change-Id: I8acfa11cdfcdcd36be0e137245d1dd7324f1abd3
Signed-off-by: Patrick Brady <pb071s@att.com>
Issue-ID: APPC-13
Diffstat (limited to 'appc-oam/appc-oam-bundle/src/test/java/org/onap')
11 files changed, 2415 insertions, 0 deletions
diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/AppcOamTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/AppcOamTest.java new file mode 100644 index 000000000..110198370 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/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.onap.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.onap.appc.oam.rev170303.AppcState; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.GetAppcStateOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.MaintenanceModeOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.RestartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopOutput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.opendaylight.yangtools.yang.common.RpcResult; +import org.onap.appc.oam.processor.OamMmodeProcessor; +import org.onap.appc.oam.processor.OamRestartProcessor; +import org.onap.appc.oam.processor.OamStartProcessor; +import org.onap.appc.oam.processor.OamStopProcessor; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.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/onap/appc/oam/OAMCommandStatusTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/OAMCommandStatusTest.java new file mode 100644 index 000000000..269c4f811 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/OAMCommandStatusTest.java @@ -0,0 +1,99 @@ +/*- + * ============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.onap.appc.oam; + +import org.junit.Assert; +import org.junit.Test; +import org.onap.appc.executor.objects.Params; + +import java.util.HashMap; +import java.util.Map; + +public class OAMCommandStatusTest { + private Map<OAMCommandStatus, Integer> CODE_MAP = new HashMap<OAMCommandStatus, Integer>() { + { + put(OAMCommandStatus.ABORT, 304); + put(OAMCommandStatus.ACCEPTED, 100); + put(OAMCommandStatus.INVALID_PARAMETER, 302); + put(OAMCommandStatus.REJECTED, 300); + put(OAMCommandStatus.SUCCESS, 400); + put(OAMCommandStatus.TIMEOUT, 303); + put(OAMCommandStatus.UNEXPECTED_ERROR, 200); + } + }; + private Map<OAMCommandStatus, String> MSG_MAP = new HashMap<OAMCommandStatus, String>() { + { + put(OAMCommandStatus.ABORT, "OPERATION ABORT - ${errorMsg}"); + put(OAMCommandStatus.ACCEPTED, "ACCEPTED - request accepted"); + put(OAMCommandStatus.INVALID_PARAMETER, "INVALID PARAMETER - ${errorMsg}"); + put(OAMCommandStatus.REJECTED, "REJECTED - ${errorMsg}"); + put(OAMCommandStatus.SUCCESS, "SUCCESS - request has been processed successfully"); + put(OAMCommandStatus.TIMEOUT, "OPERATION TIMEOUT REACHED - ${errorMsg}"); + put(OAMCommandStatus.UNEXPECTED_ERROR, "UNEXPECTED ERROR - ${errorMsg}"); + } + }; + + @Test + public void testGetResponseMessage() throws Exception { + for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { + String expectedMsg = MSG_MAP.get(oamCommandStatus); + Assert.assertEquals(String.format("Should have message (%s).", expectedMsg), + expectedMsg, oamCommandStatus.getResponseMessage()); + } + } + + @Test + public void testGetResponseCode() throws Exception { + for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { + Integer expectedCode = CODE_MAP.get(oamCommandStatus); + Assert.assertEquals(String.format("Should have code (%d).", expectedCode), + expectedCode, Integer.valueOf(oamCommandStatus.getResponseCode())); + } + } + + @Test + public void testGetFormattedMessage() throws Exception { + String message = "test message"; + Params params = new Params().addParam("errorMsg", message); + for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { + String expectedMsg1 = MSG_MAP.get(oamCommandStatus); + String expectedMsg2 = expectedMsg1.replaceAll("\\$\\{errorMsg\\}", message); + Assert.assertEquals("Should returned " + expectedMsg1, + expectedMsg1, oamCommandStatus.getFormattedMessage(null)); + Assert.assertEquals("Should returned " + expectedMsg2, + expectedMsg2, oamCommandStatus.getFormattedMessage(params)); + } + } + + @Test + public void testToString() throws Exception { + for (OAMCommandStatus oamCommandStatus : OAMCommandStatus.values()) { + String expectedString = String.format(oamCommandStatus.TO_STRING_FORMAT, + CODE_MAP.get(oamCommandStatus), MSG_MAP.get(oamCommandStatus)); + Assert.assertEquals(String.format("Should have string (%s).", expectedString), + expectedString, oamCommandStatus.toString()); + } + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/messageadapter/MessageAdapterTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/messageadapter/MessageAdapterTest.java new file mode 100644 index 000000000..d3ebfda51 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/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.onap.appc.oam.messageadapter; + +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.onap.appc.adapter.message.MessageAdapterFactory; +import org.onap.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/onap/appc/oam/processor/BaseActionRunnableTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseActionRunnableTest.java new file mode 100644 index 000000000..daf0f6e07 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseActionRunnableTest.java @@ -0,0 +1,293 @@ +/*- + * ============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.onap.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.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.BundleHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.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.anyMap; +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 BundleHelper mockBundleHelper = mock(BundleHelper.class); + + @SuppressWarnings("ResultOfMethodCallIgnored") + @Before + public void setUp() throws Exception { + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + + testProcessor = spy( + new TestProcessor(mockLogger, mockConfigHelper, mockStateHelper, null, mockOperHelper)); + Whitebox.setInternalState(testProcessor, "bundleHelper", mockBundleHelper); + + 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); + long expectedTimeout = 10000L; + Mockito.doReturn(expectedTimeout).when(mockConfigHelper).getOAMOperationTimeoutValue(any()); + testBaseAcionRunnable.setTimeoutValues(); + Assert.assertEquals("Should set timeoutMs", expectedTimeout, 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); + expectedTimeout = 20000L; + Mockito.doReturn(expectedTimeout).when(mockConfigHelper).getOAMOperationTimeoutValue(any()); + testBaseAcionRunnable.setTimeoutValues(); + Assert.assertEquals("Should set timeoutMs", expectedTimeout, 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); + expectedTimeout = 0L; + Mockito.doReturn(expectedTimeout).when(mockConfigHelper).getOAMOperationTimeoutValue(any()); + testBaseAcionRunnable.setTimeoutValues(); + Assert.assertEquals("Should set timeoutMs", expectedTimeout, 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(true).when(testBaseAcionRunnable).checkState(); + testBaseAcionRunnable.run(); + Assert.assertFalse("isWaiting should still be false", + Whitebox.getInternalState(testBaseAcionRunnable, "isWaiting")); + + // with checkState return false + Mockito.doReturn(false).when(testBaseAcionRunnable).checkState(); + 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 abort code", OAMCommandStatus.ABORT.getResponseCode(), + testBaseAcionRunnable.status.getCode().intValue()); + Assert.assertTrue("Should set abort due to execution error message", + testBaseAcionRunnable.status.getMessage().endsWith( + String.format(testBaseAcionRunnable.ABORT_MESSAGE_FORMAT, + testRpc.name(), testBaseAcionRunnable.DUE_TO_EXECUTION_ERROR))); + } + + @Test + public void testCheckState() throws Exception { + // 1. with isTimeout true + Mockito.doReturn(true).when(testBaseAcionRunnable).isTimeout("checkState"); + Assert.assertTrue("Should return true", testBaseAcionRunnable.checkState()); + + // 2. with isTimeout false and + Mockito.doReturn(false).when(testBaseAcionRunnable).isTimeout("checkState"); + + // 2.1 with task not all done + Mockito.doReturn(false).when(mockBundleHelper).isAllTaskDone(any()); + Assert.assertFalse("Should return false", testBaseAcionRunnable.checkState()); + + // 2. 2 with task all done + Mockito.doReturn(true).when(mockBundleHelper).isAllTaskDone(any()); + + // 2.2.1 with has bundle failure + Mockito.doReturn(true).when(testBaseAcionRunnable).hasBundleOperationFailure(); + Assert.assertTrue("Should return true", testBaseAcionRunnable.checkState()); + + // 2.2.2 with no bundle failure + Mockito.doReturn(false).when(testBaseAcionRunnable).hasBundleOperationFailure(); + + 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))); + } + + @SuppressWarnings("unchecked") + @Test + public void testHasBundleOperationFailure() throws Exception { + Mockito.when(mockBundleHelper.getFailedMetrics(anyMap())).thenReturn(Long.valueOf("0")); + Assert.assertFalse("should return false", testBaseAcionRunnable.hasBundleOperationFailure()); + + Mockito.when(mockStateHelper.getCurrentOamState()).thenReturn(AppcOamStates.Restarting); + long failedNumber = 1; + Mockito.doReturn(failedNumber).when(mockBundleHelper).getFailedMetrics(anyMap()); + Assert.assertTrue("should return true", testBaseAcionRunnable.hasBundleOperationFailure()); + Mockito.verify(testBaseAcionRunnable, times(1)).setStatus(OAMCommandStatus.UNEXPECTED_ERROR, + String.format(testBaseAcionRunnable.BUNDLE_OPERATION_FAILED_FORMAT, failedNumber)); + Mockito.verify(testBaseAcionRunnable, times(1)).postAction(AppcOamStates.Error); + } + + @Test + public void testAbortRunnable() throws Exception { + Mockito.doReturn(AppcOamStates.Restarting).when(mockStateHelper).getCurrentOamState(); + AppcOam.RPC newRpc = AppcOam.RPC.restart; + testBaseAcionRunnable.abortRunnable(newRpc); + Assert.assertEquals("Should return abort code", OAMCommandStatus.ABORT.getResponseCode(), + testBaseAcionRunnable.status.getCode().intValue()); + Assert.assertTrue("Should set abort due to new request message", + testBaseAcionRunnable.status.getMessage().endsWith( + String.format(testBaseAcionRunnable.ABORT_MESSAGE_FORMAT, testRpc.name(), + String.format(testBaseAcionRunnable.NEW_RPC_OPERATION_REQUEST, newRpc.name())))); + Mockito.verify(mockOperHelper, times(1)).sendNotificationMessage(any(), any(), any()); + Mockito.verify(testBaseAcionRunnable, times(1)).resetLogProperties(false); + Mockito.verify(testBaseAcionRunnable, times(1)).resetLogProperties(true); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseCommonTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseCommonTest.java new file mode 100644 index 000000000..59bddb0e4 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseCommonTest.java @@ -0,0 +1,182 @@ +/*- + * ============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.onap.appc.oam.processor; + +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.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +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 org.slf4j.MDC; + +import java.util.Map; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.times; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + +@RunWith(PowerMockRunner.class) +@PrepareForTest({BaseCommon.class, MDC.class}) +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); + private CommonHeader mockCommonHeader = mock(CommonHeader.class); + + @Before + public void setUp() throws Exception { + testBaseCommon = spy(new TestAbc(null, mockConfigHelper, mockStateHelper, null)); + + Whitebox.setInternalState(testBaseCommon, "commonHeader", mockCommonHeader); + Whitebox.setInternalState(testBaseCommon, "rpc", AppcOam.RPC.maintenance_mode); + + // 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(); + Mockito.doReturn("testRequestId").when(mockCommonHeader).getRequestId(); + Mockito.doReturn("testOrigId").when(mockCommonHeader).getOriginatorId(); + + 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()); + Mockito.verify(testBaseCommon, times(1)).resetLogProperties(false); + Mockito.verify(testBaseCommon, times(1)).resetLogProperties(true); + + oamCommandStatus = OAMCommandStatus.REJECTED; + t = new InvalidStateException(exceptionMessage); + testBaseCommon.setErrorStatus(t); + status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + Mockito.verify(testBaseCommon, times(2)).resetLogProperties(false); + Mockito.verify(testBaseCommon, times(2)).resetLogProperties(true); + + oamCommandStatus = OAMCommandStatus.UNEXPECTED_ERROR; + t = new NullPointerException(exceptionMessage); + testBaseCommon.setErrorStatus(t); + status = testBaseCommon.status; + Assert.assertEquals("Should have code", oamCommandStatus.getResponseCode(), status.getCode().intValue()); + Mockito.verify(testBaseCommon, times(3)).resetLogProperties(false); + Mockito.verify(testBaseCommon, times(3)).resetLogProperties(true); + } + + @Test + public void testSetInitialLogProperties() throws Exception { + mockStatic(MDC.class); + testBaseCommon.setInitialLogProperties(); + PowerMockito.verifyStatic(times(5)); + } + + @Test + public void testClearRequestLogProperties() throws Exception { + mockStatic(MDC.class); + testBaseCommon.clearRequestLogProperties(); + PowerMockito.verifyStatic(times(5)); + } + + @Test + public void testResetLogProperties() throws Exception { + testBaseCommon.setInitialLogProperties(); + + testBaseCommon.resetLogProperties(false); + Mockito.verify(mockCommonHeader, times(2)).getRequestId(); + Mockito.verify(mockCommonHeader, times(2)).getOriginatorId(); + Map<String, String> oldMdcMap = Whitebox.getInternalState(testBaseCommon, "oldMdcContent"); + Assert.assertTrue("Should have 5 entries in persisted map", oldMdcMap.size() == 5); + + testBaseCommon.resetLogProperties(false); + Mockito.verify(mockCommonHeader, times(3)).getRequestId(); + Mockito.verify(mockCommonHeader, times(3)).getOriginatorId(); + + // test oldMdcMap is cleared + testBaseCommon.resetLogProperties(false); + Mockito.verify(mockCommonHeader, times(4)).getRequestId(); + Mockito.verify(mockCommonHeader, times(4)).getOriginatorId(); + oldMdcMap = Whitebox.getInternalState(testBaseCommon, "oldMdcContent"); + Assert.assertTrue("Should have 5 entries in persisted map", oldMdcMap.size() == 5); + } +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseProcessorTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseProcessorTest.java new file mode 100644 index 000000000..6769352c6 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/processor/BaseProcessorTest.java @@ -0,0 +1,174 @@ +/*- + * ============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.onap.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.onap.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.status.Status; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.i18n.Msg; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.oam.OAMCommandStatus; +import org.onap.appc.oam.util.AsyncTaskHelper; +import org.onap.appc.oam.util.ConfigurationHelper; +import org.onap.appc.oam.util.OperationHelper; +import org.onap.appc.oam.util.StateHelper; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.powermock.reflect.Whitebox; + +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(); + Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "runnable") == null); + Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "scheduledRunnable") == null); + + BaseActionRunnable mockRunnable = mock(BaseActionRunnable.class); + Whitebox.setInternalState(testBaseProcessor, "runnable", mockRunnable); + testBaseProcessor.scheduleAsyncTask(); + // scheduledRunnable should still be null, there's no mock done + // as I have trouble to make mockTaskHelper.scheduleBaseRunnable to return a proper Future + Assert.assertTrue(Whitebox.getInternalState(testBaseProcessor, "scheduledRunnable") == null); + } + +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/AsyncTaskHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/AsyncTaskHelperTest.java new file mode 100644 index 000000000..ddeb99440 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/AsyncTaskHelperTest.java @@ -0,0 +1,665 @@ +/*- + * ============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.onap.appc.oam.util; + +import com.att.eelf.configuration.EELFLogger; +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.statemachine.impl.readers.AppcOamStates; +import org.osgi.framework.Bundle; +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 java.util.LinkedList; +import java.util.concurrent.Future; +import java.util.concurrent.Semaphore; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Supplier; + +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.powermock.api.mockito.PowerMockito.mockStatic; + + +@RunWith(PowerMockRunner.class) +@PrepareForTest({FrameworkUtil.class}) +public class AsyncTaskHelperTest { + private AsyncTaskHelper asyncTaskHelper; + + private long initialDelayMillis = 0; + private long delayMillis = 10; + + + @Before + public void setUp() throws Exception { + + // to avoid operation on logger fail, mock up the logger + EELFLogger mockLogger = mock(EELFLogger.class); + + + mockStatic(FrameworkUtil.class); + Bundle myBundle = mock(Bundle.class); + Mockito.doReturn("TestBundle").when(myBundle).getSymbolicName(); + PowerMockito.when(FrameworkUtil.getBundle(any())).thenReturn(myBundle); + + asyncTaskHelper = new AsyncTaskHelper(mockLogger); + + + } + + + @After + public void shutdown(){ + asyncTaskHelper.close(); + } + + + /** + * Test that Base Runnable + * + * Runs at a fix rate; + * Only one Base Runnable can be scheduled at time; + * Future.cancle stops the Base Runnable; + * That another Base Runnable can be scheduled once the previous isDone. + */ + @Test + public void test_scheduleBaseRunnable_Base_isDone() throws Exception{ + + + + //loop is to test we can run consecutive Base Runnable + for(int testIteration = 0; testIteration < 3;testIteration++){ + final ExecuteTest et = new ExecuteTest(); + + Future<?> future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , s -> { } + ,initialDelayMillis + ,delayMillis + ); + + //make sure it is running at a fix rate + Assert.assertTrue("It should be iterating", et.waitForTestExec(5000)); + Assert.assertFalse("It Should not be Done", future.isDone()); + Assert.assertTrue("It should be iterating", et.waitForTestExec(5000)); + Assert.assertFalse("It Should not be Done", future.isDone()); + + + //make sure a seconds Runnable cannot be scheduled when one is already running + try { + asyncTaskHelper.scheduleBaseRunnable(et::test + , s -> {} + ,initialDelayMillis + ,delayMillis + ); + Assert.fail("scheduling should have been prevented. "); + } catch (IllegalStateException e) { + //IllegalStateException means the second scheduling was not allowed. + } + + + //let it cancel itself + et.cancelSelfOnNextExecution(future); + + //it should be done after it executes itself one more time. + Assert.assertTrue("it should be done", waitFor(future::isDone, 5000)); + Assert.assertTrue("The test failed to execute", et.isExecuted); + } + + + } + + + /** + * Makes sure the Future.isDone one only returns true if its runnable is not currently executing and will not + * execute in the future. Default implementation of isDone() returns true immediately after the future is + * canceled -- Even if is there is still a thread actively executing the runnable + */ + @Test + public void test_scheduleBaseRunnable_Base_isDone_Ignore_Interrupt() throws Exception{ + + + final ExecuteTest et = new ExecuteTest(); + + //configure test to run long and ignore interrupt + et.isContinuous = true; + et.isIgnoreInterrupt = true; + + + + Future<?> future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , s->{} + ,initialDelayMillis + ,delayMillis + ); + + //make sure it is running + Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); + Assert.assertTrue("It should be running",et.waitForTestExec(1000)); + Assert.assertFalse("It Should not be Done", future.isDone()); + + //cancel it and make sure it is still running + future.cancel(true); + Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); + Assert.assertTrue("It should be running",et.waitForTestExec(1000)); + Assert.assertFalse("It Should not be Done", future.isDone()); + + //let the thread die and then make sure its done + et.isContinuous = false; + Assert.assertTrue("It should not be running",waitForNot(et::isExecuting,1000)); + Assert.assertTrue("It Should be Done", future.isDone()); + + } + + + + + /** + * Make sure the base Future.isDone returns false until the sub callable has completed execution. + */ + @Test + public void test_scheduleBaseRunnable_SubTask_isDone_Ignore_Interrupt() throws Exception{ + + + final ExecuteTest baseET = new ExecuteTest(); + final ExecuteTest subET = new ExecuteTest(); + + //configure sub test to run long and ignore interrupt + subET.isContinuous = true; + subET.isIgnoreInterrupt = true; + + + //schedule the Base test to run and make sure it is running. + Future<?> baseFuture = asyncTaskHelper.scheduleBaseRunnable( + baseET::test + ,s->{} + ,initialDelayMillis + ,delayMillis + ); + Assert.assertTrue("baseET should be running",waitFor(baseET::isExecuted,1000)); + Assert.assertFalse("baseET Should not be Done because it runs at a fix rate", baseFuture.isDone()); + + + //schedule the sub task and make sure it is running + Future<?> subFuture = asyncTaskHelper.submitBaseSubCallable(subET::test); + Assert.assertTrue("subET should be running",waitFor(subET::isExecuting,1000)); + Assert.assertTrue("subET should be running",subET.waitForTestExec(1000)); + Assert.assertFalse("subET Should not be Done", subFuture.isDone()); + Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); + + //cancel the base task and make sure isDone is still false + baseFuture.cancel(true); + Assert.assertTrue("subET should be running",waitFor(subET::isExecuting,1000)); + Assert.assertTrue("subET should be running",subET.waitForTestExec(1000)); + Assert.assertFalse("subET Should not be Done",subFuture.isDone()); + Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); + + + //let the sub task die and and make sure the base is now finally done + subET.isContinuous = false; + Assert.assertTrue("subET should not be running",waitForNot(subET::isExecuting,1000)); + Assert.assertTrue("subET Should be Done", subFuture.isDone()); + Assert.assertTrue("baseET Should be Done", baseFuture.isDone()); + + } + + + /** + * Make sure the base Future.isDone returns false until the 3 sub callable has completed execution. + * Each sub callable will be shutdown one at a time. + */ + @Test + public void test_scheduleBaseRunnable_SubTasks_isDone() throws Exception { + + + //loop is to test we can run consecutive Base Runnable + for (int testIteration = 0; testIteration < 3; testIteration++) { + final ExecuteTest baseET = new ExecuteTest(); + final LinkedList<Sub> subList = new LinkedList<>(); + for (int i = 0; i < 3; i++) { + Sub sub = new Sub(); + sub.et.isContinuous = true; + subList.add(sub); + } + + + //schedule the base runnable and make sure it is running + Future<?> baseFuture = asyncTaskHelper.scheduleBaseRunnable( + baseET::test + , s -> { + } + , initialDelayMillis + , delayMillis + ); + Assert.assertTrue("baseET should be running", waitFor(baseET::isExecuted, 1000)); + Assert.assertFalse("baseET Should not be Done because it runs at a fix rate", baseFuture.isDone()); + + + //schedule the sub Callables and make sure these are running + subList.forEach(sub -> sub.future = asyncTaskHelper.submitBaseSubCallable(sub.et::test)); + for (Sub sub : subList) { + Assert.assertTrue("subET should be running", waitFor(sub.et::isExecuting, 100)); + Assert.assertTrue("subET should be running", sub.et.waitForTestExec(1000)); + Assert.assertFalse("subET Should not be Done", sub.future.isDone()); + } + Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); + + + //On each iteration shut down a sub callable. Make sure it stops, the others are still running and the + // //base is still running. + while (!subList.isEmpty()) { + + //stop one sub and make sure it stopped + { + Sub sub = subList.removeFirst(); + Assert.assertTrue("subET should be running", waitFor(sub.et::isExecuting, 1000)); + sub.et.isContinuous = false; + Assert.assertTrue("subET should not be running", waitForNot(sub.et::isExecuting,1000)); + Assert.assertTrue("subET Should not be Done", sub.future.isDone()); + } + + //make sure the other are still running + for (Sub sub : subList) { + Assert.assertTrue("subET should be running", waitFor(sub.et::isExecuting, 1000)); + Assert.assertTrue("subET should be running", sub.et.waitForTestExec(1000)); + Assert.assertFalse("subET Should not be Done", sub.future.isDone()); + } + + //Make sure the Base is still running + Assert.assertFalse("baseET Should not be Done", baseFuture.isDone()); + } + + //let the base cancel itself and make sure it stops + baseET.cancelSelfOnNextExecution(baseFuture); + Assert.assertTrue("baseET should be done", waitFor(baseFuture::isDone, 1000)); + } + } + + + /** + * Make sure SubCallable cannot be scheduled when there is not BaseRunnable + */ + @Test(expected=IllegalStateException.class) + public void test_SubTasksScheduleFailWhenNoBase() throws Exception { + asyncTaskHelper.submitBaseSubCallable(()->null); + } + + + + /** + * Make sure SubCallable cannot be scheduled when BaseRunnable is cancelled but is still actively running. + */ + @Test(expected=IllegalStateException.class) + public void test_SubTasksScheduleFailWhenBaseCanceledBeforeisDone() throws Exception { + + final ExecuteTest et = new ExecuteTest(); + et.isContinuous = true; + + Future<?> future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , s -> { } + ,initialDelayMillis + ,delayMillis + ); + + Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); + future.cancel(false); + Assert.assertTrue("It should be running",waitFor(et::isExecuting,1000)); + + try { + asyncTaskHelper.submitBaseSubCallable(() -> null); + } finally { + et.isContinuous = false; + } + + + + } + + + /** + * Make sure SubCallable cannot be scheduled after a BaseRunnable has completed + */ + @Test(expected=IllegalStateException.class) + public void test_SubTasksScheduleFailAfterBaseDone() throws Exception { + + final ExecuteTest et = new ExecuteTest(); + + Future<?> future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , s -> { } + ,initialDelayMillis + ,delayMillis + ); + + + future.cancel(false); + Assert.assertTrue("It should not be running",waitFor(future::isDone,1000)); + + try { + asyncTaskHelper.submitBaseSubCallable(() -> null); + } finally { + et.isContinuous = false; + } + + } + + + /** + * Test {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}} + * Test cancel does not block when BaseRunnable is not scheduled + */ + @Test + public void test_cancel_noBlockingWhenBaseRunnableNotScheduled() throws Exception{ + //nothing is running so this should return immediately without TimeoutException + asyncTaskHelper.cancelBaseActionRunnable(AppcOam.RPC.stop , AppcOamStates.Started , 1, TimeUnit.MILLISECONDS); + } + + + + /** + * Test {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}} + * Test cancel does blocks until BaseRunnable is done scheduled + */ + @Test() + public void test_cancel_BlockingWhenBaseRunnableNotDone() throws Exception { + + + final ExecuteTest et = new ExecuteTest(); + et.isContinuous = true; + et.isIgnoreInterrupt = true; + asyncTaskHelper.scheduleBaseRunnable( + et::test + , s -> { + } + , initialDelayMillis + , delayMillis + ); + + Assert.assertTrue("It should be running", waitFor(et::isExecuting, 1000)); + + + //we should get a timeout + try { + asyncTaskHelper.cancelBaseActionRunnable( + AppcOam.RPC.stop, + AppcOamStates.Started, + 1, + TimeUnit.MILLISECONDS); + Assert.fail("Should have gotten TimeoutException"); + } catch (TimeoutException e) { + //just ignore as it is expected + } + + + //release the test thread + et.isContinuous = false; + + + //we should not get a timeout + asyncTaskHelper.cancelBaseActionRunnable( + AppcOam.RPC.stop, + AppcOamStates.Started, + 1000, + TimeUnit.MILLISECONDS); + + } + + + + /** + * Test {@link AsyncTaskHelper#cancelBaseActionRunnable(AppcOam.RPC, AppcOamStates, long, TimeUnit)}} + * Test cancel does not block when BaseRunnable is not scheduled + */ + @Test + public void test_BaseRunnableCancelCallback() throws Exception{ + + AtomicReference<AppcOam.RPC> cancelCallback = new AtomicReference<>(null); + + final ExecuteTest et = new ExecuteTest(); + et.isContinuous = true; + Future<?> future = asyncTaskHelper.scheduleBaseRunnable( + et::test + , cancelCallback::set + , initialDelayMillis + , delayMillis + ); + + Assert.assertTrue("It should be running", waitFor(et::isExecuting, 1000)); + Assert.assertTrue("It should be running", waitForNot(future::isDone, 1000)); + + + try { + asyncTaskHelper.cancelBaseActionRunnable( + AppcOam.RPC.stop, + AppcOamStates.Started, + 1, + TimeUnit.MILLISECONDS); + Assert.fail("Should have gotten TimeoutException"); + } catch (TimeoutException e) { + //just ignore as it is expected + } + + + Assert.assertEquals("Unexpected rpc in call back",AppcOam.RPC.stop,cancelCallback.get()); + } + + + + + + + + + /** + * @return true if the negation of the expected value is returned from the supplier within the specified + * amount of time + */ + private static boolean waitForNot(Supplier<Boolean> s,long timeoutMillis)throws Exception{ + return waitFor(()->!s.get(),timeoutMillis); + } + + + /** + * @return true if the expected value is returned from the supplier within the specified + * amount of time + */ + private static boolean waitFor(Supplier<Boolean> s,long timeoutMillis) throws Exception { + long timeout = TimeUnit.MILLISECONDS.toMillis(timeoutMillis); + long expiryTime = System.currentTimeMillis() + timeout; + long elapsedTime; + while(!s.get()){ + elapsedTime = expiryTime - System.currentTimeMillis(); + if(elapsedTime < 1) { + break; + } + Thread.sleep(10); + } + return s.get(); + } + + + /** + * This class is used control a thread executed in th {@link #test()} + */ + @SuppressWarnings("unused") + private static class ExecuteTest { + + + /** A fail safe to insure this TEst does not run indefinitely */ + private final long EXPIRY_TIME = System.currentTimeMillis() + 10000; + + + + /** A thread sets this value to true when it has completed the execution the of executes {@link #test()} */ + private volatile boolean isExecuted = false; + + /** + * A thread sets this value to true when it is actively executing {@link #test()} and back to false when + * it is not + */ + private volatile boolean isExecuting = false; + + /** + * While this value is true, a thread will not be allowed to return from {@link #test()} It will simulate a + * long execution. + */ + private volatile boolean isContinuous = false; + + /** + * When this value is set to true, an ongoing simulation of a long execution of {@link #test()} cannot be force + * to abort via a {@link Thread#interrupt()} + */ + private volatile boolean isIgnoreInterrupt = false; + + + + /** Use to send a signal to the thread executing {@link #notifyTestExcuted(long)} */ + private Semaphore inner = new Semaphore(0); + + /** Use to send a signal to the thread executing {@link #waitForTestExec(long)} */ + private Semaphore outer = new Semaphore(0); + + /** The {@link Future} of the Thread executing {@link #test()}*/ + private volatile Future<?> future; + + /** + * When set the Thread executing {@link #test()} will cancel itself + * @param future - The {@link Future} of the Thread executing {@link #test()} + */ + private void cancelSelfOnNextExecution(Future<?> future) { + this.future = future; + } + + + private boolean isExecuted() { + return isExecuted; + } + + private boolean isExecuting() { + return isExecuting; + } + + + private boolean isContinuous() { + return isContinuous; + } + + + private boolean isIgnoreInterrupt() { + return isIgnoreInterrupt; + } + + + + /** + * The thread executing this method if blocked from returning until the thread executing + * {@link #test()} invokes {@link #notifyTestExcuted(long)} or the specified time elapses + * @param timeoutMillis - the amount of time to wait for a execution iteration. + * @return true if the Thread is released because of an invocation of {@link #notifyTestExcuted(long)} + * @throws InterruptedException - If the Caller thread is interrupted. + */ + private boolean waitForTestExec(long timeoutMillis) throws InterruptedException { + inner.release(); + return outer.tryAcquire(timeoutMillis,TimeUnit.MILLISECONDS); + } + + + /** + * Test simulator + * @return Always returns true. + */ + private Boolean test() { + isTestExpired(); + System.out.println("started"); + isExecuting = true; + try { + if (future != null) { + future.cancel(false); + } + if(!isContinuous){ + notifyTestExcuted(1); + } + + while(isContinuous){ + notifyTestExcuted(100); + isTestExpired(); + } + + } finally { + isExecuting = false; + isExecuted = true; + } + return true; + } + + + /** @throws RuntimeException if the test has bee running too long */ + private void isTestExpired(){ + if(System.currentTimeMillis() > EXPIRY_TIME){ + throw new RuntimeException("Something went wrong the test expired."); + } + } + + + /** + * The thread executing {@link #test()} if blocked from returning until another thread invokes + * {@link #waitForTestExec(long)} or the specified time elapses + * @param timeoutMillis - the amount of time to wait for a execution iteration. + * @return true if the Thread is released because of an invocation of {@link #waitForTestExec(long)} + */ + private boolean notifyTestExcuted(long timeoutMillis){ + try { + boolean acquire = inner.tryAcquire(timeoutMillis,TimeUnit.MILLISECONDS); + if(acquire){ + outer.release(); + System.out.println("release"); + } + } catch (InterruptedException e) { + if(!isIgnoreInterrupt){ + return false; + } + } + return true; + } + } + + + static class Sub { + ExecuteTest et = new ExecuteTest(); + Future<?> future = null; + } + +} diff --git a/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/BundleHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/BundleHelperTest.java new file mode 100644 index 000000000..433e87517 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/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.onap.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.onap.appc.configuration.Configuration; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.oam.AppcOam; +import org.onap.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,null); + Assert.assertTrue("Should be completed", result); + Mockito.verify(mockTaskHelper, times(1)).submitBaseSubCallable(any()); + + // test start aborted + Mockito.doReturn(false).when(mockStateHelper).isSameState(appcOamStates); + result = bundleHelper.bundleOperations(AppcOam.RPC.start, new HashMap<>(), mockTaskHelper,null); + Assert.assertFalse("Should be abort", result); + Mockito.verify(mockTaskHelper, times(1)).submitBaseSubCallable(any()); + + // test stop + result = bundleHelper.bundleOperations(AppcOam.RPC.stop, new HashMap<>(), mockTaskHelper,null); + Assert.assertTrue("Should be completed", result); + Mockito.verify(mockTaskHelper, times(2)).submitBaseSubCallable(any()); + } + + @Test(expected = APPCException.class) + public void testBundleOperationsRpcException() throws Exception { + bundleHelper.bundleOperations(AppcOam.RPC.maintenance_mode, new HashMap<>(), mockTaskHelper,null); + } + + @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/onap/appc/oam/util/ConfigurationHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/ConfigurationHelperTest.java new file mode 100644 index 000000000..348517b72 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/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.onap.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.onap.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/onap/appc/oam/util/OperationHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/OperationHelperTest.java new file mode 100644 index 000000000..77edd1701 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/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.onap.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.onap.appc.oam.rev170303.MaintenanceModeInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StartInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.StopInput; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.CommonHeader; +import org.opendaylight.yang.gen.v1.org.onap.appc.oam.rev170303.common.header.common.header.Flags; +import org.onap.appc.exceptions.APPCException; +import org.onap.appc.exceptions.InvalidInputException; +import org.onap.appc.exceptions.InvalidStateException; +import org.onap.appc.lifecyclemanager.LifecycleManager; +import org.onap.appc.lifecyclemanager.objects.LifecycleException; +import org.onap.appc.lifecyclemanager.objects.NoTransitionDefinedException; +import org.onap.appc.oam.AppcOam; +import org.onap.appc.statemachine.impl.readers.AppcOamMetaDataReader; +import org.onap.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/onap/appc/oam/util/StateHelperTest.java b/appc-oam/appc-oam-bundle/src/test/java/org/onap/appc/oam/util/StateHelperTest.java new file mode 100644 index 000000000..9a3050e84 --- /dev/null +++ b/appc-oam/appc-oam-bundle/src/test/java/org/onap/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.onap.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.onap.appc.oam.rev170303.AppcState; +import org.onap.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()); + } +} |