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