Make RuntimeRpc revision aware
[netconf.git] / netconf / mdsal-netconf-connector / src / test / java / org / opendaylight / netconf / mdsal / connector / ops / RuntimeRpcTest.java
1 /*
2  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.netconf.mdsal.connector.ops;
10
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;
18
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.net.URI;
24 import java.util.Collection;
25 import java.util.Collections;
26 import javax.annotation.Nonnull;
27 import javax.annotation.Nullable;
28 import org.custommonkey.xmlunit.DetailedDiff;
29 import org.custommonkey.xmlunit.Diff;
30 import org.custommonkey.xmlunit.XMLUnit;
31 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
32 import org.junit.Before;
33 import org.junit.Test;
34 import org.mockito.Mock;
35 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
36 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
37 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
38 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
39 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
40 import org.opendaylight.controller.sal.core.api.model.SchemaService;
41 import org.opendaylight.netconf.api.DocumentedException;
42 import org.opendaylight.netconf.api.DocumentedException.ErrorSeverity;
43 import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
44 import org.opendaylight.netconf.api.DocumentedException.ErrorType;
45 import org.opendaylight.netconf.api.xml.XmlUtil;
46 import org.opendaylight.netconf.mapping.api.HandlingPriority;
47 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
48 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
49 import org.opendaylight.netconf.util.test.XmlFileLoader;
50 import org.opendaylight.yangtools.concepts.ListenerRegistration;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
53 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
54 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
57 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.Module;
59 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
62 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
63 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
64 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
65 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
66 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
67 import org.slf4j.Logger;
68 import org.slf4j.LoggerFactory;
69 import org.w3c.dom.Document;
70
71 public class RuntimeRpcTest {
72     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
73     private static final String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
74     private static final Document RPC_REPLY_OK = RuntimeRpcTest.getReplyOk();
75
76     @SuppressWarnings("illegalCatch")
77     private static Document getReplyOk() {
78         Document doc;
79         try {
80             doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
81         } catch (final Exception e) {
82             LOG.debug("unable to load rpc reply ok.", e);
83             doc = XmlUtil.newDocument();
84         }
85         return doc;
86     }
87
88     private static final DOMRpcService RPC_SERVICE_VOID_INVOKER = new DOMRpcService() {
89         @Nonnull
90         @Override
91         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
92                 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
93             return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(null, Collections.emptyList()));
94         }
95
96         @Nonnull
97         @Override
98         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
99                 @Nonnull final T listener) {
100             return null;
101         }
102     };
103
104     private static final DOMRpcService RPC_SERVICE_FAILED_INVOCATION = new DOMRpcService() {
105         @Nonnull
106         @Override
107         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
108                 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
109             return Futures.immediateFailedCheckedFuture(new DOMRpcException("rpc invocation not implemented yet") {
110                 private static final long serialVersionUID = 1L;
111             });
112         }
113
114         @Nonnull
115         @Override
116         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
117                 @Nonnull final T listener) {
118             return null;
119         }
120     };
121
122     private final DOMRpcService rpcServiceSuccessfulInvocation = new DOMRpcService() {
123         @Nonnull
124         @Override
125         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
126                 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
127             final Collection<DataContainerChild<? extends PathArgument, ?>> children =
128                     (Collection<DataContainerChild<? extends PathArgument, ?>>) input.getValue();
129             final Module module = schemaContext.findModules(type.getLastComponent().getNamespace()).stream()
130                 .findFirst().orElse(null);
131             final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(
132                 module, module.getNamespace(), type.getLastComponent().getLocalName());
133             final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
134             final ContainerNode node = ImmutableContainerNodeBuilder.create()
135                     .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
136                     .withValue(children).build();
137
138             return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(node));
139         }
140
141         @Nonnull
142         @Override
143         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
144                 @Nonnull final T lsnr) {
145             return null;
146         }
147     };
148
149     private SchemaContext schemaContext = null;
150     private CurrentSchemaContext currentSchemaContext = null;
151
152     @Mock
153     private SchemaService schemaService;
154     @Mock
155     private SchemaContextListener listener;
156     @Mock
157     private ListenerRegistration<?> registration;
158     @Mock
159     private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
160
161     @Before
162     public void setUp() throws Exception {
163         initMocks(this);
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(invocationOnMock -> {
171             ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
172             return registration;
173         }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
174
175         XMLUnit.setIgnoreWhitespace(true);
176         XMLUnit.setIgnoreAttributeOrder(true);
177
178         doAnswer(invocationOnMock -> {
179             final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
180             final YangTextSchemaSource yangTextSchemaSource =
181                     YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
182             return Futures.immediateCheckedFuture(yangTextSchemaSource);
183
184         }).when(sourceProvider).getSource(any(SourceIdentifier.class));
185
186         this.schemaContext = YangParserTestUtils.parseYangResource("/yang/mdsal-netconf-rpc-test.yang");
187         this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
188     }
189
190     @Test
191     public void testVoidOutputRpc() throws Exception {
192         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
193
194         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
195         final HandlingPriority priority = rpc.canHandle(rpcDocument);
196         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
197
198         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
199
200         verifyResponse(response, RPC_REPLY_OK);
201     }
202
203     @Test
204     public void testSuccesfullNonVoidInvocation() throws Exception {
205         final RuntimeRpc rpc = new RuntimeRpc(
206             SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
207
208         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
209         final HandlingPriority priority = rpc.canHandle(rpcDocument);
210         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
211
212         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
213         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
214     }
215
216     @Test
217     public void testSuccesfullContainerInvocation() throws Exception {
218         final RuntimeRpc rpc = new RuntimeRpc(
219             SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
220
221         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
222         final HandlingPriority priority = rpc.canHandle(rpcDocument);
223         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
224
225         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
226         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
227     }
228
229     @Test
230     public void testFailedInvocation() throws Exception {
231         final RuntimeRpc rpc = new RuntimeRpc(
232             SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_FAILED_INVOCATION);
233
234         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
235         final HandlingPriority priority = rpc.canHandle(rpcDocument);
236         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
237
238         try {
239             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
240             fail("should have failed with rpc invocation not implemented yet");
241         } catch (final DocumentedException e) {
242             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
243             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
244             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
245         }
246     }
247
248     @Test
249     public void testVoidInputOutputRpc() throws Exception {
250         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
251
252         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
253         final HandlingPriority priority = rpc.canHandle(rpcDocument);
254         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
255
256         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
257
258         verifyResponse(response, RPC_REPLY_OK);
259     }
260
261     @Test
262     public void testBadNamespaceInRpc() throws Exception {
263         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
264         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
265
266         try {
267             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
268             fail("Should have failed, rpc has bad namespace");
269         } catch (final DocumentedException e) {
270             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
271             assertTrue(e.getErrorTag() == ErrorTag.BAD_ELEMENT);
272             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
273         }
274     }
275
276     private static void verifyResponse(final Document response, final Document template) {
277         final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
278         dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
279         //we care about order so response has to be identical
280         assertTrue(dd.identical());
281     }
282
283     private static RpcDefinition getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
284             final String name) {
285         for (final RpcDefinition rpcDef : module.getRpcs()) {
286             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
287                     && rpcDef.getQName().getLocalName().equals(name)) {
288                 return rpcDef;
289             }
290         }
291
292         return null;
293     }
294 }