Merge "BUG-4117: add support of Old Notif. for Statistics"
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / device / DeviceContextImplTest.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
9 package org.opendaylight.openflowplugin.impl.device;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertNull;
14 import static org.junit.Assert.assertTrue;
15 import static org.mockito.Matchers.any;
16 import static org.mockito.Matchers.eq;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.verify;
19 import static org.mockito.Mockito.when;
20
21 import com.google.common.base.Optional;
22 import com.google.common.collect.Lists;
23 import com.google.common.util.concurrent.CheckedFuture;
24 import com.google.common.util.concurrent.Futures;
25 import com.google.common.util.concurrent.ListenableFuture;
26 import com.google.common.util.concurrent.SettableFuture;
27 import io.netty.util.HashedWheelTimer;
28 import io.netty.util.Timeout;
29 import java.math.BigInteger;
30 import java.net.InetSocketAddress;
31 import java.util.concurrent.atomic.AtomicLong;
32 import org.junit.Assert;
33 import org.junit.Before;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36 import org.mockito.InOrder;
37 import org.mockito.Mock;
38 import org.mockito.Mockito;
39 import org.mockito.invocation.InvocationOnMock;
40 import org.mockito.runners.MockitoJUnitRunner;
41 import org.mockito.stubbing.Answer;
42 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
43 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
44 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
45 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
46 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
47 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
48 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
49 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
50 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
51 import org.opendaylight.openflowjava.protocol.api.keys.MessageTypeKey;
52 import org.opendaylight.openflowplugin.api.OFConstants;
53 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
54 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
55 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
56 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
57 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
58 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
59 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
60 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
61 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
62 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
63 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
64 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
65 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
66 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
67 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
68 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
69 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
70 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
71 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
72 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
73 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
74 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
75 import org.opendaylight.openflowplugin.extension.api.ConvertorMessageFromOFJava;
76 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
77 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
78 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
79 import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
80 import org.opendaylight.openflowplugin.openflow.md.util.OpenflowPortsUtil;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.message.service.rev151020.ExperimenterMessageFromDev;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemovedBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.*;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.experimenter.core.ExperimenterDataOfChoice;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
104 import org.opendaylight.yangtools.concepts.Registration;
105 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
106 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
107 import org.opendaylight.yangtools.yang.common.RpcResult;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
110
111 @RunWith(MockitoJUnitRunner.class)
112 public class DeviceContextImplTest {
113     private static final Logger LOG = LoggerFactory
114             .getLogger(DeviceContextImplTest.class);
115     private static final short DUMMY_AUXILIARY_ID = 33;
116     private static final BigInteger DUMMY_COOKIE = new BigInteger("33");
117     private static final Long DUMMY_XID = 544L;
118     private static final Long DUMMY_PORT_NUMBER = 159L;
119     private static final BigInteger DUMMY_DATAPATH_ID = new BigInteger("55");
120     Xid xid;
121     Xid xidMulti;
122     DeviceContextImpl deviceContext;
123     @Mock
124     TransactionChainManager txChainManager;
125     @Mock
126     RequestContext<GetAsyncReply> requestContext;
127     @Mock
128     RequestContext<MultipartReply> requestContextMultiReply;
129
130     @Mock
131     ConnectionContext connectionContext;
132     @Mock
133     DeviceState deviceState;
134     @Mock
135     GetFeaturesOutput featuresOutput;
136     @Mock
137     DataBroker dataBroker;
138     @Mock
139     WriteTransaction wTx;
140     @Mock
141     ReadOnlyTransaction rTx;
142     @Mock
143     BindingTransactionChain txChainFactory;
144     @Mock
145     HashedWheelTimer timer;
146     @Mock
147     MessageIntelligenceAgency messageIntelligenceAgency;
148     @Mock
149     OutboundQueueProvider outboundQueueProvider;
150     @Mock
151     ConnectionAdapter connectionAdapter;
152     NodeId nodeId = new NodeId("h2g2:42");
153     KeyedInstanceIdentifier<Node, NodeKey> nodeKeyIdent = DeviceStateUtil.createNodeInstanceIdentifier(nodeId);
154     @Mock
155     TranslatorLibrary translatorLibrary;
156     @Mock
157     Registration registration;
158     @Mock
159     MessageTranslator messageTranslatorPacketReceived;
160     @Mock
161     MessageTranslator messageTranslatorFlowCapableNodeConnector;
162     @Mock
163     private MessageTranslator<Object, Object> messageTranslatorFlowRemoved;
164     @Mock
165     private LifecycleConductor lifecycleConductor;
166
167     private InOrder inOrderDevState;
168
169     private final AtomicLong atomicLong = new AtomicLong(0);
170
171     private DeviceContext deviceContextSpy;
172
173     @Before
174     public void setUp() {
175         final CheckedFuture<Optional<Node>, ReadFailedException> noExistNodeFuture = Futures.immediateCheckedFuture(Optional.<Node>absent());
176         Mockito.when(rTx.read(LogicalDatastoreType.OPERATIONAL, nodeKeyIdent)).thenReturn(noExistNodeFuture);
177         Mockito.when(dataBroker.newReadOnlyTransaction()).thenReturn(rTx);
178         Mockito.when(dataBroker.createTransactionChain(Mockito.any(TransactionChainManager.class))).thenReturn(txChainFactory);
179         Mockito.when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodeKeyIdent);
180         Mockito.when(deviceState.getNodeId()).thenReturn(nodeId);
181 //        txChainManager = new TransactionChainManager(dataBroker, deviceState);
182         final SettableFuture<RpcResult<GetAsyncReply>> settableFuture = SettableFuture.create();
183         final SettableFuture<RpcResult<MultipartReply>> settableFutureMultiReply = SettableFuture.create();
184         Mockito.when(requestContext.getFuture()).thenReturn(settableFuture);
185         Mockito.doAnswer(new Answer<Object>() {
186             @SuppressWarnings("unchecked")
187             @Override
188             public Object answer(final InvocationOnMock invocation) {
189                 settableFuture.set((RpcResult<GetAsyncReply>) invocation.getArguments()[0]);
190                 return null;
191             }
192         }).when(requestContext).setResult(any(RpcResult.class));
193
194         Mockito.when(requestContextMultiReply.getFuture()).thenReturn(settableFutureMultiReply);
195         Mockito.doAnswer(new Answer<Object>() {
196             @SuppressWarnings("unchecked")
197             @Override
198             public Object answer(final InvocationOnMock invocation) {
199                 settableFutureMultiReply.set((RpcResult<MultipartReply>) invocation.getArguments()[0]);
200                 return null;
201             }
202         }).when(requestContextMultiReply).setResult(any(RpcResult.class));
203         Mockito.when(txChainFactory.newWriteOnlyTransaction()).thenReturn(wTx);
204         Mockito.when(dataBroker.newReadOnlyTransaction()).thenReturn(rTx);
205         Mockito.when(connectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
206         Mockito.when(connectionContext.getConnectionAdapter()).thenReturn(connectionAdapter);
207         final FeaturesReply mockedFeaturesReply = mock(FeaturesReply.class);
208         when(connectionContext.getFeatures()).thenReturn(mockedFeaturesReply);
209         when(connectionContext.getFeatures().getCapabilities()).thenReturn(mock(Capabilities.class));
210
211         Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
212         Mockito.when(featuresOutput.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
213         Mockito.when(featuresOutput.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
214         Mockito.when(deviceState.getFeatures()).thenReturn(featuresOutput);
215         Mockito.when(messageTranslatorPacketReceived.translate(any(Object.class), any(DeviceState.class), any(Object.class))).thenReturn(mock(PacketReceived.class));
216         Mockito.when(messageTranslatorFlowCapableNodeConnector.translate(any(Object.class), any(DeviceState.class), any(Object.class))).thenReturn(mock(FlowCapableNodeConnector.class));
217         Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PacketIn.class.getName())))).thenReturn(messageTranslatorPacketReceived);
218         Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PortGrouping.class.getName())))).thenReturn(messageTranslatorFlowCapableNodeConnector);
219         Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3,
220                 org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved.class.getName()))))
221                 .thenReturn(messageTranslatorFlowRemoved);
222         Mockito.when(lifecycleConductor.getMessageIntelligenceAgency()).thenReturn(messageIntelligenceAgency);
223
224         deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary, false);
225
226         deviceContextSpy = Mockito.spy(deviceContext);
227
228         xid = new Xid(atomicLong.incrementAndGet());
229         xidMulti = new Xid(atomicLong.incrementAndGet());
230     }
231
232     @Test(expected = NullPointerException.class)
233     public void testDeviceContextImplConstructorNullDataBroker() throws Exception {
234         new DeviceContextImpl(connectionContext, deviceState, null, lifecycleConductor, outboundQueueProvider, translatorLibrary, false).close();
235     }
236
237     @Test(expected = NullPointerException.class)
238     public void testDeviceContextImplConstructorNullDeviceState() throws Exception {
239         new DeviceContextImpl(connectionContext, null, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary, false).close();
240     }
241
242     @Test(expected = NullPointerException.class)
243     public void testDeviceContextImplConstructorNullTimer() throws Exception {
244         new DeviceContextImpl(null, deviceState, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary, false).close();
245     }
246
247     @Test
248     public void testGetDeviceState() {
249         final DeviceState deviceSt = deviceContext.getDeviceState();
250         assertNotNull(deviceSt);
251         assertEquals(deviceState, deviceSt);
252     }
253
254     @Test
255     public void testGetReadTransaction() {
256         final ReadTransaction readTx = deviceContext.getReadTransaction();
257         assertNotNull(readTx);
258         assertEquals(rTx, readTx);
259     }
260
261     /**
262      * @throws Exception
263      */
264     @Test
265     public void testInitialSubmitTransaction() throws Exception {
266         Mockito.when(wTx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
267         final InstanceIdentifier<Nodes> dummyII = InstanceIdentifier.create(Nodes.class);
268         deviceContext.getTransactionChainManager().activateTransactionManager() ;
269         deviceContext.getTransactionChainManager().enableSubmit();
270         deviceContext.addDeleteToTxChain(LogicalDatastoreType.CONFIGURATION, dummyII);
271         deviceContext.initialSubmitTransaction();
272         verify(wTx).submit();
273     }
274
275     @Test
276     public void testGetReservedXid() {
277         deviceContext.reserveXidForDeviceMessage();
278         verify(outboundQueueProvider).reserveEntry();
279     }
280
281     @Test
282     public void testAuxiliaryConnectionContext() {
283         final ConnectionContext mockedConnectionContext = addDummyAuxiliaryConnectionContext();
284         final ConnectionContext pickedConnectiobContexts = deviceContext.getAuxiliaryConnectiobContexts(DUMMY_COOKIE);
285         assertEquals(mockedConnectionContext, pickedConnectiobContexts);
286     }
287     @Test
288     public void testRemoveAuxiliaryConnectionContext() {
289         final ConnectionContext mockedConnectionContext = addDummyAuxiliaryConnectionContext();
290
291         final ConnectionAdapter mockedAuxConnectionAdapter = mock(ConnectionAdapter.class);
292         when(mockedConnectionContext.getConnectionAdapter()).thenReturn(mockedAuxConnectionAdapter);
293
294         assertNotNull(deviceContext.getAuxiliaryConnectiobContexts(DUMMY_COOKIE));
295         deviceContext.removeAuxiliaryConnectionContext(mockedConnectionContext);
296         assertNull(deviceContext.getAuxiliaryConnectiobContexts(DUMMY_COOKIE));
297     }
298
299     private ConnectionContext addDummyAuxiliaryConnectionContext() {
300         final ConnectionContext mockedConnectionContext = prepareConnectionContext();
301         deviceContext.addAuxiliaryConnectionContext(mockedConnectionContext);
302         return mockedConnectionContext;
303     }
304
305     private ConnectionContext prepareConnectionContext() {
306         final ConnectionContext mockedConnectionContext = mock(ConnectionContext.class);
307         final FeaturesReply mockedFeaturesReply = mock(FeaturesReply.class);
308         when(mockedFeaturesReply.getAuxiliaryId()).thenReturn(DUMMY_AUXILIARY_ID);
309         when(mockedConnectionContext.getFeatures()).thenReturn(mockedFeaturesReply);
310         return mockedConnectionContext;
311     }
312
313     /**
314      * @throws Exception
315      */
316     @Test
317     public void testAddDeleteToTxChain() throws Exception{
318         final InstanceIdentifier<Nodes> dummyII = InstanceIdentifier.create(Nodes.class);
319         deviceContext.getTransactionChainManager().activateTransactionManager() ;
320         deviceContext.getTransactionChainManager().enableSubmit();
321         deviceContext.addDeleteToTxChain(LogicalDatastoreType.CONFIGURATION, dummyII);
322         verify(wTx).delete(eq(LogicalDatastoreType.CONFIGURATION), eq(dummyII));
323     }
324
325     /**
326      * @throws Exception
327      */
328     @Test
329     public void testSubmitTransaction() throws Exception {
330         deviceContext.getTransactionChainManager().activateTransactionManager() ;
331         deviceContext.getTransactionChainManager().enableSubmit();
332         assertTrue(deviceContext.submitTransaction());
333     }
334
335     @Test
336     public void testGetPrimaryConnectionContext() {
337         final ConnectionContext primaryConnectionContext = deviceContext.getPrimaryConnectionContext();
338         assertEquals(connectionContext, primaryConnectionContext);
339     }
340
341     @Test
342     public void testGetDeviceFlowRegistry() {
343         final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
344         assertNotNull(deviceFlowRegistry);
345     }
346
347     @Test
348     public void testGetDeviceGroupRegistry() {
349         final DeviceGroupRegistry deviceGroupRegistry = deviceContext.getDeviceGroupRegistry();
350         assertNotNull(deviceGroupRegistry);
351     }
352
353     @Test
354     public void testGetDeviceMeterRegistry() {
355         final DeviceMeterRegistry deviceMeterRegistry = deviceContext.getDeviceMeterRegistry();
356         assertNotNull(deviceMeterRegistry);
357     }
358
359     @Test
360     public void testGetRpcContext() {
361         final RpcContext rpcContext = mock(RpcContext.class);
362         deviceContext.setRpcContext(rpcContext);
363         assertNotNull(deviceContext.getRpcContext());
364     }
365
366     @Test
367     public void testProcessReply() {
368         final Error mockedError = mock(Error.class);
369         deviceContext.processReply(mockedError);
370         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE));
371         final OfHeader mockedOfHeader = mock(OfHeader.class);
372         deviceContext.processReply(mockedOfHeader);
373         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS));
374     }
375
376     @Test
377     public void testProcessReply2() {
378         final MultipartReply mockedMultipartReply = mock(MultipartReply.class);
379         final Xid dummyXid = new Xid(DUMMY_XID);
380         deviceContext.processReply(dummyXid, Lists.newArrayList(mockedMultipartReply));
381         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE));
382     }
383
384     @Test
385     public void testProcessPacketInMessageFutureSuccess() {
386         final PacketInMessage mockedPacketInMessage = mock(PacketInMessage.class);
387         final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
388         final ListenableFuture stringListenableFuture = Futures.immediateFuture(new String("dummy value"));
389
390         when(mockedNotificationPublishService.offerNotification(any(PacketReceived.class))).thenReturn(stringListenableFuture);
391         deviceContext.setNotificationPublishService(mockedNotificationPublishService);
392         deviceContext.processPacketInMessage(mockedPacketInMessage);
393         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS));
394     }
395
396     @Test
397     public void testProcessPacketInMessageFutureFailure() {
398         final PacketInMessage mockedPacketInMessage = mock(PacketInMessage.class);
399         final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
400         final ListenableFuture dummyFuture = Futures.immediateFailedFuture(new IllegalStateException());
401
402         when(mockedNotificationPublishService.offerNotification(any(PacketReceived.class))).thenReturn(dummyFuture);
403         deviceContext.setNotificationPublishService(mockedNotificationPublishService);
404         deviceContext.processPacketInMessage(mockedPacketInMessage);
405         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED));
406     }
407
408     @Test
409     public void testTranslatorLibrary() {
410         final TranslatorLibrary pickedTranslatorLibrary = deviceContext.oook();
411         assertEquals(translatorLibrary, pickedTranslatorLibrary);
412     }
413
414     @Test
415     public void testShutdownConnection() {
416         final ConnectionAdapter mockedConnectionAdapter = mock(ConnectionAdapter.class);
417         final InetSocketAddress mockRemoteAddress = InetSocketAddress.createUnresolved("odl-unit.example.org",999);
418         when(mockedConnectionAdapter.getRemoteAddress()).thenReturn(mockRemoteAddress);
419         when(connectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
420
421         final NodeId dummyNodeId = new NodeId("dummyNodeId");
422         when(deviceState.getNodeId()).thenReturn(dummyNodeId);
423
424         final ConnectionContext mockedAuxiliaryConnectionContext = prepareConnectionContext();
425         deviceContext.addAuxiliaryConnectionContext(mockedAuxiliaryConnectionContext);
426         final DeviceTerminationPhaseHandler mockedDeviceContextClosedHandler = mock(DeviceTerminationPhaseHandler.class);
427         when(deviceState.isValid()).thenReturn(true);
428         deviceContext.shutdownConnection();
429         verify(connectionContext).closeConnection(true);
430     }
431
432     @Test
433     public void testBarrierFieldSetGet() {
434         final Timeout mockedTimeout = mock(Timeout.class);
435         deviceContext.setCurrentBarrierTimeout(mockedTimeout);
436         final Timeout pickedBarrierTimeout = deviceContext.getBarrierTaskTimeout();
437         assertEquals(mockedTimeout, pickedBarrierTimeout);
438     }
439
440     @Test
441     public void testGetMessageSpy() {
442         final MessageSpy pickedMessageSpy = deviceContext.getMessageSpy();
443         assertEquals(messageIntelligenceAgency, pickedMessageSpy);
444     }
445
446     @Test
447     public void testNodeConnector() {
448         final NodeConnectorRef mockedNodeConnectorRef = mock(NodeConnectorRef.class);
449         deviceContext.storeNodeConnectorRef(DUMMY_PORT_NUMBER, mockedNodeConnectorRef);
450         final NodeConnectorRef nodeConnectorRef = deviceContext.lookupNodeConnectorRef(DUMMY_PORT_NUMBER);
451         assertEquals(mockedNodeConnectorRef, nodeConnectorRef);
452
453     }
454
455     @Test
456     public void testOnPublished() {
457         final ConnectionContext auxiliaryConnectionContext = addDummyAuxiliaryConnectionContext();
458
459         final ConnectionAdapter mockedAuxConnectionAdapter = mock(ConnectionAdapter.class);
460         when(auxiliaryConnectionContext.getConnectionAdapter()).thenReturn(mockedAuxConnectionAdapter);
461
462         final ConnectionAdapter mockedConnectionAdapter = mock(ConnectionAdapter.class);
463         when(connectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
464
465         deviceContext.onPublished();
466         verify(mockedAuxConnectionAdapter).setPacketInFiltering(eq(false));
467         verify(mockedConnectionAdapter).setPacketInFiltering(eq(false));
468     }
469
470     @Test
471     public void testPortStatusMessage() {
472         final PortStatusMessage mockedPortStatusMessage = mock(PortStatusMessage.class);
473         final Class dummyClass = Class.class;
474         when(mockedPortStatusMessage.getImplementedInterface()).thenReturn(dummyClass);
475
476
477         final GetFeaturesOutput mockedFeature = mock(GetFeaturesOutput.class);
478         when(mockedFeature.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
479         when(deviceState.getFeatures()).thenReturn(mockedFeature);
480
481         when(mockedPortStatusMessage.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
482         when(mockedPortStatusMessage.getReason()).thenReturn(PortReason.OFPPRADD);
483
484         OpenflowPortsUtil.init();
485         deviceContext.processPortStatusMessage(mockedPortStatusMessage);
486 //        verify(txChainManager).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class), any(DataObject.class));
487     }
488
489     @Test
490     public void testProcessFlowRemovedMessage() throws Exception {
491         // prepare translation result
492         final FlowRemovedBuilder flowRemovedMdsalBld = new FlowRemovedBuilder()
493                 .setTableId((short) 0)
494                 .setPriority(42)
495                 .setCookie(new FlowCookie(BigInteger.ONE))
496                 .setMatch(new MatchBuilder().build());
497
498         Mockito.when(messageTranslatorFlowRemoved.translate(any(Object.class), any(DeviceState.class), any(Object.class)))
499                 .thenReturn(flowRemovedMdsalBld.build());
500
501         // insert flow+flowId into local registry
502         final FlowRegistryKey flowRegKey = FlowRegistryKeyFactory.create(flowRemovedMdsalBld.build());
503         final FlowDescriptor flowDescriptor = FlowDescriptorFactory.create((short) 0, new FlowId("ut-ofp:f456"));
504         deviceContext.getDeviceFlowRegistry().store(flowRegKey, flowDescriptor);
505
506         // plug in lifecycleListener
507         final ItemLifecycleListener itemLifecycleListener = Mockito.mock(ItemLifecycleListener.class);
508         for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
509             lifeCycleSource.setItemLifecycleListener(itemLifecycleListener);
510         }
511
512         // prepare empty input message
513         final FlowRemovedMessageBuilder flowRemovedBld = new FlowRemovedMessageBuilder();
514
515         // prepare path to flow to be removed
516         final KeyedInstanceIdentifier<Flow, FlowKey> flowToBeRemovedPath = nodeKeyIdent
517                 .augmentation(FlowCapableNode.class)
518                 .child(Table.class, new TableKey((short) 0))
519                 .child(Flow.class, new FlowKey(new FlowId("ut-ofp:f456")));
520
521         deviceContext.processFlowRemovedMessage(flowRemovedBld.build());
522         Mockito.verify(itemLifecycleListener).onRemoved(flowToBeRemovedPath);
523     }
524
525     @Test
526     public void testProcessExperimenterMessage() {
527         final ConvertorMessageFromOFJava mockedMessageConverter = mock(ConvertorMessageFromOFJava.class);
528         final ExtensionConverterProvider mockedExtensionConverterProvider = mock(ExtensionConverterProvider.class);
529         when(mockedExtensionConverterProvider.getMessageConverter(any(MessageTypeKey.class))).thenReturn(mockedMessageConverter);
530
531         final ExperimenterDataOfChoice mockedExperimenterDataOfChoice = mock(ExperimenterDataOfChoice.class);
532         final ExperimenterMessage experimenterMessage = new ExperimenterMessageBuilder()
533                 .setExperimenterDataOfChoice(mockedExperimenterDataOfChoice).build();
534
535         final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
536
537         deviceContext.setNotificationPublishService(mockedNotificationPublishService);
538         deviceContext.setExtensionConverterProvider(mockedExtensionConverterProvider);
539         deviceContext.processExperimenterMessage(experimenterMessage);
540
541         verify(mockedNotificationPublishService).offerNotification(any(ExperimenterMessageFromDev.class));
542     }
543
544     @Test
545     public void testOnDeviceDisconnected() throws Exception {
546         final DeviceTerminationPhaseHandler deviceContextClosedHandler = mock(DeviceTerminationPhaseHandler.class);
547
548         assertEquals(0, deviceContext.getDeviceFlowRegistry().getAllFlowDescriptors().size());
549         assertEquals(0, deviceContext.getDeviceGroupRegistry().getAllGroupIds().size());
550         assertEquals(0, deviceContext.getDeviceMeterRegistry().getAllMeterIds().size());
551
552     }
553
554     @Test
555     public void testOnClusterRoleChange() throws Exception {
556         // test role.equals(oldRole)
557         Assert.assertNull(deviceContextSpy.onClusterRoleChange(OfpRole.BECOMEMASTER, OfpRole.BECOMEMASTER).get());
558
559         // test call transactionChainManager.deactivateTransactionManager()
560         Assert.assertNull(deviceContextSpy.onClusterRoleChange(OfpRole.BECOMESLAVE, OfpRole.NOCHANGE).get());
561
562         // test call MdSalRegistrationUtils.unregisterServices(rpcContext)
563         final RpcContext rpcContext = mock(RpcContext.class);
564         deviceContextSpy.setRpcContext(rpcContext);
565         Assert.assertNull(deviceContextSpy.onClusterRoleChange(OfpRole.BECOMESLAVE, OfpRole.NOCHANGE).get());
566
567         final StatisticsContext statisticsContext = mock(StatisticsContext.class);
568         deviceContextSpy.setStatisticsContext(statisticsContext);
569
570         deviceContextSpy.onClusterRoleChange(OfpRole.NOCHANGE, OfpRole.BECOMEMASTER);
571         verify(deviceContextSpy).onDeviceTakeClusterLeadership();
572
573         Mockito.when(wTx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
574         deviceContextSpy.onClusterRoleChange(OfpRole.NOCHANGE, OfpRole.BECOMESLAVE);
575         verify(deviceContextSpy).onDeviceLostClusterLeadership();
576     }
577 }