Merge "DeviceState changes"
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsManagerImplTest.java
index 904cc7be57763e6984baaa9ec08270b913493a0a..aab0e8e04a6f5a02ed91782e0a6b15390f57a288 100644 (file)
@@ -1,20 +1,26 @@
+/**
+ * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
 package org.opendaylight.openflowplugin.impl.statistics;
 
+import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
-
 import com.google.common.base.Optional;
 import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
 import io.netty.util.HashedWheelTimer;
 import io.netty.util.Timeout;
-import io.netty.util.TimerTask;
 import java.lang.reflect.Field;
 import java.math.BigInteger;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.Future;
-import java.util.concurrent.TimeUnit;
 import org.junit.Assert;
 import org.junit.Before;
 import org.junit.Test;
@@ -34,6 +40,7 @@ import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
 import org.opendaylight.openflowplugin.api.OFConstants;
 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
+import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
@@ -49,6 +56,9 @@ import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext
 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
@@ -58,6 +68,7 @@ import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflow
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
+import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
 import org.opendaylight.yangtools.yang.common.RpcResult;
 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
 import org.slf4j.Logger;
@@ -71,6 +82,7 @@ public class StatisticsManagerImplTest {
 
     private static final BigInteger DUMMY_DATAPATH_ID = new BigInteger("444");
     private static final Short DUMMY_VERSION = OFConstants.OFP_VERSION_1_3;
+    public static final NodeId NODE_ID = new NodeId("ofp-unit-dummy-node-id");
 
     @Mock
     RequestContextStack mockedRequestContextStack;
@@ -112,12 +124,21 @@ public class StatisticsManagerImplTest {
     private LifecycleConductor conductor;
     @Mock
     private GetFeaturesOutput featuresOutput;
+    @Mock
+    private DeviceInitializationPhaseHandler deviceInitializationPhaseHandler;
+    @Mock
+    private DeviceInfo deviceInfo;
 
     private RequestContext<List<MultipartReply>> currentRequestContext;
     private StatisticsManagerImpl statisticsManager;
 
+
     @Before
     public void initialization() {
+        final KeyedInstanceIdentifier<Node, NodeKey> nodePath = KeyedInstanceIdentifier
+                .create(Nodes.class)
+                .child(Node.class, new NodeKey(new NodeId("openflow:10")));
+
         when(mockedFeatures.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
         when(mockedFeatures.getVersion()).thenReturn(DUMMY_VERSION);
         when(mockedFeaturesOutput.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
@@ -126,7 +147,7 @@ public class StatisticsManagerImplTest {
         when(mockedPrimConnectionContext.getFeatures()).thenReturn(mockedFeatures);
         when(mockedPrimConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
         when(mockedPrimConnectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
-        when(mockedPrimConnectionContext.getNodeId()).thenReturn(new NodeId("ut-node:123"));
+        when(mockedPrimConnectionContext.getNodeId()).thenReturn(NODE_ID);
         when(mockedPrimConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueue);
 
         when(mockedDeviceState.isFlowStatisticsAvailable()).thenReturn(Boolean.TRUE);
@@ -135,10 +156,11 @@ public class StatisticsManagerImplTest {
         when(mockedDeviceState.isPortStatisticsAvailable()).thenReturn(Boolean.TRUE);
         when(mockedDeviceState.isQueueStatisticsAvailable()).thenReturn(Boolean.TRUE);
         when(mockedDeviceState.isTableStatisticsAvailable()).thenReturn(Boolean.TRUE);
-        when(mockedDeviceState.getFeatures()).thenReturn(featuresOutput);
 
-        when(mockedDeviceState.getNodeId()).thenReturn(new NodeId("ofp-unit-dummy-node-id"));
+        when(deviceInfo.getNodeInstanceIdentifier()).thenReturn(nodePath);
+        when(deviceInfo.getNodeId()).thenReturn(NODE_ID);
 
+        when(mockedDeviceContext.getDeviceInfo()).thenReturn(deviceInfo);
         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimConnectionContext);
         when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessagSpy);
         when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(new DeviceFlowRegistryImpl());
@@ -159,16 +181,16 @@ public class StatisticsManagerImplTest {
                 Matchers.<StatisticsManagerControlService>any())).thenReturn(serviceControlRegistration);
 
         statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, false, conductor);
-        when(deviceManager.getDeviceContextFromNodeId(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
-        when(conductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
+        statisticsManager.setDeviceInitializationPhaseHandler(deviceInitializationPhaseHandler);
+        when(deviceManager.getDeviceContextFromNodeId(deviceInfo)).thenReturn(mockedDeviceContext);
+        when(conductor.getDeviceContext(deviceInfo)).thenReturn(mockedDeviceContext);
     }
 
     @Test
     public void testOnDeviceContextLevelUp() throws Exception {
-        statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, true, conductor);
         Mockito.doAnswer(new Answer<Void>() {
             @Override
-            public Void answer(final InvocationOnMock invocation) throws Throwable {
+            public Void answer(InvocationOnMock invocation) throws Throwable {
                 final FutureCallback<OfHeader> callback = (FutureCallback<OfHeader>) invocation.getArguments()[2];
                 LOG.debug("committing entry: {}", ((MultipartRequestInput) invocation.getArguments()[1]).getType());
                 callback.onSuccess(null);
@@ -179,36 +201,32 @@ public class StatisticsManagerImplTest {
                 .commitEntry(Matchers.anyLong(), Matchers.<OfHeader>any(), Matchers.<FutureCallback<OfHeader>>any());
 
         statisticsManager.setDeviceInitializationPhaseHandler(mockedDevicePhaseHandler);
-        statisticsManager.onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
-
-        verify(mockedDeviceContext, Mockito.never()).reserveXidForDeviceMessage();
-        verify(mockedDeviceState).setDeviceSynchronized(true);
-        verify(mockedDevicePhaseHandler).onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
-        verify(hashedWheelTimer, Mockito.never()).newTimeout(Matchers.<TimerTask>any(), Matchers.anyLong(), Matchers.<TimeUnit>any());
+        statisticsManager.onDeviceContextLevelUp(deviceInfo);
+        verify(mockedDevicePhaseHandler).onDeviceContextLevelUp(deviceInfo);
     }
 
     @Test
     public void testOnDeviceContextClosed() throws Exception {
         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
-        final Map<NodeId, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
+        final Map<DeviceInfo, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
 
-        contextsMap.put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
+        contextsMap.put(deviceInfo, statisticContext);
         Assert.assertEquals(1, contextsMap.size());
 
         statisticsManager.setDeviceTerminationPhaseHandler(mockedTerminationPhaseHandler);
-        statisticsManager.onDeviceContextLevelDown(mockedDeviceContext);
+        statisticsManager.onDeviceContextLevelDown(deviceInfo);
         verify(statisticContext).close();
-        verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(mockedDeviceContext);
+        verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(deviceInfo);
         Assert.assertEquals(0, contextsMap.size());
     }
 
-    private static Map<NodeId, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
+    private static Map<DeviceInfo, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
             throws NoSuchFieldException, IllegalAccessException {
         // HACK: contexts map for testing shall be accessed in some more civilized way
         final Field contextsField = StatisticsManagerImpl.class.getDeclaredField("contexts");
         Assert.assertNotNull(contextsField);
         contextsField.setAccessible(true);
-        return (Map<NodeId, StatisticsContext>) contextsField.get(statisticsManager);
+        return (Map<DeviceInfo, StatisticsContext>) contextsField.get(statisticsManager);
     }
 
     @Test
@@ -234,7 +252,7 @@ public class StatisticsManagerImplTest {
         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
                 Collections.<ItemLifeCycleSource>emptyList());
 
-        getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
+        getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
 
         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
                 new ChangeStatisticsWorkModeInputBuilder()
@@ -270,7 +288,7 @@ public class StatisticsManagerImplTest {
         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
                 Collections.singletonList(itemLifecycleSource));
 
-        getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
+        getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
 
         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
                 new ChangeStatisticsWorkModeInputBuilder()
@@ -307,7 +325,7 @@ public class StatisticsManagerImplTest {
         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
                 Collections.singletonList(itemLifecycleSource));
 
-        getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
+        getContextsMap(statisticsManager).put(deviceInfo, statisticContext);
 
         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
                 new ChangeStatisticsWorkModeInputBuilder()
@@ -342,11 +360,38 @@ public class StatisticsManagerImplTest {
     @Test
     public void testCalculateTimerDelay() throws Exception {
         final TimeCounter timeCounter = Mockito.mock(TimeCounter.class);
-        when(timeCounter.getAverageTimeBetweenMarks()).thenReturn((Long)2000L, (Long)4000L);
+        when(timeCounter.getAverageTimeBetweenMarks()).thenReturn(2000L, (Long)4000L);
 
         statisticsManager.calculateTimerDelay(timeCounter);
         Assert.assertEquals(3000L, StatisticsManagerImpl.getCurrentTimerDelay());
         statisticsManager.calculateTimerDelay(timeCounter);
         Assert.assertEquals(6000L, StatisticsManagerImpl.getCurrentTimerDelay());
     }
+
+    @Test
+    public void testPollStatistics() throws Exception {
+        final StatisticsContext statisticsContext = Mockito.mock(StatisticsContext.class);
+        final TimeCounter mockTimerCounter = Mockito.mock(TimeCounter.class);
+
+        statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
+        verify(mockedDeviceContext).getDeviceInfo();
+
+        when(mockedDeviceContext.getDeviceState().isValid()).thenReturn(true);
+        statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
+        // TODO Make scheduleNextPolling visible for tests?
+
+        when(mockedDeviceContext.getDeviceState().isStatisticsPollingEnabled()).thenReturn(true);
+        statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
+        // TODO Make scheduleNextPolling visible for tests?
+
+        when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateCheckedFuture(Boolean.TRUE));
+        when(statisticsContext.isSchedulingEnabled()).thenReturn(Boolean.TRUE);
+        statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
+        Mockito.verify(mockTimerCounter).markStart();
+        Mockito.verify(mockTimerCounter).addTimeMark();
+
+        when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateFailedFuture(new Throwable("error msg")));
+        statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
+        Mockito.verify(mockTimerCounter,times(2)).addTimeMark();
+    }
 }
\ No newline at end of file