Remove RestconfError.ErrorTag
[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 package org.opendaylight.controller.sal.restconf.impl.test;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertNull;
13 import static org.junit.Assert.assertSame;
14 import static org.junit.Assert.assertThrows;
15 import static org.junit.Assert.assertTrue;
16 import static org.mockito.ArgumentMatchers.any;
17 import static org.mockito.ArgumentMatchers.eq;
18 import static org.mockito.Mockito.doCallRealMethod;
19 import static org.mockito.Mockito.doReturn;
20 import static org.mockito.Mockito.mock;
21 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
22 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
23
24 import java.io.FileNotFoundException;
25 import java.util.Arrays;
26 import java.util.Collection;
27 import java.util.List;
28 import java.util.Optional;
29 import java.util.Set;
30 import javax.ws.rs.WebApplicationException;
31 import javax.ws.rs.core.MultivaluedHashMap;
32 import javax.ws.rs.core.MultivaluedMap;
33 import javax.ws.rs.core.Response;
34 import javax.ws.rs.core.UriInfo;
35 import org.junit.BeforeClass;
36 import org.junit.Ignore;
37 import org.junit.Test;
38 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
39 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
40 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
41 import org.opendaylight.mdsal.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.RestconfImpl;
45 import org.opendaylight.restconf.common.ErrorTags;
46 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
47 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
48 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
49 import org.opendaylight.restconf.common.errors.RestconfError;
50 import org.opendaylight.yangtools.yang.common.ErrorTag;
51 import org.opendaylight.yangtools.yang.common.ErrorType;
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.common.XMLNamespace;
56 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
57 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
58 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
61 import org.opendaylight.yangtools.yang.data.api.schema.builder.NormalizedNodeBuilder;
62 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaAwareBuilders;
63 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
64 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
67 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.Module;
69 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
71 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
72
73 public class InvokeRpcMethodTest {
74
75     private static UriInfo uriInfo;
76     private static EffectiveModelContext schemaContext;
77
78     private final RestconfImpl restconfImpl;
79     private final ControllerContext controllerContext;
80     private final BrokerFacade brokerFacade = mock(BrokerFacade.class);
81
82     public InvokeRpcMethodTest() {
83         controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
84         restconfImpl = RestconfImpl.newInstance(brokerFacade, controllerContext);
85     }
86
87     @BeforeClass
88     public static void init() throws FileNotFoundException, ReactorException {
89         schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs", "/invoke-rpc");
90         final Collection<? extends Module> allModules = schemaContext.getModules();
91         assertNotNull(allModules);
92         final Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
93         assertNotNull(module);
94
95         uriInfo = mock(UriInfo.class);
96         final MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
97         map.put("prettyPrint", List.of("true"));
98         doReturn(map).when(uriInfo).getQueryParameters(any(Boolean.class));
99     }
100
101     /**
102      * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
103      * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
104      * string - first argument).
105      */
106     @Test
107     @Ignore
108     public void invokeRpcMethodTest() {
109         controllerContext.findModuleNameByNamespace(XMLNamespace.of("invoke:rpc:module"));
110
111         final NormalizedNodeContext payload = prepareDomPayload();
112
113         final NormalizedNodeContext rpcResponse =
114                 restconfImpl.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
115         assertNotNull(rpcResponse);
116         assertNull(rpcResponse.getData());
117
118     }
119
120     private NormalizedNodeContext prepareDomPayload() {
121         final EffectiveModelContext schema = controllerContext.getGlobalSchema();
122         final Module rpcModule = schema.findModules("invoke-rpc-module").iterator().next();
123         assertNotNull(rpcModule);
124         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "rpc-test");
125         ContainerLike rpcInputSchemaNode = null;
126         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
127             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
128                 rpcInputSchemaNode = rpc.getInput();
129                 break;
130             }
131         }
132         assertNotNull(rpcInputSchemaNode);
133
134         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> container =
135                 SchemaAwareBuilders.containerBuilder(rpcInputSchemaNode);
136
137         final QName contQName = QName.create(rpcModule.getQNameModule(), "cont");
138         final DataSchemaNode contSchemaNode = rpcInputSchemaNode.getDataChildByName(contQName);
139         assertTrue(contSchemaNode instanceof ContainerSchemaNode);
140         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> contNode =
141                 SchemaAwareBuilders.containerBuilder((ContainerSchemaNode) contSchemaNode);
142
143         final QName lfQName = QName.create(rpcModule.getQNameModule(), "lf");
144         final DataSchemaNode lfSchemaNode = ((ContainerSchemaNode) contSchemaNode).getDataChildByName(lfQName);
145         assertTrue(lfSchemaNode instanceof LeafSchemaNode);
146         final LeafNode<Object> lfNode =
147                 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) lfSchemaNode).withValue("any value").build();
148         contNode.withChild(lfNode);
149         container.withChild(contNode.build());
150
151         return new NormalizedNodeContext(
152                 new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), container.build());
153     }
154
155     @Test
156     public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
157         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
158
159         doReturn(immediateFailedFluentFuture(new DOMRpcImplementationNotAvailableException("testExeption")))
160             .when(brokerFacade).invokeRpc(eq(qname), any());
161
162         final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
163             () -> this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo));
164         verifyRestconfDocumentedException(ex, 0, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED,
165             Optional.empty(), Optional.empty());
166     }
167
168     void verifyRestconfDocumentedException(final RestconfDocumentedException restDocumentedException, final int index,
169             final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
170             final Optional<String> expAppTag) {
171
172         final List<RestconfError> errors = restDocumentedException.getErrors();
173         assertTrue("RestconfError not found at index " + index, errors.size() > index);
174
175         RestconfError actual = errors.get(index);
176
177         assertEquals("getErrorType", expErrorType, actual.getErrorType());
178         assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
179         assertNotNull("getErrorMessage is null", actual.getErrorMessage());
180
181         if (expErrorMsg.isPresent()) {
182             assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
183         }
184
185         if (expAppTag.isPresent()) {
186             assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
187         }
188     }
189
190     @Test
191     public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
192         final List<RpcError> rpcErrors = Arrays.asList(
193                 RpcResultBuilder.newError(RpcError.ErrorType.TRANSPORT, "bogusTag", "foo"),
194                 RpcResultBuilder.newWarning(RpcError.ErrorType.RPC, "in-use", "bar",
195                         "app-tag", null, null));
196
197         final DOMRpcResult result = new DefaultDOMRpcResult(rpcErrors);
198         final QName path = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
199         doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(path), any());
200
201         final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
202             () -> this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo));
203
204         // We are performing pass-through here of error-tag, hence the tag remains as specified, but we want to make
205         // sure the HTTP status remains the same as
206         final ErrorTag bogus = new ErrorTag("bogusTag");
207         verifyRestconfDocumentedException(ex, 0, ErrorType.TRANSPORT, bogus, Optional.of("foo"), Optional.empty());
208         assertEquals(ErrorTags.statusOf(ErrorTag.OPERATION_FAILED), ErrorTags.statusOf(bogus));
209
210         verifyRestconfDocumentedException(ex, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
211             Optional.of("app-tag"));
212     }
213
214     @Test
215     public void testInvokeRpcWithNoPayload_Success() {
216         final NormalizedNode resultObj = null;
217         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
218
219         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
220
221         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(qname), any());
222
223         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
224         assertNotNull(output);
225         assertEquals(null, output.getData());
226         // additional validation in the fact that the restconfImpl does not
227         // throw an exception.
228     }
229
230     @Test
231     public void testInvokeRpcWithEmptyOutput() {
232         final ContainerNode resultObj = mock(ContainerNode.class);
233         doReturn(Set.of()).when(resultObj).body();
234         doCallRealMethod().when(resultObj).isEmpty();
235         final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
236
237         final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
238         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(qname), any());
239
240         WebApplicationException exceptionToBeThrown = assertThrows(WebApplicationException.class,
241             () -> this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo));
242         assertEquals(Response.Status.NO_CONTENT.getStatusCode(), exceptionToBeThrown.getResponse().getStatus());
243     }
244
245     @Test
246     public void testInvokeRpcMethodWithBadMethodName() {
247         final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
248             () -> this.restconfImpl.invokeRpc("toaster:bad-method", null, uriInfo));
249         verifyRestconfDocumentedException(ex, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
250             Optional.empty(), Optional.empty());
251     }
252
253     @Test
254     @Ignore
255     public void testInvokeRpcMethodWithInput() {
256         final DOMRpcResult expResult = mock(DOMRpcResult.class);
257         final QName path = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast");
258
259         final Module rpcModule = schemaContext.findModules("toaster").iterator().next();
260         assertNotNull(rpcModule);
261         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
262
263         RpcDefinition rpcDef = null;
264         ContainerLike rpcInputSchemaNode = null;
265         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
266             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
267                 rpcInputSchemaNode = rpc.getInput();
268                 rpcDef = rpc;
269                 break;
270             }
271         }
272
273         assertNotNull(rpcDef);
274         assertNotNull(rpcInputSchemaNode);
275         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
276                 SchemaAwareBuilders.containerBuilder(rpcInputSchemaNode);
277
278         final NormalizedNodeContext payload =
279                 new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
280                 null, schemaContext), containerBuilder.build());
281
282         doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), any(NormalizedNode.class));
283
284         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
285         assertNotNull(output);
286         assertEquals(null, output.getData());
287         // additional validation in the fact that the restconfImpl does not
288         // throw an exception.
289     }
290
291     @Test
292     public void testThrowExceptionWhenSlashInModuleName() {
293         final RestconfDocumentedException ex = assertThrows(RestconfDocumentedException.class,
294             () -> this.restconfImpl.invokeRpc("toaster/slash", null, uriInfo));
295         verifyRestconfDocumentedException(ex, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
296             Optional.empty(), Optional.empty());
297     }
298
299     @Test
300     public void testInvokeRpcWithNoPayloadWithOutput_Success() {
301         final SchemaContext schema = controllerContext.getGlobalSchema();
302         final Module rpcModule = schema.findModules("toaster").iterator().next();
303         assertNotNull(rpcModule);
304         final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
305         final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
306
307         RpcDefinition rpcDef = null;
308         ContainerLike rpcOutputSchemaNode = null;
309         for (final RpcDefinition rpc : rpcModule.getRpcs()) {
310             if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
311                 rpcOutputSchemaNode = rpc.getOutput();
312                 rpcDef = rpc;
313                 break;
314             }
315         }
316         assertNotNull(rpcDef);
317         assertNotNull(rpcOutputSchemaNode);
318         final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
319                 SchemaAwareBuilders.containerBuilder(rpcOutputSchemaNode);
320         final DataSchemaNode leafSchema = rpcOutputSchemaNode
321                 .getDataChildByName(QName.create(rpcModule.getQNameModule(), "textOut"));
322         assertTrue(leafSchema instanceof LeafSchemaNode);
323         final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
324                 SchemaAwareBuilders.leafBuilder((LeafSchemaNode) leafSchema);
325         leafBuilder.withValue("brm");
326         containerBuilder.withChild(leafBuilder.build());
327         final ContainerNode container = containerBuilder.build();
328
329         final DOMRpcResult result = new DefaultDOMRpcResult(container);
330
331         doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(rpcDef.getQName()), any());
332
333         final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:testOutput", null, uriInfo);
334         assertNotNull(output);
335         assertNotNull(output.getData());
336         assertSame(container, output.getData());
337         assertNotNull(output.getInstanceIdentifierContext());
338         assertNotNull(output.getInstanceIdentifierContext().getSchemaContext());
339     }
340
341     /**
342      * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
343      * This rpc is then executed.
344      * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
345      * invoked.
346      */
347     @Test
348     public void testMountedRpcCallNoPayload_Success() throws Exception {
349         // FIXME find how to use mockito for it
350     }
351 }