BUG 5523 - DeviceContext additional functionality
[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.mockito.Matchers.any;
14 import static org.mockito.Matchers.eq;
15 import static org.mockito.Mockito.mock;
16 import static org.mockito.Mockito.verify;
17 import static org.mockito.Mockito.when;
18 import com.google.common.base.Optional;
19 import com.google.common.collect.Lists;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.Futures;
22 import com.google.common.util.concurrent.ListenableFuture;
23 import com.google.common.util.concurrent.SettableFuture;
24 import io.netty.util.HashedWheelTimer;
25 import io.netty.util.Timeout;
26 import java.math.BigInteger;
27 import java.net.InetSocketAddress;
28 import java.util.ArrayList;
29 import java.util.List;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.atomic.AtomicLong;
32 import org.junit.Assert;
33 import org.junit.Before;
34 import org.junit.Ignore;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.mockito.InOrder;
38 import org.mockito.Mock;
39 import org.mockito.Mockito;
40 import org.mockito.invocation.InvocationOnMock;
41 import org.mockito.runners.MockitoJUnitRunner;
42 import org.mockito.stubbing.Answer;
43 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
44 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
45 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
46 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
47 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
48 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
49 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
50 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
51 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
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.md.core.TranslatorKey;
63 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
64 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
65 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
66 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
67 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
68 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
69 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
70 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
71 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
72 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
73 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
74 import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
75 import org.opendaylight.openflowplugin.openflow.md.util.OpenflowPortsUtil;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemovedBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessageBuilder;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncReply;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketIn;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
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     DataBroker dataBroker;
136     @Mock
137     WriteTransaction wTx;
138     @Mock
139     ReadOnlyTransaction rTx;
140     @Mock
141     BindingTransactionChain txChainFactory;
142     @Mock
143     HashedWheelTimer timer;
144     @Mock
145     MessageIntelligenceAgency messageIntelligenceAgency;
146     @Mock
147     OutboundQueueProvider outboundQueueProvider;
148     @Mock
149     ConnectionAdapter connectionAdapter;
150     NodeId nodeId = new NodeId("h2g2:42");
151     KeyedInstanceIdentifier<Node, NodeKey> nodeKeyIdent = DeviceStateUtil.createNodeInstanceIdentifier(nodeId);
152     @Mock
153     TranslatorLibrary translatorLibrary;
154     @Mock
155     Registration registration;
156     @Mock
157     MessageTranslator messageTranslatorPacketReceived;
158     @Mock
159     MessageTranslator messageTranslatorFlowCapableNodeConnector;
160     @Mock
161     private MessageTranslator<Object, Object> messageTranslatorFlowRemoved;
162
163     private InOrder inOrderDevState;
164
165     private final AtomicLong atomicLong = new AtomicLong(0);
166
167     @Before
168     public void setUp() {
169         final CheckedFuture<Optional<Node>, ReadFailedException> noExistNodeFuture = Futures.immediateCheckedFuture(Optional.<Node>absent());
170         Mockito.when(rTx.read(LogicalDatastoreType.OPERATIONAL, nodeKeyIdent)).thenReturn(noExistNodeFuture);
171         Mockito.when(dataBroker.newReadOnlyTransaction()).thenReturn(rTx);
172         Mockito.when(dataBroker.createTransactionChain(Mockito.any(TransactionChainManager.class))).thenReturn(txChainFactory);
173         Mockito.when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodeKeyIdent);
174         Mockito.when(deviceState.getNodeId()).thenReturn(nodeId);
175 //        txChainManager = new TransactionChainManager(dataBroker, deviceState);
176         final SettableFuture<RpcResult<GetAsyncReply>> settableFuture = SettableFuture.create();
177         final SettableFuture<RpcResult<MultipartReply>> settableFutureMultiReply = SettableFuture.create();
178         Mockito.when(requestContext.getFuture()).thenReturn(settableFuture);
179         Mockito.doAnswer(new Answer<Object>() {
180             @SuppressWarnings("unchecked")
181             @Override
182             public Object answer(final InvocationOnMock invocation) {
183                 settableFuture.set((RpcResult<GetAsyncReply>) invocation.getArguments()[0]);
184                 return null;
185             }
186         }).when(requestContext).setResult(any(RpcResult.class));
187
188         Mockito.when(requestContextMultiReply.getFuture()).thenReturn(settableFutureMultiReply);
189         Mockito.doAnswer(new Answer<Object>() {
190             @SuppressWarnings("unchecked")
191             @Override
192             public Object answer(final InvocationOnMock invocation) {
193                 settableFutureMultiReply.set((RpcResult<MultipartReply>) invocation.getArguments()[0]);
194                 return null;
195             }
196         }).when(requestContextMultiReply).setResult(any(RpcResult.class));
197         Mockito.when(txChainFactory.newWriteOnlyTransaction()).thenReturn(wTx);
198         Mockito.when(dataBroker.newReadOnlyTransaction()).thenReturn(rTx);
199         Mockito.when(connectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
200         Mockito.when(connectionContext.getConnectionAdapter()).thenReturn(connectionAdapter);
201
202         Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
203         Mockito.when(messageTranslatorPacketReceived.translate(any(Object.class), any(DeviceContext.class), any(Object.class))).thenReturn(mock(PacketReceived.class));
204         Mockito.when(messageTranslatorFlowCapableNodeConnector.translate(any(Object.class), any(DeviceContext.class), any(Object.class))).thenReturn(mock(FlowCapableNodeConnector.class));
205         Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PacketIn.class.getName())))).thenReturn(messageTranslatorPacketReceived);
206         Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PortGrouping.class.getName())))).thenReturn(messageTranslatorFlowCapableNodeConnector);
207         Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3,
208                 org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved.class.getName()))))
209                 .thenReturn(messageTranslatorFlowRemoved);
210
211         deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker, timer, messageIntelligenceAgency, outboundQueueProvider, translatorLibrary, false);
212
213         xid = new Xid(atomicLong.incrementAndGet());
214         xidMulti = new Xid(atomicLong.incrementAndGet());
215     }
216
217     @Test(expected = NullPointerException.class)
218     public void testDeviceContextImplConstructorNullDataBroker() throws Exception {
219         new DeviceContextImpl(connectionContext, deviceState, null, timer, messageIntelligenceAgency, outboundQueueProvider, translatorLibrary, false).close();
220     }
221
222     @Test(expected = NullPointerException.class)
223     public void testDeviceContextImplConstructorNullDeviceState() throws Exception {
224         new DeviceContextImpl(connectionContext, null, dataBroker, timer, messageIntelligenceAgency, outboundQueueProvider, translatorLibrary, false).close();
225     }
226
227     @Test(expected = NullPointerException.class)
228     public void testDeviceContextImplConstructorNullTimer() throws Exception {
229         new DeviceContextImpl(null, deviceState, dataBroker, null, messageIntelligenceAgency, outboundQueueProvider, translatorLibrary, false).close();
230     }
231
232     @Test
233     public void testGetDeviceState() {
234         final DeviceState deviceSt = deviceContext.getDeviceState();
235         assertNotNull(deviceSt);
236         Assert.assertEquals(deviceState, deviceSt);
237     }
238
239     @Test
240     public void testGetReadTransaction() {
241         final ReadTransaction readTx = deviceContext.getReadTransaction();
242         assertNotNull(readTx);
243         Assert.assertEquals(rTx, readTx);
244     }
245
246     /**
247      * FIXME: Need to change the test on behalf the clustering transaction chain manager changes
248      * @throws Exception
249      */
250     @Ignore
251     @Test
252     public void testInitialSubmitTransaction() throws Exception {
253         deviceContext.initialSubmitTransaction();
254         verify(txChainManager).initialSubmitWriteTransaction();
255     }
256
257     @Test
258     public void testGetReservedXid() {
259         deviceContext.reservedXidForDeviceMessage();
260         verify(outboundQueueProvider).reserveEntry();
261     }
262
263     @Test
264     public void testAuxiliaryConnectionContext() {
265         final ConnectionContext mockedConnectionContext = addDummyAuxiliaryConnectionContext();
266         final ConnectionContext pickedConnectiobContexts = deviceContext.getAuxiliaryConnectiobContexts(DUMMY_COOKIE);
267         assertEquals(mockedConnectionContext, pickedConnectiobContexts);
268     }
269
270     private ConnectionContext addDummyAuxiliaryConnectionContext() {
271         final ConnectionContext mockedConnectionContext = prepareConnectionContext();
272         deviceContext.addAuxiliaryConnectionContext(mockedConnectionContext);
273         return mockedConnectionContext;
274     }
275
276     private ConnectionContext prepareConnectionContext() {
277         final ConnectionContext mockedConnectionContext = mock(ConnectionContext.class);
278         final FeaturesReply mockedFeaturesReply = mock(FeaturesReply.class);
279         when(mockedFeaturesReply.getAuxiliaryId()).thenReturn(DUMMY_AUXILIARY_ID);
280         when(mockedConnectionContext.getFeatures()).thenReturn(mockedFeaturesReply);
281         return mockedConnectionContext;
282     }
283
284     /**
285      * FIXME: Need to change the test on behalf the clustering transaction chain manager changes
286      * @throws Exception
287      */
288     @Ignore
289     @Test
290     public void testAddDeleteToTxChain() throws Exception{
291         final InstanceIdentifier<Nodes> dummyII = InstanceIdentifier.create(Nodes.class);
292         deviceContext.addDeleteToTxChain(LogicalDatastoreType.CONFIGURATION, dummyII);
293         verify(txChainManager).addDeleteOperationTotTxChain(eq(LogicalDatastoreType.CONFIGURATION), eq(dummyII));
294     }
295
296     /**
297      * FIXME: Need to change the test on behalf the clustering transaction chain manager changes
298      * @throws Exception
299      */
300     @Ignore
301     @Test
302     public void testSubmitTransaction() throws Exception {
303         deviceContext.submitTransaction();
304         verify(txChainManager).submitWriteTransaction();
305     }
306
307     @Test
308     public void testGetPrimaryConnectionContext() {
309         final ConnectionContext primaryConnectionContext = deviceContext.getPrimaryConnectionContext();
310         assertEquals(connectionContext, primaryConnectionContext);
311     }
312
313     @Test
314     public void testGetDeviceFlowRegistry() {
315         final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
316         assertNotNull(deviceFlowRegistry);
317     }
318
319     @Test
320     public void testGetDeviceGroupRegistry() {
321         final DeviceGroupRegistry deviceGroupRegistry = deviceContext.getDeviceGroupRegistry();
322         assertNotNull(deviceGroupRegistry);
323     }
324
325     @Test
326     public void testGetDeviceMeterRegistry() {
327         final DeviceMeterRegistry deviceMeterRegistry = deviceContext.getDeviceMeterRegistry();
328         assertNotNull(deviceMeterRegistry);
329     }
330
331     @Test
332     public void testProcessReply() {
333         final Error mockedError = mock(Error.class);
334         deviceContext.processReply(mockedError);
335         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE));
336         final OfHeader mockedOfHeader = mock(OfHeader.class);
337         deviceContext.processReply(mockedOfHeader);
338         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS));
339     }
340
341     @Test
342     public void testProcessReply2() {
343         final MultipartReply mockedMultipartReply = mock(MultipartReply.class);
344         final Xid dummyXid = new Xid(DUMMY_XID);
345         deviceContext.processReply(dummyXid, Lists.newArrayList(mockedMultipartReply));
346         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE));
347     }
348
349     @Test
350     public void testProcessPacketInMessageFutureSuccess() {
351         final PacketInMessage mockedPacketInMessage = mock(PacketInMessage.class);
352         final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
353         final ListenableFuture stringListenableFuture = Futures.immediateFuture(new String("dummy value"));
354
355         when(mockedNotificationPublishService.offerNotification(any(PacketReceived.class))).thenReturn(stringListenableFuture);
356         deviceContext.setNotificationPublishService(mockedNotificationPublishService);
357         deviceContext.processPacketInMessage(mockedPacketInMessage);
358         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS));
359     }
360
361     @Test
362     public void testProcessPacketInMessageFutureFailure() {
363         final PacketInMessage mockedPacketInMessage = mock(PacketInMessage.class);
364         final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
365         final ListenableFuture dummyFuture = Futures.immediateFailedFuture(new IllegalStateException());
366
367         when(mockedNotificationPublishService.offerNotification(any(PacketReceived.class))).thenReturn(dummyFuture);
368         deviceContext.setNotificationPublishService(mockedNotificationPublishService);
369         deviceContext.processPacketInMessage(mockedPacketInMessage);
370         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED));
371     }
372
373     @Test
374     public void testTranslatorLibrary() {
375         final TranslatorLibrary pickedTranslatorLibrary = deviceContext.oook();
376         assertEquals(translatorLibrary, pickedTranslatorLibrary);
377     }
378
379     @Test
380     public void testGetTimer() {
381         final HashedWheelTimer pickedTimer = deviceContext.getTimer();
382         assertEquals(timer, pickedTimer);
383     }
384
385     @Test
386     public void testClose() {
387         final ConnectionAdapter mockedConnectionAdapter = mock(ConnectionAdapter.class);
388         final InetSocketAddress mockRemoteAddress = InetSocketAddress.createUnresolved("odl-unit.example.org",999);
389         when(mockedConnectionAdapter.getRemoteAddress()).thenReturn(mockRemoteAddress);
390         when(connectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
391
392         final NodeId dummyNodeId = new NodeId("dummyNodeId");
393         when(deviceState.getNodeId()).thenReturn(dummyNodeId);
394
395         final ConnectionContext mockedAuxiliaryConnectionContext = prepareConnectionContext();
396         deviceContext.addAuxiliaryConnectionContext(mockedAuxiliaryConnectionContext);
397         final DeviceTerminationPhaseHandler mockedDeviceContextClosedHandler = mock(DeviceTerminationPhaseHandler.class);
398         deviceContext.addDeviceContextClosedHandler(mockedDeviceContextClosedHandler);
399         when(deviceState.isValid()).thenReturn(true);
400         deviceContext.close();
401         verify(connectionContext).closeConnection(false);
402     }
403
404     @Test
405     public void testBarrierFieldSetGet() {
406         final Timeout mockedTimeout = mock(Timeout.class);
407         deviceContext.setCurrentBarrierTimeout(mockedTimeout);
408         final Timeout pickedBarrierTimeout = deviceContext.getBarrierTaskTimeout();
409         assertEquals(mockedTimeout, pickedBarrierTimeout);
410     }
411
412     @Test
413     public void testGetMessageSpy() {
414         final MessageSpy pickedMessageSpy = deviceContext.getMessageSpy();
415         assertEquals(messageIntelligenceAgency, pickedMessageSpy);
416     }
417
418     @Test
419     public void testNodeConnector() {
420         final NodeConnectorRef mockedNodeConnectorRef = mock(NodeConnectorRef.class);
421         deviceContext.storeNodeConnectorRef(DUMMY_PORT_NUMBER, mockedNodeConnectorRef);
422         final NodeConnectorRef nodeConnectorRef = deviceContext.lookupNodeConnectorRef(DUMMY_PORT_NUMBER);
423         assertEquals(mockedNodeConnectorRef, nodeConnectorRef);
424
425     }
426
427     @Test
428     public void testOnPublished() {
429         final ConnectionContext auxiliaryConnectionContext = addDummyAuxiliaryConnectionContext();
430
431         final ConnectionAdapter mockedAuxConnectionAdapter = mock(ConnectionAdapter.class);
432         when(auxiliaryConnectionContext.getConnectionAdapter()).thenReturn(mockedAuxConnectionAdapter);
433
434         final ConnectionAdapter mockedConnectionAdapter = mock(ConnectionAdapter.class);
435         when(connectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
436
437         deviceContext.onPublished();
438         verify(mockedAuxConnectionAdapter).setPacketInFiltering(eq(false));
439         verify(mockedConnectionAdapter).setPacketInFiltering(eq(false));
440     }
441
442     @Test
443     public void testPortStatusMessage() {
444         final PortStatusMessage mockedPortStatusMessage = mock(PortStatusMessage.class);
445         final Class dummyClass = Class.class;
446         when(mockedPortStatusMessage.getImplementedInterface()).thenReturn(dummyClass);
447
448
449         final GetFeaturesOutput mockedFeature = mock(GetFeaturesOutput.class);
450         when(mockedFeature.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
451         when(deviceState.getFeatures()).thenReturn(mockedFeature);
452
453         when(mockedPortStatusMessage.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
454         when(mockedPortStatusMessage.getReason()).thenReturn(PortReason.OFPPRADD);
455
456         OpenflowPortsUtil.init();
457         deviceContext.processPortStatusMessage(mockedPortStatusMessage);
458 //        verify(txChainManager).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class), any(DataObject.class));
459     }
460
461     @Test
462     public void testProcessFlowRemovedMessage() throws Exception {
463         // prepare translation result
464         final FlowRemovedBuilder flowRemovedMdsalBld = new FlowRemovedBuilder()
465                 .setTableId((short) 0)
466                 .setPriority(42)
467                 .setCookie(new FlowCookie(BigInteger.ONE))
468                 .setMatch(new MatchBuilder().build());
469
470         Mockito.when(messageTranslatorFlowRemoved.translate(any(Object.class), any(DeviceContext.class), any(Object.class)))
471                 .thenReturn(flowRemovedMdsalBld.build());
472
473         // insert flow+flowId into local registry
474         final FlowRegistryKey flowRegKey = FlowRegistryKeyFactory.create(flowRemovedMdsalBld.build());
475         final FlowDescriptor flowDescriptor = FlowDescriptorFactory.create((short) 0, new FlowId("ut-ofp:f456"));
476         deviceContext.getDeviceFlowRegistry().store(flowRegKey, flowDescriptor);
477
478         // plug in lifecycleListener
479         final ItemLifecycleListener itemLifecycleListener = Mockito.mock(ItemLifecycleListener.class);
480         for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
481             lifeCycleSource.setItemLifecycleListener(itemLifecycleListener);
482         }
483
484         // prepare empty input message
485         final FlowRemovedMessageBuilder flowRemovedBld = new FlowRemovedMessageBuilder();
486
487         // prepare path to flow to be removed
488         final KeyedInstanceIdentifier<Flow, FlowKey> flowToBeRemovedPath = nodeKeyIdent
489                 .augmentation(FlowCapableNode.class)
490                 .child(Table.class, new TableKey((short) 0))
491                 .child(Flow.class, new FlowKey(new FlowId("ut-ofp:f456")));
492
493         deviceContext.processFlowRemovedMessage(flowRemovedBld.build());
494         Mockito.verify(itemLifecycleListener).onRemoved(flowToBeRemovedPath);
495     }
496
497     @Test
498     public void testOnDeviceDisconnected() throws Exception {
499         final DeviceTerminationPhaseHandler deviceContextClosedHandler = mock(DeviceTerminationPhaseHandler.class);
500         deviceContext.addDeviceContextClosedHandler(deviceContextClosedHandler);
501
502         deviceContext.onDeviceDisconnected(connectionContext);
503
504 //        Mockito.verify(deviceState).setValid(false);
505 //        Mockito.verify(deviceContextClosedHandler).onDeviceContextClosed(deviceContext);
506         Assert.assertEquals(0, deviceContext.getDeviceFlowRegistry().getAllFlowDescriptors().size());
507         Assert.assertEquals(0, deviceContext.getDeviceGroupRegistry().getAllGroupIds().size());
508         Assert.assertEquals(0, deviceContext.getDeviceMeterRegistry().getAllMeterIds().size());
509
510     }
511
512 }