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