Fix yang source provisioning from MD-SAL netconf northbound
[netconf.git] / opendaylight / 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.IOException;
24 import java.io.InputStream;
25 import java.net.URI;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.Collection;
29 import java.util.Collections;
30 import java.util.List;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import javax.xml.transform.TransformerException;
34 import org.custommonkey.xmlunit.DetailedDiff;
35 import org.custommonkey.xmlunit.Diff;
36 import org.custommonkey.xmlunit.XMLUnit;
37 import org.custommonkey.xmlunit.examples.RecursiveElementNameAndTextQualifier;
38 import org.junit.Before;
39 import org.junit.Test;
40 import org.mockito.Mock;
41 import org.mockito.invocation.InvocationOnMock;
42 import org.mockito.stubbing.Answer;
43 import org.opendaylight.controller.config.util.xml.DocumentedException;
44 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorSeverity;
45 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorTag;
46 import org.opendaylight.controller.config.util.xml.DocumentedException.ErrorType;
47 import org.opendaylight.controller.config.util.xml.XmlUtil;
48 import org.opendaylight.controller.md.sal.dom.api.DOMRpcAvailabilityListener;
49 import org.opendaylight.controller.md.sal.dom.api.DOMRpcException;
50 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
51 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
52 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
53 import org.opendaylight.controller.sal.core.api.model.SchemaService;
54 import org.opendaylight.netconf.mapping.api.HandlingPriority;
55 import org.opendaylight.netconf.mapping.api.NetconfOperationChainedExecution;
56 import org.opendaylight.netconf.mdsal.connector.CurrentSchemaContext;
57 import org.opendaylight.netconf.util.test.XmlFileLoader;
58 import org.opendaylight.yangtools.concepts.ListenerRegistration;
59 import org.opendaylight.yangtools.yang.common.RpcError;
60 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.api.schema.NormalizedNode;
64 import org.opendaylight.yangtools.yang.data.impl.schema.builder.impl.ImmutableContainerNodeBuilder;
65 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.Module;
67 import org.opendaylight.yangtools.yang.model.api.RpcDefinition;
68 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
70 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
71 import org.opendaylight.yangtools.yang.model.parser.api.YangSyntaxErrorException;
72 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
73 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
74 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
75 import org.opendaylight.yangtools.yang.parser.builder.impl.BuilderUtils;
76 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79 import org.w3c.dom.Document;
80
81 public class RuntimeRpcTest {
82
83     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
84
85     private String sessionIdForReporting = "netconf-test-session1";
86
87     private static Document RPC_REPLY_OK = null;
88
89     static {
90         try {
91             RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
92         } catch (Exception e) {
93             LOG.debug("unable to load rpc reply ok.", e);
94             RPC_REPLY_OK = XmlUtil.newDocument();
95         }
96     }
97
98     private DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
99         @Nonnull
100         @Override
101         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
102             return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(null, Collections.<RpcError>emptyList()));
103         }
104
105         @Nonnull
106         @Override
107         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
108             return null;
109         }
110     };
111
112     private DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
113         @Nonnull
114         @Override
115         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
116             return Futures.immediateFailedCheckedFuture((DOMRpcException) new DOMRpcException("rpc invocation not implemented yet") {
117             });
118         }
119
120         @Nonnull
121         @Override
122         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
123             return null;
124         }
125     };
126
127     private DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
128         @Nonnull
129         @Override
130         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
131             Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> children = (Collection) input.getValue();
132             Module module = schemaContext.findModuleByNamespaceAndRevision(type.getLastComponent().getNamespace(), null);
133             RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(), type.getLastComponent().getLocalName());
134             ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
135             ContainerNode node = ImmutableContainerNodeBuilder.create()
136                     .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
137                     .withValue(children).build();
138
139             return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(node));
140         }
141
142         @Nonnull
143         @Override
144         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
145             return null;
146         }
147     };
148
149     private SchemaContext schemaContext = null;
150     private CurrentSchemaContext currentSchemaContext = null;
151     @Mock
152     private SchemaService schemaService;
153     @Mock
154     private SchemaContextListener listener;
155     @Mock
156     private ListenerRegistration registration;
157     @Mock
158     private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
159
160     @Before
161     public void setUp() throws Exception {
162
163         initMocks(this);
164         doNothing().when(registration).close();
165         doReturn(listener).when(registration).getInstance();
166         doNothing().when(schemaService).addModule(any(Module.class));
167         doNothing().when(schemaService).removeModule(any(Module.class));
168         doReturn(schemaContext).when(schemaService).getGlobalContext();
169         doReturn(schemaContext).when(schemaService).getSessionContext();
170         doAnswer(new Answer() {
171             @Override
172             public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
173                 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
174                 return registration;
175             }
176         }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
177
178         XMLUnit.setIgnoreWhitespace(true);
179         XMLUnit.setIgnoreAttributeOrder(true);
180
181         doAnswer(new Answer() {
182             @Override
183             public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
184                 final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
185                 final YangTextSchemaSource yangTextSchemaSource =
186                         YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
187                 return Futures.immediateCheckedFuture(yangTextSchemaSource);
188
189             }
190         }).when(sourceProvider).getSource(any(SourceIdentifier.class));
191
192         this.schemaContext = parseSchemas(getYangSchemas());
193         this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
194     }
195
196     @Test
197     public void testVoidOutputRpc() throws Exception {
198         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
199
200         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
201         HandlingPriority priority = rpc.canHandle(rpcDocument);
202         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
203
204         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
205
206         verifyResponse(response, RPC_REPLY_OK);
207     }
208
209     @Test
210     public void testSuccesfullNonVoidInvocation() throws Exception {
211         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
212
213         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
214         HandlingPriority priority = rpc.canHandle(rpcDocument);
215         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
216
217         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
218         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
219     }
220
221     @Test
222     public void testSuccesfullContainerInvocation() throws Exception {
223         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
224
225         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
226         HandlingPriority priority = rpc.canHandle(rpcDocument);
227         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
228
229         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
230         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
231     }
232
233     @Test
234     public void testFailedInvocation() throws Exception {
235         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceFailedInvocation);
236
237         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
238         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 (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         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
254
255         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
256         HandlingPriority priority = rpc.canHandle(rpcDocument);
257         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
258
259         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         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
267         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 (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 void verifyResponse(Document response, Document template) throws IOException, TransformerException {
280         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 RpcDefinition getRpcDefinitionFromModule(Module module, URI namespaceURI, String name) {
287         for (RpcDefinition rpcDef : module.getRpcs()) {
288             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
289                     && rpcDef.getQName().getLocalName().equals(name)) {
290                 return rpcDef;
291             }
292         }
293
294         return null;
295
296     }
297
298     private Collection<InputStream> getYangSchemas() {
299         final List<String> schemaPaths = Arrays.asList("/yang/mdsal-netconf-rpc-test.yang");
300         final List<InputStream> schemas = new ArrayList<>();
301
302         for (String schemaPath : schemaPaths) {
303             InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
304             schemas.add(resourceAsStream);
305         }
306
307         return schemas;
308     }
309
310     private SchemaContext parseSchemas(Collection<InputStream> schemas) throws IOException, YangSyntaxErrorException {
311         final YangParserImpl parser = new YangParserImpl();
312         Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(schemas);
313         return parser.parseSources(sources);
314     }
315 }