2 * Copyright (c) 2013, 2015 Brocade Communication Systems, Inc., Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.controller.sal.restconf.impl.test;
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertSame;
13 import static org.junit.Assert.assertTrue;
14 import static org.junit.Assert.fail;
15 import static org.mockito.ArgumentMatchers.any;
16 import static org.mockito.ArgumentMatchers.eq;
17 import static org.mockito.Mockito.doReturn;
18 import static org.mockito.Mockito.mock;
19 import static org.mockito.Mockito.when;
20 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
21 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
23 import com.google.common.base.Optional;
24 import java.io.FileNotFoundException;
26 import java.net.URISyntaxException;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.List;
31 import javax.ws.rs.WebApplicationException;
32 import javax.ws.rs.core.MultivaluedHashMap;
33 import javax.ws.rs.core.MultivaluedMap;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.core.UriInfo;
36 import org.junit.Assert;
37 import org.junit.BeforeClass;
38 import org.junit.Ignore;
39 import org.junit.Test;
40 import org.mockito.Mockito;
41 import org.opendaylight.controller.md.sal.rest.common.TestRestconfUtils;
42 import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
43 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
44 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
45 import org.opendaylight.netconf.sal.restconf.impl.BrokerFacade;
46 import org.opendaylight.netconf.sal.restconf.impl.ControllerContext;
47 import org.opendaylight.netconf.sal.restconf.impl.RestconfImpl;
48 import org.opendaylight.restconf.common.context.InstanceIdentifierContext;
49 import org.opendaylight.restconf.common.context.NormalizedNodeContext;
50 import org.opendaylight.restconf.common.errors.RestconfDocumentedException;
51 import org.opendaylight.restconf.common.errors.RestconfError;
52 import org.opendaylight.restconf.common.errors.RestconfError.ErrorTag;
53 import org.opendaylight.restconf.common.errors.RestconfError.ErrorType;
54 import org.opendaylight.yangtools.yang.common.QName;
55 import org.opendaylight.yangtools.yang.common.RpcError;
56 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
57 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
58 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
59 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
60 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
61 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
62 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeBuilder;
63 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeBuilder;
64 import org.opendaylight.yangtools.yang.model.api.ContainerLike;
65 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
68 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.Module;
70 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
73 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
75 public class InvokeRpcMethodTest {
77 private static UriInfo uriInfo;
78 private static EffectiveModelContext schemaContext;
80 private final RestconfImpl restconfImpl;
81 private final ControllerContext controllerContext;
82 private final BrokerFacade brokerFacade = mock(BrokerFacade.class);
84 public InvokeRpcMethodTest() {
85 controllerContext = TestRestconfUtils.newControllerContext(schemaContext);
86 restconfImpl = RestconfImpl.newInstance(brokerFacade, controllerContext);
90 public static void init() throws FileNotFoundException, ReactorException {
91 schemaContext = TestUtils.loadSchemaContext("/full-versions/yangs", "/invoke-rpc");
92 final Collection<? extends Module> allModules = schemaContext.getModules();
93 assertNotNull(allModules);
94 final Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
95 assertNotNull(module);
97 uriInfo = mock(UriInfo.class);
98 final MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
99 map.put("prettyPrint", Collections.singletonList("true"));
100 when(uriInfo.getQueryParameters(any(Boolean.class))).thenReturn(map);
104 * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
105 * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
106 * string - first argument).
110 public void invokeRpcMethodTest() {
112 controllerContext.findModuleNameByNamespace(new URI("invoke:rpc:module"));
113 } catch (final URISyntaxException e) {
114 assertTrue("Uri wasn't created sucessfuly", false);
117 final NormalizedNodeContext payload = prepareDomPayload();
119 final NormalizedNodeContext rpcResponse =
120 restconfImpl.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
121 assertTrue(rpcResponse != null);
122 assertTrue(rpcResponse.getData() == null);
126 private NormalizedNodeContext prepareDomPayload() {
127 final EffectiveModelContext schema = controllerContext.getGlobalSchema();
128 final Module rpcModule = schema.findModules("invoke-rpc-module").iterator().next();
129 assertNotNull(rpcModule);
130 final QName rpcQName = QName.create(rpcModule.getQNameModule(), "rpc-test");
131 final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
132 ContainerLike rpcInputSchemaNode = null;
133 for (final RpcDefinition rpc : rpcModule.getRpcs()) {
134 if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
135 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
139 assertNotNull(rpcInputSchemaNode);
141 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> container =
142 Builders.containerBuilder(rpcInputSchemaNode);
144 final QName contQName = QName.create(rpcModule.getQNameModule(), "cont");
145 final DataSchemaNode contSchemaNode = rpcInputSchemaNode.getDataChildByName(contQName);
146 assertTrue(contSchemaNode instanceof ContainerSchemaNode);
147 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> contNode =
148 Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);
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());
158 return new NormalizedNodeContext(
159 new InstanceIdentifierContext<>(null, rpcInputSchemaNode, null, schema), container.build());
163 public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
164 final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
166 doReturn(immediateFailedFluentFuture(new DOMRpcImplementationNotAvailableException("testExeption")))
167 .when(brokerFacade).invokeRpc(eq(qname), any());
170 this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
171 fail("Expected an exception to be thrown.");
172 } catch (final RestconfDocumentedException e) {
173 verifyRestconfDocumentedException(e, 0, ErrorType.APPLICATION, ErrorTag.OPERATION_NOT_SUPPORTED,
174 Optional.absent(), Optional.absent());
178 void verifyRestconfDocumentedException(final RestconfDocumentedException restDocumentedException, final int index,
179 final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
180 final Optional<String> expAppTag) {
181 RestconfError actual = null;
183 actual = restDocumentedException.getErrors().get(index);
184 } catch (final ArrayIndexOutOfBoundsException ex) {
185 fail("RestconfError not found at index " + index);
188 assertEquals("getErrorType", expErrorType, actual.getErrorType());
189 assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
190 assertNotNull("getErrorMessage is null", actual.getErrorMessage());
192 if (expErrorMsg.isPresent()) {
193 assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
196 if (expAppTag.isPresent()) {
197 assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
202 public void testInvokeRpcWithNoPayloadRpc_FailWithRpcError() {
203 final List<RpcError> rpcErrors = Arrays.asList(
204 RpcResultBuilder.newError(RpcError.ErrorType.TRANSPORT, "bogusTag", "foo"),
205 RpcResultBuilder.newWarning(RpcError.ErrorType.RPC, "in-use", "bar",
206 "app-tag", null, null));
208 final DOMRpcResult result = new DefaultDOMRpcResult(rpcErrors);
209 final QName path = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
210 doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(path), any());
213 this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
214 fail("Expected an exception to be thrown.");
215 } catch (final RestconfDocumentedException e) {
216 verifyRestconfDocumentedException(e, 0, ErrorType.TRANSPORT, ErrorTag.OPERATION_FAILED, Optional.of("foo"),
218 verifyRestconfDocumentedException(e, 1, ErrorType.RPC, ErrorTag.IN_USE, Optional.of("bar"),
219 Optional.of("app-tag"));
224 public void testInvokeRpcWithNoPayload_Success() {
225 final NormalizedNode<?, ?> resultObj = null;
226 final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
228 final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
230 doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(qname), any());
232 final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
233 assertNotNull(output);
234 assertEquals(null, output.getData());
235 // additional validation in the fact that the restconfImpl does not
236 // throw an exception.
240 public void testInvokeRpcWithEmptyOutput() {
241 final ContainerNode resultObj = Mockito.mock(ContainerNode.class);
242 Mockito.when(resultObj.getValue()).thenReturn(Collections.emptySet());
243 final DOMRpcResult expResult = new DefaultDOMRpcResult(resultObj);
245 final QName qname = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast");
246 doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(qname), any());
248 WebApplicationException exceptionToBeThrown = null;
250 this.restconfImpl.invokeRpc("toaster:cancel-toast", null, uriInfo);
251 } catch (final WebApplicationException exception) {
252 exceptionToBeThrown = exception;
255 Assert.assertNotNull("WebApplicationException with status code 204 is expected.", exceptionToBeThrown);
256 Assert.assertEquals(Response.Status.NO_CONTENT.getStatusCode(), exceptionToBeThrown.getResponse().getStatus());
260 public void testInvokeRpcMethodWithBadMethodName() {
262 this.restconfImpl.invokeRpc("toaster:bad-method", null, uriInfo);
263 fail("Expected an exception");
264 } catch (final RestconfDocumentedException e) {
265 verifyRestconfDocumentedException(e, 0, ErrorType.RPC, ErrorTag.UNKNOWN_ELEMENT,
266 Optional.absent(), Optional.absent());
272 public void testInvokeRpcMethodWithInput() {
273 final DOMRpcResult expResult = mock(DOMRpcResult.class);
274 final QName path = QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast");
276 final Module rpcModule = schemaContext.findModules("toaster").iterator().next();
277 assertNotNull(rpcModule);
278 final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
279 final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
281 RpcDefinition rpcDef = null;
282 ContainerLike rpcInputSchemaNode = null;
283 for (final RpcDefinition rpc : rpcModule.getRpcs()) {
284 if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
285 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
291 assertNotNull(rpcDef);
292 assertNotNull(rpcInputSchemaNode);
293 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
294 Builders.containerBuilder(rpcInputSchemaNode);
296 final NormalizedNodeContext payload =
297 new NormalizedNodeContext(new InstanceIdentifierContext<>(null, rpcInputSchemaNode,
298 null, schemaContext), containerBuilder.build());
300 doReturn(immediateFluentFuture(expResult)).when(brokerFacade).invokeRpc(eq(path), any(NormalizedNode.class));
302 final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
303 assertNotNull(output);
304 assertEquals(null, output.getData());
305 // additional validation in the fact that the restconfImpl does not
306 // throw an exception.
310 public void testThrowExceptionWhenSlashInModuleName() {
312 this.restconfImpl.invokeRpc("toaster/slash", null, uriInfo);
313 fail("Expected an exception.");
314 } catch (final RestconfDocumentedException e) {
315 verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
316 Optional.absent(), Optional.absent());
321 public void testInvokeRpcWithNoPayloadWithOutput_Success() {
322 final SchemaContext schema = controllerContext.getGlobalSchema();
323 final Module rpcModule = schema.findModules("toaster").iterator().next();
324 assertNotNull(rpcModule);
325 final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
326 final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
328 RpcDefinition rpcDef = null;
329 ContainerLike rpcOutputSchemaNode = null;
330 for (final RpcDefinition rpc : rpcModule.getRpcs()) {
331 if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
332 rpcOutputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcOutputQName);
337 assertNotNull(rpcDef);
338 assertNotNull(rpcOutputSchemaNode);
339 final DataContainerNodeBuilder<NodeIdentifier, ContainerNode> containerBuilder =
340 Builders.containerBuilder(rpcOutputSchemaNode);
341 final DataSchemaNode leafSchema = rpcOutputSchemaNode
342 .getDataChildByName(QName.create(rpcModule.getQNameModule(), "textOut"));
343 assertTrue(leafSchema instanceof LeafSchemaNode);
344 final NormalizedNodeBuilder<NodeIdentifier, Object, LeafNode<Object>> leafBuilder =
345 Builders.leafBuilder((LeafSchemaNode) leafSchema);
346 leafBuilder.withValue("brm");
347 containerBuilder.withChild(leafBuilder.build());
348 final ContainerNode container = containerBuilder.build();
350 final DOMRpcResult result = new DefaultDOMRpcResult(container);
352 doReturn(immediateFluentFuture(result)).when(brokerFacade).invokeRpc(eq(rpcDef.getQName()), any());
354 final NormalizedNodeContext output = this.restconfImpl.invokeRpc("toaster:testOutput", null, uriInfo);
355 assertNotNull(output);
356 assertNotNull(output.getData());
357 assertSame(container, output.getData());
358 assertNotNull(output.getInstanceIdentifierContext());
359 assertNotNull(output.getInstanceIdentifierContext().getSchemaContext());
363 * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
364 * This rpc is then executed.
365 * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
369 @Ignore // FIXME find how to use mockito for it
370 public void testMountedRpcCallNoPayload_Success() throws Exception {