Bug 4957 RoleContext updated with initialization
[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.Test;
34 import org.junit.runner.RunWith;
35 import org.mockito.InOrder;
36 import org.mockito.Mock;
37 import org.mockito.Mockito;
38 import org.mockito.invocation.InvocationOnMock;
39 import org.mockito.runners.MockitoJUnitRunner;
40 import org.mockito.stubbing.Answer;
41 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
42 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
43 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
44 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
45 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
46 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
47 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
48 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
49 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
50 import org.opendaylight.openflowplugin.api.OFConstants;
51 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
52 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
53 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
54 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
55 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
56 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
57 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
58 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
59 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceContextClosedHandler;
60 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
61 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
62 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
63 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
64 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
65 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
66 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
67 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
68 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
69 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
70 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
71 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
72 import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
73 import org.opendaylight.openflowplugin.openflow.md.util.OpenflowPortsUtil;
74 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
75 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
76 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
77 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
78 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
79 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
80 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemovedBuilder;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemovedMessageBuilder;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetAsyncReply;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketIn;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PacketInMessage;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortGrouping;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.PortStatusMessage;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
102 import org.opendaylight.yangtools.concepts.Registration;
103 import org.opendaylight.yangtools.yang.binding.DataObject;
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
174         final SettableFuture<RpcResult<GetAsyncReply>> settableFuture = SettableFuture.create();
175         final SettableFuture<RpcResult<MultipartReply>> settableFutureMultiReply = SettableFuture.create();
176         Mockito.when(requestContext.getFuture()).thenReturn(settableFuture);
177         Mockito.doAnswer(new Answer<Object>() {
178             @SuppressWarnings("unchecked")
179             @Override
180             public Object answer(final InvocationOnMock invocation) {
181                 settableFuture.set((RpcResult<GetAsyncReply>) invocation.getArguments()[0]);
182                 return null;
183             }
184         }).when(requestContext).setResult(any(RpcResult.class));
185
186         Mockito.when(requestContextMultiReply.getFuture()).thenReturn(settableFutureMultiReply);
187         Mockito.doAnswer(new Answer<Object>() {
188             @SuppressWarnings("unchecked")
189             @Override
190             public Object answer(final InvocationOnMock invocation) {
191                 settableFutureMultiReply.set((RpcResult<MultipartReply>) invocation.getArguments()[0]);
192                 return null;
193             }
194         }).when(requestContextMultiReply).setResult(any(RpcResult.class));
195         Mockito.when(txChainFactory.newWriteOnlyTransaction()).thenReturn(wTx);
196         Mockito.when(dataBroker.newReadOnlyTransaction()).thenReturn(rTx);
197         Mockito.when(connectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
198         Mockito.when(connectionContext.getConnectionAdapter()).thenReturn(connectionAdapter);
199
200         Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
201         Mockito.when(messageTranslatorPacketReceived.translate(any(Object.class), any(DeviceContext.class), any(Object.class))).thenReturn(mock(PacketReceived.class));
202         Mockito.when(messageTranslatorFlowCapableNodeConnector.translate(any(Object.class), any(DeviceContext.class), any(Object.class))).thenReturn(mock(FlowCapableNodeConnector.class));
203         Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PacketIn.class.getName())))).thenReturn(messageTranslatorPacketReceived);
204         Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PortGrouping.class.getName())))).thenReturn(messageTranslatorFlowCapableNodeConnector);
205         Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3,
206                 org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved.class.getName()))))
207                 .thenReturn(messageTranslatorFlowRemoved);
208
209         deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker, timer, messageIntelligenceAgency, outboundQueueProvider, translatorLibrary);
210         deviceContext.setTransactionChainManager(txChainManager);
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).close();
219     }
220
221     @Test(expected = NullPointerException.class)
222     public void testDeviceContextImplConstructorNullDeviceState() throws Exception {
223         new DeviceContextImpl(connectionContext, null, dataBroker, timer, messageIntelligenceAgency, outboundQueueProvider, translatorLibrary).close();
224     }
225
226     @Test(expected = NullPointerException.class)
227     public void testDeviceContextImplConstructorNullTimer() throws Exception {
228         new DeviceContextImpl(null, deviceState, dataBroker, null, messageIntelligenceAgency, outboundQueueProvider, translatorLibrary).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     @Test
246     public void testInitialSubmitTransaction() {
247         deviceContext.initialSubmitTransaction();
248         verify(txChainManager).initialSubmitWriteTransaction();
249     }
250
251     @Test
252     public void testGetReservedXid() {
253         deviceContext.getReservedXid();
254         verify(outboundQueueProvider).reserveEntry();
255     }
256
257     @Test
258     public void testAuxiliaryConnectionContext() {
259         ConnectionContext mockedConnectionContext = addDummyAuxiliaryConnectionContext();
260         final ConnectionContext pickedConnectiobContexts = deviceContext.getAuxiliaryConnectiobContexts(DUMMY_COOKIE);
261         assertEquals(mockedConnectionContext, pickedConnectiobContexts);
262     }
263
264     private ConnectionContext addDummyAuxiliaryConnectionContext() {
265         ConnectionContext mockedConnectionContext = prepareConnectionContext();
266         deviceContext.addAuxiliaryConenctionContext(mockedConnectionContext);
267         return mockedConnectionContext;
268     }
269
270     private ConnectionContext prepareConnectionContext() {
271         ConnectionContext mockedConnectionContext = mock(ConnectionContext.class);
272         FeaturesReply mockedFeaturesReply = mock(FeaturesReply.class);
273         when(mockedFeaturesReply.getAuxiliaryId()).thenReturn(DUMMY_AUXILIARY_ID);
274         when(mockedConnectionContext.getFeatures()).thenReturn(mockedFeaturesReply);
275         return mockedConnectionContext;
276     }
277
278     @Test
279     public void testAddDeleteToTxChain() {
280         InstanceIdentifier<Nodes> dummyII = InstanceIdentifier.create(Nodes.class);
281         deviceContext.addDeleteToTxChain(LogicalDatastoreType.CONFIGURATION, dummyII);
282         verify(txChainManager).addDeleteOperationTotTxChain(eq(LogicalDatastoreType.CONFIGURATION), eq(dummyII));
283     }
284
285     @Test
286     public void testSubmitTransaction() {
287         deviceContext.submitTransaction();
288         verify(txChainManager).submitWriteTransaction();
289     }
290
291     @Test
292     public void testGetPrimaryConnectionContext() {
293         final ConnectionContext primaryConnectionContext = deviceContext.getPrimaryConnectionContext();
294         assertEquals(connectionContext, primaryConnectionContext);
295     }
296
297     @Test
298     public void testGetDeviceFlowRegistry() {
299         final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
300         assertNotNull(deviceFlowRegistry);
301     }
302
303     @Test
304     public void testGetDeviceGroupRegistry() {
305         final DeviceGroupRegistry deviceGroupRegistry = deviceContext.getDeviceGroupRegistry();
306         assertNotNull(deviceGroupRegistry);
307     }
308
309     @Test
310     public void testGetDeviceMeterRegistry() {
311         final DeviceMeterRegistry deviceMeterRegistry = deviceContext.getDeviceMeterRegistry();
312         assertNotNull(deviceMeterRegistry);
313     }
314
315     @Test
316     public void testProcessReply() {
317         Error mockedError = mock(Error.class);
318         deviceContext.processReply(mockedError);
319         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE));
320         OfHeader mockedOfHeader = mock(OfHeader.class);
321         deviceContext.processReply(mockedOfHeader);
322         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS));
323     }
324
325     @Test
326     public void testProcessReply2() {
327         MultipartReply mockedMultipartReply = mock(MultipartReply.class);
328         Xid dummyXid = new Xid(DUMMY_XID);
329         deviceContext.processReply(dummyXid, Lists.newArrayList(mockedMultipartReply));
330         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE));
331     }
332
333     @Test
334     public void testProcessPacketInMessageFutureSuccess() {
335         PacketInMessage mockedPacketInMessage = mock(PacketInMessage.class);
336         NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
337         final ListenableFuture stringListenableFuture = Futures.immediateFuture(new String("dummy value"));
338
339         when(mockedNotificationPublishService.offerNotification(any(PacketReceived.class))).thenReturn(stringListenableFuture);
340         deviceContext.setNotificationPublishService(mockedNotificationPublishService);
341         deviceContext.processPacketInMessage(mockedPacketInMessage);
342         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS));
343     }
344
345     @Test
346     public void testProcessPacketInMessageFutureFailure() {
347         PacketInMessage mockedPacketInMessage = mock(PacketInMessage.class);
348         NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
349         final ListenableFuture dummyFuture = Futures.immediateFailedFuture(new IllegalStateException());
350
351         when(mockedNotificationPublishService.offerNotification(any(PacketReceived.class))).thenReturn(dummyFuture);
352         deviceContext.setNotificationPublishService(mockedNotificationPublishService);
353         deviceContext.processPacketInMessage(mockedPacketInMessage);
354         verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED));
355     }
356
357     @Test
358     public void testTranslatorLibrary() {
359         final TranslatorLibrary pickedTranslatorLibrary = deviceContext.oook();
360         assertEquals(translatorLibrary, pickedTranslatorLibrary);
361     }
362
363     @Test
364     public void testGetTimer() {
365         final HashedWheelTimer pickedTimer = deviceContext.getTimer();
366         assertEquals(timer, pickedTimer);
367     }
368
369     @Test
370     public void testClose() {
371         ConnectionAdapter mockedConnectionAdapter = mock(ConnectionAdapter.class);
372         InetSocketAddress mockRemoteAddress = InetSocketAddress.createUnresolved("odl-unit.example.org",999);
373         when(mockedConnectionAdapter.getRemoteAddress()).thenReturn(mockRemoteAddress);
374         when(connectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
375
376         NodeId dummyNodeId = new NodeId("dummyNodeId");
377         when(deviceState.getNodeId()).thenReturn(dummyNodeId);
378
379         ConnectionContext mockedAuxiliaryConnectionContext = prepareConnectionContext();
380         deviceContext.addAuxiliaryConenctionContext(mockedAuxiliaryConnectionContext);
381         DeviceContextClosedHandler mockedDeviceContextClosedHandler = mock(DeviceContextClosedHandler.class);
382         deviceContext.addDeviceContextClosedHandler(mockedDeviceContextClosedHandler);
383         deviceContext.close();
384         verify(connectionContext).closeConnection(eq(false));
385         verify(deviceState).setValid(eq(false));
386         verify(txChainManager).close();
387         verify(mockedAuxiliaryConnectionContext).closeConnection(eq(false));
388     }
389
390     @Test
391     public void testBarrierFieldSetGet() {
392         Timeout mockedTimeout = mock(Timeout.class);
393         deviceContext.setCurrentBarrierTimeout(mockedTimeout);
394         final Timeout pickedBarrierTimeout = deviceContext.getBarrierTaskTimeout();
395         assertEquals(mockedTimeout, pickedBarrierTimeout);
396     }
397
398     @Test
399     public void testGetMessageSpy() {
400         final MessageSpy pickedMessageSpy = deviceContext.getMessageSpy();
401         assertEquals(messageIntelligenceAgency, pickedMessageSpy);
402     }
403
404     @Test
405     public void testNodeConnector() {
406         NodeConnectorRef mockedNodeConnectorRef = mock(NodeConnectorRef.class);
407         deviceContext.storeNodeConnectorRef(DUMMY_PORT_NUMBER, mockedNodeConnectorRef);
408         final NodeConnectorRef nodeConnectorRef = deviceContext.lookupNodeConnectorRef(DUMMY_PORT_NUMBER);
409         assertEquals(mockedNodeConnectorRef, nodeConnectorRef);
410
411     }
412
413     @Test
414     public void testOnPublished() {
415         final ConnectionContext auxiliaryConnectionContext = addDummyAuxiliaryConnectionContext();
416
417         ConnectionAdapter mockedAuxConnectionAdapter = mock(ConnectionAdapter.class);
418         when(auxiliaryConnectionContext.getConnectionAdapter()).thenReturn(mockedAuxConnectionAdapter);
419
420         ConnectionAdapter mockedConnectionAdapter = mock(ConnectionAdapter.class);
421         when(connectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
422
423         deviceContext.onPublished();
424         verify(mockedAuxConnectionAdapter).setPacketInFiltering(eq(false));
425         verify(mockedConnectionAdapter).setPacketInFiltering(eq(false));
426     }
427
428     @Test
429     public void testPortStatusMessage() {
430         PortStatusMessage mockedPortStatusMessage = mock(PortStatusMessage.class);
431         Class dummyClass = Class.class;
432         when(mockedPortStatusMessage.getImplementedInterface()).thenReturn(dummyClass);
433
434
435         GetFeaturesOutput mockedFeature = mock(GetFeaturesOutput.class);
436         when(mockedFeature.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
437         when(deviceState.getFeatures()).thenReturn(mockedFeature);
438
439         when(mockedPortStatusMessage.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
440         when(mockedPortStatusMessage.getReason()).thenReturn(PortReason.OFPPRADD);
441
442         OpenflowPortsUtil.init();
443         deviceContext.processPortStatusMessage(mockedPortStatusMessage);
444         verify(txChainManager).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class), any(DataObject.class));
445     }
446
447     @Test
448     public void testProcessFlowRemovedMessage() throws Exception {
449         // prepare translation result
450         final FlowRemovedBuilder flowRemovedMdsalBld = new FlowRemovedBuilder()
451                 .setTableId((short) 0)
452                 .setPriority(42)
453                 .setCookie(new FlowCookie(BigInteger.ONE))
454                 .setMatch(new MatchBuilder().build());
455
456         Mockito.when(messageTranslatorFlowRemoved.translate(any(Object.class), any(DeviceContext.class), any(Object.class)))
457                 .thenReturn(flowRemovedMdsalBld.build());
458
459         // insert flow+flowId into local registry
460         FlowRegistryKey flowRegKey = FlowRegistryKeyFactory.create(flowRemovedMdsalBld.build());
461         FlowDescriptor flowDescriptor = FlowDescriptorFactory.create((short) 0, new FlowId("ut-ofp:f456"));
462         deviceContext.getDeviceFlowRegistry().store(flowRegKey, flowDescriptor);
463
464         // plug in lifecycleListener
465         final ItemLifecycleListener itemLifecycleListener = Mockito.mock(ItemLifecycleListener.class);
466         for (ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
467             lifeCycleSource.setItemLifecycleListener(itemLifecycleListener);
468         }
469
470         // prepare empty input message
471         final FlowRemovedMessageBuilder flowRemovedBld = new FlowRemovedMessageBuilder();
472
473         // prepare path to flow to be removed
474         KeyedInstanceIdentifier<Flow, FlowKey> flowToBeRemovedPath = nodeKeyIdent
475                 .augmentation(FlowCapableNode.class)
476                 .child(Table.class, new TableKey((short) 0))
477                 .child(Flow.class, new FlowKey(new FlowId("ut-ofp:f456")));
478
479         deviceContext.processFlowRemovedMessage(flowRemovedBld.build());
480         Mockito.verify(itemLifecycleListener).onRemoved(flowToBeRemovedPath);
481     }
482
483     @Test
484     public void testOnDeviceDisconnected() throws Exception {
485         DeviceContextClosedHandler deviceContextClosedHandler = mock(DeviceContextClosedHandler.class);
486         deviceContext.addDeviceContextClosedHandler(deviceContextClosedHandler);
487
488         deviceContext.onDeviceDisconnected(connectionContext);
489
490         Mockito.verify(deviceState).setValid(false);
491         Mockito.verify(deviceContextClosedHandler).onDeviceContextClosed(deviceContext);
492         Assert.assertEquals(0, deviceContext.getDeviceFlowRegistry().getAllFlowDescriptors().size());
493         Assert.assertEquals(0, deviceContext.getDeviceGroupRegistry().getAllGroupIds().size());
494         Assert.assertEquals(0, deviceContext.getDeviceMeterRegistry().getAllMeterIds().size());
495
496         Mockito.verify(txChainManager).close();
497     }
498 }