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