Bug 7432 - eliminate use of yang-parser-impl internals
[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.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.repo.api.SourceIdentifier;
72 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
73 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
74 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
75 import org.slf4j.Logger;
76 import org.slf4j.LoggerFactory;
77 import org.w3c.dom.Document;
78
79 public class RuntimeRpcTest {
80
81     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
82
83     private final String sessionIdForReporting = "netconf-test-session1";
84
85     private static Document RPC_REPLY_OK = null;
86
87     static {
88         try {
89             RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
90         } catch (final Exception e) {
91             LOG.debug("unable to load rpc reply ok.", e);
92             RPC_REPLY_OK = XmlUtil.newDocument();
93         }
94     }
95
96     private final DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
97         @Nonnull
98         @Override
99         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
100             return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(null, Collections.<RpcError>emptyList()));
101         }
102
103         @Nonnull
104         @Override
105         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
106             return null;
107         }
108     };
109
110     private final DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
111         @Nonnull
112         @Override
113         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
114             return Futures.immediateFailedCheckedFuture((DOMRpcException) new DOMRpcException("rpc invocation not implemented yet") {
115             });
116         }
117
118         @Nonnull
119         @Override
120         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@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(@Nonnull final SchemaPath type, @Nullable final NormalizedNode<?, ?> input) {
129             final Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> children = (Collection) input.getValue();
130             final Module module = schemaContext.findModuleByNamespaceAndRevision(type.getLastComponent().getNamespace(), null);
131             final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(), type.getLastComponent().getLocalName());
132             final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
133             final ContainerNode node = ImmutableContainerNodeBuilder.create()
134                     .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
135                     .withValue(children).build();
136
137             return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(node));
138         }
139
140         @Nonnull
141         @Override
142         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull final T listener) {
143             return null;
144         }
145     };
146
147     private SchemaContext schemaContext = null;
148     private CurrentSchemaContext currentSchemaContext = null;
149     @Mock
150     private SchemaService schemaService;
151     @Mock
152     private SchemaContextListener listener;
153     @Mock
154     private ListenerRegistration registration;
155     @Mock
156     private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
157
158     @Before
159     public void setUp() throws Exception {
160
161         initMocks(this);
162         doNothing().when(registration).close();
163         doReturn(listener).when(registration).getInstance();
164         doNothing().when(schemaService).addModule(any(Module.class));
165         doNothing().when(schemaService).removeModule(any(Module.class));
166         doReturn(schemaContext).when(schemaService).getGlobalContext();
167         doReturn(schemaContext).when(schemaService).getSessionContext();
168         doAnswer(new Answer() {
169             @Override
170             public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
171                 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
172                 return registration;
173             }
174         }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
175
176         XMLUnit.setIgnoreWhitespace(true);
177         XMLUnit.setIgnoreAttributeOrder(true);
178
179         doAnswer(new Answer() {
180             @Override
181             public Object answer(final InvocationOnMock invocationOnMock) throws Throwable {
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             }
188         }).when(sourceProvider).getSource(any(SourceIdentifier.class));
189
190         this.schemaContext = YangParserTestUtils.parseYangStreams(getYangSchemas());
191         this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
192     }
193
194     @Test
195     public void testVoidOutputRpc() throws Exception {
196         final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
197
198         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
199         final HandlingPriority priority = rpc.canHandle(rpcDocument);
200         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
201
202         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
203
204         verifyResponse(response, RPC_REPLY_OK);
205     }
206
207     @Test
208     public void testSuccesfullNonVoidInvocation() throws Exception {
209         final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, 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(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
222
223         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
224         final HandlingPriority priority = rpc.canHandle(rpcDocument);
225         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
226
227         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
228         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
229     }
230
231     @Test
232     public void testFailedInvocation() throws Exception {
233         final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceFailedInvocation);
234
235         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
236         final HandlingPriority priority = rpc.canHandle(rpcDocument);
237         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
238
239         try {
240             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
241             fail("should have failed with rpc invocation not implemented yet");
242         } catch (final DocumentedException e) {
243             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
244             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
245             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
246         }
247     }
248
249     @Test
250     public void testVoidInputOutputRpc() throws Exception {
251         final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
252
253         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
254         final HandlingPriority priority = rpc.canHandle(rpcDocument);
255         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
256
257         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
258
259         verifyResponse(response, RPC_REPLY_OK);
260     }
261
262     @Test
263     public void testBadNamespaceInRpc() throws Exception {
264         final RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
265         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
266
267         try {
268             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
269             fail("Should have failed, rpc has bad namespace");
270         } catch (final DocumentedException e) {
271             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
272             assertTrue(e.getErrorTag() == ErrorTag.BAD_ELEMENT);
273             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
274         }
275     }
276
277     private void verifyResponse(final Document response, final Document template) throws IOException, TransformerException {
278         final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
279         dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
280         //we care about order so response has to be identical
281         assertTrue(dd.identical());
282     }
283
284     private RpcDefinition getRpcDefinitionFromModule(final Module module, final URI namespaceURI, final String name) {
285         for (final RpcDefinition rpcDef : module.getRpcs()) {
286             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
287                     && rpcDef.getQName().getLocalName().equals(name)) {
288                 return rpcDef;
289             }
290         }
291
292         return null;
293
294     }
295
296     private List<InputStream> getYangSchemas() {
297         final List<String> schemaPaths = Arrays.asList("/yang/mdsal-netconf-rpc-test.yang");
298         final List<InputStream> schemas = new ArrayList<>();
299
300         for (final String schemaPath : schemaPaths) {
301             final InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
302             schemas.add(resourceAsStream);
303         }
304
305         return schemas;
306     }
307 }