2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
9 package org.opendaylight.openflowplugin.impl.device;
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;
21 import com.google.common.base.Optional;
22 import com.google.common.collect.Lists;
23 import com.google.common.util.concurrent.CheckedFuture;
24 import com.google.common.util.concurrent.Futures;
25 import com.google.common.util.concurrent.ListenableFuture;
26 import com.google.common.util.concurrent.SettableFuture;
27 import io.netty.util.HashedWheelTimer;
28 import io.netty.util.Timeout;
29 import java.math.BigInteger;
30 import java.net.InetSocketAddress;
31 import java.util.concurrent.atomic.AtomicLong;
32 import org.junit.Assert;
33 import org.junit.Before;
34 import org.junit.Test;
35 import org.junit.runner.RunWith;
36 import org.mockito.InOrder;
37 import org.mockito.Mock;
38 import org.mockito.Mockito;
39 import org.mockito.invocation.InvocationOnMock;
40 import org.mockito.runners.MockitoJUnitRunner;
41 import org.mockito.stubbing.Answer;
42 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
43 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
44 import org.opendaylight.controller.md.sal.binding.api.NotificationPublishService;
45 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
46 import org.opendaylight.controller.md.sal.binding.api.ReadTransaction;
47 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
48 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
49 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
50 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
51 import org.opendaylight.openflowjava.protocol.api.keys.MessageTypeKey;
52 import org.opendaylight.openflowplugin.api.OFConstants;
53 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
54 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
55 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
56 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
57 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
58 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
59 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
60 import org.opendaylight.openflowplugin.api.openflow.device.Xid;
61 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceTerminationPhaseHandler;
62 import org.opendaylight.openflowplugin.api.openflow.lifecycle.LifecycleConductor;
63 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
64 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
65 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
66 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
67 import org.opendaylight.openflowplugin.api.openflow.registry.group.DeviceGroupRegistry;
68 import org.opendaylight.openflowplugin.api.openflow.registry.meter.DeviceMeterRegistry;
69 import org.opendaylight.openflowplugin.api.openflow.rpc.ItemLifeCycleSource;
70 import org.opendaylight.openflowplugin.api.openflow.rpc.RpcContext;
71 import org.opendaylight.openflowplugin.api.openflow.rpc.listener.ItemLifecycleListener;
72 import org.opendaylight.openflowplugin.api.openflow.statistics.StatisticsContext;
73 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
74 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageSpy;
75 import org.opendaylight.openflowplugin.extension.api.ConvertorMessageFromOFJava;
76 import org.opendaylight.openflowplugin.extension.api.core.extension.ExtensionConverterProvider;
77 import org.opendaylight.openflowplugin.impl.registry.flow.FlowDescriptorFactory;
78 import org.opendaylight.openflowplugin.impl.registry.flow.FlowRegistryKeyFactory;
79 import org.opendaylight.openflowplugin.impl.util.DeviceStateUtil;
80 import org.opendaylight.openflowplugin.openflow.md.util.OpenflowPortsUtil;
81 import org.opendaylight.yang.gen.v1.urn.opendaylight.experimenter.message.service.rev151020.ExperimenterMessageFromDev;
82 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
83 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector;
84 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowId;
85 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
86 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
87 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow;
88 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.FlowKey;
89 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.service.rev130819.FlowRemovedBuilder;
90 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.FlowCookie;
91 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.rev131026.flow.MatchBuilder;
92 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorRef;
93 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
94 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
95 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
96 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
97 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
98 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.PortReason;
99 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.*;
100 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.Error;
101 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.experimenter.core.ExperimenterDataOfChoice;
102 import org.opendaylight.yang.gen.v1.urn.opendaylight.packet.service.rev130709.PacketReceived;
103 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
104 import org.opendaylight.yangtools.concepts.Registration;
105 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
106 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
107 import org.opendaylight.yangtools.yang.common.RpcResult;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
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");
122 DeviceContextImpl deviceContext;
124 TransactionChainManager txChainManager;
126 RequestContext<GetAsyncReply> requestContext;
128 RequestContext<MultipartReply> requestContextMultiReply;
131 ConnectionContext connectionContext;
133 DeviceState deviceState;
135 GetFeaturesOutput featuresOutput;
137 DataBroker dataBroker;
139 WriteTransaction wTx;
141 ReadOnlyTransaction rTx;
143 BindingTransactionChain txChainFactory;
145 HashedWheelTimer timer;
147 MessageIntelligenceAgency messageIntelligenceAgency;
149 OutboundQueueProvider outboundQueueProvider;
151 ConnectionAdapter connectionAdapter;
152 NodeId nodeId = new NodeId("h2g2:42");
153 KeyedInstanceIdentifier<Node, NodeKey> nodeKeyIdent = DeviceStateUtil.createNodeInstanceIdentifier(nodeId);
155 TranslatorLibrary translatorLibrary;
157 Registration registration;
159 MessageTranslator messageTranslatorPacketReceived;
161 MessageTranslator messageTranslatorFlowCapableNodeConnector;
163 private MessageTranslator<Object, Object> messageTranslatorFlowRemoved;
165 private LifecycleConductor lifecycleConductor;
167 private InOrder inOrderDevState;
169 private final AtomicLong atomicLong = new AtomicLong(0);
171 private DeviceContext deviceContextSpy;
174 public void setUp() {
175 final CheckedFuture<Optional<Node>, ReadFailedException> noExistNodeFuture = Futures.immediateCheckedFuture(Optional.<Node>absent());
176 Mockito.when(rTx.read(LogicalDatastoreType.OPERATIONAL, nodeKeyIdent)).thenReturn(noExistNodeFuture);
177 Mockito.when(dataBroker.newReadOnlyTransaction()).thenReturn(rTx);
178 Mockito.when(dataBroker.createTransactionChain(Mockito.any(TransactionChainManager.class))).thenReturn(txChainFactory);
179 Mockito.when(deviceState.getNodeInstanceIdentifier()).thenReturn(nodeKeyIdent);
180 Mockito.when(deviceState.getNodeId()).thenReturn(nodeId);
181 // txChainManager = new TransactionChainManager(dataBroker, deviceState);
182 final SettableFuture<RpcResult<GetAsyncReply>> settableFuture = SettableFuture.create();
183 final SettableFuture<RpcResult<MultipartReply>> settableFutureMultiReply = SettableFuture.create();
184 Mockito.when(requestContext.getFuture()).thenReturn(settableFuture);
185 Mockito.doAnswer(new Answer<Object>() {
186 @SuppressWarnings("unchecked")
188 public Object answer(final InvocationOnMock invocation) {
189 settableFuture.set((RpcResult<GetAsyncReply>) invocation.getArguments()[0]);
192 }).when(requestContext).setResult(any(RpcResult.class));
194 Mockito.when(requestContextMultiReply.getFuture()).thenReturn(settableFutureMultiReply);
195 Mockito.doAnswer(new Answer<Object>() {
196 @SuppressWarnings("unchecked")
198 public Object answer(final InvocationOnMock invocation) {
199 settableFutureMultiReply.set((RpcResult<MultipartReply>) invocation.getArguments()[0]);
202 }).when(requestContextMultiReply).setResult(any(RpcResult.class));
203 Mockito.when(txChainFactory.newWriteOnlyTransaction()).thenReturn(wTx);
204 Mockito.when(dataBroker.newReadOnlyTransaction()).thenReturn(rTx);
205 Mockito.when(connectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
206 Mockito.when(connectionContext.getConnectionAdapter()).thenReturn(connectionAdapter);
207 final FeaturesReply mockedFeaturesReply = mock(FeaturesReply.class);
208 when(connectionContext.getFeatures()).thenReturn(mockedFeaturesReply);
209 when(connectionContext.getFeatures().getCapabilities()).thenReturn(mock(Capabilities.class));
211 Mockito.when(deviceState.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
212 Mockito.when(featuresOutput.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
213 Mockito.when(featuresOutput.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
214 Mockito.when(deviceState.getFeatures()).thenReturn(featuresOutput);
215 Mockito.when(messageTranslatorPacketReceived.translate(any(Object.class), any(DeviceState.class), any(Object.class))).thenReturn(mock(PacketReceived.class));
216 Mockito.when(messageTranslatorFlowCapableNodeConnector.translate(any(Object.class), any(DeviceState.class), any(Object.class))).thenReturn(mock(FlowCapableNodeConnector.class));
217 Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PacketIn.class.getName())))).thenReturn(messageTranslatorPacketReceived);
218 Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3, PortGrouping.class.getName())))).thenReturn(messageTranslatorFlowCapableNodeConnector);
219 Mockito.when(translatorLibrary.lookupTranslator(eq(new TranslatorKey(OFConstants.OFP_VERSION_1_3,
220 org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FlowRemoved.class.getName()))))
221 .thenReturn(messageTranslatorFlowRemoved);
222 Mockito.when(lifecycleConductor.getMessageIntelligenceAgency()).thenReturn(messageIntelligenceAgency);
224 deviceContext = new DeviceContextImpl(connectionContext, deviceState, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary, false);
226 deviceContextSpy = Mockito.spy(deviceContext);
228 xid = new Xid(atomicLong.incrementAndGet());
229 xidMulti = new Xid(atomicLong.incrementAndGet());
232 @Test(expected = NullPointerException.class)
233 public void testDeviceContextImplConstructorNullDataBroker() throws Exception {
234 new DeviceContextImpl(connectionContext, deviceState, null, lifecycleConductor, outboundQueueProvider, translatorLibrary, false).close();
237 @Test(expected = NullPointerException.class)
238 public void testDeviceContextImplConstructorNullDeviceState() throws Exception {
239 new DeviceContextImpl(connectionContext, null, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary, false).close();
242 @Test(expected = NullPointerException.class)
243 public void testDeviceContextImplConstructorNullTimer() throws Exception {
244 new DeviceContextImpl(null, deviceState, dataBroker, lifecycleConductor, outboundQueueProvider, translatorLibrary, false).close();
248 public void testGetDeviceState() {
249 final DeviceState deviceSt = deviceContext.getDeviceState();
250 assertNotNull(deviceSt);
251 assertEquals(deviceState, deviceSt);
255 public void testGetReadTransaction() {
256 final ReadTransaction readTx = deviceContext.getReadTransaction();
257 assertNotNull(readTx);
258 assertEquals(rTx, readTx);
265 public void testInitialSubmitTransaction() throws Exception {
266 Mockito.when(wTx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
267 final InstanceIdentifier<Nodes> dummyII = InstanceIdentifier.create(Nodes.class);
268 deviceContext.getTransactionChainManager().activateTransactionManager() ;
269 deviceContext.getTransactionChainManager().enableSubmit();
270 deviceContext.addDeleteToTxChain(LogicalDatastoreType.CONFIGURATION, dummyII);
271 deviceContext.initialSubmitTransaction();
272 verify(wTx).submit();
276 public void testGetReservedXid() {
277 deviceContext.reserveXidForDeviceMessage();
278 verify(outboundQueueProvider).reserveEntry();
282 public void testAuxiliaryConnectionContext() {
283 final ConnectionContext mockedConnectionContext = addDummyAuxiliaryConnectionContext();
284 final ConnectionContext pickedConnectiobContexts = deviceContext.getAuxiliaryConnectiobContexts(DUMMY_COOKIE);
285 assertEquals(mockedConnectionContext, pickedConnectiobContexts);
288 public void testRemoveAuxiliaryConnectionContext() {
289 final ConnectionContext mockedConnectionContext = addDummyAuxiliaryConnectionContext();
291 final ConnectionAdapter mockedAuxConnectionAdapter = mock(ConnectionAdapter.class);
292 when(mockedConnectionContext.getConnectionAdapter()).thenReturn(mockedAuxConnectionAdapter);
294 assertNotNull(deviceContext.getAuxiliaryConnectiobContexts(DUMMY_COOKIE));
295 deviceContext.removeAuxiliaryConnectionContext(mockedConnectionContext);
296 assertNull(deviceContext.getAuxiliaryConnectiobContexts(DUMMY_COOKIE));
299 private ConnectionContext addDummyAuxiliaryConnectionContext() {
300 final ConnectionContext mockedConnectionContext = prepareConnectionContext();
301 deviceContext.addAuxiliaryConnectionContext(mockedConnectionContext);
302 return mockedConnectionContext;
305 private ConnectionContext prepareConnectionContext() {
306 final ConnectionContext mockedConnectionContext = mock(ConnectionContext.class);
307 final FeaturesReply mockedFeaturesReply = mock(FeaturesReply.class);
308 when(mockedFeaturesReply.getAuxiliaryId()).thenReturn(DUMMY_AUXILIARY_ID);
309 when(mockedConnectionContext.getFeatures()).thenReturn(mockedFeaturesReply);
310 return mockedConnectionContext;
317 public void testAddDeleteToTxChain() throws Exception{
318 final InstanceIdentifier<Nodes> dummyII = InstanceIdentifier.create(Nodes.class);
319 deviceContext.getTransactionChainManager().activateTransactionManager() ;
320 deviceContext.getTransactionChainManager().enableSubmit();
321 deviceContext.addDeleteToTxChain(LogicalDatastoreType.CONFIGURATION, dummyII);
322 verify(wTx).delete(eq(LogicalDatastoreType.CONFIGURATION), eq(dummyII));
329 public void testSubmitTransaction() throws Exception {
330 deviceContext.getTransactionChainManager().activateTransactionManager() ;
331 deviceContext.getTransactionChainManager().enableSubmit();
332 assertTrue(deviceContext.submitTransaction());
336 public void testGetPrimaryConnectionContext() {
337 final ConnectionContext primaryConnectionContext = deviceContext.getPrimaryConnectionContext();
338 assertEquals(connectionContext, primaryConnectionContext);
342 public void testGetDeviceFlowRegistry() {
343 final DeviceFlowRegistry deviceFlowRegistry = deviceContext.getDeviceFlowRegistry();
344 assertNotNull(deviceFlowRegistry);
348 public void testGetDeviceGroupRegistry() {
349 final DeviceGroupRegistry deviceGroupRegistry = deviceContext.getDeviceGroupRegistry();
350 assertNotNull(deviceGroupRegistry);
354 public void testGetDeviceMeterRegistry() {
355 final DeviceMeterRegistry deviceMeterRegistry = deviceContext.getDeviceMeterRegistry();
356 assertNotNull(deviceMeterRegistry);
360 public void testGetRpcContext() {
361 final RpcContext rpcContext = mock(RpcContext.class);
362 deviceContext.setRpcContext(rpcContext);
363 assertNotNull(deviceContext.getRpcContext());
367 public void testProcessReply() {
368 final Error mockedError = mock(Error.class);
369 deviceContext.processReply(mockedError);
370 verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE));
371 final OfHeader mockedOfHeader = mock(OfHeader.class);
372 deviceContext.processReply(mockedOfHeader);
373 verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS));
377 public void testProcessReply2() {
378 final MultipartReply mockedMultipartReply = mock(MultipartReply.class);
379 final Xid dummyXid = new Xid(DUMMY_XID);
380 deviceContext.processReply(dummyXid, Lists.newArrayList(mockedMultipartReply));
381 verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_FAILURE));
385 public void testProcessPacketInMessageFutureSuccess() {
386 final PacketInMessage mockedPacketInMessage = mock(PacketInMessage.class);
387 final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
388 final ListenableFuture stringListenableFuture = Futures.immediateFuture(new String("dummy value"));
390 when(mockedNotificationPublishService.offerNotification(any(PacketReceived.class))).thenReturn(stringListenableFuture);
391 deviceContext.setNotificationPublishService(mockedNotificationPublishService);
392 deviceContext.processPacketInMessage(mockedPacketInMessage);
393 verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_PUBLISHED_SUCCESS));
397 public void testProcessPacketInMessageFutureFailure() {
398 final PacketInMessage mockedPacketInMessage = mock(PacketInMessage.class);
399 final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
400 final ListenableFuture dummyFuture = Futures.immediateFailedFuture(new IllegalStateException());
402 when(mockedNotificationPublishService.offerNotification(any(PacketReceived.class))).thenReturn(dummyFuture);
403 deviceContext.setNotificationPublishService(mockedNotificationPublishService);
404 deviceContext.processPacketInMessage(mockedPacketInMessage);
405 verify(messageIntelligenceAgency).spyMessage(any(Class.class), eq(MessageSpy.STATISTIC_GROUP.FROM_SWITCH_NOTIFICATION_REJECTED));
409 public void testTranslatorLibrary() {
410 final TranslatorLibrary pickedTranslatorLibrary = deviceContext.oook();
411 assertEquals(translatorLibrary, pickedTranslatorLibrary);
415 public void testShutdownConnection() {
416 final ConnectionAdapter mockedConnectionAdapter = mock(ConnectionAdapter.class);
417 final InetSocketAddress mockRemoteAddress = InetSocketAddress.createUnresolved("odl-unit.example.org",999);
418 when(mockedConnectionAdapter.getRemoteAddress()).thenReturn(mockRemoteAddress);
419 when(connectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
421 final NodeId dummyNodeId = new NodeId("dummyNodeId");
422 when(deviceState.getNodeId()).thenReturn(dummyNodeId);
424 final ConnectionContext mockedAuxiliaryConnectionContext = prepareConnectionContext();
425 deviceContext.addAuxiliaryConnectionContext(mockedAuxiliaryConnectionContext);
426 final DeviceTerminationPhaseHandler mockedDeviceContextClosedHandler = mock(DeviceTerminationPhaseHandler.class);
427 when(deviceState.isValid()).thenReturn(true);
428 deviceContext.shutdownConnection();
429 verify(connectionContext).closeConnection(true);
433 public void testBarrierFieldSetGet() {
434 final Timeout mockedTimeout = mock(Timeout.class);
435 deviceContext.setCurrentBarrierTimeout(mockedTimeout);
436 final Timeout pickedBarrierTimeout = deviceContext.getBarrierTaskTimeout();
437 assertEquals(mockedTimeout, pickedBarrierTimeout);
441 public void testGetMessageSpy() {
442 final MessageSpy pickedMessageSpy = deviceContext.getMessageSpy();
443 assertEquals(messageIntelligenceAgency, pickedMessageSpy);
447 public void testNodeConnector() {
448 final NodeConnectorRef mockedNodeConnectorRef = mock(NodeConnectorRef.class);
449 deviceContext.storeNodeConnectorRef(DUMMY_PORT_NUMBER, mockedNodeConnectorRef);
450 final NodeConnectorRef nodeConnectorRef = deviceContext.lookupNodeConnectorRef(DUMMY_PORT_NUMBER);
451 assertEquals(mockedNodeConnectorRef, nodeConnectorRef);
456 public void testOnPublished() {
457 final ConnectionContext auxiliaryConnectionContext = addDummyAuxiliaryConnectionContext();
459 final ConnectionAdapter mockedAuxConnectionAdapter = mock(ConnectionAdapter.class);
460 when(auxiliaryConnectionContext.getConnectionAdapter()).thenReturn(mockedAuxConnectionAdapter);
462 final ConnectionAdapter mockedConnectionAdapter = mock(ConnectionAdapter.class);
463 when(connectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
465 deviceContext.onPublished();
466 verify(mockedAuxConnectionAdapter).setPacketInFiltering(eq(false));
467 verify(mockedConnectionAdapter).setPacketInFiltering(eq(false));
471 public void testPortStatusMessage() {
472 final PortStatusMessage mockedPortStatusMessage = mock(PortStatusMessage.class);
473 final Class dummyClass = Class.class;
474 when(mockedPortStatusMessage.getImplementedInterface()).thenReturn(dummyClass);
477 final GetFeaturesOutput mockedFeature = mock(GetFeaturesOutput.class);
478 when(mockedFeature.getDatapathId()).thenReturn(DUMMY_DATAPATH_ID);
479 when(deviceState.getFeatures()).thenReturn(mockedFeature);
481 when(mockedPortStatusMessage.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
482 when(mockedPortStatusMessage.getReason()).thenReturn(PortReason.OFPPRADD);
484 OpenflowPortsUtil.init();
485 deviceContext.processPortStatusMessage(mockedPortStatusMessage);
486 // verify(txChainManager).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL), any(InstanceIdentifier.class), any(DataObject.class));
490 public void testProcessFlowRemovedMessage() throws Exception {
491 // prepare translation result
492 final FlowRemovedBuilder flowRemovedMdsalBld = new FlowRemovedBuilder()
493 .setTableId((short) 0)
495 .setCookie(new FlowCookie(BigInteger.ONE))
496 .setMatch(new MatchBuilder().build());
498 Mockito.when(messageTranslatorFlowRemoved.translate(any(Object.class), any(DeviceState.class), any(Object.class)))
499 .thenReturn(flowRemovedMdsalBld.build());
501 // insert flow+flowId into local registry
502 final FlowRegistryKey flowRegKey = FlowRegistryKeyFactory.create(flowRemovedMdsalBld.build());
503 final FlowDescriptor flowDescriptor = FlowDescriptorFactory.create((short) 0, new FlowId("ut-ofp:f456"));
504 deviceContext.getDeviceFlowRegistry().store(flowRegKey, flowDescriptor);
506 // plug in lifecycleListener
507 final ItemLifecycleListener itemLifecycleListener = Mockito.mock(ItemLifecycleListener.class);
508 for (final ItemLifeCycleSource lifeCycleSource : deviceContext.getItemLifeCycleSourceRegistry().getLifeCycleSources()) {
509 lifeCycleSource.setItemLifecycleListener(itemLifecycleListener);
512 // prepare empty input message
513 final FlowRemovedMessageBuilder flowRemovedBld = new FlowRemovedMessageBuilder();
515 // prepare path to flow to be removed
516 final KeyedInstanceIdentifier<Flow, FlowKey> flowToBeRemovedPath = nodeKeyIdent
517 .augmentation(FlowCapableNode.class)
518 .child(Table.class, new TableKey((short) 0))
519 .child(Flow.class, new FlowKey(new FlowId("ut-ofp:f456")));
521 deviceContext.processFlowRemovedMessage(flowRemovedBld.build());
522 Mockito.verify(itemLifecycleListener).onRemoved(flowToBeRemovedPath);
526 public void testProcessExperimenterMessage() {
527 final ConvertorMessageFromOFJava mockedMessageConverter = mock(ConvertorMessageFromOFJava.class);
528 final ExtensionConverterProvider mockedExtensionConverterProvider = mock(ExtensionConverterProvider.class);
529 when(mockedExtensionConverterProvider.getMessageConverter(any(MessageTypeKey.class))).thenReturn(mockedMessageConverter);
531 final ExperimenterDataOfChoice mockedExperimenterDataOfChoice = mock(ExperimenterDataOfChoice.class);
532 final ExperimenterMessage experimenterMessage = new ExperimenterMessageBuilder()
533 .setExperimenterDataOfChoice(mockedExperimenterDataOfChoice).build();
535 final NotificationPublishService mockedNotificationPublishService = mock(NotificationPublishService.class);
537 deviceContext.setNotificationPublishService(mockedNotificationPublishService);
538 deviceContext.setExtensionConverterProvider(mockedExtensionConverterProvider);
539 deviceContext.processExperimenterMessage(experimenterMessage);
541 verify(mockedNotificationPublishService).offerNotification(any(ExperimenterMessageFromDev.class));
545 public void testOnDeviceDisconnected() throws Exception {
546 final DeviceTerminationPhaseHandler deviceContextClosedHandler = mock(DeviceTerminationPhaseHandler.class);
548 assertEquals(0, deviceContext.getDeviceFlowRegistry().getAllFlowDescriptors().size());
549 assertEquals(0, deviceContext.getDeviceGroupRegistry().getAllGroupIds().size());
550 assertEquals(0, deviceContext.getDeviceMeterRegistry().getAllMeterIds().size());
555 public void testOnClusterRoleChange() throws Exception {
556 // test role.equals(oldRole)
557 Assert.assertNull(deviceContextSpy.onClusterRoleChange(OfpRole.BECOMEMASTER, OfpRole.BECOMEMASTER).get());
559 // test call transactionChainManager.deactivateTransactionManager()
560 Assert.assertNull(deviceContextSpy.onClusterRoleChange(OfpRole.BECOMESLAVE, OfpRole.NOCHANGE).get());
562 // test call MdSalRegistrationUtils.unregisterServices(rpcContext)
563 final RpcContext rpcContext = mock(RpcContext.class);
564 deviceContextSpy.setRpcContext(rpcContext);
565 Assert.assertNull(deviceContextSpy.onClusterRoleChange(OfpRole.BECOMESLAVE, OfpRole.NOCHANGE).get());
567 final StatisticsContext statisticsContext = mock(StatisticsContext.class);
568 deviceContextSpy.setStatisticsContext(statisticsContext);
570 deviceContextSpy.onClusterRoleChange(OfpRole.NOCHANGE, OfpRole.BECOMEMASTER);
571 verify(deviceContextSpy).onDeviceTakeClusterLeadership();
573 Mockito.when(wTx.submit()).thenReturn(Futures.immediateCheckedFuture(null));
574 deviceContextSpy.onClusterRoleChange(OfpRole.NOCHANGE, OfpRole.BECOMESLAVE);
575 verify(deviceContextSpy).onDeviceLostClusterLeadership();