Merge "Bug 9092: revert to org.json temporarily"
[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.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.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.netconf.sal.restconf.impl.BrokerFacade;
44 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
45 import org.opendaylight.netconf.sal.restconf.impl.InstanceIdentifierContext;
46 import org.opendaylight.netconf.sal.restconf.impl.NormalizedNodeContext;
47 import org.opendaylight.netconf.sal.restconf.impl.RestconfDocumentedException;
48 import org.opendaylight.netconf.sal.restconf.impl.RestconfError;
49 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorTag;
50 import org.opendaylight.netconf.sal.restconf.impl.RestconfError.ErrorType;
51 import org.opendaylight.netconf.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 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
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, ReactorException {
81         final SchemaContext schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs", "/invoke-rpc");
82         final Set<Module> allModules = schemaContext.getModules();
83         assertNotNull(allModules);
84         final Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
85         assertNotNull(module);
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         this.restconfImpl = RestconfImpl.getInstance();
97         this.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 static 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 =
146                 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 =
152                 Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);
153
154         final QName lfQName = QName.create(rpcModule.getQNameModule(), "lf");
155         final DataSchemaNode lfSchemaNode = ((ContainerSchemaNode) contSchemaNode).getDataChildByName(lfQName);
156         assertTrue(lfSchemaNode instanceof LeafSchemaNode);
157         final LeafNode<Object> lfNode =
158                 Builders.leafBuilder((LeafSchemaNode) lfSchemaNode).withValue("any value").build();
159         contNode.withChild(lfNode);
160         container.withChild(contNode.build());
161
162         return new NormalizedNodeContext(
163                 new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), container.build());
164     }
165
166     @Test
167     public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
168         final DOMRpcException exception = new DOMRpcImplementationNotAvailableException("testExeption");
169         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateFailedCheckedFuture(exception);
170
171         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
172
173         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
174         final SchemaPath type = SchemaPath.create(true, qname);
175
176         when(brokerFacade.invokeRpc(eq(type), any(NormalizedNode.class))).thenReturn(future);
177
178         this.restconfImpl.setBroker(brokerFacade);
179
180         try {
181             this.restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
182             fail("Expected an exception to be thrown.");
183         } catch (final RestconfDocumentedException e) {
184             verifyRestconfDocumentedException(e, 0, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED,
185                     Optional.<String>absent(), Optional.<String>absent());
186         }
187     }
188
189     void verifyRestconfDocumentedException(final RestconfDocumentedException restDocumentedException, final int index,
190             final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
191             final Optional<String> expAppTag) {
192         RestconfError actual = null;
193         try {
194             actual = restDocumentedException.getErrors().get(index);
195         } catch (final ArrayIndexOutOfBoundsException ex) {
196             fail("RestconfError not found at index " + index);
197         }
198
199         assertEquals("getErrorType", expErrorType, actual.getErrorType());
200         assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
201         assertNotNull("getErrorMessage is null", actual.getErrorMessage());
202
203         if (expErrorMsg.isPresent()) {
204             assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
205         }
206
207         if (expAppTag.isPresent()) {
208             assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
209         }
210     }
211
212     @Test
213     public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
214         final List<RpcError> rpcErrors = Arrays.asList(
215                 RpcResultBuilder.newError(RpcError.ErrorType.TRANSPORT, "bogusTag", "foo"),
216                 RpcResultBuilder.newWarning(RpcError.ErrorType.RPC, "in-use", "bar",
217                         "app-tag", null, null));
218
219         final DOMRpcResult resutl = new DefaultDOMRpcResult(rpcErrors);
220         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(resutl);
221
222         final SchemaPath path = SchemaPath.create(true,
223                 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast"));
224
225         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
226         when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
227
228         this.restconfImpl.setBroker(brokerFacade);
229
230         try {
231             this.restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
232             fail("Expected an exception to be thrown.");
233         } catch (final RestconfDocumentedException e) {
234             verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
235                     Optional.<String>absent());
236             verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
237                     Optional.of("app-tag"));
238         }
239     }
240
241     @Test
242     public void testInvokeRpcWithNoPayload_Success() {
243         final NormalizedNode<?, ?> resultObj = null;
244         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
245         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
246
247         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
248         final SchemaPath path = SchemaPath.create(true, qname);
249
250         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
251         when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
252
253         this.restconfImpl.setBroker(brokerFacade);
254
255         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:cancel-toast", "", uriInfo);
256         assertNotNull(output);
257         assertEquals(null, output.getData());
258         // additional validation in the fact that the restconfImpl does not
259         // throw an exception.
260     }
261
262     @Test
263     public void testInvokeRpcMethodExpectingNoPayloadButProvidePayload() {
264         try {
265             this.restconfImpl.invokeRpc("toaster:cancel-toast", " a payload ", uriInfo);
266             fail("Expected an exception");
267         } catch (final RestconfDocumentedException e) {
268             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
269                     Optional.<String>absent(), Optional.<String>absent());
270         }
271     }
272
273     @Test
274     public void testInvokeRpcMethodWithBadMethodName() {
275         try {
276             this.restconfImpl.invokeRpc("toaster:bad-method", "", uriInfo);
277             fail("Expected an exception");
278         } catch (final RestconfDocumentedException e) {
279             verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
280                     Optional.<String>absent(), Optional.<String>absent());
281         }
282     }
283
284     @Test
285     @Ignore
286     public void testInvokeRpcMethodWithInput() {
287         final DOMRpcResult expResult = mock(DOMRpcResult.class);
288         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
289         final SchemaPath path = SchemaPath.create(true,
290                 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast"));
291
292         final SchemaContext schemaContext = controllerContext.getGlobalSchema();
293         final Module rpcModule = schemaContext.findModuleByName("toaster", null);
294         assertNotNull(rpcModule);
295         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
296         final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
297
298         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
299         RpcDefinition rpcDef = null;
300         ContainerSchemaNode rpcInputSchemaNode = null;
301
302         for (final RpcDefinition rpc : setRpcs) {
303             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
304                 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
305                 rpcDef = rpc;
306                 break;
307             }
308         }
309
310         assertNotNull(rpcDef);
311         assertNotNull(rpcInputSchemaNode);
312         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
313                 Builders.containerBuilder(rpcInputSchemaNode);
314
315         final NormalizedNodeContext payload =
316                 new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
317                 null, schemaContext), containerBuilder.build());
318
319         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
320         when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
321         this.restconfImpl.setBroker(brokerFacade);
322
323         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
324         assertNotNull(output);
325         assertEquals(null, output.getData());
326         // additional validation in the fact that the restconfImpl does not
327         // throw an exception.
328     }
329
330     @Test
331     public void testThrowExceptionWhenSlashInModuleName() {
332         try {
333             this.restconfImpl.invokeRpc("toaster/slash", "", uriInfo);
334             fail("Expected an exception.");
335         } catch (final RestconfDocumentedException e) {
336             verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
337                     Optional.<String>absent(), Optional.<String>absent());
338         }
339     }
340
341     @Test
342     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
343         final SchemaContext schema = controllerContext.getGlobalSchema();
344         final Module rpcModule = schema.findModuleByName("toaster", null);
345         assertNotNull(rpcModule);
346         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
347         final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
348
349         final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
350         RpcDefinition rpcDef = null;
351         ContainerSchemaNode rpcOutputSchemaNode = null;
352         for (final RpcDefinition rpc : setRpcs) {
353             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
354                 rpcOutputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcOutputQName);
355                 rpcDef = rpc;
356                 break;
357             }
358         }
359         assertNotNull(rpcDef);
360         assertNotNull(rpcOutputSchemaNode);
361         final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
362                 Builders.containerBuilder(rpcOutputSchemaNode);
363         final DataSchemaNode leafSchema = rpcOutputSchemaNode
364                 .getDataChildByName(QName.create(rpcModule.getQNameModule(), "textOut"));
365         assertTrue(leafSchema instanceof LeafSchemaNode);
366         final NormalizedNodeAttrBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
367                 Builders.leafBuilder((LeafSchemaNode) leafSchema);
368         leafBuilder.withValue("brm");
369         containerBuilder.withChild(leafBuilder.build());
370         final ContainerNode container = containerBuilder.build();
371
372         final DOMRpcResult result = new DefaultDOMRpcResult(container);
373         final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(result);
374
375         final BrokerFacade brokerFacade = mock(BrokerFacade.class);
376         when(brokerFacade.invokeRpc(eq(rpcDef.getPath()), any(NormalizedNode.class))).thenReturn(future);
377
378         this.restconfImpl.setBroker(brokerFacade);
379
380         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:testOutput", "", uriInfo);
381         assertNotNull(output);
382         assertNotNull(output.getData());
383         assertSame(container, output.getData());
384         assertNotNull(output.getInstanceIdentifierContext());
385         assertNotNull(output.getInstanceIdentifierContext().getSchemaContext());
386     }
387
388     /**
389      * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
390      * This rpc is then executed.
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 }