8ec6befe162ce80efb255d3213d30781dc66b50d
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / device / DeviceManagerImplTest.java
1 /*
2  *
3  *  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
4  *  *
5  *  * This program and the accompanying materials are made available under the
6  *  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  *  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  *
9  *
10  */
11
12 package org.opendaylight.openflowplugin.impl.device;
13
14 import static org.mockito.Matchers.any;
15 import static org.mockito.Mockito.doThrow;
16 import static org.mockito.Mockito.inOrder;
17 import static org.mockito.Mockito.mock;
18 import static org.mockito.Mockito.verify;
19 import static org.mockito.Mockito.when;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.FutureCallback;
22 import java.lang.reflect.Field;
23 import java.math.BigInteger;
24 import java.util.Collections;
25 import java.util.concurrent.ConcurrentHashMap;
26 import org.junit.Assert;
27 import org.junit.Before;
28 import org.junit.Test;
29 import org.junit.runner.RunWith;
30 import org.mockito.InOrder;
31 import org.mockito.Matchers;
32 import org.mockito.Mock;
33 import org.mockito.Mockito;
34 import org.mockito.invocation.InvocationOnMock;
35 import org.mockito.runners.MockitoJUnitRunner;
36 import org.mockito.stubbing.Answer;
37 import org.opendaylight.controller.md.sal.binding.api.BindingTransactionChain;
38 import org.opendaylight.controller.md.sal.binding.api.DataBroker;
39 import org.opendaylight.controller.md.sal.binding.api.WriteTransaction;
40 import org.opendaylight.controller.md.sal.common.api.data.TransactionChainListener;
41 import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException;
42 import org.opendaylight.openflowjava.protocol.api.connection.ConnectionAdapter;
43 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueue;
44 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandler;
45 import org.opendaylight.openflowjava.protocol.api.connection.OutboundQueueHandlerRegistration;
46 import org.opendaylight.openflowplugin.api.OFConstants;
47 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
48 import org.opendaylight.openflowplugin.api.openflow.connection.OutboundQueueProvider;
49 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
50 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
51 import org.opendaylight.openflowplugin.api.openflow.device.MessageTranslator;
52 import org.opendaylight.openflowplugin.api.openflow.device.TranslatorLibrary;
53 import org.opendaylight.openflowplugin.api.openflow.device.handlers.DeviceInitializationPhaseHandler;
54 import org.opendaylight.openflowplugin.api.openflow.md.core.TranslatorKey;
55 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.MessageIntelligenceAgency;
56 import org.opendaylight.openflowplugin.openflow.md.util.OpenflowPortsUtil;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.Capabilities;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.CapabilitiesV10;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartRequestInput;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.OfHeader;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.features.reply.PhyPortBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.role.service.rev150727.OfpRole;
68 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
69 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
70
71 @RunWith(MockitoJUnitRunner.class)
72 public class DeviceManagerImplTest {
73
74     private static final boolean TEST_VALUE_SWITCH_FEATURE_MANDATORY = true;
75     private static final long TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA = 2000l;
76     private static final KeyedInstanceIdentifier<Node, NodeKey> DUMMY_NODE_II = InstanceIdentifier.create(Nodes.class)
77             .child(Node.class, new NodeKey(new NodeId("dummyNodeId")));
78     private static final Short DUMMY_TABLE_ID = 1;
79     private static final Long DUMMY_MAX_METER = 544L;
80     private static final String DUMMY_DATAPATH_ID = "44";
81     private static final Long DUMMY_PORT_NUMBER = 21L;
82
83     @Mock
84     CheckedFuture<Void, TransactionCommitFailedException> mockedFuture;
85     @Mock
86     private FeaturesReply mockFeatures;
87     @Mock
88     private OutboundQueue outboundQueueProvider;
89     @Mock
90     private DeviceInitializationPhaseHandler deviceInitPhaseHandler;
91     @Mock
92     private TranslatorLibrary translatorLibrary;
93     @Mock
94     private ConnectionContext mockConnectionContext;
95     @Mock
96     private ConnectionAdapter mockedConnectionAdapter;
97     @Mock
98     private DeviceContextImpl mockedDeviceContext;
99     @Mock
100     private NodeId mockedNodeId;
101
102     @Before
103     public void setUp() throws Exception {
104         OpenflowPortsUtil.init();
105
106         when(mockConnectionContext.getNodeId()).thenReturn(new NodeId("dummyNodeId"));
107         when(mockConnectionContext.getFeatures()).thenReturn(mockFeatures);
108         when(mockConnectionContext.getConnectionAdapter()).thenReturn(mockedConnectionAdapter);
109         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockConnectionContext);
110
111         final Capabilities capabilitiesV13 = Mockito.mock(Capabilities.class);
112         final CapabilitiesV10 capabilitiesV10 = Mockito.mock(CapabilitiesV10.class);
113         when(mockFeatures.getCapabilities()).thenReturn(capabilitiesV13);
114         when(mockFeatures.getCapabilitiesV10()).thenReturn(capabilitiesV10);
115         when(mockFeatures.getDatapathId()).thenReturn(BigInteger.valueOf(21L));
116     }
117
118     @Test(expected = IllegalStateException.class)
119     public void onDeviceContextLevelUpFailTest() throws Exception {
120         onDeviceContextLevelUp(true);
121     }
122
123     @Test
124     public void onDeviceContextLevelUpSuccessTest() throws Exception {
125         onDeviceContextLevelUp(false);
126     }
127
128     private DeviceManagerImpl prepareDeviceManager() {
129         return prepareDeviceManager(false);
130     }
131
132     private DeviceManagerImpl prepareDeviceManager(final boolean withException) {
133         final DataBroker mockedDataBroker = mock(DataBroker.class);
134         final WriteTransaction mockedWriteTransaction = mock(WriteTransaction.class);
135
136         final BindingTransactionChain mockedTxChain = mock(BindingTransactionChain.class);
137         final WriteTransaction mockedWTx = mock(WriteTransaction.class);
138         when(mockedTxChain.newWriteOnlyTransaction()).thenReturn(mockedWTx);
139         when(mockedDataBroker.createTransactionChain(any(TransactionChainListener.class))).thenReturn
140                 (mockedTxChain);
141         when(mockedDataBroker.newWriteOnlyTransaction()).thenReturn(mockedWriteTransaction);
142
143         when(mockedWriteTransaction.submit()).thenReturn(mockedFuture);
144
145         final MessageIntelligenceAgency mockedMessageIntelligenceAgency = mock(MessageIntelligenceAgency.class);
146         final DeviceManagerImpl deviceManager = new DeviceManagerImpl(mockedDataBroker, mockedMessageIntelligenceAgency,
147                 TEST_VALUE_GLOBAL_NOTIFICATION_QUOTA, false);
148         deviceManager.setDeviceInitializationPhaseHandler(deviceInitPhaseHandler);
149
150         return deviceManager;
151     }
152
153     public void onDeviceContextLevelUp(final boolean withException) throws Exception {
154         final DeviceManagerImpl deviceManager = prepareDeviceManager(withException);
155         final DeviceState mockedDeviceState = mock(DeviceState.class);
156         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
157         when(mockedDeviceState.getRole()).thenReturn(OfpRole.BECOMEMASTER);
158
159         if (withException) {
160             doThrow(new IllegalStateException("dummy")).when(mockedDeviceContext).initialSubmitTransaction();
161         }
162
163         deviceManager.onDeviceContextLevelUp(mockedDeviceContext);
164         if (withException) {
165             verify(mockedDeviceContext).close();
166         } else {
167             verify(mockedDeviceContext).initialSubmitTransaction();
168             verify(mockedDeviceContext).onPublished();
169         }
170     }
171
172     @Test
173     public void deviceConnectedTest() throws Exception{
174         final DeviceManagerImpl deviceManager = prepareDeviceManager();
175         injectMockTranslatorLibrary(deviceManager);
176         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_3);
177
178         deviceManager.deviceConnected(mockConnectionContext);
179
180         final InOrder order = inOrder(mockConnectionContext);
181         order.verify(mockConnectionContext).getFeatures();
182         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
183         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
184                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
185         order.verify(mockConnectionContext).getNodeId();
186         Mockito.verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceContext>any());
187     }
188
189     @Test
190     public void deviceConnectedV10Test() throws Exception{
191         final DeviceManagerImpl deviceManager = prepareDeviceManager();
192         injectMockTranslatorLibrary(deviceManager);
193         final ConnectionContext mockConnectionContext = buildMockConnectionContext(OFConstants.OFP_VERSION_1_0);
194
195         final PhyPortBuilder phyPort = new PhyPortBuilder()
196                 .setPortNo(41L);
197         when(mockFeatures.getPhyPort()).thenReturn(Collections.singletonList(phyPort.build()));
198         final MessageTranslator<Object, Object> mockedTranslator = Mockito.mock(MessageTranslator.class);
199         when(mockedTranslator.translate(Matchers.<Object>any(), Matchers.<DeviceContext>any(), Matchers.any()))
200                 .thenReturn(null);
201         when(translatorLibrary.lookupTranslator(Matchers.<TranslatorKey>any())).thenReturn(mockedTranslator);
202
203         deviceManager.deviceConnected(mockConnectionContext);
204
205         final InOrder order = inOrder(mockConnectionContext);
206         order.verify(mockConnectionContext).getFeatures();
207         order.verify(mockConnectionContext).setOutboundQueueProvider(any(OutboundQueueProvider.class));
208         order.verify(mockConnectionContext).setOutboundQueueHandleRegistration(
209                 Mockito.<OutboundQueueHandlerRegistration<OutboundQueueProvider>>any());
210         order.verify(mockConnectionContext).getNodeId();
211         Mockito.verify(deviceInitPhaseHandler).onDeviceContextLevelUp(Matchers.<DeviceContext>any());
212     }
213
214     protected ConnectionContext buildMockConnectionContext(final short ofpVersion) {
215         when(mockFeatures.getVersion()).thenReturn(ofpVersion);
216         when(outboundQueueProvider.reserveEntry()).thenReturn(43L);
217         Mockito.doAnswer(new Answer<Void>() {
218             @Override
219             public Void answer(final InvocationOnMock invocation) throws Throwable {
220                 final FutureCallback<OfHeader> callBack = (FutureCallback<OfHeader>) invocation.getArguments()[2];
221                 callBack.onSuccess(null);
222                 return null;
223             }
224         })
225                 .when(outboundQueueProvider)
226                 .commitEntry(Matchers.anyLong(), Matchers.<MultipartRequestInput>any(), Matchers.<FutureCallback<OfHeader>>any());
227
228         when(mockedConnectionAdapter.registerOutboundQueueHandler(Matchers.<OutboundQueueHandler>any(), Matchers.anyInt(), Matchers.anyLong()))
229                 .thenAnswer(new Answer<OutboundQueueHandlerRegistration<OutboundQueueHandler>>() {
230                     @Override
231                     public OutboundQueueHandlerRegistration<OutboundQueueHandler> answer(final InvocationOnMock invocation) throws Throwable {
232                         final OutboundQueueHandler handler = (OutboundQueueHandler) invocation.getArguments()[0];
233                         handler.onConnectionQueueChanged(outboundQueueProvider);
234                         return null;
235                     }
236                 });
237
238         when(mockConnectionContext.getOutboundQueueProvider()).thenReturn(outboundQueueProvider);
239         return mockConnectionContext;
240     }
241
242     private void injectMockTranslatorLibrary(final DeviceManagerImpl deviceManager) {
243         deviceManager.setTranslatorLibrary(translatorLibrary);
244     }
245
246     @Test
247     public void testClose() throws Exception {
248         final DeviceContext deviceContext = Mockito.mock(DeviceContext.class);
249         final DeviceManagerImpl deviceManager = prepareDeviceManager();
250         final ConcurrentHashMap<NodeId, DeviceContext> deviceContexts = getContextsCollection(deviceManager);
251         deviceContexts.put(mockedNodeId, deviceContext);
252         Assert.assertEquals(1, deviceContexts.size());
253
254         deviceManager.close();
255
256         Mockito.verify(deviceContext).close();
257     }
258
259     private static ConcurrentHashMap<NodeId, DeviceContext> getContextsCollection(final DeviceManagerImpl deviceManager) throws NoSuchFieldException, IllegalAccessException {
260         // HACK: contexts collection for testing shall be accessed in some more civilized way
261         final Field contextsField = DeviceManagerImpl.class.getDeclaredField("deviceContexts");
262         Assert.assertNotNull(contextsField);
263         contextsField.setAccessible(true);
264         return (ConcurrentHashMap<NodeId, DeviceContext>) contextsField.get(deviceManager);
265     }
266
267 }