Remove redundant code constructs
[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.Matchers.any;
17 import static org.mockito.Matchers.eq;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.when;
20
21 import com.google.common.base.Optional;
22 import com.google.common.util.concurrent.CheckedFuture;
23 import com.google.common.util.concurrent.Futures;
24 import java.io.FileNotFoundException;
25 import java.net.URI;
26 import java.net.URISyntaxException;
27 import java.util.Arrays;
28 import java.util.Collections;
29 import java.util.List;
30 import java.util.Set;
31 import javax.ws.rs.core.MultivaluedHashMap;
32 import javax.ws.rs.core.MultivaluedMap;
33 import javax.ws.rs.core.UriInfo;
34 import org.junit.BeforeClass;
35 import org.junit.Ignore;
36 import org.junit.Test;
37 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
38 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
39 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
40 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
41 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
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.DataContainerNodeAttrBuilder;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
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 DataContainerNodeAttrBuilder<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 DataContainerNodeAttrBuilder<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 DOMRpcException exception = new DOMRpcImplementationNotAvailableException("testExeption");
162         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateFailedCheckedFuture(exception);
163
164         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
165         final SchemaPath type = SchemaPath.create(true, qname);
166
167         when(brokerFacade.invokeRpc(eq(type), any(NormalizedNode.class))).thenReturn(future);
168
169         try {
170             this.restconfImpl.invokeRpc("toaster:cancel-toast", "", 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 resutl = new DefaultDOMRpcResult(rpcErrors);
209         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(resutl);
210
211         final SchemaPath path = SchemaPath.create(true,
212                 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast"));
213
214         when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
215
216         try {
217             this.restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
218             fail("Expected an exception to be thrown.");
219         } catch (final RestconfDocumentedException e) {
220             verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
221                     Optional.absent());
222             verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
223                     Optional.of("app-tag"));
224         }
225     }
226
227     @Test
228     public void testInvokeRpcWithNoPayload_Success() {
229         final NormalizedNode<?, ?> resultObj = null;
230         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
231         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
232
233         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
234         final SchemaPath path = SchemaPath.create(true, qname);
235
236         when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
237
238         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
239         assertNotNull(output);
240         assertEquals(null, output.getData());
241         // additional validation in the fact that the restconfImpl does not
242         // throw an exception.
243     }
244
245     @Test
246     public void testInvokeRpcMethodExpectingNoPayloadButProvidePayload() {
247         try {
248             this.restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ", uriInfo);
249             fail("Expected an exception");
250         } catch (final RestconfDocumentedException e) {
251             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
252                     Optional.absent(), Optional.absent());
253         }
254     }
255
256     @Test
257     public void testInvokeRpcMethodWithBadMethodName() {
258         try {
259             this.restconfImpl.invokeRpc("toaster:bad-method", "", uriInfo);
260             fail("Expected an exception");
261         } catch (final RestconfDocumentedException e) {
262             verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
263                     Optional.absent(), Optional.absent());
264         }
265     }
266
267     @Test
268     @Ignore
269     public void testInvokeRpcMethodWithInput() {
270         final DOMRpcResult expResult = mock(DOMRpcResult.class);
271         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
272         final SchemaPath path = SchemaPath.create(true,
273                 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast"));
274
275         final Module rpcModule = schemaContext.findModules("toaster").iterator().next();
276         assertNotNull(rpcModule);
277         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
278         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
279
280         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
281         RpcDefinition rpcDef = null;
282         ContainerSchemaNode rpcInputSchemaNode = null;
283
284         for (final RpcDefinition rpc : setRpcs) {
285             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
286                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
287                 rpcDef = rpc;
288                 break;
289             }
290         }
291
292         assertNotNull(rpcDef);
293         assertNotNull(rpcInputSchemaNode);
294         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
295                 Builders.containerBuilder(rpcInputSchemaNode);
296
297         final NormalizedNodeContext payload =
298                 new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
299                 null, schemaContext), containerBuilder.build());
300
301         when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
302
303         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
304         assertNotNull(output);
305         assertEquals(null, output.getData());
306         // additional validation in the fact that the restconfImpl does not
307         // throw an exception.
308     }
309
310     @Test
311     public void testThrowExceptionWhenSlashInModuleName() {
312         try {
313             this.restconfImpl.invokeRpc("toaster/slash", "", uriInfo);
314             fail("Expected an exception.");
315         } catch (final RestconfDocumentedException e) {
316             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
317                     Optional.absent(), Optional.absent());
318         }
319     }
320
321     @Test
322     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
323         final SchemaContext schema = controllerContext.getGlobalSchema();
324         final Module rpcModule = schema.findModules("toaster").iterator().next();
325         assertNotNull(rpcModule);
326         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
327         final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
328
329         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
330         RpcDefinition rpcDef = null;
331         ContainerSchemaNode rpcOutputSchemaNode = null;
332         for (final RpcDefinition rpc : setRpcs) {
333             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
334                 rpcOutputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcOutputQName);
335                 rpcDef = rpc;
336                 break;
337             }
338         }
339         assertNotNull(rpcDef);
340         assertNotNull(rpcOutputSchemaNode);
341         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
342                 Builders.containerBuilder(rpcOutputSchemaNode);
343         final DataSchemaNode leafSchema = rpcOutputSchemaNode
344                 .getDataChildByName(QName.create(rpcModule.getQNameModule(), "textOut"));
345         assertTrue(leafSchema instanceof LeafSchemaNode);
346         final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
347                 Builders.leafBuilder((LeafSchemaNode) leafSchema);
348         leafBuilder.withValue("brm");
349         containerBuilder.withChild(leafBuilder.build());
350         final ContainerNode container = containerBuilder.build();
351
352         final DOMRpcResult result = new DefaultDOMRpcResult(container);
353         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(result);
354
355         when(brokerFacade.invokeRpc(eq(rpcDef.getPath()), any(NormalizedNode.class))).thenReturn(future);
356
357         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:testOutput", "", uriInfo);
358         assertNotNull(output);
359         assertNotNull(output.getData());
360         assertSame(container, output.getData());
361         assertNotNull(output.getInstanceIdentifierContext());
362         assertNotNull(output.getInstanceIdentifierContext().getSchemaContext());
363     }
364
365     /**
366      * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
367      * This rpc is then executed.
368      * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
369      * invoked.
370      */
371     @Test
372     @Ignore // FIXME find how to use mockito for it
373     public void testMountedRpcCallNoPayload_Success() throws Exception {
374     }
375 }