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