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;
23 import java.io.IOException;
24 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.List;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import javax.xml.transform.TransformerException;
34 import org.custommonkey.xmlunit.DetailedDiff;
35 import org.custommonkey.xmlunit.Diff;
36 import org.custommonkey.xmlunit.XMLUnit;
37 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
38 import org.junit.Before;
39 import org.junit.Test;
40 import org.mockito.Mock;
41 import org.mockito.invocation.InvocationOnMock;
42 import org.mockito.stubbing.Answer;
43 import org.opendaylight.controller.config.util.xml.DocumentedException;
44 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
45 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
46 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
47 import org.opendaylight.controller.config.util.xml.XmlUtil;
48 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
52 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
53 import org.opendaylight.controller.sal.core.api.model.SchemaService;
54 import org.opendaylight.netconf.mapping.api.HandlingPriority;
55 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
56 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
57 import org.opendaylight.netconf.util.test.XmlFileLoader;
58 import org.opendaylight.yangtools.concepts.ListenerRegistration;
59 import org.opendaylight.yangtools.yang.common.RpcError;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
61 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
62 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
63 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
65 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.Module;
67 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
70 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
71 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
72 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
73 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
74 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import org.w3c.dom.Document;
79 public class RuntimeRpcTest {
81 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
83 private final String sessionIdForReporting = "netconf-test-session1";
85 private static Document RPC_REPLY_OK = null;
89 RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
90 } catch (final Exception e) {
91 LOG.debug("unable to load rpc reply ok.", e);
92 RPC_REPLY_OK = XmlUtil.newDocument();
96 private final DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
99 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
100 return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(null, Collections.<RpcError>emptyList()));
105 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
110 private final DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
113 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
114 return Futures.immediateFailedCheckedFuture((DOMRpcException) new DOMRpcException("rpc invocation not implemented yet") {
120 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
125 private final DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
128 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
129 final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> children = (Collection) input.getValue();
130 final Module module = schemaContext.findModuleByNamespaceAndRevision(type.getLastComponent().getNamespace(), null);
131 final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(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((DOMRpcResult) new DefaultDOMRpcResult(node));
142 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
147 private SchemaContext schemaContext = null;
148 private CurrentSchemaContext currentSchemaContext = null;
150 private SchemaService schemaService;
152 private SchemaContextListener listener;
154 private ListenerRegistration registration;
156 private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
159 public void setUp() throws Exception {
162 doNothing().when(registration).close();
163 doReturn(listener).when(registration).getInstance();
164 doNothing().when(schemaService).addModule(any(Module.class));
165 doNothing().when(schemaService).removeModule(any(Module.class));
166 doReturn(schemaContext).when(schemaService).getGlobalContext();
167 doReturn(schemaContext).when(schemaService).getSessionContext();
168 doAnswer(new Answer() {
170 public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
171 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
174 }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
176 XMLUnit.setIgnoreWhitespace(true);
177 XMLUnit.setIgnoreAttributeOrder(true);
179 doAnswer(new Answer() {
181 public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
182 final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
183 final YangTextSchemaSource yangTextSchemaSource =
184 YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
185 return Futures.immediateCheckedFuture(yangTextSchemaSource);
188 }).when(sourceProvider).getSource(any(SourceIdentifier.class));
190 this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
191 this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
195 public void testVoidOutputRpc() throws Exception {
196 final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
198 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
199 final HandlingPriority priority = rpc.canHandle(rpcDocument);
200 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
202 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
204 verifyResponse(response, RPC_REPLY_OK);
208 public void testSuccesfullNonVoidInvocation() throws Exception {
209 final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
211 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
212 final HandlingPriority priority = rpc.canHandle(rpcDocument);
213 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
215 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
216 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
220 public void testSuccesfullContainerInvocation() throws Exception {
221 final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
223 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
224 final HandlingPriority priority = rpc.canHandle(rpcDocument);
225 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
227 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
228 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
232 public void testFailedInvocation() throws Exception {
233 final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceFailedInvocation);
235 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
236 final HandlingPriority priority = rpc.canHandle(rpcDocument);
237 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
240 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
241 fail("should have failed with rpc invocation not implemented yet");
242 } catch (final DocumentedException e) {
243 assertTrue(e.getErrorType() == ErrorType.APPLICATION);
244 assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
245 assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
250 public void testVoidInputOutputRpc() throws Exception {
251 final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
253 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
254 final HandlingPriority priority = rpc.canHandle(rpcDocument);
255 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
257 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
259 verifyResponse(response, RPC_REPLY_OK);
263 public void testBadNamespaceInRpc() throws Exception {
264 final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
265 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
268 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
269 fail("Should have failed, rpc has bad namespace");
270 } catch (final DocumentedException e) {
271 assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
272 assertTrue(e.getErrorTag() == ErrorTag.BAD_ELEMENT);
273 assertTrue(e.getErrorType() == ErrorType.APPLICATION);
277 private void verifyResponse(final Document response, final Document template) throws IOException, TransformerException {
278 final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
279 dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
280 //we care about order so response has to be identical
281 assertTrue(dd.identical());
284 private RpcDefinition getRpcDefinitionFromModule(final Module module, final URI namespaceURI, final String name) {
285 for (final RpcDefinition rpcDef : module.getRpcs()) {
286 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
287 && rpcDef.getQName().getLocalName().equals(name)) {
296 private List<InputStream> getYangSchemas() {
297 final List<String> schemaPaths = Arrays.asList("/yang/mdsal-netconf-rpc-test.yang");
298 final List<InputStream> schemas = new ArrayList<>();
300 for (final String schemaPath : schemaPaths) {
301 final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
302 schemas.add(resourceAsStream);