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.controller.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.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.netconf.api.NetconfDocumentedException;
49 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
50 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
51 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
52 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
53 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
54 import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
55 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
56 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
57 import org.opendaylight.controller.sal.core.api.model.SchemaService;
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.parser.builder.impl.BuilderUtils;
73 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76 import org.w3c.dom.Document;
78 public class RuntimeRpcTest {
80 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
82 private String sessionIdForReporting = "netconf-test-session1";
84 private static Document RPC_REPLY_OK = null;
88 RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
89 } catch (Exception e) {
90 LOG.debug("unable to load rpc reply ok.", e);
91 RPC_REPLY_OK = XmlUtil.newDocument();
95 private DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
98 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
99 return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(null, Collections.<RpcError>emptyList()));
104 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
109 private DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
112 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
113 return Futures.immediateFailedCheckedFuture((DOMRpcException) new DOMRpcException("rpc invocation not implemented yet") {
119 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
124 private DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
127 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
128 Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> children = (Collection) input.getValue();
129 Module module = schemaContext.findModuleByNamespaceAndRevision(type.getLastComponent().getNamespace(), null);
130 RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(), type.getLastComponent().getLocalName());
131 ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
132 ContainerNode node = ImmutableContainerNodeBuilder.create()
133 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
134 .withValue(children).build();
136 return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(node));
141 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
146 private SchemaContext schemaContext = null;
147 private CurrentSchemaContext currentSchemaContext = null;
149 private SchemaService schemaService;
151 private SchemaContextListener listener;
153 private ListenerRegistration registration;
156 public void setUp() throws Exception {
159 doNothing().when(registration).close();
160 doReturn(listener).when(registration).getInstance();
161 doNothing().when(schemaService).addModule(any(Module.class));
162 doNothing().when(schemaService).removeModule(any(Module.class));
163 doReturn(schemaContext).when(schemaService).getGlobalContext();
164 doReturn(schemaContext).when(schemaService).getSessionContext();
165 doAnswer(new Answer() {
167 public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
168 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
171 }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
173 XMLUnit.setIgnoreWhitespace(true);
174 XMLUnit.setIgnoreAttributeOrder(true);
176 this.schemaContext = parseSchemas(getYangSchemas());
177 this.currentSchemaContext = new CurrentSchemaContext(schemaService);
181 public void testVoidOutputRpc() throws Exception {
182 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
184 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
185 HandlingPriority priority = rpc.canHandle(rpcDocument);
186 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
188 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
190 verifyResponse(response, RPC_REPLY_OK);
194 public void testSuccesfullNonVoidInvocation() throws Exception {
195 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
197 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
198 HandlingPriority priority = rpc.canHandle(rpcDocument);
199 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
201 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
202 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
206 public void testSuccesfullContainerInvocation() throws Exception {
207 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
209 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
210 HandlingPriority priority = rpc.canHandle(rpcDocument);
211 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
213 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
214 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
218 public void testFailedInvocation() throws Exception {
219 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceFailedInvocation);
221 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
222 HandlingPriority priority = rpc.canHandle(rpcDocument);
223 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
226 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
227 fail("should have failed with rpc invocation not implemented yet");
228 } catch (NetconfDocumentedException e) {
229 assertTrue(e.getErrorType() == ErrorType.application);
230 assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
231 assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
236 public void testVoidInputOutputRpc() throws Exception {
237 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
239 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
240 HandlingPriority priority = rpc.canHandle(rpcDocument);
241 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
243 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
245 verifyResponse(response, RPC_REPLY_OK);
248 private void verifyResponse(Document response, Document template) throws IOException, TransformerException {
249 DetailedDiff dd = new DetailedDiff(new Diff(response, template));
250 dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
251 //we care about order so response has to be identical
252 assertTrue(dd.identical());
255 private RpcDefinition getRpcDefinitionFromModule(Module module, URI namespaceURI, String name) {
256 for (RpcDefinition rpcDef : module.getRpcs()) {
257 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
258 && rpcDef.getQName().getLocalName().equals(name)) {
267 private Collection<InputStream> getYangSchemas() {
268 final List<String> schemaPaths = Arrays.asList("/yang/mdsal-netconf-rpc-test.yang");
269 final List<InputStream> schemas = new ArrayList<>();
271 for (String schemaPath : schemaPaths) {
272 InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
273 schemas.add(resourceAsStream);
279 private SchemaContext parseSchemas(Collection<InputStream> schemas) throws IOException, YangSyntaxErrorException {
280 final YangParserImpl parser = new YangParserImpl();
281 Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(schemas);
282 return parser.parseSources(sources);