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

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.