Bump upstreams for Silicon
[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.ContainerLike;
65 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
68 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.Module;
70 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
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         ContainerLike 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
166         doReturn(immediateFailedFluentFuture(new DOMRpcImplementationNotAvailableException("testExeption")))
167         .when(brokerFacade).invokeRpc(eq(qname), any());
168
169         try {
170             this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
171             fail("Expected an exception to be thrown.");
172         } catch (final RestconfDocumentedException e) {
173             verifyRestconfDocumentedException(e, 0, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED,
174                     Optional.absent(), Optional.absent());
175         }
176     }
177
178     void verifyRestconfDocumentedException(final RestconfDocumentedException restDocumentedException, final int index,
179             final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
180             final Optional<String> expAppTag) {
181         RestconfError actual = null;
182         try {
183             actual = restDocumentedException.getErrors().get(index);
184         } catch (final ArrayIndexOutOfBoundsException ex) {
185             fail("RestconfError not found at index " + index);
186         }
187
188         assertEquals("getErrorType", expErrorType, actual.getErrorType());
189         assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
190         assertNotNull("getErrorMessage is null", actual.getErrorMessage());
191
192         if (expErrorMsg.isPresent()) {
193             assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
194         }
195
196         if (expAppTag.isPresent()) {
197             assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
198         }
199     }
200
201     @Test
202     public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
203         final List<RpcError> rpcErrors = Arrays.asList(
204                 RpcResultBuilder.newError(RpcError.ErrorType.TRANSPORT, "bogusTag", "foo"),
205                 RpcResultBuilder.newWarning(RpcError.ErrorType.RPC, "in-use", "bar",
206                         "app-tag", null, null));
207
208         final DOMRpcResult result = new DefaultDOMRpcResult(rpcErrors);
209         final QName path = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
210         doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(path), any());
211
212         try {
213             this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
214             fail("Expected an exception to be thrown.");
215         } catch (final RestconfDocumentedException e) {
216             verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
217                     Optional.absent());
218             verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
219                     Optional.of("app-tag"));
220         }
221     }
222
223     @Test
224     public void testInvokeRpcWithNoPayload_Success() {
225         final NormalizedNode<?, ?> resultObj = null;
226         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
227
228         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
229
230         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(qname), any());
231
232         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
233         assertNotNull(output);
234         assertEquals(null, output.getData());
235         // additional validation in the fact that the restconfImpl does not
236         // throw an exception.
237     }
238
239     @Test
240     public void testInvokeRpcWithEmptyOutput() {
241         final ContainerNode resultObj = Mockito.mock(ContainerNode.class);
242         Mockito.when(resultObj.getValue()).thenReturn(Collections.emptySet());
243         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
244
245         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
246         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(qname), any());
247
248         WebApplicationException exceptionToBeThrown = null;
249         try {
250             this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
251         } catch (final WebApplicationException exception) {
252             exceptionToBeThrown = exception;
253
254         }
255         Assert.assertNotNull("WebApplicationException with status code 204 is expected.", exceptionToBeThrown);
256         Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), exceptionToBeThrown.getResponse().getStatus());
257     }
258
259     @Test
260     public void testInvokeRpcMethodWithBadMethodName() {
261         try {
262             this.restconfImpl.invokeRpc("toaster:bad-method", null, uriInfo);
263             fail("Expected an exception");
264         } catch (final RestconfDocumentedException e) {
265             verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
266                     Optional.absent(), Optional.absent());
267         }
268     }
269
270     @Test
271     @Ignore
272     public void testInvokeRpcMethodWithInput() {
273         final DOMRpcResult expResult = mock(DOMRpcResult.class);
274         final QName path = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast");
275
276         final Module rpcModule = schemaContext.findModules("toaster").iterator().next();
277         assertNotNull(rpcModule);
278         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
279         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
280
281         RpcDefinition rpcDef = null;
282         ContainerLike rpcInputSchemaNode = null;
283         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
284             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
285                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
286                 rpcDef = rpc;
287                 break;
288             }
289         }
290
291         assertNotNull(rpcDef);
292         assertNotNull(rpcInputSchemaNode);
293         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
294                 Builders.containerBuilder(rpcInputSchemaNode);
295
296         final NormalizedNodeContext payload =
297                 new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
298                 null, schemaContext), containerBuilder.build());
299
300         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), any(NormalizedNode.class));
301
302         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
303         assertNotNull(output);
304         assertEquals(null, output.getData());
305         // additional validation in the fact that the restconfImpl does not
306         // throw an exception.
307     }
308
309     @Test
310     public void testThrowExceptionWhenSlashInModuleName() {
311         try {
312             this.restconfImpl.invokeRpc("toaster/slash", null, uriInfo);
313             fail("Expected an exception.");
314         } catch (final RestconfDocumentedException e) {
315             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
316                     Optional.absent(), Optional.absent());
317         }
318     }
319
320     @Test
321     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
322         final SchemaContext schema = controllerContext.getGlobalSchema();
323         final Module rpcModule = schema.findModules("toaster").iterator().next();
324         assertNotNull(rpcModule);
325         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
326         final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
327
328         RpcDefinition rpcDef = null;
329         ContainerLike rpcOutputSchemaNode = null;
330         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
331             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
332                 rpcOutputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcOutputQName);
333                 rpcDef = rpc;
334                 break;
335             }
336         }
337         assertNotNull(rpcDef);
338         assertNotNull(rpcOutputSchemaNode);
339         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
340                 Builders.containerBuilder(rpcOutputSchemaNode);
341         final DataSchemaNode leafSchema = rpcOutputSchemaNode
342                 .getDataChildByName(QName.create(rpcModule.getQNameModule(), "textOut"));
343         assertTrue(leafSchema instanceof LeafSchemaNode);
344         final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
345                 Builders.leafBuilder((LeafSchemaNode) leafSchema);
346         leafBuilder.withValue("brm");
347         containerBuilder.withChild(leafBuilder.build());
348         final ContainerNode container = containerBuilder.build();
349
350         final DOMRpcResult result = new DefaultDOMRpcResult(container);
351
352         doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(rpcDef.getQName()), any());
353
354         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:testOutput", null, uriInfo);
355         assertNotNull(output);
356         assertNotNull(output.getData());
357         assertSame(container, output.getData());
358         assertNotNull(output.getInstanceIdentifierContext());
359         assertNotNull(output.getInstanceIdentifierContext().getSchemaContext());
360     }
361
362     /**
363      * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
364      * This rpc is then executed.
365      * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
366      * invoked.
367      */
368     @Test
369     @Ignore // FIXME find how to use mockito for it
370     public void testMountedRpcCallNoPayload_Success() throws Exception {
371     }
372 }