2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
3 * Copyright (c) 2014 Brocade Communications Systems, Inc.
5 * This program and the accompanying materials are made available under the
6 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.controller.sal.restconf.impl.test;
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 com.google.common.util.concurrent.ListenableFuture;
25 import java.io.FileNotFoundException;
27 import java.net.URISyntaxException;
28 import java.util.Arrays;
29 import java.util.Collections;
30 import java.util.HashSet;
31 import java.util.List;
33 import javax.ws.rs.core.MultivaluedHashMap;
34 import javax.ws.rs.core.MultivaluedMap;
35 import javax.ws.rs.core.UriInfo;
36 import org.junit.Before;
37 import org.junit.BeforeClass;
38 import org.junit.Ignore;
39 import org.junit.Test;
40 import org.opendaylight.controller.md.sal.dom.api.DOMMountPoint;
41 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
42 import org.opendaylight.controller.md.sal.dom.api.DOMRpcImplementationNotAvailableException;
43 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
44 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
45 import org.opendaylight.controller.sal.core.api.RpcProvisionRegistry;
46 import org.opendaylight.controller.sal.restconf.impl.BrokerFacade;
47 import org.opendaylight.controller.sal.restconf.impl.ControllerContext;
48 import org.opendaylight.controller.sal.restconf.impl.InstanceIdentifierContext;
49 import org.opendaylight.controller.sal.restconf.impl.NormalizedNodeContext;
50 import org.opendaylight.controller.sal.restconf.impl.RestconfDocumentedException;
51 import org.opendaylight.controller.sal.restconf.impl.RestconfError;
52 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorTag;
53 import org.opendaylight.controller.sal.restconf.impl.RestconfError.ErrorType;
54 import org.opendaylight.controller.sal.restconf.impl.RestconfImpl;
55 import org.opendaylight.yangtools.yang.common.QName;
56 import org.opendaylight.yangtools.yang.common.RpcError;
57 import org.opendaylight.yangtools.yang.common.RpcResult;
58 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
59 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
63 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
64 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
65 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.DataContainerNodeAttrBuilder;
66 import org.opendaylight.yangtools.yang.data.impl.schema.builder.api.NormalizedNodeAttrBuilder;
67 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.Module;
71 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
72 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
73 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
74 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
76 public class InvokeRpcMethodTest {
78 private RestconfImpl restconfImpl = null;
79 private static ControllerContext controllerContext = null;
80 private static UriInfo uriInfo;
84 public static void init() throws FileNotFoundException {
85 final Set<Module> allModules = new HashSet<Module>(TestUtils.loadModulesFrom("/full-versions/yangs"));
86 allModules.addAll(TestUtils.loadModulesFrom("/invoke-rpc"));
87 assertNotNull(allModules);
88 final Module module = TestUtils.resolveModule("invoke-rpc-module", allModules);
89 assertNotNull(module);
90 final SchemaContext schemaContext = TestUtils.loadSchemaContext(allModules);
91 controllerContext = spy(ControllerContext.getInstance());
92 controllerContext.setSchemas(schemaContext);
93 uriInfo = mock(UriInfo.class);
94 final MultivaluedMap<String, String> map = new MultivaluedHashMap<>();
95 map.put("prettyPrint", Collections.singletonList("true"));
96 when(uriInfo.getQueryParameters(any(Boolean.class))).thenReturn(map);
100 public void initMethod() {
101 restconfImpl = RestconfImpl.getInstance();
102 restconfImpl.setControllerContext(controllerContext);
106 * Test method invokeRpc in RestconfImpl class tests if composite node as input parameter of method invokeRpc
107 * (second argument) is wrapped to parent composite node which has QName equals to QName of rpc (resolved from
108 * string - first argument).
111 public void invokeRpcMethodTest() {
112 final ControllerContext contContext = controllerContext;
114 contContext.findModuleNameByNamespace(new URI("invoke:rpc:module"));
115 } catch (final URISyntaxException e) {
116 assertTrue("Uri wasn't created sucessfuly", false);
119 final BrokerFacade mockedBrokerFacade = mock(BrokerFacade.class);
121 final RestconfImpl restconf = RestconfImpl.getInstance();
122 restconf.setBroker(mockedBrokerFacade);
123 restconf.setControllerContext(contContext);
125 final NormalizedNodeContext payload = prepareDomPayload();
127 final NormalizedNodeContext rpcResponse = restconf.invokeRpc("invoke-rpc-module:rpc-test", payload, uriInfo);
128 assertTrue(rpcResponse != null);
129 assertTrue(rpcResponse.getData() == null);
133 private NormalizedNodeContext prepareDomPayload() {
134 final SchemaContext schema = controllerContext.getGlobalSchema();
135 final Module rpcModule = schema.findModuleByName("invoke-rpc-module", null);
136 assertNotNull(rpcModule);
137 final QName rpcQName = QName.create(rpcModule.getQNameModule(), "rpc-test");
138 final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
139 final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
140 ContainerSchemaNode rpcInputSchemaNode = null;
141 for (final RpcDefinition rpc : setRpcs) {
142 if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
143 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
147 assertNotNull(rpcInputSchemaNode);
149 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> container = Builders.containerBuilder(rpcInputSchemaNode);
151 final QName contQName = QName.create(rpcModule.getQNameModule(), "cont");
152 final DataSchemaNode contSchemaNode = rpcInputSchemaNode.getDataChildByName(contQName);
153 assertTrue(contSchemaNode instanceof ContainerSchemaNode);
154 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> contNode = Builders.containerBuilder((ContainerSchemaNode) contSchemaNode);
156 final QName lfQName = QName.create(rpcModule.getQNameModule(), "lf");
157 final DataSchemaNode lfSchemaNode = ((ContainerSchemaNode) contSchemaNode).getDataChildByName(lfQName);
158 assertTrue(lfSchemaNode instanceof LeafSchemaNode);
159 final LeafNode<Object> lfNode = (Builders.leafBuilder((LeafSchemaNode) lfSchemaNode).withValue("any value")).build();
160 contNode.withChild(lfNode);
161 container.withChild(contNode.build());
163 return new NormalizedNodeContext(new InstanceIdentifierContext(null, rpcInputSchemaNode, null, schema), container.build());
167 public void testInvokeRpcWithNoPayloadRpc_FailNoErrors() {
168 final DOMRpcException exception = new DOMRpcImplementationNotAvailableException("testExeption");
169 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateFailedCheckedFuture(exception);
171 final BrokerFacade brokerFacade = mock(BrokerFacade.class);
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);
176 when(brokerFacade.invokeRpc(eq(type), any(NormalizedNode.class))).thenReturn(future);
178 restconfImpl.setBroker(brokerFacade);
181 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_FAILED,
185 Optional.<String> absent(), Optional.<String> absent());
189 void verifyRestconfDocumentedException(final RestconfDocumentedException e, final int index,
190 final ErrorType expErrorType, final ErrorTag expErrorTag, final Optional<String> expErrorMsg,
191 final Optional<String> expAppTag) {
192 RestconfError actual = null;
194 actual = e.getErrors().get(index);
195 } catch (final ArrayIndexOutOfBoundsException ex) {
196 fail("RestconfError not found at index " + index);
199 assertEquals("getErrorType", expErrorType, actual.getErrorType());
200 assertEquals("getErrorTag", expErrorTag, actual.getErrorTag());
201 assertNotNull("getErrorMessage is null", actual.getErrorMessage());
203 if (expErrorMsg.isPresent()) {
204 assertEquals("getErrorMessage", expErrorMsg.get(), actual.getErrorMessage());
207 if (expAppTag.isPresent()) {
208 assertEquals("getErrorAppTag", expAppTag.get(), actual.getErrorAppTag());
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 ) );
219 final DOMRpcResult resutl = new DefaultDOMRpcResult(rpcErrors);
220 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(resutl);
222 final SchemaPath path = SchemaPath.create(true,
223 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)cancel-toast"));
225 final BrokerFacade brokerFacade = mock(BrokerFacade.class);
226 when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
228 restconfImpl.setBroker(brokerFacade);
231 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"));
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);
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);
250 final BrokerFacade brokerFacade = mock(BrokerFacade.class);
251 when(brokerFacade.invokeRpc(eq(path), any (NormalizedNode.class))).thenReturn(future);
253 restconfImpl.setBroker(brokerFacade);
255 final NormalizedNodeContext output = 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.
263 public void testInvokeRpcMethodExpectingNoPayloadButProvidePayload() {
265 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());
274 public void testInvokeRpcMethodWithBadMethodName() {
276 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());
285 public void testInvokeRpcMethodWithInput() {
286 final DOMRpcResult expResult = mock(DOMRpcResult.class);
287 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(expResult);
288 final SchemaPath path = SchemaPath.create(true,
289 QName.create("(http://netconfcentral.org/ns/toaster?revision=2009-11-20)make-toast"));
291 final SchemaContext schemaContext = controllerContext.getGlobalSchema();
292 final Module rpcModule = schemaContext.findModuleByName("toaster", null);
293 assertNotNull(rpcModule);
294 final QName rpcQName = QName.create(rpcModule.getQNameModule(), "make-toast");
295 final QName rpcInputQName = QName.create(rpcModule.getQNameModule(),"input");
297 final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
298 RpcDefinition rpcDef = null;
299 ContainerSchemaNode rpcInputSchemaNode = null;
301 for (final RpcDefinition rpc : setRpcs) {
302 if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
303 rpcInputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcInputQName);
309 assertNotNull(rpcDef);
310 assertNotNull(rpcInputSchemaNode);
311 assertTrue(rpcInputSchemaNode instanceof ContainerSchemaNode);
312 final DataContainerNodeAttrBuilder<NodeIdentifier, ContainerNode> containerBuilder =
313 Builders.containerBuilder(rpcInputSchemaNode);
315 final NormalizedNodeContext payload = new NormalizedNodeContext(new InstanceIdentifierContext(null, rpcInputSchemaNode,
316 null, schemaContext), containerBuilder.build());
318 final BrokerFacade brokerFacade = mock(BrokerFacade.class);
319 when(brokerFacade.invokeRpc(eq(path), any(NormalizedNode.class))).thenReturn(future);
320 restconfImpl.setBroker(brokerFacade);
322 final NormalizedNodeContext output = restconfImpl.invokeRpc("toaster:make-toast", payload, uriInfo);
323 assertNotNull(output);
324 assertEquals(null, output.getData());
325 // additional validation in the fact that the restconfImpl does not
326 // throw an exception.
330 public void testThrowExceptionWhenSlashInModuleName() {
332 restconfImpl.invokeRpc("toaster/slash", "", uriInfo);
333 fail("Expected an exception.");
334 } catch (final RestconfDocumentedException e) {
335 verifyRestconfDocumentedException(e, 0, ErrorType.PROTOCOL, ErrorTag.INVALID_VALUE,
336 Optional.<String> absent(), Optional.<String> absent());
341 public void testInvokeRpcWithNoPayloadWithOutput_Success() {
342 final SchemaContext schema = controllerContext.getGlobalSchema();
343 final Module rpcModule = schema.findModuleByName("toaster", null);
344 assertNotNull(rpcModule);
345 final QName rpcQName = QName.create(rpcModule.getQNameModule(), "testOutput");
346 final QName rpcOutputQName = QName.create(rpcModule.getQNameModule(),"output");
348 final Set<RpcDefinition> setRpcs = rpcModule.getRpcs();
349 RpcDefinition rpcDef = null;
350 ContainerSchemaNode rpcOutputSchemaNode = null;
351 for (final RpcDefinition rpc : setRpcs) {
352 if (rpcQName.isEqualWithoutRevision(rpc.getQName())) {
353 rpcOutputSchemaNode = SchemaNodeUtils.getRpcDataSchema(rpc, rpcOutputQName);
358 assertNotNull(rpcDef);
359 assertNotNull(rpcOutputSchemaNode);
360 assertTrue(rpcOutputSchemaNode instanceof ContainerSchemaNode);
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();
372 final DOMRpcResult result = new DefaultDOMRpcResult(container);
373 final CheckedFuture<DOMRpcResult, DOMRpcException> future = Futures.immediateCheckedFuture(result);
375 final BrokerFacade brokerFacade = mock(BrokerFacade.class);
376 when(brokerFacade.invokeRpc(eq(rpcDef.getPath()), any(NormalizedNode.class))).thenReturn(future);
378 restconfImpl.setBroker(brokerFacade);
380 final NormalizedNodeContext output = 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());
390 * Tests calling of RestConfImpl method invokeRpc. In the method there is searched rpc in remote schema context.
391 * This rpc is then executed.
393 * I wasn't able to simulate calling of rpc on remote device therefore this testing method raise method when rpc is
397 @Ignore // FIXME find how to use mockito for it
398 public void testMountedRpcCallNoPayload_Success() throws Exception {
399 final RpcResult<CompositeNode> rpcResult = RpcResultBuilder.<CompositeNode>success().build();
401 final ListenableFuture<RpcResult<CompositeNode>> mockListener = mock(ListenableFuture.class);
402 when(mockListener.get()).thenReturn(rpcResult);
404 final QName cancelToastQName = QName.create("namespace", "2014-05-28", "cancelToast");
406 final RpcDefinition mockRpc = mock(RpcDefinition.class);
407 when(mockRpc.getQName()).thenReturn(cancelToastQName);
409 final DOMMountPoint mockMountPoint = mock(DOMMountPoint.class);
410 final RpcProvisionRegistry mockedRpcProvisionRegistry = mock(RpcProvisionRegistry.class);
411 when(mockedRpcProvisionRegistry.invokeRpc(eq(cancelToastQName), any(CompositeNode.class))).thenReturn(mockListener);
412 when(mockMountPoint.getService(eq(RpcProvisionRegistry.class))).thenReturn(Optional.of(mockedRpcProvisionRegistry));
413 when(mockMountPoint.getSchemaContext()).thenReturn(TestUtils.loadSchemaContext("/invoke-rpc"));
415 final InstanceIdentifierContext mockedInstanceId = mock(InstanceIdentifierContext.class);
416 when(mockedInstanceId.getMountPoint()).thenReturn(mockMountPoint);
418 final ControllerContext mockedContext = mock(ControllerContext.class);
419 final String rpcNoop = "invoke-rpc-module:rpc-noop";
420 when(mockedContext.urlPathArgDecode(rpcNoop)).thenReturn(rpcNoop);
421 when(mockedContext.getRpcDefinition(rpcNoop)).thenReturn(mockRpc);
423 mockedContext.toMountPointIdentifier(eq("opendaylight-inventory:nodes/node/"
424 + "REMOTE_HOST/yang-ext:mount/invoke-rpc-module:rpc-noop"))).thenReturn(mockedInstanceId);
426 restconfImpl.setControllerContext(mockedContext);
428 restconfImpl.invokeRpc(
429 "opendaylight-inventory:nodes/node/REMOTE_HOST/yang-ext:mount/invoke-rpc-module:rpc-noop", "",
431 fail("RestconfDocumentedException wasn't raised");
432 } catch (final RestconfDocumentedException e) {
433 final List<RestconfError> errors = e.getErrors();
434 assertNotNull(errors);
435 assertEquals(1, errors.size());
436 assertEquals(ErrorType.APPLICATION, errors.iterator().next().getErrorType());
437 assertEquals(ErrorTag.OPERATION_FAILED, errors.iterator().next().getErrorTag());
440 // additional validation in the fact that the restconfImpl does not
441 // throw an exception.