684e2e995a77cabab6beacdbb6838bb1c70ce25c
[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.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
16 import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
17
18 import com.google.common.base.Preconditions;
19 import com.google.common.io.ByteSource;
20 import com.google.common.util.concurrent.FluentFuture;
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.DocumentedException.ErrorSeverity;
45 import org.opendaylight.netconf.api.DocumentedException.ErrorTag;
46 import org.opendaylight.netconf.api.DocumentedException.ErrorType;
47 import org.opendaylight.netconf.api.xml.XmlUtil;
48 import org.opendaylight.netconf.mapping.api.HandlingPriority;
49 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
50 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
51 import org.opendaylight.netconf.util.test.XmlFileLoader;
52 import org.opendaylight.yangtools.concepts.ListenerRegistration;
53 import org.opendaylight.yangtools.concepts.NoOpListenerRegistration;
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;
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.api.schema.NormalizedNode;
60 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
61 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
62 import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
63 import org.opendaylight.yangtools.yang.model.api.Module;
64 import org.opendaylight.yangtools.yang.model.api.OutputSchemaNode;
65 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
66 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
67 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
68 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
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 String SESSION_ID_FOR_REPORTING = "netconf-test-session1";
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 FluentFuture<DOMRpcResult> invokeRpc(final QName type, final NormalizedNode input) {
93             return immediateFluentFuture(new DefaultDOMRpcResult(null, List.of()));
94         }
95
96         @Override
97         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T listener) {
98             return NoOpListenerRegistration.of(listener);
99         }
100     };
101
102     private static final DOMRpcService RPC_SERVICE_FAILED_INVOCATION = new DOMRpcService() {
103         @Override
104         public FluentFuture<DOMRpcResult> invokeRpc(final QName type, final NormalizedNode input) {
105             return immediateFailedFluentFuture(new DOMRpcException("rpc invocation not implemented yet") {
106                 private static final long serialVersionUID = 1L;
107             });
108         }
109
110         @Override
111         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T listener) {
112             return NoOpListenerRegistration.of(listener);
113         }
114     };
115
116     private final DOMRpcService rpcServiceSuccessfulInvocation = new DOMRpcService() {
117         @Override
118         public FluentFuture<DOMRpcResult> invokeRpc(final QName type, final NormalizedNode input) {
119             final Collection<DataContainerChild> children = ((ContainerNode) input).body();
120             final Module module = SCHEMA_CONTEXT.findModules(type.getNamespace()).stream()
121                 .findFirst().orElse(null);
122             final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(),
123                 type.getLocalName());
124             final OutputSchemaNode outputSchemaNode = rpcDefinition.getOutput();
125             final ContainerNode node = ImmutableContainerNodeBuilder.create()
126                     .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
127                     .withValue(children).build();
128
129             return immediateFluentFuture(new DefaultDOMRpcResult(node));
130         }
131
132         @Override
133         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(final T lsnr) {
134             return NoOpListenerRegistration.of(lsnr);
135         }
136     };
137
138     private static EffectiveModelContext SCHEMA_CONTEXT = null;
139     private CurrentSchemaContext currentSchemaContext = null;
140
141     @Mock
142     private DOMSchemaService schemaService;
143     @Mock
144     private EffectiveModelContextListener listener;
145     @Mock
146     private ListenerRegistration<?> registration;
147     @Mock
148     private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
149
150     @BeforeClass
151     public static void beforeClass() {
152         SCHEMA_CONTEXT = YangParserTestUtils.parseYangResource("/yang/mdsal-netconf-rpc-test.yang");
153     }
154
155     @AfterClass
156     public static void afterClass() {
157         SCHEMA_CONTEXT = null;
158     }
159
160     @Before
161     public void setUp() throws Exception {
162         doNothing().when(registration).close();
163         doAnswer(invocationOnMock -> {
164             ((EffectiveModelContextListener) invocationOnMock.getArguments()[0]).onModelContextUpdated(SCHEMA_CONTEXT);
165             return registration;
166         }).when(schemaService).registerSchemaContextListener(any(EffectiveModelContextListener.class));
167
168         XMLUnit.setIgnoreWhitespace(true);
169         XMLUnit.setIgnoreAttributeOrder(true);
170
171         doAnswer(invocationOnMock -> {
172             final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
173             final YangTextSchemaSource yangTextSchemaSource =
174                     YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
175             return immediateFluentFuture(yangTextSchemaSource);
176         }).when(sourceProvider).getSource(any(SourceIdentifier.class));
177
178         this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
179     }
180
181     @After
182     public void tearDown() {
183         currentSchemaContext.close();
184     }
185
186     @Test
187     public void testVoidOutputRpc() throws Exception {
188         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
189
190         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
191         final HandlingPriority priority = rpc.canHandle(rpcDocument);
192         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
193
194         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
195
196         verifyResponse(response, RPC_REPLY_OK);
197     }
198
199     @Test
200     public void testSuccesfullNonVoidInvocation() throws Exception {
201         final RuntimeRpc rpc = new RuntimeRpc(
202             SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
203
204         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
205         final HandlingPriority priority = rpc.canHandle(rpcDocument);
206         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
207
208         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
209         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
210     }
211
212     @Test
213     public void testSuccesfullContainerInvocation() throws Exception {
214         final RuntimeRpc rpc = new RuntimeRpc(
215             SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
216
217         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
218         final HandlingPriority priority = rpc.canHandle(rpcDocument);
219         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
220
221         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
222         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
223     }
224
225     @Test
226     public void testFailedInvocation() throws Exception {
227         final RuntimeRpc rpc = new RuntimeRpc(
228             SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_FAILED_INVOCATION);
229
230         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
231         final HandlingPriority priority = rpc.canHandle(rpcDocument);
232         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
233
234         try {
235             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
236             fail("should have failed with rpc invocation not implemented yet");
237         } catch (final DocumentedException e) {
238             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
239             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
240             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
241         }
242     }
243
244     @Test
245     public void testVoidInputOutputRpc() throws Exception {
246         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
247
248         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
249         final HandlingPriority priority = rpc.canHandle(rpcDocument);
250         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
251
252         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
253
254         verifyResponse(response, RPC_REPLY_OK);
255     }
256
257     @Test
258     public void testBadNamespaceInRpc() throws Exception {
259         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
260         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
261
262         try {
263             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
264             fail("Should have failed, rpc has bad namespace");
265         } catch (final DocumentedException e) {
266             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
267             assertTrue(e.getErrorTag() == ErrorTag.BAD_ELEMENT);
268             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
269         }
270     }
271
272     private static void verifyResponse(final Document response, final Document template) {
273         final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
274         dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
275         //we care about order so response has to be identical
276         assertTrue(dd.identical());
277     }
278
279     private static RpcDefinition getRpcDefinitionFromModule(final Module module, final XMLNamespace namespaceURI,
280             final String name) {
281         for (final RpcDefinition rpcDef : module.getRpcs()) {
282             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
283                     && rpcDef.getQName().getLocalName().equals(name)) {
284                 return rpcDef;
285             }
286         }
287
288         return null;
289     }
290 }