2 * Copyright (c) 2015 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
9 package org.opendaylight.netconf.mdsal.connector.ops;
11 import static org.junit.Assert.assertTrue;
12 import static org.junit.Assert.fail;
13 import static org.mockito.Matchers.any;
14 import static org.mockito.Mockito.doAnswer;
15 import static org.mockito.Mockito.doNothing;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.MockitoAnnotations.initMocks;
19 import com.google.common.base.Preconditions;
20 import com.google.common.io.ByteSource;
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.Futures;
24 import java.util.Collection;
25 import java.util.Collections;
26 import javax.annotation.Nonnull;
27 import javax.annotation.Nullable;
28 import org.custommonkey.xmlunit.DetailedDiff;
29 import org.custommonkey.xmlunit.Diff;
30 import org.custommonkey.xmlunit.XMLUnit;
31 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.mockito.Mock;
35 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
36 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
37 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
38 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
39 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
40 import org.opendaylight.controller.sal.core.api.model.SchemaService;
41 import org.opendaylight.netconf.api.DocumentedException;
42 import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
43 import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
44 import org.opendaylight.netconf.api.DocumentedException.ErrorType;
45 import org.opendaylight.netconf.api.xml.XmlUtil;
46 import org.opendaylight.netconf.mapping.api.HandlingPriority;
47 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
48 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
49 import org.opendaylight.netconf.util.test.XmlFileLoader;
50 import org.opendaylight.yangtools.concepts.ListenerRegistration;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
53 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
57 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.Module;
59 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
62 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
63 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
65 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
66 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.w3c.dom.Document;
71 public class RuntimeRpcTest {
72 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
73 private static final String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
74 private static final Document RPC_REPLY_OK = RuntimeRpcTest.getReplyOk();
76 @SuppressWarnings("illegalCatch")
77 private static Document getReplyOk() {
80 doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
81 } catch (final Exception e) {
82 LOG.debug("unable to load rpc reply ok.", e);
83 doc = XmlUtil.newDocument();
88 private static final DOMRpcService RPC_SERVICE_VOID_INVOKER = new DOMRpcService() {
91 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
92 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
93 return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(null, Collections.emptyList()));
98 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
99 @Nonnull final T listener) {
104 private static final DOMRpcService RPC_SERVICE_FAILED_INVOCATION = new DOMRpcService() {
107 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
108 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
109 return Futures.immediateFailedCheckedFuture(new DOMRpcException("rpc invocation not implemented yet") {
110 private static final long serialVersionUID = 1L;
116 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
117 @Nonnull final T listener) {
122 private final DOMRpcService rpcServiceSuccessfulInvocation = new DOMRpcService() {
125 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
126 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
127 final Collection<DataContainerChild<? extends PathArgument, ?>> children =
128 (Collection<DataContainerChild<? extends PathArgument, ?>>) input.getValue();
129 final Module module = schemaContext.findModules(type.getLastComponent().getNamespace()).stream()
130 .findFirst().orElse(null);
131 final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(
132 module, module.getNamespace(), type.getLastComponent().getLocalName());
133 final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
134 final ContainerNode node = ImmutableContainerNodeBuilder.create()
135 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
136 .withValue(children).build();
138 return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(node));
143 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
144 @Nonnull final T lsnr) {
149 private SchemaContext schemaContext = null;
150 private CurrentSchemaContext currentSchemaContext = null;
153 private SchemaService schemaService;
155 private SchemaContextListener listener;
157 private ListenerRegistration<?> registration;
159 private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
162 public void setUp() throws Exception {
164 doNothing().when(registration).close();
165 doReturn(listener).when(registration).getInstance();
166 doNothing().when(schemaService).addModule(any(Module.class));
167 doNothing().when(schemaService).removeModule(any(Module.class));
168 doReturn(schemaContext).when(schemaService).getGlobalContext();
169 doReturn(schemaContext).when(schemaService).getSessionContext();
170 doAnswer(invocationOnMock -> {
171 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
173 }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
175 XMLUnit.setIgnoreWhitespace(true);
176 XMLUnit.setIgnoreAttributeOrder(true);
178 doAnswer(invocationOnMock -> {
179 final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
180 final YangTextSchemaSource yangTextSchemaSource =
181 YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
182 return Futures.immediateCheckedFuture(yangTextSchemaSource);
184 }).when(sourceProvider).getSource(any(SourceIdentifier.class));
186 this.schemaContext = YangParserTestUtils.parseYangResource("/yang/mdsal-netconf-rpc-test.yang");
187 this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
191 public void testVoidOutputRpc() throws Exception {
192 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
194 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
195 final HandlingPriority priority = rpc.canHandle(rpcDocument);
196 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
198 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
200 verifyResponse(response, RPC_REPLY_OK);
204 public void testSuccesfullNonVoidInvocation() throws Exception {
205 final RuntimeRpc rpc = new RuntimeRpc(
206 SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
208 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
209 final HandlingPriority priority = rpc.canHandle(rpcDocument);
210 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
212 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
213 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
217 public void testSuccesfullContainerInvocation() throws Exception {
218 final RuntimeRpc rpc = new RuntimeRpc(
219 SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
221 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
222 final HandlingPriority priority = rpc.canHandle(rpcDocument);
223 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
225 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
226 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
230 public void testFailedInvocation() throws Exception {
231 final RuntimeRpc rpc = new RuntimeRpc(
232 SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_FAILED_INVOCATION);
234 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
235 final HandlingPriority priority = rpc.canHandle(rpcDocument);
236 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
239 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
240 fail("should have failed with rpc invocation not implemented yet");
241 } catch (final DocumentedException e) {
242 assertTrue(e.getErrorType() == ErrorType.APPLICATION);
243 assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
244 assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
249 public void testVoidInputOutputRpc() throws Exception {
250 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
252 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
253 final HandlingPriority priority = rpc.canHandle(rpcDocument);
254 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
256 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
258 verifyResponse(response, RPC_REPLY_OK);
262 public void testBadNamespaceInRpc() throws Exception {
263 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
264 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
267 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
268 fail("Should have failed, rpc has bad namespace");
269 } catch (final DocumentedException e) {
270 assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
271 assertTrue(e.getErrorTag() == ErrorTag.BAD_ELEMENT);
272 assertTrue(e.getErrorType() == ErrorType.APPLICATION);
276 private static void verifyResponse(final Document response, final Document template) {
277 final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
278 dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
279 //we care about order so response has to be identical
280 assertTrue(dd.identical());
283 private static RpcDefinition getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
285 for (final RpcDefinition rpcDef : module.getRpcs()) {
286 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
287 && rpcDef.getQName().getLocalName().equals(name)) {