Add missing license headers
[openflowplugin.git] / openflowplugin-impl / src / test / java / org / opendaylight / openflowplugin / impl / services / MultipartRequestOnTheFlyCallbackTest.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 package org.opendaylight.openflowplugin.impl.services;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertTrue;
13 import static org.mockito.Matchers.eq;
14 import static org.mockito.Mockito.mock;
15 import static org.mockito.Mockito.times;
16 import static org.mockito.Mockito.verify;
17 import static org.mockito.Mockito.when;
18
19 import com.google.common.base.Optional;
20 import com.google.common.util.concurrent.CheckedFuture;
21 import com.google.common.util.concurrent.Futures;
22 import java.math.BigInteger;
23 import java.util.Collections;
24 import java.util.List;
25 import java.util.concurrent.ExecutionException;
26 import org.junit.Before;
27 import org.junit.Test;
28 import org.junit.runner.RunWith;
29 import org.mockito.Matchers;
30 import org.mockito.Mock;
31 import org.mockito.Mockito;
32 import org.mockito.runners.MockitoJUnitRunner;
33 import org.opendaylight.controller.md.sal.binding.api.ReadOnlyTransaction;
34 import org.opendaylight.controller.md.sal.common.api.data.LogicalDatastoreType;
35 import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException;
36 import org.opendaylight.openflowplugin.api.OFConstants;
37 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
38 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
39 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
40 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
41 import org.opendaylight.openflowplugin.api.openflow.device.RequestContext;
42 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
43 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
44 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier;
45 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
46 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyImpl;
47 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey;
52 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeId;
53 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes;
54 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node;
55 import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey;
56 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.FlowModFlags;
57 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartRequestFlags;
58 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.common.types.rev130731.MultipartType;
59 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.entries.grouping.MatchEntry;
60 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.oxm.rev150225.match.grouping.MatchBuilder;
61 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.FeaturesReply;
62 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.GetFeaturesOutput;
63 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.HelloMessage;
64 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReply;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.MultipartReplyMessageBuilder;
66 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.MultipartReplyFlowCaseBuilder;
67 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.MultipartReplyFlowBuilder;
68 import org.opendaylight.yang.gen.v1.urn.opendaylight.openflow.protocol.rev130731.multipart.reply.multipart.reply.body.multipart.reply.flow._case.multipart.reply.flow.FlowStatsBuilder;
69 import org.opendaylight.yangtools.yang.binding.DataObject;
70 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
71 import org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier;
72 import org.opendaylight.yangtools.yang.common.RpcError;
73 import org.opendaylight.yangtools.yang.common.RpcResult;
74 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
75
76 @RunWith(MockitoJUnitRunner.class)
77 public class MultipartRequestOnTheFlyCallbackTest {
78
79     private static final String DUMMY_NODE_ID = "dummyNodeId";
80     private static final String DUMMY_EVENT_NAME = "dummy event name 1";
81     private static final String DUMMY_DEVICE_ID = "dummy device id 1";
82     private static final Long DUMMY_XID = 55L;
83     private static final KeyedInstanceIdentifier<Node, NodeKey> NODE_PATH = KeyedInstanceIdentifier
84             .create(Nodes.class)
85             .child(Node.class, new NodeKey(new NodeId("uf-node:123")));
86
87     @Mock
88     private DeviceContext mockedDeviceContext;
89     @Mock
90     private RequestContext<List<MultipartReply>> mockedRequestContext;
91     @Mock
92     private ConnectionContext mockedPrimaryConnection;
93     @Mock
94     private NodeId mockedNodeId;
95     @Mock
96     private FeaturesReply mockedFeaturesReply;
97     @Mock
98     private DeviceState mockedDeviceState;
99     @Mock
100     private DeviceInfo mockedDeviceInfo;
101     @Mock
102     private GetFeaturesOutput mocketGetFeaturesOutput;
103     @Mock
104     private DeviceFlowRegistry mockedFlowRegistry;
105     @Mock
106     private ReadOnlyTransaction mockedReadOnlyTx;
107
108     private AbstractRequestContext<List<MultipartReply>> dummyRequestContext;
109     private final EventIdentifier dummyEventIdentifier = new EventIdentifier(DUMMY_EVENT_NAME, DUMMY_DEVICE_ID);
110     private MultipartRequestOnTheFlyCallback multipartRequestOnTheFlyCallback;
111     private final short tableId = 0;
112
113     @Before
114     public void initialization() {
115         when(mockedDeviceContext.getMessageSpy()).thenReturn(new MessageIntelligenceAgencyImpl());
116         when(mockedNodeId.toString()).thenReturn(DUMMY_NODE_ID);
117         when(mockedPrimaryConnection.getNodeId()).thenReturn(mockedNodeId);
118         when(mockedPrimaryConnection.getFeatures()).thenReturn(mockedFeaturesReply);
119         when(mockedFeaturesReply.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
120         when(mockedFeaturesReply.getDatapathId()).thenReturn(BigInteger.valueOf(123L));
121
122         when(mocketGetFeaturesOutput.getTables()).thenReturn(tableId);
123         when(mocketGetFeaturesOutput.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
124         when(mocketGetFeaturesOutput.getDatapathId()).thenReturn(BigInteger.valueOf(123L));
125
126         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimaryConnection);
127         when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(NODE_PATH);
128         when(mockedDeviceState.deviceSynchronized()).thenReturn(true);
129         when(mockedDeviceInfo.getNodeId()).thenReturn(mockedNodeId);
130         when(mockedDeviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
131
132         when(mockedDeviceContext.getDeviceState()).thenReturn(mockedDeviceState);
133         when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
134         when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(mockedFlowRegistry);
135
136         final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceInfo.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
137         final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
138         flowNodeBuilder.setTable(Collections.<Table> emptyList());
139         final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
140         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFuture = Futures.immediateCheckedFuture(flowNodeOpt);
141         when(mockedReadOnlyTx.read(LogicalDatastoreType.OPERATIONAL, nodePath)).thenReturn(flowNodeFuture);
142         when(mockedDeviceContext.getReadTransaction()).thenReturn(mockedReadOnlyTx);
143
144         dummyRequestContext = new AbstractRequestContext<List<MultipartReply>>(DUMMY_XID) {
145
146             @Override
147             public void close() {
148                 //NOOP
149             }
150         };
151         multipartRequestOnTheFlyCallback = new MultipartRequestOnTheFlyCallback(dummyRequestContext, String.class,
152                 mockedDeviceContext.getMessageSpy(),dummyEventIdentifier, mockedDeviceInfo,
153                 mockedDeviceContext.getDeviceFlowRegistry(), mockedDeviceContext);
154     }
155
156
157     @Test
158     public void testOnSuccessWithNull() throws Exception {
159         multipartRequestOnTheFlyCallback.onSuccess(null);
160         final RpcResult<List<MultipartReply>> expectedRpcResult = RpcResultBuilder.success(Collections.<MultipartReply>emptyList()).build();
161         final RpcResult<List<MultipartReply>> actualResult = dummyRequestContext.getFuture().get();
162         assertEquals(expectedRpcResult.getErrors(), actualResult.getErrors());
163         assertEquals(expectedRpcResult.getResult(), actualResult.getResult());
164         assertEquals(expectedRpcResult.isSuccessful(), actualResult.isSuccessful());
165     }
166
167     @Test
168     public void testOnSuccessWithNotMultiNoMultipart() throws Exception {
169         final HelloMessage mockedHelloMessage = mock(HelloMessage.class);
170         multipartRequestOnTheFlyCallback.onSuccess(mockedHelloMessage);
171
172         final RpcResult<List<MultipartReply>> expectedRpcResult =
173                 RpcResultBuilder.<List<MultipartReply>>failed().withError(RpcError.ErrorType.APPLICATION,
174                         String.format("Unexpected response type received %s.", mockedHelloMessage.getClass())).build();
175         final RpcResult<List<MultipartReply>> actualResult = dummyRequestContext.getFuture().get();
176         assertNotNull(actualResult.getErrors());
177         assertEquals(1, actualResult.getErrors().size());
178
179         final RpcError actualError = actualResult.getErrors().iterator().next();
180         assertEquals(actualError.getMessage(), String.format("Unexpected response type received %s.", mockedHelloMessage.getClass()));
181         assertEquals(actualError.getErrorType(),RpcError.ErrorType.APPLICATION);
182         assertEquals(expectedRpcResult.getResult(), actualResult.getResult());
183         assertEquals(expectedRpcResult.isSuccessful(), actualResult.isSuccessful());
184
185         Mockito.verify(mockedDeviceContext, Mockito.never()).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL),
186                 Matchers.<InstanceIdentifier>any(), Matchers.<DataObject>any());
187         Mockito.verify(mockedDeviceContext).submitTransaction();
188     }
189
190     /**
191      * not the last reply
192      *
193      * @throws ExecutionException
194      * @throws InterruptedException
195      */
196     @Test
197     public void testOnSuccessWithValidMultipart1() throws Exception {
198         final MatchBuilder matchBuilder = new MatchBuilder()
199                 .setMatchEntry(Collections.<MatchEntry>emptyList());
200         final FlowStatsBuilder flowStatsBuilder = new FlowStatsBuilder()
201 .setTableId(tableId)
202                 .setPriority(2)
203                 .setCookie(BigInteger.ZERO)
204                 .setByteCount(BigInteger.TEN)
205                 .setPacketCount(BigInteger.ONE)
206                 .setDurationSec(11L)
207                 .setDurationNsec(12L)
208                 .setMatch(matchBuilder.build())
209                 .setFlags(new FlowModFlags(true, false, false, false, false));
210         final MultipartReplyFlowBuilder multipartReplyFlowBuilder = new MultipartReplyFlowBuilder()
211                 .setFlowStats(Collections.singletonList(flowStatsBuilder.build()));
212         final MultipartReplyFlowCaseBuilder multipartReplyFlowCaseBuilder = new MultipartReplyFlowCaseBuilder()
213                 .setMultipartReplyFlow(multipartReplyFlowBuilder.build());
214         final MultipartReplyMessageBuilder mpReplyMessage = new MultipartReplyMessageBuilder()
215                 .setType(MultipartType.OFPMPFLOW)
216                 .setFlags(new MultipartRequestFlags(true))
217                 .setMultipartReplyBody(multipartReplyFlowCaseBuilder.build())
218                 .setXid(21L);
219
220         final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceInfo.getNodeInstanceIdentifier()
221                 .augmentation(FlowCapableNode.class);
222         final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
223         final TableBuilder tableDataBld = new TableBuilder();
224         tableDataBld.setId(tableId);
225         flowNodeBuilder.setTable(Collections.singletonList(tableDataBld.build()));
226         final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
227         final CheckedFuture<Optional<FlowCapableNode>, ReadFailedException> flowNodeFuture = Futures
228                 .immediateCheckedFuture(flowNodeOpt);
229         when(mockedReadOnlyTx.read(LogicalDatastoreType.OPERATIONAL, nodePath)).thenReturn(flowNodeFuture);
230         when(mockedDeviceContext.getReadTransaction()).thenReturn(mockedReadOnlyTx);
231
232         multipartRequestOnTheFlyCallback.onSuccess(mpReplyMessage.build());
233         final InstanceIdentifier<Table> tableIdent = nodePath.child(Table.class, new TableKey(tableId));
234
235         verify(mockedReadOnlyTx, times(1)).read(LogicalDatastoreType.OPERATIONAL, nodePath);
236         verify(mockedReadOnlyTx, times(1)).close();
237         verify(mockedFlowRegistry).storeIfNecessary(Matchers.<FlowRegistryKey> any());
238         verify(mockedDeviceContext, times(1)).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL),
239                 eq(tableIdent), Matchers.<Table> any());
240         /*
241          * One call for Table one call for Flow
242          * we are not able to create Flow InstanceIdentifier because we are missing FlowId
243          */
244         verify(mockedDeviceContext, times(2)).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL),
245                 Matchers.<InstanceIdentifier> any(), Matchers.<DataObject> any());
246     }
247
248     /**
249      * the last reply
250      *
251      * @throws ExecutionException
252      * @throws InterruptedException
253      */
254     @Test
255     public void testOnSuccessWithValidMultipart2() throws Exception {
256         final MultipartReplyMessageBuilder mpReplyMessage = new MultipartReplyMessageBuilder()
257                 .setType(MultipartType.OFPMPDESC)
258                 .setFlags(new MultipartRequestFlags(false));
259
260         multipartRequestOnTheFlyCallback.onSuccess(mpReplyMessage.build());
261
262         final RpcResult<List<MultipartReply>> actualResult = dummyRequestContext.getFuture().get();
263         assertNotNull(actualResult.getErrors());
264         assertTrue(actualResult.getErrors().isEmpty());
265         assertNotNull(actualResult.getResult());
266         assertTrue(actualResult.getResult().isEmpty());
267
268         Mockito.verify(mockedFlowRegistry, Mockito.never()).storeIfNecessary(Matchers.any());
269         Mockito.verify(mockedDeviceContext, Mockito.never()).writeToTransaction(Matchers.eq(LogicalDatastoreType.OPERATIONAL),
270                 Matchers.<InstanceIdentifier>any(), Matchers.<DataObject>any());
271     }
272 }