Update MRI projects for Aluminium
[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.Collection;
30 import java.util.Collections;
31 import java.util.List;
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.DataContainerNodeBuilder;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
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.api.SchemaPath;
73 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
74 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
75
76 public class InvokeRpcMethodTest {
77
78     private static UriInfo uriInfo;
79     private static EffectiveModelContext schemaContext;
80
81     private final RestconfImpl restconfImpl;
82     private final ControllerContext controllerContext;
83     private final BrokerFacade brokerFacade = mock(BrokerFacade.class);
84
85     public InvokeRpcMethodTest() {
86         controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
87         restconfImpl = RestconfImpl.newInstance(brokerFacade, controllerContext);
88     }
89
90     @BeforeClass
91     public static void init() throws FileNotFoundException, ReactorException {
92         schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs", "/invoke-rpc");
93         final Collection<? extends Module> allModules = schemaContext.getModules();
94         assertNotNull(allModules);
95         final Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
96         assertNotNull(module);
97
98         uriInfo = mock(UriInfo.class);
99         final MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
100         map.put("prettyPrint", Collections.singletonList("true"));
101         when(uriInfo.getQueryParameters(any(Boolean.class))).thenReturn(map);
102     }
103
104     /**
105      * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
106      * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
107      * string - first argument).
108      */
109     @Test
110     @Ignore
111     public void invokeRpcMethodTest() {
112         try {
113             controllerContext.findModuleNameByNamespace(new URI("invoke:rpc:module"));
114         } catch (final URISyntaxException e) {
115             assertTrue("Uri wasn't created sucessfuly", false);
116         }
117
118         final NormalizedNodeContext payload = prepareDomPayload();
119
120         final NormalizedNodeContext rpcResponse =
121                 restconfImpl.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
122         assertTrue(rpcResponse != null);
123         assertTrue(rpcResponse.getData() == null);
124
125     }
126
127     private NormalizedNodeContext prepareDomPayload() {
128         final EffectiveModelContext schema = controllerContext.getGlobalSchema();
129         final Module rpcModule = schema.findModules("invoke-rpc-module").iterator().next();
130         assertNotNull(rpcModule);
131         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "rpc-test");
132         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
133         ContainerSchemaNode rpcInputSchemaNode = null;
134         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
135             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
136                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
137                 break;
138             }
139         }
140         assertNotNull(rpcInputSchemaNode);
141
142         final DataContainerNodeBuilder<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 DataContainerNodeBuilder<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         RpcDefinition rpcDef = null;
288         ContainerSchemaNode rpcInputSchemaNode = null;
289         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
290             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
291                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
292                 rpcDef = rpc;
293                 break;
294             }
295         }
296
297         assertNotNull(rpcDef);
298         assertNotNull(rpcInputSchemaNode);
299         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
300                 Builders.containerBuilder(rpcInputSchemaNode);
301
302         final NormalizedNodeContext payload =
303                 new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
304                 null, schemaContext), containerBuilder.build());
305
306         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), any(NormalizedNode.class));
307
308         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
309         assertNotNull(output);
310         assertEquals(null, output.getData());
311         // additional validation in the fact that the restconfImpl does not
312         // throw an exception.
313     }
314
315     @Test
316     public void testThrowExceptionWhenSlashInModuleName() {
317         try {
318             this.restconfImpl.invokeRpc("toaster/slash", null, uriInfo);
319             fail("Expected an exception.");
320         } catch (final RestconfDocumentedException e) {
321             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
322                     Optional.absent(), Optional.absent());
323         }
324     }
325
326     @Test
327     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
328         final SchemaContext schema = controllerContext.getGlobalSchema();
329         final Module rpcModule = schema.findModules("toaster").iterator().next();
330         assertNotNull(rpcModule);
331         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
332         final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
333
334         RpcDefinition rpcDef = null;
335         ContainerSchemaNode rpcOutputSchemaNode = null;
336         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
337             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
338                 rpcOutputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcOutputQName);
339                 rpcDef = rpc;
340                 break;
341             }
342         }
343         assertNotNull(rpcDef);
344         assertNotNull(rpcOutputSchemaNode);
345         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
346                 Builders.containerBuilder(rpcOutputSchemaNode);
347         final DataSchemaNode leafSchema = rpcOutputSchemaNode
348                 .getDataChildByName(QName.create(rpcModule.getQNameModule(), "textOut"));
349         assertTrue(leafSchema instanceof LeafSchemaNode);
350         final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
351                 Builders.leafBuilder((LeafSchemaNode) leafSchema);
352         leafBuilder.withValue("brm");
353         containerBuilder.withChild(leafBuilder.build());
354         final ContainerNode container = containerBuilder.build();
355
356         final DOMRpcResult result = new DefaultDOMRpcResult(container);
357
358         doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(rpcDef.getPath()), isNull());
359
360         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:testOutput", null, uriInfo);
361         assertNotNull(output);
362         assertNotNull(output.getData());
363         assertSame(container, output.getData());
364         assertNotNull(output.getInstanceIdentifierContext());
365         assertNotNull(output.getInstanceIdentifierContext().getSchemaContext());
366     }
367
368     /**
369      * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
370      * This rpc is then executed.
371      * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
372      * invoked.
373      */
374     @Test
375     @Ignore // FIXME find how to use mockito for it
376     public void testMountedRpcCallNoPayload_Success() throws Exception {
377     }
378 }