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") {
118 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
119 @Nonnull final T listener) {
124 private final DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
127 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
128 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
129 final Collection<DataContainerChild<? extends PathArgument, ?>> children = (Collection) input.getValue();
130 final Module module = schemaContext.findModuleByNamespaceAndRevision(
131 type.getLastComponent().getNamespace(), null);
132 final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(
133 module, module.getNamespace(), type.getLastComponent().getLocalName());
134 final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
135 final ContainerNode node = ImmutableContainerNodeBuilder.create()
136 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
137 .withValue(children).build();
139 return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(node));
144 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
145 @Nonnull final T listener) {
150 private SchemaContext schemaContext = null;
151 private CurrentSchemaContext currentSchemaContext = null;
154 private SchemaService schemaService;
156 private SchemaContextListener listener;
158 private ListenerRegistration registration;
160 private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
163 public void setUp() throws Exception {
165 doNothing().when(registration).close();
166 doReturn(listener).when(registration).getInstance();
167 doNothing().when(schemaService).addModule(any(Module.class));
168 doNothing().when(schemaService).removeModule(any(Module.class));
169 doReturn(schemaContext).when(schemaService).getGlobalContext();
170 doReturn(schemaContext).when(schemaService).getSessionContext();
171 doAnswer(invocationOnMock -> {
172 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
174 }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
176 XMLUnit.setIgnoreWhitespace(true);
177 XMLUnit.setIgnoreAttributeOrder(true);
179 doAnswer(invocationOnMock -> {
180 final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
181 final YangTextSchemaSource yangTextSchemaSource =
182 YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
183 return Futures.immediateCheckedFuture(yangTextSchemaSource);
185 }).when(sourceProvider).getSource(any(SourceIdentifier.class));
187 this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
188 this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
192 public void testVoidOutputRpc() throws Exception {
193 final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
195 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
196 final HandlingPriority priority = rpc.canHandle(rpcDocument);
197 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
199 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
201 verifyResponse(response, RPC_REPLY_OK);
205 public void testSuccesfullNonVoidInvocation() throws Exception {
206 final RuntimeRpc rpc = new RuntimeRpc(
207 SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation);
209 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
210 final HandlingPriority priority = rpc.canHandle(rpcDocument);
211 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
213 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
214 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
218 public void testSuccesfullContainerInvocation() throws Exception {
219 final RuntimeRpc rpc = new RuntimeRpc(
220 SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation);
222 final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
223 final HandlingPriority priority = rpc.canHandle(rpcDocument);
224 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
226 final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
227 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
231 public void testFailedInvocation() throws Exception {
232 final RuntimeRpc rpc = new RuntimeRpc(
233 SESSION_ID_FOR_REPORTING, 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(SESSION_ID_FOR_REPORTING, 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(SESSION_ID_FOR_REPORTING, 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 Exception {
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)) {
295 private List<InputStream> getYangSchemas() {
296 final List<String> schemaPaths = Collections.singletonList("/yang/mdsal-netconf-rpc-test.yang");
297 final List<InputStream> schemas = new ArrayList<>();
299 for (final String schemaPath : schemaPaths) {
300 final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
301 schemas.add(resourceAsStream);