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