Use ControllerContext non-statically
[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 = RestconfImpl.getInstance();
77     private final ControllerContext controllerContext;
78
79     public InvokeRpcMethodTest() {
80         controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
81         restconfImpl.setControllerContext(controllerContext);
82     }
83
84     @BeforeClass
85     public static void init() throws FileNotFoundException, ReactorException {
86         schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs", "/invoke-rpc");
87         final Set<Module> allModules = schemaContext.getModules();
88         assertNotNull(allModules);
89         final Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
90         assertNotNull(module);
91
92         uriInfo = mock(UriInfo.class);
93         final MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
94         map.put("prettyPrint", Collections.singletonList("true"));
95         when(uriInfo.getQueryParameters(any(Boolean.class))).thenReturn(map);
96     }
97
98     /**
99      * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
100      * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
101      * string - first argument).
102      */
103     @Test
104     @Ignore
105     public void invokeRpcMethodTest() {
106         try {
107             controllerContext.findModuleNameByNamespace(new URI("invoke:rpc:module"));
108         } catch (final URISyntaxException e) {
109             assertTrue("Uri wasn't created sucessfuly", false);
110         }
111
112         final BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
113
114         restconfImpl.setBroker(mockedBrokerFacade);
115
116         final NormalizedNodeContext payload = prepareDomPayload();
117
118         final NormalizedNodeContext rpcResponse =
119                 restconfImpl.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
120         assertTrue(rpcResponse != null);
121         assertTrue(rpcResponse.getData() == null);
122
123     }
124
125     private NormalizedNodeContext prepareDomPayload() {
126         final SchemaContext schema = controllerContext.getGlobalSchema();
127         final Module rpcModule = schema.findModules("invoke-rpc-module").iterator().next();
128         assertNotNull(rpcModule);
129         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "rpc-test");
130         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
131         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
132         ContainerSchemaNode rpcInputSchemaNode = null;
133         for (final RpcDefinition rpc : setRpcs) {
134             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
135                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
136                 break;
137             }
138         }
139         assertNotNull(rpcInputSchemaNode);
140
141         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> container =
142                 Builders.containerBuilder(rpcInputSchemaNode);
143
144         final QName contQName = QName.create(rpcModule.getQNameModule(), "cont");
145         final DataSchemaNode contSchemaNode = rpcInputSchemaNode.getDataChildByName(contQName);
146         assertTrue(contSchemaNode instanceof ContainerSchemaNode);
147         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> contNode =
148                 Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);
149
150         final QName lfQName = QName.create(rpcModule.getQNameModule(), "lf");
151         final DataSchemaNode lfSchemaNode = ((ContainerSchemaNode) contSchemaNode).getDataChildByName(lfQName);
152         assertTrue(lfSchemaNode instanceof LeafSchemaNode);
153         final LeafNode<Object> lfNode =
154                 Builders.leafBuilder((LeafSchemaNode) lfSchemaNode).withValue("any value").build();
155         contNode.withChild(lfNode);
156         container.withChild(contNode.build());
157
158         return new NormalizedNodeContext(
159                 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         this.restconfImpl.setBroker(brokerFacade);
175
176         try {
177             this.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_NOT_SUPPORTED,
181                     Optional.<String>absent(), Optional.<String>absent());
182         }
183     }
184
185     void verifyRestconfDocumentedException(final RestconfDocumentedException restDocumentedException, 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 = restDocumentedException.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         this.restconfImpl.setBroker(brokerFacade);
225
226         try {
227             this.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         this.restconfImpl.setBroker(brokerFacade);
250
251         final NormalizedNodeContext output = this.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             this.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             this.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 Module rpcModule = schemaContext.findModules("toaster").iterator().next();
289         assertNotNull(rpcModule);
290         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
291         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
292
293         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
294         RpcDefinition rpcDef = null;
295         ContainerSchemaNode rpcInputSchemaNode = null;
296
297         for (final RpcDefinition rpc : setRpcs) {
298             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
299                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
300                 rpcDef = rpc;
301                 break;
302             }
303         }
304
305         assertNotNull(rpcDef);
306         assertNotNull(rpcInputSchemaNode);
307         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
308                 Builders.containerBuilder(rpcInputSchemaNode);
309
310         final NormalizedNodeContext payload =
311                 new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
312                 null, schemaContext), containerBuilder.build());
313
314         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
315         when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
316         this.restconfImpl.setBroker(brokerFacade);
317
318         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
319         assertNotNull(output);
320         assertEquals(null, output.getData());
321         // additional validation in the fact that the restconfImpl does not
322         // throw an exception.
323     }
324
325     @Test
326     public void testThrowExceptionWhenSlashInModuleName() {
327         try {
328             this.restconfImpl.invokeRpc("toaster/slash", "", uriInfo);
329             fail("Expected an exception.");
330         } catch (final RestconfDocumentedException e) {
331             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
332                     Optional.<String>absent(), Optional.<String>absent());
333         }
334     }
335
336     @Test
337     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
338         final SchemaContext schema = controllerContext.getGlobalSchema();
339         final Module rpcModule = schema.findModules("toaster").iterator().next();
340         assertNotNull(rpcModule);
341         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
342         final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
343
344         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
345         RpcDefinition rpcDef = null;
346         ContainerSchemaNode rpcOutputSchemaNode = null;
347         for (final RpcDefinition rpc : setRpcs) {
348             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
349                 rpcOutputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcOutputQName);
350                 rpcDef = rpc;
351                 break;
352             }
353         }
354         assertNotNull(rpcDef);
355         assertNotNull(rpcOutputSchemaNode);
356         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
357                 Builders.containerBuilder(rpcOutputSchemaNode);
358         final DataSchemaNode leafSchema = rpcOutputSchemaNode
359                 .getDataChildByName(QName.create(rpcModule.getQNameModule(), "textOut"));
360         assertTrue(leafSchema instanceof LeafSchemaNode);
361         final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
362                 Builders.leafBuilder((LeafSchemaNode) leafSchema);
363         leafBuilder.withValue("brm");
364         containerBuilder.withChild(leafBuilder.build());
365         final ContainerNode container = containerBuilder.build();
366
367         final DOMRpcResult result = new DefaultDOMRpcResult(container);
368         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(result);
369
370         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
371         when(brokerFacade.invokeRpc(eq(rpcDef.getPath()), any(NormalizedNode.class))).thenReturn(future);
372
373         this.restconfImpl.setBroker(brokerFacade);
374
375         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:testOutput", "", uriInfo);
376         assertNotNull(output);
377         assertNotNull(output.getData());
378         assertSame(container, output.getData());
379         assertNotNull(output.getInstanceIdentifierContext());
380         assertNotNull(output.getInstanceIdentifierContext().getSchemaContext());
381     }
382
383     /**
384      * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
385      * This rpc is then executed.
386      * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
387      * invoked.
388      */
389     @Test
390     @Ignore // FIXME find how to use mockito for it
391     public void testMountedRpcCallNoPayload_Success() throws Exception {
392     }
393 }