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.parser.api.YangSyntaxErrorException;
72 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
73 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
74 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
75 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
76 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79 import org.w3c.dom.Document;
81 public class RuntimeRpcTest {
83 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
85 private String sessionIdForReporting = "netconf-test-session1";
87 private static Document RPC_REPLY_OK = null;
91 RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
92 } catch (Exception e) {
93 LOG.debug("unable to load rpc reply ok.", e);
94 RPC_REPLY_OK = XmlUtil.newDocument();
98 private DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
101 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
102 return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(null, Collections.<RpcError>emptyList()));
107 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
112 private DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
115 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
116 return Futures.immediateFailedCheckedFuture((DOMRpcException) new DOMRpcException("rpc invocation not implemented yet") {
122 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
127 private DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
130 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
131 Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> children = (Collection) input.getValue();
132 Module module = schemaContext.findModuleByNamespaceAndRevision(type.getLastComponent().getNamespace(), null);
133 RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(), type.getLastComponent().getLocalName());
134 ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
135 ContainerNode node = ImmutableContainerNodeBuilder.create()
136 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
137 .withValue(children).build();
139 return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(node));
144 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
149 private SchemaContext schemaContext = null;
150 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 {
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(new Answer() {
172 public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
173 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
176 }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
178 XMLUnit.setIgnoreWhitespace(true);
179 XMLUnit.setIgnoreAttributeOrder(true);
181 doAnswer(new Answer() {
183 public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
184 final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
185 final YangTextSchemaSource yangTextSchemaSource =
186 YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
187 return Futures.immediateCheckedFuture(yangTextSchemaSource);
190 }).when(sourceProvider).getSource(any(SourceIdentifier.class));
192 this.schemaContext = parseSchemas(getYangSchemas());
193 this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
197 public void testVoidOutputRpc() throws Exception {
198 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
200 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
201 HandlingPriority priority = rpc.canHandle(rpcDocument);
202 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
204 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
206 verifyResponse(response, RPC_REPLY_OK);
210 public void testSuccesfullNonVoidInvocation() throws Exception {
211 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
213 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
214 HandlingPriority priority = rpc.canHandle(rpcDocument);
215 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
217 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
218 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
222 public void testSuccesfullContainerInvocation() throws Exception {
223 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
225 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
226 HandlingPriority priority = rpc.canHandle(rpcDocument);
227 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
229 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
230 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
234 public void testFailedInvocation() throws Exception {
235 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceFailedInvocation);
237 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
238 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 (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 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
255 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
256 HandlingPriority priority = rpc.canHandle(rpcDocument);
257 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
259 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
261 verifyResponse(response, RPC_REPLY_OK);
265 public void testBadNamespaceInRpc() throws Exception {
266 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
267 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 (DocumentedException e) {
273 assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
274 assertTrue(e.getErrorTag() == ErrorTag.bad_element);
275 assertTrue(e.getErrorType() == ErrorType.application);
279 private void verifyResponse(Document response, Document template) throws IOException, TransformerException {
280 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 RpcDefinition getRpcDefinitionFromModule(Module module, URI namespaceURI, String name) {
287 for (RpcDefinition rpcDef : module.getRpcs()) {
288 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
289 && rpcDef.getQName().getLocalName().equals(name)) {
298 private Collection<InputStream> getYangSchemas() {
299 final List<String> schemaPaths = Arrays.asList("/yang/mdsal-netconf-rpc-test.yang");
300 final List<InputStream> schemas = new ArrayList<>();
302 for (String schemaPath : schemaPaths) {
303 InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
304 schemas.add(resourceAsStream);
310 private SchemaContext parseSchemas(Collection<InputStream> schemas) throws IOException, YangSyntaxErrorException {
311 final YangParserImpl parser = new YangParserImpl();
312 Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(schemas);
313 return parser.parseSources(sources);