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 org.custommonkey.xmlunit.DetailedDiff;
34 import org.custommonkey.xmlunit.Diff;
35 import org.custommonkey.xmlunit.XMLUnit;
36 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
37 import org.junit.Before;
38 import org.junit.Test;
39 import org.mockito.Mock;
40 import org.mockito.invocation.InvocationOnMock;
41 import org.mockito.stubbing.Answer;
42 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
43 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
44 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
45 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
46 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
47 import org.opendaylight.controller.netconf.api.NetconfDocumentedException;
48 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
49 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
50 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
51 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
52 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
53 import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
54 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
55 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
56 import org.opendaylight.controller.sal.core.api.model.SchemaService;
57 import org.opendaylight.yangtools.concepts.ListenerRegistration;
58 import org.opendaylight.yangtools.yang.common.RpcError;
59 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
60 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
61 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
62 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
63 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
64 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.Module;
66 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
67 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
69 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
70 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
71 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
72 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
73 import org.slf4j.Logger;
74 import org.slf4j.LoggerFactory;
75 import org.w3c.dom.Document;
77 public class RuntimeRpcTest {
79 private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
81 private String sessionIdForReporting = "netconf-test-session1";
83 private static Document RPC_REPLY_OK = null;
87 RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
88 } catch (Exception e) {
89 LOG.debug("unable to load rpc reply ok.", e);
90 RPC_REPLY_OK = XmlUtil.newDocument();
94 private DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
97 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
98 return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(null, Collections.<RpcError>emptyList()));
103 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
108 private DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
111 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
112 return Futures.immediateFailedCheckedFuture((DOMRpcException) new DOMRpcException("rpc invocation not implemented yet") {
118 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
123 private DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
126 public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
127 Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> children = (Collection) input.getValue();
128 Module module = schemaContext.findModuleByNamespaceAndRevision(type.getLastComponent().getNamespace(), null);
129 RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(), type.getLastComponent().getLocalName());
130 ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
131 ContainerNode node = ImmutableContainerNodeBuilder.create()
132 .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
133 .withValue(children).build();
135 return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(node));
140 public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
145 private SchemaContext schemaContext = null;
146 private CurrentSchemaContext currentSchemaContext = null;
148 private SchemaService schemaService;
150 private SchemaContextListener listener;
152 private ListenerRegistration registration;
155 public void setUp() throws Exception {
158 doNothing().when(registration).close();
159 doReturn(listener).when(registration).getInstance();
160 doNothing().when(schemaService).addModule(any(Module.class));
161 doNothing().when(schemaService).removeModule(any(Module.class));
162 doReturn(schemaContext).when(schemaService).getGlobalContext();
163 doReturn(schemaContext).when(schemaService).getSessionContext();
164 doAnswer(new Answer() {
166 public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
167 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
170 }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
172 XMLUnit.setIgnoreWhitespace(true);
173 XMLUnit.setIgnoreAttributeOrder(true);
175 this.schemaContext = parseSchemas(getYangSchemas());
176 this.currentSchemaContext = new CurrentSchemaContext(schemaService);
180 public void testVoidOutputRpc() throws Exception {
181 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
183 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
184 HandlingPriority priority = rpc.canHandle(rpcDocument);
185 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
187 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
189 verifyResponse(response, RPC_REPLY_OK);
193 public void testSuccesfullNonVoidInvocation() throws Exception {
194 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
196 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
197 HandlingPriority priority = rpc.canHandle(rpcDocument);
198 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
200 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
201 verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
205 public void testFailedInvocation() throws Exception {
206 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceFailedInvocation);
208 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
209 HandlingPriority priority = rpc.canHandle(rpcDocument);
210 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
213 rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
214 fail("should have failed with rpc invocation not implemented yet");
215 } catch (NetconfDocumentedException e) {
216 assertTrue(e.getErrorType() == ErrorType.application);
217 assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
218 assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
223 public void testVoidInputOutputRpc() throws Exception {
224 RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
226 Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
227 HandlingPriority priority = rpc.canHandle(rpcDocument);
228 Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
230 Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
232 verifyResponse(response, RPC_REPLY_OK);
235 private void verifyResponse(Document response, Document template) {
236 DetailedDiff dd = new DetailedDiff(new Diff(response, template));
237 dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
238 assertTrue(dd.similar());
241 private RpcDefinition getRpcDefinitionFromModule(Module module, URI namespaceURI, String name) {
242 for (RpcDefinition rpcDef : module.getRpcs()) {
243 if (rpcDef.getQName().getNamespace().equals(namespaceURI)
244 && rpcDef.getQName().getLocalName().equals(name)) {
253 private Collection<InputStream> getYangSchemas() {
254 final List<String> schemaPaths = Arrays.asList("/yang/mdsal-netconf-rpc-test.yang");
255 final List<InputStream> schemas = new ArrayList<>();
257 for (String schemaPath : schemaPaths) {
258 InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
259 schemas.add(resourceAsStream);
265 private SchemaContext parseSchemas(Collection<InputStream> schemas) throws IOException, YangSyntaxErrorException {
266 final YangParserImpl parser = new YangParserImpl();
267 Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(schemas);
268 return parser.parseSources(sources);