Bug 5543 - JUnit tests update
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / statistics / StatisticsManagerImplTest.java
1 /**
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.openflowplugin.impl.statistics;
9
10 import static org.mockito.Mockito.atLeastOnce;
11 import static org.mockito.Mockito.times;
12 import static org.mockito.Mockito.verify;
13 import static org.mockito.Mockito.when;
14
15 import com.google.common.base.Optional;
16 import com.google.common.util.concurrent.FutureCallback;
17 import com.google.common.util.concurrent.Futures;
18 import io.netty.util.HashedWheelTimer;
19 import io.netty.util.Timeout;
20 import java.lang.reflect.Field;
21 import java.math.BigInteger;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.concurrent.Future;
26
27 import org.junit.Assert;
28 import org.junit.Before;
29 import org.junit.Test;
30 import org.junit.runner.RunWith;
31 import org.mockito.ArgumentCaptor;
32 import org.mockito.Captor;
33 import org.mockito.Matchers;
34 import org.mockito.Mock;
35 import org.mockito.Mockito;
36 import org.mockito.invocation.InvocationOnMock;
37 import org.mockito.runners.MockitoJUnitRunner;
38 import org.mockito.stubbing.Answer;
39 import org.opendaylight.controller.sal.binding.api.BindingAwareBroker;
40 import org.opendaylight.controller.sal.binding.api.RpcProviderRegistry;
41 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
42 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
43 import org.opendaylight.openflowplugin.api.OFConstants;
44 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
45 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
46 import org.opendaylight.openflowplugin.api.openflow.device.DeviceManager;
47 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
48 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
49 import org.opendaylight.openflowplugin.api.openflow.device.RequestContextStack;
50 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
51 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
52 import org.opendaylight.openflowplugin.api.openflow.device.handlers.MultiMsgCollector;
53 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
54 import org.opendaylight.openflowplugin.api.openflow.registry.ItemLifeCycleRegistry;
55 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
56 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
57 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
58 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsManager;
59 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
60 import org.opendaylight.openflowplugin.impl.registry.flow.DeviceFlowRegistryImpl;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
69 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
70 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.ChangeStatisticsWorkModeInputBuilder;
71 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.GetStatisticsWorkModeOutput;
72 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsManagerControlService;
73 import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.openflowplugin.sm.control.rev150812.StatisticsWorkMode;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
75 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
76 import org.opendaylight.yangtools.yang.common.RpcResult;
77 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
78 import org.slf4j.Logger;
79 import org.slf4j.LoggerFactory;
80
81
82 @RunWith(MockitoJUnitRunner.class)
83 public class StatisticsManagerImplTest {
84
85     private static final Logger LOG = LoggerFactory.getLogger(StatisticsManagerImplTest.class);
86
87     private static final BigInteger DUMMY_DATAPATH_ID = new BigInteger("444");
88     private static final Short DUMMY_VERSION = OFConstants.OFP_VERSION_1_3;
89
90     @Mock
91     RequestContextStack mockedRequestContextStack;
92     @Mock
93     ConnectionContext mockedPrimConnectionContext;
94     @Mock
95     FeaturesReply mockedFeatures;
96     @Mock
97     GetFeaturesOutput mockedFeaturesOutput;
98     @Mock
99     ConnectionAdapter mockedConnectionAdapter;
100     @Mock
101     MessageSpy mockedMessagSpy;
102     @Mock
103     DeviceContext mockedDeviceContext;
104     @Mock
105     DeviceState mockedDeviceState;
106     @Mock
107     DeviceInitializationPhaseHandler mockedDevicePhaseHandler;
108     @Mock
109     DeviceTerminationPhaseHandler mockedTerminationPhaseHandler;
110     @Mock
111     private RpcProviderRegistry rpcProviderRegistry;
112     @Mock
113     private HashedWheelTimer hashedWheelTimer;
114     @Mock
115     private OutboundQueue outboundQueue;
116     @Mock
117     private MultiMsgCollector multiMagCollector;
118     @Mock
119     private ItemLifeCycleRegistry itemLifeCycleRegistry;
120     @Captor
121     private ArgumentCaptor<ItemLifecycleListener> itemLifeCycleListenerCapt;
122     @Mock
123     private BindingAwareBroker.RpcRegistration<StatisticsManagerControlService> serviceControlRegistration;
124     @Mock
125     private DeviceManager deviceManager;
126     @Mock
127     private LifecycleConductor conductor;
128     @Mock
129     private GetFeaturesOutput featuresOutput;
130
131     private RequestContext<List<MultipartReply>> currentRequestContext;
132     private StatisticsManagerImpl statisticsManager;
133
134
135     @Before
136     public void initialization() {
137         final KeyedInstanceIdentifier<Node, NodeKey> nodePath = KeyedInstanceIdentifier
138                 .create(Nodes.class)
139                 .child(Node.class, new NodeKey(new NodeId("openflow:10")));
140
141         when(mockedFeatures.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
142         when(mockedFeatures.getVersion()).thenReturn(DUMMY_VERSION);
143         when(mockedFeaturesOutput.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
144         when(mockedFeaturesOutput.getVersion()).thenReturn(DUMMY_VERSION);
145
146         when(mockedPrimConnectionContext.getFeatures()).thenReturn(mockedFeatures);
147         when(mockedPrimConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
148         when(mockedPrimConnectionContext.getConnectionState()).thenReturn(ConnectionContext.CONNECTION_STATE.WORKING);
149         when(mockedPrimConnectionContext.getNodeId()).thenReturn(new NodeId("ut-node:123"));
150         when(mockedPrimConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueue);
151
152         when(mockedDeviceState.isFlowStatisticsAvailable()).thenReturn(Boolean.TRUE);
153         when(mockedDeviceState.isGroupAvailable()).thenReturn(Boolean.TRUE);
154         when(mockedDeviceState.isMetersAvailable()).thenReturn(Boolean.TRUE);
155         when(mockedDeviceState.isPortStatisticsAvailable()).thenReturn(Boolean.TRUE);
156         when(mockedDeviceState.isQueueStatisticsAvailable()).thenReturn(Boolean.TRUE);
157         when(mockedDeviceState.isTableStatisticsAvailable()).thenReturn(Boolean.TRUE);
158         when(mockedDeviceState.getFeatures()).thenReturn(featuresOutput);
159         when(mockedDeviceState.getNodeInstanceIdentifier()).thenReturn(nodePath);
160
161         when(mockedDeviceState.getNodeId()).thenReturn(new NodeId("ofp-unit-dummy-node-id"));
162
163         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimConnectionContext);
164         when(mockedDeviceContext.getMessageSpy()).thenReturn(mockedMessagSpy);
165         when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(new DeviceFlowRegistryImpl());
166         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
167         when(mockedDeviceContext.getMultiMsgCollector(
168                 Matchers.<RequestContext<List<MultipartReply>>>any())).thenAnswer(
169                 new Answer<MultiMsgCollector>() {
170                     @Override
171                     public MultiMsgCollector answer(InvocationOnMock invocation) throws Throwable {
172                         currentRequestContext = (RequestContext<List<MultipartReply>>) invocation.getArguments()[0];
173                         return multiMagCollector;
174                     }
175                 }
176         );
177         when(mockedDeviceContext.getItemLifeCycleSourceRegistry()).thenReturn(itemLifeCycleRegistry);
178         when(rpcProviderRegistry.addRpcImplementation(
179                 Matchers.eq(StatisticsManagerControlService.class),
180                 Matchers.<StatisticsManagerControlService>any())).thenReturn(serviceControlRegistration);
181
182         statisticsManager = new StatisticsManagerImpl(rpcProviderRegistry, false, conductor);
183         when(deviceManager.getDeviceContextFromNodeId(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
184         when(conductor.getDeviceContext(Mockito.<NodeId>any())).thenReturn(mockedDeviceContext);
185     }
186
187     @Test
188     public void testOnDeviceContextLevelUp() throws Exception {
189         Mockito.doAnswer(new Answer<Void>() {
190             @Override
191             public Void answer(InvocationOnMock invocation) throws Throwable {
192                 final FutureCallback<OfHeader> callback = (FutureCallback<OfHeader>) invocation.getArguments()[2];
193                 LOG.debug("committing entry: {}", ((MultipartRequestInput) invocation.getArguments()[1]).getType());
194                 callback.onSuccess(null);
195                 currentRequestContext.setResult(RpcResultBuilder.<List<MultipartReply>>success().build());
196                 return null;
197             }
198         }).when(outboundQueue)
199                 .commitEntry(Matchers.anyLong(), Matchers.<OfHeader>any(), Matchers.<FutureCallback<OfHeader>>any());
200
201         statisticsManager.setDeviceInitializationPhaseHandler(mockedDevicePhaseHandler);
202         statisticsManager.onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
203         verify(mockedDevicePhaseHandler).onDeviceContextLevelUp(mockedDeviceContext.getDeviceState().getNodeId());
204     }
205
206     @Test
207     public void testOnDeviceContextClosed() throws Exception {
208         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
209         final Map<NodeId, StatisticsContext> contextsMap = getContextsMap(statisticsManager);
210
211         contextsMap.put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
212         Assert.assertEquals(1, contextsMap.size());
213
214         statisticsManager.setDeviceTerminationPhaseHandler(mockedTerminationPhaseHandler);
215         statisticsManager.onDeviceContextLevelDown(mockedDeviceContext);
216         verify(statisticContext).close();
217         verify(mockedTerminationPhaseHandler).onDeviceContextLevelDown(mockedDeviceContext);
218         Assert.assertEquals(0, contextsMap.size());
219     }
220
221     private static Map<NodeId, StatisticsContext> getContextsMap(final StatisticsManagerImpl statisticsManager)
222             throws NoSuchFieldException, IllegalAccessException {
223         // HACK: contexts map for testing shall be accessed in some more civilized way
224         final Field contextsField = StatisticsManagerImpl.class.getDeclaredField("contexts");
225         Assert.assertNotNull(contextsField);
226         contextsField.setAccessible(true);
227         return (Map<NodeId, StatisticsContext>) contextsField.get(statisticsManager);
228     }
229
230     @Test
231     public void testGetStatisticsWorkMode() throws Exception {
232         final Future<RpcResult<GetStatisticsWorkModeOutput>> workMode = statisticsManager.getStatisticsWorkMode();
233         Assert.assertTrue(workMode.isDone());
234         Assert.assertTrue(workMode.get().isSuccessful());
235         Assert.assertNotNull(workMode.get().getResult());
236         Assert.assertEquals(StatisticsWorkMode.COLLECTALL, workMode.get().getResult().getMode());
237     }
238
239     /**
240      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; no pollTimeout and no lifecycleRegistry
241      *
242      * @throws Exception
243      */
244     @Test
245     public void testChangeStatisticsWorkMode1() throws Exception {
246         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
247         when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
248         when(statisticContext.getPollTimeout()).thenReturn(
249                 Optional.<Timeout>absent());
250         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
251                 Collections.<ItemLifeCycleSource>emptyList());
252
253         getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
254
255         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
256                 new ChangeStatisticsWorkModeInputBuilder()
257                         .setMode(StatisticsWorkMode.FULLYDISABLED);
258
259         final Future<RpcResult<Void>> workMode = statisticsManager
260                 .changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
261
262         checkWorkModeChangeOutcome(workMode);
263         Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
264         Mockito.verify(statisticContext).getPollTimeout();
265     }
266
267     private static void checkWorkModeChangeOutcome(Future<RpcResult<Void>> workMode) throws InterruptedException, java.util.concurrent.ExecutionException {
268         Assert.assertTrue(workMode.isDone());
269         Assert.assertTrue(workMode.get().isSuccessful());
270     }
271
272
273     /**
274      * switching to {@link StatisticsWorkMode#FULLYDISABLED}; with pollTimeout and lifecycleRegistry
275      *
276      * @throws Exception
277      */
278     @Test
279     public void testChangeStatisticsWorkMode2() throws Exception {
280         final Timeout pollTimeout = Mockito.mock(Timeout.class);
281         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
282         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
283         when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
284         when(statisticContext.getPollTimeout()).thenReturn(
285                 Optional.of(pollTimeout));
286         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
287                 Collections.singletonList(itemLifecycleSource));
288
289         getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
290
291         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
292                 new ChangeStatisticsWorkModeInputBuilder()
293                         .setMode(StatisticsWorkMode.FULLYDISABLED);
294
295         Future<RpcResult<Void>> workMode = statisticsManager.changeStatisticsWorkMode(changeStatisticsWorkModeInputBld.build());
296         checkWorkModeChangeOutcome(workMode);
297
298         Mockito.verify(itemLifeCycleRegistry).getLifeCycleSources();
299         Mockito.verify(statisticContext).getPollTimeout();
300         Mockito.verify(pollTimeout).cancel();
301         Mockito.verify(itemLifecycleSource).setItemLifecycleListener(Matchers.<ItemLifecycleListener>any());
302     }
303
304     /**
305      * switching to {@link StatisticsWorkMode#FULLYDISABLED} and back
306      * to {@link StatisticsWorkMode#COLLECTALL}; with lifecycleRegistry and pollTimeout
307      *
308      * @throws Exception
309      */
310     @Test
311     public void testChangeStatisticsWorkMode3() throws Exception {
312         final Timeout pollTimeout = Mockito.mock(Timeout.class);
313         final ItemLifeCycleSource itemLifecycleSource = Mockito.mock(ItemLifeCycleSource.class);
314         Mockito.doNothing().when(itemLifecycleSource)
315                 .setItemLifecycleListener(itemLifeCycleListenerCapt.capture());
316
317         final StatisticsContext statisticContext = Mockito.mock(StatisticsContext.class);
318         when(statisticContext.getDeviceContext()).thenReturn(mockedDeviceContext);
319         when(statisticContext.getPollTimeout()).thenReturn(
320                 Optional.of(pollTimeout));
321         when(statisticContext.getItemLifeCycleListener()).thenReturn(
322                 Mockito.mock(ItemLifecycleListener.class));
323         when(itemLifeCycleRegistry.getLifeCycleSources()).thenReturn(
324                 Collections.singletonList(itemLifecycleSource));
325
326         getContextsMap(statisticsManager).put(mockedDeviceContext.getDeviceState().getNodeId(), statisticContext);
327
328         final ChangeStatisticsWorkModeInputBuilder changeStatisticsWorkModeInputBld =
329                 new ChangeStatisticsWorkModeInputBuilder()
330                         .setMode(StatisticsWorkMode.FULLYDISABLED);
331
332         Future<RpcResult<Void>> workMode;
333         workMode = statisticsManager.changeStatisticsWorkMode(
334                 changeStatisticsWorkModeInputBld.build());
335         checkWorkModeChangeOutcome(workMode);
336
337         changeStatisticsWorkModeInputBld.setMode(StatisticsWorkMode.COLLECTALL);
338         workMode = statisticsManager.changeStatisticsWorkMode(
339                 changeStatisticsWorkModeInputBld.build());
340         checkWorkModeChangeOutcome(workMode);
341
342         Mockito.verify(itemLifeCycleRegistry, Mockito.times(2)).getLifeCycleSources();
343         Mockito.verify(statisticContext).getPollTimeout();
344         Mockito.verify(pollTimeout).cancel();
345
346         final List<ItemLifecycleListener> itemLifeCycleListenerValues = itemLifeCycleListenerCapt.getAllValues();
347         Assert.assertEquals(2, itemLifeCycleListenerValues.size());
348         Assert.assertNotNull(itemLifeCycleListenerValues.get(0));
349         Assert.assertNull(itemLifeCycleListenerValues.get(1));
350     }
351
352     @Test
353     public void testClose() throws Exception {
354         statisticsManager.close();
355         Mockito.verify(serviceControlRegistration).close();
356     }
357
358     @Test
359     public void testCalculateTimerDelay() throws Exception {
360         final TimeCounter timeCounter = Mockito.mock(TimeCounter.class);
361         when(timeCounter.getAverageTimeBetweenMarks()).thenReturn((Long)2000L, (Long)4000L);
362
363         statisticsManager.calculateTimerDelay(timeCounter);
364         Assert.assertEquals(3000L, StatisticsManagerImpl.getCurrentTimerDelay());
365         statisticsManager.calculateTimerDelay(timeCounter);
366         Assert.assertEquals(6000L, StatisticsManagerImpl.getCurrentTimerDelay());
367     }
368
369     @Test
370     public void testPollStatistics() {
371         StatisticsManager statisticsManagerSpy = Mockito.spy(statisticsManager);
372
373         final StatisticsContext statisticsContext = Mockito.mock(StatisticsContext.class);
374         final TimeCounter mockTimerCounter = Mockito.mock(TimeCounter.class);
375
376         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
377         verify(mockedDeviceContext, times(2)).getDeviceState();
378
379         when(mockedDeviceContext.getDeviceState().isValid()).thenReturn(true);
380         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
381         // TODO Make scheduleNextPolling visible for tests?
382
383         when(mockedDeviceContext.getDeviceState().isStatisticsPollingEnabled()).thenReturn(true);
384         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
385         // TODO Make scheduleNextPolling visible for tests?
386
387         when(mockedDeviceContext.getDeviceState().getRole()).thenReturn(OfpRole.BECOMEMASTER);
388         when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateCheckedFuture(Boolean.TRUE));
389         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
390         Mockito.verify(mockTimerCounter).markStart();
391         Mockito.verify(mockTimerCounter).addTimeMark();
392
393         when(statisticsContext.gatherDynamicData()).thenReturn(Futures.immediateFailedFuture(new Throwable("error msg")));
394         statisticsManager.pollStatistics(mockedDeviceContext, statisticsContext, mockTimerCounter);
395         Mockito.verify(mockTimerCounter,times(2)).addTimeMark();
396     }
397 }