Bump upstreams
[netconf.git] / plugins / netconf-server-mdsal / src / test / java / org / opendaylight / netconf / server / mdsal / operations / 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.server.mdsal.operations;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertNotNull;
12 import static org.junit.Assert.assertThrows;
13 import static org.junit.Assert.assertTrue;
14 import static org.mockito.ArgumentMatchers.any;
15 import static org.mockito.Mockito.doAnswer;
16 import static org.mockito.Mockito.doNothing;
17
18 import com.google.common.io.CharSource;
19 import com.google.common.util.concurrent.Futures;
20 import com.google.common.util.concurrent.ListenableFuture;
21 import java.io.IOException;
22 import java.io.Serial;
23 import java.util.Collection;
24 import java.util.List;
25 import java.util.function.Consumer;
26 import javax.xml.parsers.ParserConfigurationException;
27 import org.custommonkey.xmlunit.DetailedDiff;
28 import org.custommonkey.xmlunit.Diff;
29 import org.custommonkey.xmlunit.XMLUnit;
30 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
31 import org.junit.After;
32 import org.junit.AfterClass;
33 import org.junit.Before;
34 import org.junit.BeforeClass;
35 import org.junit.Test;
36 import org.junit.runner.RunWith;
37 import org.mockito.Mock;
38 import org.mockito.junit.MockitoJUnitRunner;
39 import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
40 import org.opendaylight.mdsal.dom.api.DOMRpcException;
41 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
42 import org.opendaylight.mdsal.dom.api.DOMRpcService;
43 import org.opendaylight.mdsal.dom.api.DOMSchemaService;
44 import org.opendaylight.mdsal.dom.api.DOMSchemaService.YangTextSourceExtension;
45 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
46 import org.opendaylight.netconf.api.DocumentedException;
47 import org.opendaylight.netconf.api.xml.XmlUtil;
48 import org.opendaylight.netconf.server.api.operations.HandlingPriority;
49 import org.opendaylight.netconf.server.api.operations.NetconfOperationChainedExecution;
50 import org.opendaylight.netconf.server.mdsal.CurrentSchemaContext;
51 import org.opendaylight.netconf.test.util.XmlFileLoader;
52 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.base._1._0.rev110601.SessionIdType;
53 import org.opendaylight.yangtools.concepts.Registration;
54 import org.opendaylight.yangtools.yang.common.ErrorSeverity;
55 import org.opendaylight.yangtools.yang.common.ErrorTag;
56 import org.opendaylight.yangtools.yang.common.ErrorType;
57 import org.opendaylight.yangtools.yang.common.QName;
58 import org.opendaylight.yangtools.yang.common.Uint32;
59 import org.opendaylight.yangtools.yang.common.XMLNamespace;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
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.impl.schema.Builders;
64 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
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.source.SourceIdentifier;
68 import org.opendaylight.yangtools.yang.model.spi.source.DelegatedYangTextSource;
69 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
70 import org.slf4j.Logger;
71 import org.slf4j.LoggerFactory;
72 import org.w3c.dom.Document;
73 import org.xml.sax.SAXException;
74
75 @RunWith(MockitoJUnitRunner.StrictStubs.class)
76 public class RuntimeRpcTest {
77     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
78     private static final SessionIdType SESSION_ID_FOR_REPORTING = new SessionIdType(Uint32.valueOf(123));
79     private static final Document RPC_REPLY_OK = getReplyOk();
80
81     private static Document getReplyOk() {
82         try {
83             return XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
84         } catch (final IOException | SAXException | ParserConfigurationException e) {
85             LOG.debug("unable to load rpc reply ok.", e);
86             return XmlUtil.newDocument();
87         }
88     }
89
90     private static final DOMRpcService RPC_SERVICE_VOID_INVOKER = new DOMRpcService() {
91         @Override
92         public ListenableFuture<DOMRpcResult> invokeRpc(final QName type, final ContainerNode input) {
93             return Futures.immediateFuture(new DefaultDOMRpcResult(null, List.of()));
94         }
95
96         @Override
97         public Registration registerRpcListener(final DOMRpcAvailabilityListener listener) {
98             return () -> { };
99         }
100     };
101
102     private static final DOMRpcService RPC_SERVICE_FAILED_INVOCATION = new DOMRpcService() {
103         @Override
104         public ListenableFuture<DOMRpcResult> invokeRpc(final QName type, final ContainerNode input) {
105             return Futures.immediateFailedFuture(new DOMRpcException("rpc invocation not implemented yet") {
106                 @Serial
107                 private static final long serialVersionUID = 1L;
108             });
109         }
110
111         @Override
112         public Registration registerRpcListener(final DOMRpcAvailabilityListener listener) {
113             return () -> { };
114         }
115     };
116
117     private final DOMRpcService rpcServiceSuccessfulInvocation = new DOMRpcService() {
118         @Override
119         public ListenableFuture<DOMRpcResult> invokeRpc(final QName type, final ContainerNode input) {
120             final Collection<DataContainerChild> children = input.body();
121             final Module module = SCHEMA_CONTEXT.findModules(type.getNamespace()).stream()
122                 .findFirst().orElse(null);
123             final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(),
124                 type.getLocalName());
125             final ContainerNode node = Builders.containerBuilder()
126                     .withNodeIdentifier(new NodeIdentifier(rpcDefinition.getOutput().getQName()))
127                     .withValue(children)
128                     .build();
129
130             return Futures.immediateFuture(new DefaultDOMRpcResult(node));
131         }
132
133         @Override
134         public Registration registerRpcListener(final DOMRpcAvailabilityListener lsnr) {
135             return () -> { };
136         }
137     };
138
139     private static EffectiveModelContext SCHEMA_CONTEXT = null;
140     private CurrentSchemaContext currentSchemaContext = null;
141
142     @Mock
143     private DOMSchemaService schemaService;
144     @Mock
145     private Consumer<EffectiveModelContext> listener;
146     @Mock
147     private Registration registration;
148     @Mock
149     private YangTextSourceExtension sourceProvider;
150
151     @BeforeClass
152     public static void beforeClass() {
153         SCHEMA_CONTEXT = YangParserTestUtils.parseYangResource("/yang/mdsal-netconf-rpc-test.yang");
154     }
155
156     @AfterClass
157     public static void afterClass() {
158         SCHEMA_CONTEXT = null;
159     }
160
161     @Before
162     public void setUp() throws Exception {
163         doNothing().when(registration).close();
164         doAnswer(invocationOnMock -> {
165             ((Consumer<EffectiveModelContext>) invocationOnMock.getArgument(0)).accept(SCHEMA_CONTEXT);
166             return registration;
167         }).when(schemaService).registerSchemaContextListener(any());
168
169         XMLUnit.setIgnoreWhitespace(true);
170         XMLUnit.setIgnoreAttributeOrder(true);
171
172         doAnswer(invocationOnMock -> Futures.immediateFuture(new DelegatedYangTextSource(
173             invocationOnMock.getArgument(0, SourceIdentifier.class), CharSource.wrap("module test"))))
174             .when(sourceProvider).getYangTexttSource(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         assertNotNull(priority);
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         assertNotNull(priority);
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         assertNotNull(priority);
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         assertNotNull(priority);
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         assertNotNull(priority);
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.toString(), 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 }