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