Switch to MD-SAL APIs
[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.assertFalse;
12 import static org.junit.Assert.assertNotNull;
13 import static org.mockito.ArgumentMatchers.any;
14 import static org.mockito.ArgumentMatchers.eq;
15 import static org.mockito.Mockito.mock;
16 import static org.mockito.Mockito.times;
17 import static org.mockito.Mockito.verify;
18 import static org.mockito.Mockito.when;
19
20 import com.google.common.base.Optional;
21 import java.math.BigInteger;
22 import java.util.Collections;
23 import java.util.List;
24 import org.junit.Before;
25 import org.junit.Test;
26 import org.junit.runner.RunWith;
27 import org.mockito.ArgumentMatchers;
28 import org.mockito.Mock;
29 import org.mockito.Mockito;
30 import org.mockito.junit.MockitoJUnitRunner;
31 import org.opendaylight.mdsal.binding.api.ReadTransaction;
32 import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
33 import org.opendaylight.openflowplugin.api.OFConstants;
34 import org.opendaylight.openflowplugin.api.openflow.connection.ConnectionContext;
35 import org.opendaylight.openflowplugin.api.openflow.device.DeviceContext;
36 import org.opendaylight.openflowplugin.api.openflow.device.DeviceInfo;
37 import org.opendaylight.openflowplugin.api.openflow.device.DeviceState;
38 import org.opendaylight.openflowplugin.api.openflow.registry.flow.DeviceFlowRegistry;
39 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowDescriptor;
40 import org.opendaylight.openflowplugin.api.openflow.registry.flow.FlowRegistryKey;
41 import org.opendaylight.openflowplugin.api.openflow.statistics.ofpspecific.EventIdentifier;
42 import org.opendaylight.openflowplugin.impl.datastore.MultipartWriterProviderFactory;
43 import org.opendaylight.openflowplugin.impl.rpc.AbstractRequestContext;
44 import org.opendaylight.openflowplugin.impl.services.multilayer.MultiLayerFlowMultipartRequestOnTheFlyCallback;
45 import org.opendaylight.openflowplugin.impl.statistics.ofpspecific.MessageIntelligenceAgencyImpl;
46 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManager;
47 import org.opendaylight.openflowplugin.openflow.md.core.sal.convertor.ConvertorManagerFactory;
48 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode;
49 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeBuilder;
50 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table;
51 import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableBuilder;
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 ConnectionContext mockedPrimaryConnection;
91     @Mock
92     private NodeId mockedNodeId;
93     @Mock
94     private FeaturesReply mockedFeaturesReply;
95     @Mock
96     private DeviceState mockedDeviceState;
97     @Mock
98     private DeviceInfo mockedDeviceInfo;
99     @Mock
100     private GetFeaturesOutput mocketGetFeaturesOutput;
101     @Mock
102     private DeviceFlowRegistry mockedFlowRegistry;
103     @Mock
104     private FlowDescriptor mockedFlowDescriptor;
105     @Mock
106     private ReadTransaction mockedReadOnlyTx;
107
108     private AbstractRequestContext<List<MultipartReply>> dummyRequestContext;
109     private final EventIdentifier dummyEventIdentifier = new EventIdentifier(DUMMY_EVENT_NAME, DUMMY_DEVICE_ID);
110     private AbstractMultipartRequestOnTheFlyCallback<MultipartReply> 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.getFeatures()).thenReturn(mockedFeaturesReply);
118
119         when(mockedDeviceContext.getPrimaryConnectionContext()).thenReturn(mockedPrimaryConnection);
120         when(mockedDeviceInfo.getNodeInstanceIdentifier()).thenReturn(NODE_PATH);
121         when(mockedDeviceInfo.getNodeId()).thenReturn(mockedNodeId);
122         when(mockedDeviceInfo.getDatapathId()).thenReturn(BigInteger.TEN);
123         when(mockedDeviceInfo.getVersion()).thenReturn(OFConstants.OFP_VERSION_1_3);
124
125         when(mockedDeviceContext.getDeviceInfo()).thenReturn(mockedDeviceInfo);
126         when(mockedDeviceContext.getDeviceFlowRegistry()).thenReturn(mockedFlowRegistry);
127         when(mockedFlowRegistry.retrieveDescriptor(any(FlowRegistryKey.class)))
128                 .thenReturn(mockedFlowDescriptor);
129
130         final InstanceIdentifier<FlowCapableNode> nodePath =
131                 mockedDeviceInfo.getNodeInstanceIdentifier().augmentation(FlowCapableNode.class);
132         final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
133         flowNodeBuilder.setTable(Collections.<Table>emptyList());
134         final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
135         dummyRequestContext = new AbstractRequestContext<List<MultipartReply>>(DUMMY_XID) {
136
137             @Override
138             public void close() {
139                 //NOOP
140             }
141         };
142
143         final ConvertorManager convertorManager = ConvertorManagerFactory.createDefaultManager();
144         multipartRequestOnTheFlyCallback = new MultiLayerFlowMultipartRequestOnTheFlyCallback<>(
145             dummyRequestContext,
146             String.class,
147             mockedDeviceContext,
148             dummyEventIdentifier,
149             MultipartWriterProviderFactory.createDefaultProvider(mockedDeviceContext),
150             convertorManager);
151     }
152
153
154     @Test
155     public void testOnSuccessWithNull() throws Exception {
156         multipartRequestOnTheFlyCallback.onSuccess(null);
157         final RpcResult<List<MultipartReply>> expectedRpcResult =
158                 RpcResultBuilder.success(Collections.<MultipartReply>emptyList()).build();
159         final RpcResult<List<MultipartReply>> actualResult = dummyRequestContext.getFuture().get();
160         assertEquals(expectedRpcResult.getErrors(), actualResult.getErrors());
161         assertEquals(expectedRpcResult.getResult(), actualResult.getResult());
162         assertEquals(expectedRpcResult.isSuccessful(), actualResult.isSuccessful());
163     }
164
165     @Test
166     public void testOnSuccessWithNotMultiNoMultipart() throws Exception {
167         final HelloMessage mockedHelloMessage = mock(HelloMessage.class);
168         multipartRequestOnTheFlyCallback.onSuccess(mockedHelloMessage);
169
170         final RpcResult<List<MultipartReply>> expectedRpcResult =
171                 RpcResultBuilder.<List<MultipartReply>>failed().withError(RpcError.ErrorType.APPLICATION,
172                         String.format("Unexpected response type received: %s.", mockedHelloMessage.getClass())).build();
173         final RpcResult<List<MultipartReply>> actualResult = dummyRequestContext.getFuture().get();
174         assertNotNull(actualResult.getErrors());
175         assertEquals(1, actualResult.getErrors().size());
176
177         final RpcError actualError = actualResult.getErrors().iterator().next();
178         assertEquals(actualError.getMessage(),
179                      String.format("Unexpected response type received: %s.",
180                      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())
186                 .writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL),
187                         ArgumentMatchers.<InstanceIdentifier>any(), ArgumentMatchers.<DataObject>any());
188         Mockito.verify(mockedDeviceContext).submitTransaction();
189     }
190
191     /**
192      * Not the last reply.
193      */
194     @Test
195     public void testOnSuccessWithValidMultipart1() throws Exception {
196         final MatchBuilder matchBuilder = new MatchBuilder()
197                 .setMatchEntry(Collections.<MatchEntry>emptyList());
198         final FlowStatsBuilder flowStatsBuilder = new FlowStatsBuilder()
199                 .setTableId(tableId)
200                 .setPriority(2)
201                 .setCookie(BigInteger.ZERO)
202                 .setByteCount(BigInteger.TEN)
203                 .setPacketCount(BigInteger.ONE)
204                 .setDurationSec(11L)
205                 .setDurationNsec(12L)
206                 .setMatch(matchBuilder.build())
207                 .setFlags(new FlowModFlags(true, false, false, false, false));
208         final MultipartReplyFlowBuilder multipartReplyFlowBuilder = new MultipartReplyFlowBuilder()
209                 .setFlowStats(Collections.singletonList(flowStatsBuilder.build()));
210         final MultipartReplyFlowCaseBuilder multipartReplyFlowCaseBuilder = new MultipartReplyFlowCaseBuilder()
211                 .setMultipartReplyFlow(multipartReplyFlowBuilder.build());
212         final MultipartReplyMessageBuilder mpReplyMessage = new MultipartReplyMessageBuilder()
213                 .setType(MultipartType.OFPMPFLOW)
214                 .setFlags(new MultipartRequestFlags(true))
215                 .setMultipartReplyBody(multipartReplyFlowCaseBuilder.build())
216                 .setXid(21L);
217
218         final InstanceIdentifier<FlowCapableNode> nodePath = mockedDeviceInfo.getNodeInstanceIdentifier()
219                 .augmentation(FlowCapableNode.class);
220         final FlowCapableNodeBuilder flowNodeBuilder = new FlowCapableNodeBuilder();
221         final TableBuilder tableDataBld = new TableBuilder();
222         tableDataBld.setId(tableId);
223         flowNodeBuilder.setTable(Collections.singletonList(tableDataBld.build()));
224         final Optional<FlowCapableNode> flowNodeOpt = Optional.of(flowNodeBuilder.build());
225
226         multipartRequestOnTheFlyCallback.onSuccess(mpReplyMessage.build());
227
228         verify(mockedReadOnlyTx, times(0)).read(LogicalDatastoreType.OPERATIONAL, nodePath);
229         verify(mockedReadOnlyTx, times(0)).close();
230         verify(mockedDeviceContext, times(1)).writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL),
231                 any(), any());
232     }
233
234     /**
235      * The last reply.
236      */
237     @Test
238     public void testOnSuccessWithValidMultipart2() throws Exception {
239         final MultipartReplyMessageBuilder mpReplyMessage = new MultipartReplyMessageBuilder()
240                 .setType(MultipartType.OFPMPDESC)
241                 .setFlags(new MultipartRequestFlags(false));
242
243         multipartRequestOnTheFlyCallback.onSuccess(mpReplyMessage.build());
244
245         final RpcResult<List<MultipartReply>> actualResult = dummyRequestContext.getFuture().get();
246
247         // Nothing else than flow is supported by on the fly callback
248         assertNotNull(actualResult.getErrors());
249         assertFalse(actualResult.getErrors().isEmpty());
250         Mockito.verify(mockedFlowRegistry, Mockito.never()).store(any());
251         Mockito.verify(mockedDeviceContext, Mockito.never())
252                 .writeToTransaction(eq(LogicalDatastoreType.OPERATIONAL),
253                         ArgumentMatchers.<InstanceIdentifier>any(), ArgumentMatchers.<DataObject>any());
254     }
255 }