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.InputStream;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.List;
29 import javax.annotation.Nonnull;
30 import javax.annotation.Nullable;
31 import org.custommonkey.xmlunit.DetailedDiff;
32 import org.custommonkey.xmlunit.Diff;
33 import org.custommonkey.xmlunit.XMLUnit;
34 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.mockito.Mock;
38 import org.opendaylight.controller.config.util.xml.DocumentedException;
39 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
40 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
41 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
42 import org.opendaylight.controller.config.util.xml.XmlUtil;
43 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
44 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
45 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
46 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
47 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
48 import org.opendaylight.controller.sal.core.api.model.SchemaService;
49 import org.opendaylight.netconf.mapping.api.HandlingPriority;
50 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
51 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
52 import org.opendaylight.netconf.util.test.XmlFileLoader;
53 import org.opendaylight.yangtools.concepts.ListenerRegistration;
54 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
60 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.Module;
62 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
63 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
65 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
66 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
67 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
69 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.w3c.dom.Document;
74 public class RuntimeRpcTest {
75 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
76 private static final String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
77 private static final Document RPC_REPLY_OK = RuntimeRpcTest.getReplyOk();
79 @SuppressWarnings("illegalCatch")
80 private static Document getReplyOk() {
83 doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
84 } catch (final Exception e) {
85 LOG.debug("unable to load rpc reply ok.", e);
86 doc = XmlUtil.newDocument();
91 private final DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
94 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
95 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
96 return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(null, Collections.emptyList()));
101 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
102 @Nonnull final T listener) {
107 private final DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
110 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
111 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
112 return Futures.immediateFailedCheckedFuture(new DOMRpcException("rpc invocation not implemented yet") {
113 private static final long serialVersionUID = 1L;
119 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
120 @Nonnull final T listener) {
125 private final DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
128 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
129 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
130 final Collection<DataContainerChild<? extends PathArgument, ?>> children =
131 (Collection<DataContainerChild<? extends PathArgument, ?>>) input.getValue();
132 final Module module = schemaContext.findModuleByNamespaceAndRevision(
133 type.getLastComponent().getNamespace(), null);
134 final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(
135 module, module.getNamespace(), type.getLastComponent().getLocalName());
136 final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
137 final ContainerNode node = ImmutableContainerNodeBuilder.create()
138 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
139 .withValue(children).build();
141 return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(node));
146 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
147 @Nonnull final T listener) {
152 private SchemaContext schemaContext = null;
153 private CurrentSchemaContext currentSchemaContext = null;
156 private SchemaService schemaService;
158 private SchemaContextListener listener;
160 private ListenerRegistration<?> registration;
162 private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
165 public void setUp() throws Exception {
167 doNothing().when(registration).close();
168 doReturn(listener).when(registration).getInstance();
169 doNothing().when(schemaService).addModule(any(Module.class));
170 doNothing().when(schemaService).removeModule(any(Module.class));
171 doReturn(schemaContext).when(schemaService).getGlobalContext();
172 doReturn(schemaContext).when(schemaService).getSessionContext();
173 doAnswer(invocationOnMock -> {
174 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
176 }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
178 XMLUnit.setIgnoreWhitespace(true);
179 XMLUnit.setIgnoreAttributeOrder(true);
181 doAnswer(invocationOnMock -> {
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);
187 }).when(sourceProvider).getSource(any(SourceIdentifier.class));
189 this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
190 this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
194 public void testVoidOutputRpc() throws Exception {
195 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
197 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
198 final HandlingPriority priority = rpc.canHandle(rpcDocument);
199 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
201 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
203 verifyResponse(response, RPC_REPLY_OK);
207 public void testSuccesfullNonVoidInvocation() throws Exception {
208 final RuntimeRpc rpc = new RuntimeRpc(
209 SESSION_ID_FOR_REPORTING, 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(
222 SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation);
224 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
225 final HandlingPriority priority = rpc.canHandle(rpcDocument);
226 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
228 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
229 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
233 public void testFailedInvocation() throws Exception {
234 final RuntimeRpc rpc = new RuntimeRpc(
235 SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceFailedInvocation);
237 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
238 final HandlingPriority priority = rpc.canHandle(rpcDocument);
239 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
242 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
243 fail("should have failed with rpc invocation not implemented yet");
244 } catch (final DocumentedException e) {
245 assertTrue(e.getErrorType() == ErrorType.APPLICATION);
246 assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
247 assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
252 public void testVoidInputOutputRpc() throws Exception {
253 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
255 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
256 final HandlingPriority priority = rpc.canHandle(rpcDocument);
257 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
259 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
261 verifyResponse(response, RPC_REPLY_OK);
265 public void testBadNamespaceInRpc() throws Exception {
266 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
267 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
270 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
271 fail("Should have failed, rpc has bad namespace");
272 } catch (final DocumentedException e) {
273 assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
274 assertTrue(e.getErrorTag() == ErrorTag.BAD_ELEMENT);
275 assertTrue(e.getErrorType() == ErrorType.APPLICATION);
279 private static void verifyResponse(final Document response, final Document template) {
280 final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
281 dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
282 //we care about order so response has to be identical
283 assertTrue(dd.identical());
286 private static RpcDefinition getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
288 for (final RpcDefinition rpcDef : module.getRpcs()) {
289 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
290 && rpcDef.getQName().getLocalName().equals(name)) {
298 private List<InputStream> getYangSchemas() {
299 final List<String> schemaPaths = Collections.singletonList("/yang/mdsal-netconf-rpc-test.yang");
300 final List<InputStream> schemas = new ArrayList<>();
302 for (final String schemaPath : schemaPaths) {
303 final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
304 schemas.add(resourceAsStream);