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.config.util.xml.DocumentedException;
36 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
37 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
38 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
39 import org.opendaylight.controller.config.util.xml.XmlUtil;
40 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
41 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
42 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
43 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
44 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
45 import org.opendaylight.controller.sal.core.api.model.SchemaService;
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.findModule(type.getLastComponent().getNamespace()).orElse(null);
130 final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(
131 module, module.getNamespace(), type.getLastComponent().getLocalName());
132 final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
133 final ContainerNode node = ImmutableContainerNodeBuilder.create()
134 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
135 .withValue(children).build();
137 return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(node));
142 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
143 @Nonnull final T lsnr) {
148 private SchemaContext schemaContext = null;
149 private CurrentSchemaContext currentSchemaContext = null;
152 private SchemaService schemaService;
154 private SchemaContextListener listener;
156 private ListenerRegistration<?> registration;
158 private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
161 public void setUp() throws Exception {
163 doNothing().when(registration).close();
164 doReturn(listener).when(registration).getInstance();
165 doNothing().when(schemaService).addModule(any(Module.class));
166 doNothing().when(schemaService).removeModule(any(Module.class));
167 doReturn(schemaContext).when(schemaService).getGlobalContext();
168 doReturn(schemaContext).when(schemaService).getSessionContext();
169 doAnswer(invocationOnMock -> {
170 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
172 }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
174 XMLUnit.setIgnoreWhitespace(true);
175 XMLUnit.setIgnoreAttributeOrder(true);
177 doAnswer(invocationOnMock -> {
178 final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
179 final YangTextSchemaSource yangTextSchemaSource =
180 YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
181 return Futures.immediateCheckedFuture(yangTextSchemaSource);
183 }).when(sourceProvider).getSource(any(SourceIdentifier.class));
185 this.schemaContext = YangParserTestUtils.parseYangResource("/yang/mdsal-netconf-rpc-test.yang");
186 this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
190 public void testVoidOutputRpc() throws Exception {
191 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
193 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
194 final HandlingPriority priority = rpc.canHandle(rpcDocument);
195 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
197 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
199 verifyResponse(response, RPC_REPLY_OK);
203 public void testSuccesfullNonVoidInvocation() throws Exception {
204 final RuntimeRpc rpc = new RuntimeRpc(
205 SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
207 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
208 final HandlingPriority priority = rpc.canHandle(rpcDocument);
209 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
211 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
212 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
216 public void testSuccesfullContainerInvocation() throws Exception {
217 final RuntimeRpc rpc = new RuntimeRpc(
218 SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
220 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
221 final HandlingPriority priority = rpc.canHandle(rpcDocument);
222 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
224 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
225 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
229 public void testFailedInvocation() throws Exception {
230 final RuntimeRpc rpc = new RuntimeRpc(
231 SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_FAILED_INVOCATION);
233 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
234 final HandlingPriority priority = rpc.canHandle(rpcDocument);
235 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
238 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
239 fail("should have failed with rpc invocation not implemented yet");
240 } catch (final DocumentedException e) {
241 assertTrue(e.getErrorType() == ErrorType.APPLICATION);
242 assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
243 assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
248 public void testVoidInputOutputRpc() throws Exception {
249 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
251 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
252 final HandlingPriority priority = rpc.canHandle(rpcDocument);
253 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
255 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
257 verifyResponse(response, RPC_REPLY_OK);
261 public void testBadNamespaceInRpc() throws Exception {
262 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
263 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
266 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
267 fail("Should have failed, rpc has bad namespace");
268 } catch (final DocumentedException e) {
269 assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
270 assertTrue(e.getErrorTag() == ErrorTag.BAD_ELEMENT);
271 assertTrue(e.getErrorType() == ErrorType.APPLICATION);
275 private static void verifyResponse(final Document response, final Document template) {
276 final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
277 dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
278 //we care about order so response has to be identical
279 assertTrue(dd.identical());
282 private static RpcDefinition getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
284 for (final RpcDefinition rpcDef : module.getRpcs()) {
285 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
286 && rpcDef.getQName().getLocalName().equals(name)) {