Ensure RPC input in invocation is not null
[netconf.git] / restconf / restconf-nb-bierman02 / src / test / java / org / opendaylight / controller / sal / restconf / impl / test / InvokeRpcMethodTest.java
1 /*
2  * Copyright (c) 2013, 2015 Brocade Communication Systems, Inc., 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.controller.sal.restconf.impl.test;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertSame;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.mockito.ArgumentMatchers.any;
16 import static org.mockito.ArgumentMatchers.eq;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.when;
20 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
21 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
22
23 import com.google.common.base.Optional;
24 import java.io.FileNotFoundException;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.List;
31 import javax.ws.rs.WebApplicationException;
32 import javax.ws.rs.core.MultivaluedHashMap;
33 import javax.ws.rs.core.MultivaluedMap;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.core.UriInfo;
36 import org.junit.Assert;
37 import org.junit.BeforeClass;
38 import org.junit.Ignore;
39 import org.junit.Test;
40 import org.mockito.Mockito;
41 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
42 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
43 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
44 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
45 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
46 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
47 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
48 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
49 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
50 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
51 import org.opendaylight.restconf.common.errors.RestconfError;
52 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
53 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.RpcError;
56 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
62 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
63 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
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.EffectiveModelContext;
67 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.Module;
69 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
72 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
73 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
74
75 public class InvokeRpcMethodTest {
76
77     private static UriInfo uriInfo;
78     private static EffectiveModelContext schemaContext;
79
80     private final RestconfImpl restconfImpl;
81     private final ControllerContext controllerContext;
82     private final BrokerFacade brokerFacade = mock(BrokerFacade.class);
83
84     public InvokeRpcMethodTest() {
85         controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
86         restconfImpl = RestconfImpl.newInstance(brokerFacade, controllerContext);
87     }
88
89     @BeforeClass
90     public static void init() throws FileNotFoundException, ReactorException {
91         schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs", "/invoke-rpc");
92         final Collection<? extends Module> allModules = schemaContext.getModules();
93         assertNotNull(allModules);
94         final Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
95         assertNotNull(module);
96
97         uriInfo = mock(UriInfo.class);
98         final MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
99         map.put("prettyPrint", Collections.singletonList("true"));
100         when(uriInfo.getQueryParameters(any(Boolean.class))).thenReturn(map);
101     }
102
103     /**
104      * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
105      * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
106      * string - first argument).
107      */
108     @Test
109     @Ignore
110     public void invokeRpcMethodTest() {
111         try {
112             controllerContext.findModuleNameByNamespace(new URI("invoke:rpc:module"));
113         } catch (final URISyntaxException e) {
114             assertTrue("Uri wasn't created sucessfuly", false);
115         }
116
117         final NormalizedNodeContext payload = prepareDomPayload();
118
119         final NormalizedNodeContext rpcResponse =
120                 restconfImpl.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
121         assertTrue(rpcResponse != null);
122         assertTrue(rpcResponse.getData() == null);
123
124     }
125
126     private NormalizedNodeContext prepareDomPayload() {
127         final EffectiveModelContext schema = controllerContext.getGlobalSchema();
128         final Module rpcModule = schema.findModules("invoke-rpc-module").iterator().next();
129         assertNotNull(rpcModule);
130         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "rpc-test");
131         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
132         ContainerSchemaNode rpcInputSchemaNode = null;
133         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
134             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
135                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
136                 break;
137             }
138         }
139         assertNotNull(rpcInputSchemaNode);
140
141         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> container =
142                 Builders.containerBuilder(rpcInputSchemaNode);
143
144         final QName contQName = QName.create(rpcModule.getQNameModule(), "cont");
145         final DataSchemaNode contSchemaNode = rpcInputSchemaNode.getDataChildByName(contQName);
146         assertTrue(contSchemaNode instanceof ContainerSchemaNode);
147         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> contNode =
148                 Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);
149
150         final QName lfQName = QName.create(rpcModule.getQNameModule(), "lf");
151         final DataSchemaNode lfSchemaNode = ((ContainerSchemaNode) contSchemaNode).getDataChildByName(lfQName);
152         assertTrue(lfSchemaNode instanceof LeafSchemaNode);
153         final LeafNode<Object> lfNode =
154                 Builders.leafBuilder((LeafSchemaNode) lfSchemaNode).withValue("any value").build();
155         contNode.withChild(lfNode);
156         container.withChild(contNode.build());
157
158         return new NormalizedNodeContext(
159                 new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), container.build());
160     }
161
162     @Test
163     public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
164         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
165         final SchemaPath type = SchemaPath.create(true, qname);
166
167         doReturn(immediateFailedFluentFuture(new DOMRpcImplementationNotAvailableException("testExeption")))
168         .when(brokerFacade).invokeRpc(eq(type), any());
169
170         try {
171             this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
172             fail("Expected an exception to be thrown.");
173         } catch (final RestconfDocumentedException e) {
174             verifyRestconfDocumentedException(e, 0, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED,
175                     Optional.absent(), Optional.absent());
176         }
177     }
178
179     void verifyRestconfDocumentedException(final RestconfDocumentedException restDocumentedException, final int index,
180             final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
181             final Optional<String> expAppTag) {
182         RestconfError actual = null;
183         try {
184             actual = restDocumentedException.getErrors().get(index);
185         } catch (final ArrayIndexOutOfBoundsException ex) {
186             fail("RestconfError not found at index " + index);
187         }
188
189         assertEquals("getErrorType", expErrorType, actual.getErrorType());
190         assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
191         assertNotNull("getErrorMessage is null", actual.getErrorMessage());
192
193         if (expErrorMsg.isPresent()) {
194             assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
195         }
196
197         if (expAppTag.isPresent()) {
198             assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
199         }
200     }
201
202     @Test
203     public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
204         final List<RpcError> rpcErrors = Arrays.asList(
205                 RpcResultBuilder.newError(RpcError.ErrorType.TRANSPORT, "bogusTag", "foo"),
206                 RpcResultBuilder.newWarning(RpcError.ErrorType.RPC, "in-use", "bar",
207                         "app-tag", null, null));
208
209         final DOMRpcResult result = new DefaultDOMRpcResult(rpcErrors);
210         final SchemaPath path = SchemaPath.create(true,
211                 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast"));
212         doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(path), any());
213
214         try {
215             this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
216             fail("Expected an exception to be thrown.");
217         } catch (final RestconfDocumentedException e) {
218             verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
219                     Optional.absent());
220             verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
221                     Optional.of("app-tag"));
222         }
223     }
224
225     @Test
226     public void testInvokeRpcWithNoPayload_Success() {
227         final NormalizedNode<?, ?> resultObj = null;
228         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
229
230         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
231         final SchemaPath path = SchemaPath.create(true, qname);
232
233         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), any());
234
235         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
236         assertNotNull(output);
237         assertEquals(null, output.getData());
238         // additional validation in the fact that the restconfImpl does not
239         // throw an exception.
240     }
241
242     @Test
243     public void testInvokeRpcWithEmptyOutput() {
244         final ContainerNode resultObj = Mockito.mock(ContainerNode.class);
245         Mockito.when(resultObj.getValue()).thenReturn(Collections.emptySet());
246         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
247
248         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
249         final SchemaPath path = SchemaPath.create(true, qname);
250         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), any());
251
252         WebApplicationException exceptionToBeThrown = null;
253         try {
254             this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
255         } catch (final WebApplicationException exception) {
256             exceptionToBeThrown = exception;
257
258         }
259         Assert.assertNotNull("WebApplicationException with status code 204 is expected.", exceptionToBeThrown);
260         Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), exceptionToBeThrown.getResponse().getStatus());
261     }
262
263     @Test
264     public void testInvokeRpcMethodWithBadMethodName() {
265         try {
266             this.restconfImpl.invokeRpc("toaster:bad-method", null, uriInfo);
267             fail("Expected an exception");
268         } catch (final RestconfDocumentedException e) {
269             verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
270                     Optional.absent(), Optional.absent());
271         }
272     }
273
274     @Test
275     @Ignore
276     public void testInvokeRpcMethodWithInput() {
277         final DOMRpcResult expResult = mock(DOMRpcResult.class);
278         final SchemaPath path = SchemaPath.create(true,
279                 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast"));
280
281         final Module rpcModule = schemaContext.findModules("toaster").iterator().next();
282         assertNotNull(rpcModule);
283         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
284         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
285
286         RpcDefinition rpcDef = null;
287         ContainerSchemaNode rpcInputSchemaNode = null;
288         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
289             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
290                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
291                 rpcDef = rpc;
292                 break;
293             }
294         }
295
296         assertNotNull(rpcDef);
297         assertNotNull(rpcInputSchemaNode);
298         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
299                 Builders.containerBuilder(rpcInputSchemaNode);
300
301         final NormalizedNodeContext payload =
302                 new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
303                 null, schemaContext), containerBuilder.build());
304
305         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), any(NormalizedNode.class));
306
307         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
308         assertNotNull(output);
309         assertEquals(null, output.getData());
310         // additional validation in the fact that the restconfImpl does not
311         // throw an exception.
312     }
313
314     @Test
315     public void testThrowExceptionWhenSlashInModuleName() {
316         try {
317             this.restconfImpl.invokeRpc("toaster/slash", null, uriInfo);
318             fail("Expected an exception.");
319         } catch (final RestconfDocumentedException e) {
320             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
321                     Optional.absent(), Optional.absent());
322         }
323     }
324
325     @Test
326     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
327         final SchemaContext schema = controllerContext.getGlobalSchema();
328         final Module rpcModule = schema.findModules("toaster").iterator().next();
329         assertNotNull(rpcModule);
330         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
331         final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
332
333         RpcDefinition rpcDef = null;
334         ContainerSchemaNode rpcOutputSchemaNode = null;
335         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
336             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
337                 rpcOutputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcOutputQName);
338                 rpcDef = rpc;
339                 break;
340             }
341         }
342         assertNotNull(rpcDef);
343         assertNotNull(rpcOutputSchemaNode);
344         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
345                 Builders.containerBuilder(rpcOutputSchemaNode);
346         final DataSchemaNode leafSchema = rpcOutputSchemaNode
347                 .getDataChildByName(QName.create(rpcModule.getQNameModule(), "textOut"));
348         assertTrue(leafSchema instanceof LeafSchemaNode);
349         final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
350                 Builders.leafBuilder((LeafSchemaNode) leafSchema);
351         leafBuilder.withValue("brm");
352         containerBuilder.withChild(leafBuilder.build());
353         final ContainerNode container = containerBuilder.build();
354
355         final DOMRpcResult result = new DefaultDOMRpcResult(container);
356
357         doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(rpcDef.getPath()), any());
358
359         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:testOutput", null, uriInfo);
360         assertNotNull(output);
361         assertNotNull(output.getData());
362         assertSame(container, output.getData());
363         assertNotNull(output.getInstanceIdentifierContext());
364         assertNotNull(output.getInstanceIdentifierContext().getSchemaContext());
365     }
366
367     /**
368      * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
369      * This rpc is then executed.
370      * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
371      * invoked.
372      */
373     @Test
374     @Ignore // FIXME find how to use mockito for it
375     public void testMountedRpcCallNoPayload_Success() throws Exception {
376     }
377 }