BUG 2412 - restconf @POST invokeRpc with payload method
[controller.git] / opendaylight / md-sal / sal-rest-connector / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / InvokeRpcMethodTest.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  * Copyright (c) 2014 Brocade Communications Systems, Inc.
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 package org.opendaylight.controller.sal.restconf.impl.test;
10
11 import static org.junit.Assert.assertEquals;
12 import static org.junit.Assert.assertNotNull;
13 import static org.junit.Assert.assertSame;
14 import static org.junit.Assert.assertTrue;
15 import static org.junit.Assert.fail;
16 import static org.mockito.Matchers.any;
17 import static org.mockito.Matchers.eq;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.spy;
20 import static org.mockito.Mockito.when;
21 import com.google.common.base.Optional;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
24 import com.google.common.util.concurrent.ListenableFuture;
25 import java.io.FileNotFoundException;
26 import java.net.URI;
27 import java.net.URISyntaxException;
28 import java.util.Arrays;
29 import java.util.Collections;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Set;
33 import javax.ws.rs.core.MultivaluedHashMap;
34 import javax.ws.rs.core.MultivaluedMap;
35 import javax.ws.rs.core.UriInfo;
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.junit.Test;
39 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
40 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
41 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
42 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
43 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
44 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
45 import org.opendaylight.controller.sal.restconf.impl.InstanceIdentifierContext;
46 import org.opendaylight.controller.sal.restconf.impl.NormalizedNodeContext;
47 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
48 import org.opendaylight.controller.sal.restconf.impl.RestconfError;
49 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
50 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
51 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
52 import org.opendaylight.controller.sal.restconf.impl.StructuredData;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.common.RpcError;
55 import org.opendaylight.yangtools.yang.common.RpcResult;
56 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
57 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
58 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
59 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
62 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
63 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
64 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.Module;
68 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
71 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
72
73 public class InvokeRpcMethodTest {
74
75     private RestconfImpl restconfImpl = null;
76     private static ControllerContext controllerContext = null;
77     private static UriInfo uriInfo;
78
79     @BeforeClass
80     public static void init() throws FileNotFoundException {
81         final Set<Module> allModules = new HashSet<Module>(TestUtils.loadModulesFrom("/full-versions/yangs"));
82         allModules.addAll(TestUtils.loadModulesFrom("/invoke-rpc"));
83         assertNotNull(allModules);
84         final Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
85         assertNotNull(module);
86         final SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
87         controllerContext = spy(ControllerContext.getInstance());
88         controllerContext.setSchemas(schemaContext);
89         uriInfo = mock(UriInfo.class);
90         final MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
91         map.put("prettyPrint", Collections.singletonList("true"));
92         when(uriInfo.getQueryParameters(any(Boolean.class))).thenReturn(map);
93     }
94
95     @Before
96     public void initMethod() {
97         restconfImpl = RestconfImpl.getInstance();
98         restconfImpl.setControllerContext(controllerContext);
99     }
100
101     /**
102      * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
103      * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
104      * string - first argument).
105      */
106     @Test
107     public void invokeRpcMethodTest() {
108         final ControllerContext contContext = controllerContext;
109         try {
110             contContext.findModuleNameByNamespace(new URI("invoke:rpc:module"));
111         } catch (final URISyntaxException e) {
112             assertTrue("Uri wasn't created sucessfuly", false);
113         }
114
115         final BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
116
117         final RestconfImpl restconf = RestconfImpl.getInstance();
118         restconf.setBroker(mockedBrokerFacade);
119         restconf.setControllerContext(contContext);
120
121         final NormalizedNodeContext payload = prepareDomPayload();
122
123         final NormalizedNodeContext rpcResponse = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
124         assertTrue(rpcResponse != null);
125         assertTrue(rpcResponse.getData() == null);
126
127     }
128
129     private NormalizedNodeContext prepareDomPayload() {
130         final SchemaContext schema = controllerContext.getGlobalSchema();
131         final Module rpcModule = schema.findModuleByName("invoke-rpc-module", null);
132         assertNotNull(rpcModule);
133         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "rpc-test");
134         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
135         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
136         ContainerSchemaNode rpcInputSchemaNode = null;
137         for (final RpcDefinition rpc : setRpcs) {
138             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
139                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
140                 break;
141             }
142         }
143         assertNotNull(rpcInputSchemaNode);
144
145         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> container = Builders.containerBuilder(rpcInputSchemaNode);
146
147         final QName contQName = QName.create(rpcModule.getQNameModule(), "cont");
148         final DataSchemaNode contSchemaNode = rpcInputSchemaNode.getDataChildByName(contQName);
149         assertTrue(contSchemaNode instanceof ContainerSchemaNode);
150         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> contNode = Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);
151
152         final QName lfQName = QName.create(rpcModule.getQNameModule(), "lf");
153         final DataSchemaNode lfSchemaNode = ((ContainerSchemaNode) contSchemaNode).getDataChildByName(lfQName);
154         assertTrue(lfSchemaNode instanceof LeafSchemaNode);
155         final LeafNode<Object> lfNode = (Builders.leafBuilder((LeafSchemaNode) lfSchemaNode).withValue("any value")).build();
156         contNode.withChild(lfNode);
157         container.withChild(contNode.build());
158
159         return new NormalizedNodeContext(new InstanceIdentifierContext(null, rpcInputSchemaNode, null, schema), container.build());
160     }
161
162     @Test
163     public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
164         final RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>failed().build();
165
166         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
167         when(
168                 brokerFacade.invokeRpc(
169                         eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
170                         any(CompositeNode.class))).thenReturn(
171                 Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
172
173         restconfImpl.setBroker(brokerFacade);
174
175         try {
176             restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
177             fail("Expected an exception to be thrown.");
178         } catch (final RestconfDocumentedException e) {
179             verifyRestconfDocumentedException(e, 0, ErrorType.APPLICATION, ErrorTag.OPERATION_FAILED,
180                     Optional.<String> absent(), Optional.<String> absent());
181         }
182     }
183
184     void verifyRestconfDocumentedException(final RestconfDocumentedException e, final int index,
185             final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
186             final Optional<String> expAppTag) {
187         RestconfError actual = null;
188         try {
189             actual = e.getErrors().get(index);
190         } catch (final ArrayIndexOutOfBoundsException ex) {
191             fail("RestconfError not found at index " + index);
192         }
193
194         assertEquals("getErrorType", expErrorType, actual.getErrorType());
195         assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
196         assertNotNull("getErrorMessage is null", actual.getErrorMessage());
197
198         if (expErrorMsg.isPresent()) {
199             assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
200         }
201
202         if (expAppTag.isPresent()) {
203             assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
204         }
205     }
206
207     @Test
208     public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
209         final List<RpcError> rpcErrors = Arrays.asList(
210             RpcResultBuilder.newError( RpcError.ErrorType.TRANSPORT, "bogusTag", "foo" ),
211             RpcResultBuilder.newWarning( RpcError.ErrorType.RPC, "in-use", "bar",
212                                          "app-tag", null, null ) );
213
214         final RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>failed()
215                                                               .withRpcErrors(rpcErrors).build();
216
217         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
218         when(
219                 brokerFacade.invokeRpc(
220                         eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
221                         any(CompositeNode.class))).thenReturn(
222                 Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
223
224         restconfImpl.setBroker(brokerFacade);
225
226         try {
227             restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
228             fail("Expected an exception to be thrown.");
229         } catch (final RestconfDocumentedException e) {
230             verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
231                     Optional.<String> absent());
232             verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
233                     Optional.of("app-tag"));
234         }
235     }
236
237     @Test
238     public void testInvokeRpcWithNoPayload_Success() {
239         final RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>success().build();
240
241         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
242         when(
243                 brokerFacade.invokeRpc(
244                         eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast")),
245                         any(CompositeNode.class))).thenReturn(
246                 Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
247
248         restconfImpl.setBroker(brokerFacade);
249
250         final StructuredData output = restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
251         assertEquals(null, output);
252         // additional validation in the fact that the restconfImpl does not
253         // throw an exception.
254     }
255
256     @Test
257     public void testInvokeRpcMethodExpectingNoPayloadButProvidePayload() {
258         try {
259             restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ", uriInfo);
260             fail("Expected an exception");
261         } catch (final RestconfDocumentedException e) {
262             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
263                     Optional.<String> absent(), Optional.<String> absent());
264         }
265     }
266
267     @Test
268     public void testInvokeRpcMethodWithBadMethodName() {
269         try {
270             restconfImpl.invokeRpc("toaster:bad-method", "", uriInfo);
271             fail("Expected an exception");
272         } catch (final RestconfDocumentedException e) {
273             verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
274                     Optional.<String> absent(), Optional.<String> absent());
275         }
276     }
277
278     @Test
279     public void testInvokeRpcMethodWithInput() {
280         final DOMRpcResult expResult = mock(DOMRpcResult.class);
281         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
282         final SchemaPath path = SchemaPath.create(true,
283                 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast"));
284
285         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
286         final Module rpcModule = schemaContext.findModuleByName("toaster", null);
287         assertNotNull(rpcModule);
288         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
289         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
290
291         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
292         RpcDefinition rpcDef = null;
293         ContainerSchemaNode rpcInputSchemaNode = null;
294
295         for (final RpcDefinition rpc : setRpcs) {
296             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
297                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
298                 rpcDef = rpc;
299                 break;
300             }
301         }
302
303         assertNotNull(rpcDef);
304         assertNotNull(rpcInputSchemaNode);
305         assertTrue(rpcInputSchemaNode instanceof ContainerSchemaNode);
306         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
307                 Builders.containerBuilder(rpcInputSchemaNode);
308
309         final NormalizedNodeContext payload = new NormalizedNodeContext(new InstanceIdentifierContext(null, rpcInputSchemaNode,
310                 null, schemaContext), containerBuilder.build());
311
312         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
313         when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
314         restconfImpl.setBroker(brokerFacade);
315
316         final NormalizedNodeContext output = restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
317         assertNotNull(output);
318         assertEquals(null, output.getData());
319         // additional validation in the fact that the restconfImpl does not
320         // throw an exception.
321     }
322
323     @Test
324     public void testThrowExceptionWhenSlashInModuleName() {
325         try {
326             restconfImpl.invokeRpc("toaster/slash", "", uriInfo);
327             fail("Expected an exception.");
328         } catch (final RestconfDocumentedException e) {
329             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
330                     Optional.<String> absent(), Optional.<String> absent());
331         }
332     }
333
334     @Test
335     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
336         final CompositeNode compositeNode = mock(CompositeNode.class);
337         final RpcResult<CompositeNode> rpcResult =
338                                   RpcResultBuilder.<CompositeNode>success(compositeNode).build();
339
340         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
341         when(
342                 brokerFacade.invokeRpc(
343                         eq(QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)testOutput")),
344                         any(CompositeNode.class))).thenReturn(
345                 Futures.<RpcResult<CompositeNode>> immediateFuture(rpcResult));
346
347         restconfImpl.setBroker(brokerFacade);
348
349         final StructuredData output = restconfImpl.invokeRpc("toaster:testOutput", "", uriInfo);
350         assertNotNull(output);
351         assertSame(compositeNode, output.getData());
352         assertNotNull(output.getSchema());
353     }
354
355     /**
356      *
357      * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
358      * This rpc is then executed.
359      *
360      * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
361      * invoked.
362      */
363     @Test
364     public void testMountedRpcCallNoPayload_Success() throws Exception {
365         final RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>success().build();
366
367         final ListenableFuture<RpcResult<CompositeNode>> mockListener = mock(ListenableFuture.class);
368         when(mockListener.get()).thenReturn(rpcResult);
369
370         final QName cancelToastQName = QName.create("namespace", "2014-05-28", "cancelToast");
371
372         final RpcDefinition mockRpc = mock(RpcDefinition.class);
373         when(mockRpc.getQName()).thenReturn(cancelToastQName);
374
375         final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
376         final RpcProvisionRegistry mockedRpcProvisionRegistry = mock(RpcProvisionRegistry.class);
377         when(mockedRpcProvisionRegistry.invokeRpc(eq(cancelToastQName), any(CompositeNode.class))).thenReturn(mockListener);
378         when(mockMountPoint.getService(eq(RpcProvisionRegistry.class))).thenReturn(Optional.of(mockedRpcProvisionRegistry));
379         when(mockMountPoint.getSchemaContext()).thenReturn(TestUtils.loadSchemaContext("/invoke-rpc"));
380
381         final InstanceIdentifierContext mockedInstanceId = mock(InstanceIdentifierContext.class);
382         when(mockedInstanceId.getMountPoint()).thenReturn(mockMountPoint);
383
384         final ControllerContext mockedContext = mock(ControllerContext.class);
385         final String rpcNoop = "invoke-rpc-module:rpc-noop";
386         when(mockedContext.urlPathArgDecode(rpcNoop)).thenReturn(rpcNoop);
387         when(mockedContext.getRpcDefinition(rpcNoop)).thenReturn(mockRpc);
388         when(
389                 mockedContext.toMountPointIdentifier(eq("opendaylight-inventory:nodes/node/"
390                         + "REMOTE_HOST/yang-ext:mount/invoke-rpc-module:rpc-noop"))).thenReturn(mockedInstanceId);
391
392         restconfImpl.setControllerContext(mockedContext);
393         try {
394             restconfImpl.invokeRpc(
395                     "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/invoke-rpc-module:rpc-noop", "",
396                     uriInfo);
397             fail("RestconfDocumentedException wasn't raised");
398         } catch (final RestconfDocumentedException e) {
399             final List<RestconfError> errors = e.getErrors();
400             assertNotNull(errors);
401             assertEquals(1, errors.size());
402             assertEquals(ErrorType.APPLICATION, errors.iterator().next().getErrorType());
403             assertEquals(ErrorTag.OPERATION_FAILED, errors.iterator().next().getErrorTag());
404         }
405
406         // additional validation in the fact that the restconfImpl does not
407         // throw an exception.
408     }
409 }