Add 'features/protocol-framework/' from commit 'cb42405784db97d0ce2c5991d12a89b46d185949'
[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
9 package org.opendaylight.netconf.mdsal.connector.ops;
10
11 import static org.junit.Assert.assertTrue;
12 import static org.junit.Assert.fail;
13 import static org.mockito.Matchers.any;
14 import static org.mockito.Mockito.doAnswer;
15 import static org.mockito.Mockito.doNothing;
16 import static org.mockito.Mockito.doReturn;
17 import static org.mockito.MockitoAnnotations.initMocks;
18
19 import com.google.common.base.Preconditions;
20 import com.google.common.io.ByteSource;
21 import com.google.common.util.concurrent.CheckedFuture;
22 import com.google.common.util.concurrent.Futures;
23 import java.io.InputStream;
24 import java.net.URI;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.Collections;
28 import java.util.List;
29 import javax.annotation.Nonnull;
30 import javax.annotation.Nullable;
31 import org.custommonkey.xmlunit.DetailedDiff;
32 import org.custommonkey.xmlunit.Diff;
33 import org.custommonkey.xmlunit.XMLUnit;
34 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
35 import org.junit.Before;
36 import org.junit.Test;
37 import org.mockito.Mock;
38 import org.opendaylight.controller.config.util.xml.DocumentedException;
39 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
40 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
41 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
42 import org.opendaylight.controller.config.util.xml.XmlUtil;
43 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
44 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
45 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
46 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
47 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
48 import org.opendaylight.controller.sal.core.api.model.SchemaService;
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.yang.data.api.YangInstanceIdentifier;
55 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
56 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
57 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
58 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
59 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
60 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
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.SchemaContext;
64 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
65 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
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
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 = RuntimeRpcTest.getReplyOk();
78
79     @SuppressWarnings("illegalCatch")
80     private static Document getReplyOk() {
81         Document doc;
82         try {
83             doc = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
84         } catch (final Exception e) {
85             LOG.debug("unable to load rpc reply ok.", e);
86             doc = XmlUtil.newDocument();
87         }
88         return doc;
89     }
90
91     private final DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
92         @Nonnull
93         @Override
94         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
95                 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
96             return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(null, Collections.emptyList()));
97         }
98
99         @Nonnull
100         @Override
101         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
102                 @Nonnull final T listener) {
103             return null;
104         }
105     };
106
107     private final DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
108         @Nonnull
109         @Override
110         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
111                 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
112             return Futures.immediateFailedCheckedFuture(new DOMRpcException("rpc invocation not implemented yet") {
113                 private static final long serialVersionUID = 1L;
114             });
115         }
116
117         @Nonnull
118         @Override
119         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
120                 @Nonnull final T listener) {
121             return null;
122         }
123     };
124
125     private final DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
126         @Nonnull
127         @Override
128         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(
129                 @Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
130             final Collection<DataContainerChild<? extends PathArgument, ?>> children =
131                     (Collection<DataContainerChild<? extends PathArgument, ?>>) input.getValue();
132             final Module module = schemaContext.findModuleByNamespaceAndRevision(
133                 type.getLastComponent().getNamespace(), null);
134             final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(
135                 module, module.getNamespace(), type.getLastComponent().getLocalName());
136             final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
137             final ContainerNode node = ImmutableContainerNodeBuilder.create()
138                     .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
139                     .withValue(children).build();
140
141             return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(node));
142         }
143
144         @Nonnull
145         @Override
146         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
147                 @Nonnull final T listener) {
148             return null;
149         }
150     };
151
152     private SchemaContext schemaContext = null;
153     private CurrentSchemaContext currentSchemaContext = null;
154
155     @Mock
156     private SchemaService schemaService;
157     @Mock
158     private SchemaContextListener listener;
159     @Mock
160     private ListenerRegistration<?> registration;
161     @Mock
162     private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
163
164     @Before
165     public void setUp() throws Exception {
166         initMocks(this);
167         doNothing().when(registration).close();
168         doReturn(listener).when(registration).getInstance();
169         doNothing().when(schemaService).addModule(any(Module.class));
170         doNothing().when(schemaService).removeModule(any(Module.class));
171         doReturn(schemaContext).when(schemaService).getGlobalContext();
172         doReturn(schemaContext).when(schemaService).getSessionContext();
173         doAnswer(invocationOnMock -> {
174             ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
175             return registration;
176         }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
177
178         XMLUnit.setIgnoreWhitespace(true);
179         XMLUnit.setIgnoreAttributeOrder(true);
180
181         doAnswer(invocationOnMock -> {
182             final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
183             final YangTextSchemaSource yangTextSchemaSource =
184                     YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
185             return Futures.immediateCheckedFuture(yangTextSchemaSource);
186
187         }).when(sourceProvider).getSource(any(SourceIdentifier.class));
188
189         this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
190         this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
191     }
192
193     @Test
194     public void testVoidOutputRpc() throws Exception {
195         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
196
197         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
198         final HandlingPriority priority = rpc.canHandle(rpcDocument);
199         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
200
201         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
202
203         verifyResponse(response, RPC_REPLY_OK);
204     }
205
206     @Test
207     public void testSuccesfullNonVoidInvocation() throws Exception {
208         final RuntimeRpc rpc = new RuntimeRpc(
209             SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation);
210
211         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
212         final HandlingPriority priority = rpc.canHandle(rpcDocument);
213         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
214
215         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
216         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
217     }
218
219     @Test
220     public void testSuccesfullContainerInvocation() throws Exception {
221         final RuntimeRpc rpc = new RuntimeRpc(
222             SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccesfullInvocation);
223
224         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
225         final HandlingPriority priority = rpc.canHandle(rpcDocument);
226         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
227
228         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
229         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
230     }
231
232     @Test
233     public void testFailedInvocation() throws Exception {
234         final RuntimeRpc rpc = new RuntimeRpc(
235             SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceFailedInvocation);
236
237         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
238         final HandlingPriority priority = rpc.canHandle(rpcDocument);
239         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
240
241         try {
242             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
243             fail("should have failed with rpc invocation not implemented yet");
244         } catch (final DocumentedException e) {
245             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
246             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
247             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
248         }
249     }
250
251     @Test
252     public void testVoidInputOutputRpc() throws Exception {
253         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
254
255         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
256         final HandlingPriority priority = rpc.canHandle(rpcDocument);
257         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
258
259         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
260
261         verifyResponse(response, RPC_REPLY_OK);
262     }
263
264     @Test
265     public void testBadNamespaceInRpc() throws Exception {
266         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceVoidInvoke);
267         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
268
269         try {
270             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
271             fail("Should have failed, rpc has bad namespace");
272         } catch (final DocumentedException e) {
273             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
274             assertTrue(e.getErrorTag() == ErrorTag.BAD_ELEMENT);
275             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
276         }
277     }
278
279     private static void verifyResponse(final Document response, final Document template) {
280         final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
281         dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
282         //we care about order so response has to be identical
283         assertTrue(dd.identical());
284     }
285
286     private static RpcDefinition getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
287             final String name) {
288         for (final RpcDefinition rpcDef : module.getRpcs()) {
289             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
290                     && rpcDef.getQName().getLocalName().equals(name)) {
291                 return rpcDef;
292             }
293         }
294
295         return null;
296     }
297
298     private List<InputStream> getYangSchemas() {
299         final List<String> schemaPaths = Collections.singletonList("/yang/mdsal-netconf-rpc-test.yang");
300         final List<InputStream> schemas = new ArrayList<>();
301
302         for (final String schemaPath : schemaPaths) {
303             final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
304             schemas.add(resourceAsStream);
305         }
306
307         return schemas;
308     }
309 }