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