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