Merge "SchemaSourceCache init using YangModuleInfo"
[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.ArgumentMatchers.isNull;
18 import static org.mockito.Mockito.doReturn;
19 import static org.mockito.Mockito.mock;
20 import static org.mockito.Mockito.when;
21 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
22 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
23
24 import com.google.common.base.Optional;
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.WebApplicationException;
33 import javax.ws.rs.core.MultivaluedHashMap;
34 import javax.ws.rs.core.MultivaluedMap;
35 import javax.ws.rs.core.Response;
36 import javax.ws.rs.core.UriInfo;
37 import org.junit.Assert;
38 import org.junit.BeforeClass;
39 import org.junit.Ignore;
40 import org.junit.Test;
41 import org.mockito.Mockito;
42 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
43 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
44 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
45 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
46 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
47 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
48 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
49 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
50 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
51 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
52 import org.opendaylight.restconf.common.errors.RestconfError;
53 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
54 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.common.RpcError;
57 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
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.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
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.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 SchemaContext 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 Set<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 SchemaContext 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         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
133         ContainerSchemaNode rpcInputSchemaNode = null;
134         for (final RpcDefinition rpc : setRpcs) {
135             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
136                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
137                 break;
138             }
139         }
140         assertNotNull(rpcInputSchemaNode);
141
142         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> container =
143                 Builders.containerBuilder(rpcInputSchemaNode);
144
145         final QName contQName = QName.create(rpcModule.getQNameModule(), "cont");
146         final DataSchemaNode contSchemaNode = rpcInputSchemaNode.getDataChildByName(contQName);
147         assertTrue(contSchemaNode instanceof ContainerSchemaNode);
148         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> contNode =
149                 Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);
150
151         final QName lfQName = QName.create(rpcModule.getQNameModule(), "lf");
152         final DataSchemaNode lfSchemaNode = ((ContainerSchemaNode) contSchemaNode).getDataChildByName(lfQName);
153         assertTrue(lfSchemaNode instanceof LeafSchemaNode);
154         final LeafNode<Object> lfNode =
155                 Builders.leafBuilder((LeafSchemaNode) lfSchemaNode).withValue("any value").build();
156         contNode.withChild(lfNode);
157         container.withChild(contNode.build());
158
159         return new NormalizedNodeContext(
160                 new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), container.build());
161     }
162
163     @Test
164     public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
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         doReturn(immediateFailedFluentFuture(new DOMRpcImplementationNotAvailableException("testExeption")))
169         .when(brokerFacade).invokeRpc(eq(type), isNull());
170
171         try {
172             this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
173             fail("Expected an exception to be thrown.");
174         } catch (final RestconfDocumentedException e) {
175             verifyRestconfDocumentedException(e, 0, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED,
176                     Optional.absent(), Optional.absent());
177         }
178     }
179
180     void verifyRestconfDocumentedException(final RestconfDocumentedException restDocumentedException, final int index,
181             final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
182             final Optional<String> expAppTag) {
183         RestconfError actual = null;
184         try {
185             actual = restDocumentedException.getErrors().get(index);
186         } catch (final ArrayIndexOutOfBoundsException ex) {
187             fail("RestconfError not found at index " + index);
188         }
189
190         assertEquals("getErrorType", expErrorType, actual.getErrorType());
191         assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
192         assertNotNull("getErrorMessage is null", actual.getErrorMessage());
193
194         if (expErrorMsg.isPresent()) {
195             assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
196         }
197
198         if (expAppTag.isPresent()) {
199             assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
200         }
201     }
202
203     @Test
204     public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
205         final List<RpcError> rpcErrors = Arrays.asList(
206                 RpcResultBuilder.newError(RpcError.ErrorType.TRANSPORT, "bogusTag", "foo"),
207                 RpcResultBuilder.newWarning(RpcError.ErrorType.RPC, "in-use", "bar",
208                         "app-tag", null, null));
209
210         final DOMRpcResult result = new DefaultDOMRpcResult(rpcErrors);
211         final SchemaPath path = SchemaPath.create(true,
212                 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast"));
213         doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(path), isNull());
214
215         try {
216             this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
217             fail("Expected an exception to be thrown.");
218         } catch (final RestconfDocumentedException e) {
219             verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
220                     Optional.absent());
221             verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
222                     Optional.of("app-tag"));
223         }
224     }
225
226     @Test
227     public void testInvokeRpcWithNoPayload_Success() {
228         final NormalizedNode<?, ?> resultObj = null;
229         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
230
231         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
232         final SchemaPath path = SchemaPath.create(true, qname);
233
234         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), isNull());
235
236         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
237         assertNotNull(output);
238         assertEquals(null, output.getData());
239         // additional validation in the fact that the restconfImpl does not
240         // throw an exception.
241     }
242
243     @Test
244     public void testInvokeRpcWithEmptyOutput() {
245         final ContainerNode resultObj = Mockito.mock(ContainerNode.class);
246         Mockito.when(resultObj.getValue()).thenReturn(Collections.emptySet());
247         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
248
249         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
250         final SchemaPath path = SchemaPath.create(true, qname);
251         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), isNull());
252
253         WebApplicationException exceptionToBeThrown = null;
254         try {
255             this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
256         } catch (final WebApplicationException exception) {
257             exceptionToBeThrown = exception;
258
259         }
260         Assert.assertNotNull("WebApplicationException with status code 204 is expected.", exceptionToBeThrown);
261         Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), exceptionToBeThrown.getResponse().getStatus());
262     }
263
264     @Test
265     public void testInvokeRpcMethodWithBadMethodName() {
266         try {
267             this.restconfImpl.invokeRpc("toaster:bad-method", null, uriInfo);
268             fail("Expected an exception");
269         } catch (final RestconfDocumentedException e) {
270             verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
271                     Optional.absent(), Optional.absent());
272         }
273     }
274
275     @Test
276     @Ignore
277     public void testInvokeRpcMethodWithInput() {
278         final DOMRpcResult expResult = mock(DOMRpcResult.class);
279         final SchemaPath path = SchemaPath.create(true,
280                 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast"));
281
282         final Module rpcModule = schemaContext.findModules("toaster").iterator().next();
283         assertNotNull(rpcModule);
284         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
285         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
286
287         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
288         RpcDefinition rpcDef = null;
289         ContainerSchemaNode rpcInputSchemaNode = null;
290
291         for (final RpcDefinition rpc : setRpcs) {
292             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
293                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
294                 rpcDef = rpc;
295                 break;
296             }
297         }
298
299         assertNotNull(rpcDef);
300         assertNotNull(rpcInputSchemaNode);
301         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
302                 Builders.containerBuilder(rpcInputSchemaNode);
303
304         final NormalizedNodeContext payload =
305                 new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
306                 null, schemaContext), containerBuilder.build());
307
308         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), any(NormalizedNode.class));
309
310         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
311         assertNotNull(output);
312         assertEquals(null, output.getData());
313         // additional validation in the fact that the restconfImpl does not
314         // throw an exception.
315     }
316
317     @Test
318     public void testThrowExceptionWhenSlashInModuleName() {
319         try {
320             this.restconfImpl.invokeRpc("toaster/slash", null, uriInfo);
321             fail("Expected an exception.");
322         } catch (final RestconfDocumentedException e) {
323             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
324                     Optional.absent(), Optional.absent());
325         }
326     }
327
328     @Test
329     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
330         final SchemaContext schema = controllerContext.getGlobalSchema();
331         final Module rpcModule = schema.findModules("toaster").iterator().next();
332         assertNotNull(rpcModule);
333         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
334         final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
335
336         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
337         RpcDefinition rpcDef = null;
338         ContainerSchemaNode rpcOutputSchemaNode = null;
339         for (final RpcDefinition rpc : setRpcs) {
340             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
341                 rpcOutputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcOutputQName);
342                 rpcDef = rpc;
343                 break;
344             }
345         }
346         assertNotNull(rpcDef);
347         assertNotNull(rpcOutputSchemaNode);
348         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
349                 Builders.containerBuilder(rpcOutputSchemaNode);
350         final DataSchemaNode leafSchema = rpcOutputSchemaNode
351                 .getDataChildByName(QName.create(rpcModule.getQNameModule(), "textOut"));
352         assertTrue(leafSchema instanceof LeafSchemaNode);
353         final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
354                 Builders.leafBuilder((LeafSchemaNode) leafSchema);
355         leafBuilder.withValue("brm");
356         containerBuilder.withChild(leafBuilder.build());
357         final ContainerNode container = containerBuilder.build();
358
359         final DOMRpcResult result = new DefaultDOMRpcResult(container);
360
361         doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(rpcDef.getPath()), isNull());
362
363         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:testOutput", null, uriInfo);
364         assertNotNull(output);
365         assertNotNull(output.getData());
366         assertSame(container, output.getData());
367         assertNotNull(output.getInstanceIdentifierContext());
368         assertNotNull(output.getInstanceIdentifierContext().getSchemaContext());
369     }
370
371     /**
372      * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
373      * This rpc is then executed.
374      * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
375      * invoked.
376      */
377     @Test
378     @Ignore // FIXME find how to use mockito for it
379     public void testMountedRpcCallNoPayload_Success() throws Exception {
380     }
381 }