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