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