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