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