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