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