BUG 1848 : Use OrderedNormalizedNodeWriter in rpc transformation.
[controller.git] / opendaylight / netconf / mdsal-netconf-connector / src / test / java / org / opendaylight / controller / 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.controller.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.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.netconf.api.NetconfDocumentedException;
49 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorSeverity;
50 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorTag;
51 import org.opendaylight.controller.netconf.api.NetconfDocumentedException.ErrorType;
52 import org.opendaylight.controller.netconf.mapping.api.HandlingPriority;
53 import org.opendaylight.controller.netconf.mapping.api.NetconfOperationChainedExecution;
54 import org.opendaylight.controller.netconf.mdsal.connector.CurrentSchemaContext;
55 import org.opendaylight.controller.netconf.util.test.XmlFileLoader;
56 import org.opendaylight.controller.netconf.util.xml.XmlUtil;
57 import org.opendaylight.controller.sal.core.api.model.SchemaService;
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.parser.builder.impl.BuilderUtils;
73 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
74 import org.slf4j.Logger;
75 import org.slf4j.LoggerFactory;
76 import org.w3c.dom.Document;
77
78 public class RuntimeRpcTest {
79
80     private static final Logger LOG = LoggerFactory.getLogger(RuntimeRpcTest.class);
81
82     private String sessionIdForReporting = "netconf-test-session1";
83
84     private static Document RPC_REPLY_OK = null;
85
86     static {
87         try {
88             RPC_REPLY_OK = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/runtimerpc-ok-reply.xml");
89         } catch (Exception e) {
90             LOG.debug("unable to load rpc reply ok.", e);
91             RPC_REPLY_OK = XmlUtil.newDocument();
92         }
93     }
94
95     private DOMRpcService rpcServiceVoidInvoke = new DOMRpcService() {
96         @Nonnull
97         @Override
98         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
99             return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(null, Collections.<RpcError>emptyList()));
100         }
101
102         @Nonnull
103         @Override
104         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
105             return null;
106         }
107     };
108
109     private DOMRpcService rpcServiceFailedInvocation = new DOMRpcService() {
110         @Nonnull
111         @Override
112         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
113             return Futures.immediateFailedCheckedFuture((DOMRpcException) new DOMRpcException("rpc invocation not implemented yet") {
114             });
115         }
116
117         @Nonnull
118         @Override
119         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
120             return null;
121         }
122     };
123
124     private DOMRpcService rpcServiceSuccesfullInvocation = new DOMRpcService() {
125         @Nonnull
126         @Override
127         public CheckedFuture<DOMRpcResult, DOMRpcException> invokeRpc(@Nonnull SchemaPath type, @Nullable NormalizedNode<?, ?> input) {
128             Collection<DataContainerChild<? extends YangInstanceIdentifier.PathArgument, ?>> children = (Collection) input.getValue();
129             Module module = schemaContext.findModuleByNamespaceAndRevision(type.getLastComponent().getNamespace(), null);
130             RpcDefinition rpcDefinition = getRpcDefinitionFromModule(module, module.getNamespace(), type.getLastComponent().getLocalName());
131             ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
132             ContainerNode node = ImmutableContainerNodeBuilder.create()
133                     .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
134                     .withValue(children).build();
135
136             return Futures.immediateCheckedFuture((DOMRpcResult) new DefaultDOMRpcResult(node));
137         }
138
139         @Nonnull
140         @Override
141         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(@Nonnull T listener) {
142             return null;
143         }
144     };
145
146     private SchemaContext schemaContext = null;
147     private CurrentSchemaContext currentSchemaContext = null;
148     @Mock
149     private SchemaService schemaService;
150     @Mock
151     private SchemaContextListener listener;
152     @Mock
153     private ListenerRegistration registration;
154
155     @Before
156     public void setUp() throws Exception {
157
158         initMocks(this);
159         doNothing().when(registration).close();
160         doReturn(listener).when(registration).getInstance();
161         doNothing().when(schemaService).addModule(any(Module.class));
162         doNothing().when(schemaService).removeModule(any(Module.class));
163         doReturn(schemaContext).when(schemaService).getGlobalContext();
164         doReturn(schemaContext).when(schemaService).getSessionContext();
165         doAnswer(new Answer() {
166             @Override
167             public Object answer(InvocationOnMock invocationOnMock) throws Throwable {
168                 ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
169                 return registration;
170             }
171         }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
172
173         XMLUnit.setIgnoreWhitespace(true);
174         XMLUnit.setIgnoreAttributeOrder(true);
175
176         this.schemaContext = parseSchemas(getYangSchemas());
177         this.currentSchemaContext = new CurrentSchemaContext(schemaService);
178     }
179
180     @Test
181     public void testVoidOutputRpc() throws Exception {
182         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
183
184         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
185         HandlingPriority priority = rpc.canHandle(rpcDocument);
186         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
187
188         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
189
190         verifyResponse(response, RPC_REPLY_OK);
191     }
192
193     @Test
194     public void testSuccesfullNonVoidInvocation() throws Exception {
195         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
196
197         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
198         HandlingPriority priority = rpc.canHandle(rpcDocument);
199         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
200
201         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
202         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
203     }
204
205     @Test
206     public void testSuccesfullContainerInvocation() throws Exception {
207         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceSuccesfullInvocation);
208
209         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
210         HandlingPriority priority = rpc.canHandle(rpcDocument);
211         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
212
213         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
214         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
215     }
216
217     @Test
218     public void testFailedInvocation() throws Exception {
219         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceFailedInvocation);
220
221         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
222         HandlingPriority priority = rpc.canHandle(rpcDocument);
223         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
224
225         try {
226             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
227             fail("should have failed with rpc invocation not implemented yet");
228         } catch (NetconfDocumentedException e) {
229             assertTrue(e.getErrorType() == ErrorType.application);
230             assertTrue(e.getErrorSeverity() == ErrorSeverity.error);
231             assertTrue(e.getErrorTag() == ErrorTag.operation_failed);
232         }
233     }
234
235     @Test
236     public void testVoidInputOutputRpc() throws Exception {
237         RuntimeRpc rpc = new RuntimeRpc(sessionIdForReporting, currentSchemaContext, rpcServiceVoidInvoke);
238
239         Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
240         HandlingPriority priority = rpc.canHandle(rpcDocument);
241         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
242
243         Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
244
245         verifyResponse(response, RPC_REPLY_OK);
246     }
247
248     private void verifyResponse(Document response, Document template) throws IOException, TransformerException {
249         DetailedDiff dd = new DetailedDiff(new Diff(response, template));
250         dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
251         //we care about order so response has to be identical
252         assertTrue(dd.identical());
253     }
254
255     private RpcDefinition getRpcDefinitionFromModule(Module module, URI namespaceURI, String name) {
256         for (RpcDefinition rpcDef : module.getRpcs()) {
257             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
258                     && rpcDef.getQName().getLocalName().equals(name)) {
259                 return rpcDef;
260             }
261         }
262
263         return null;
264
265     }
266
267     private Collection<InputStream> getYangSchemas() {
268         final List<String> schemaPaths = Arrays.asList("/yang/mdsal-netconf-rpc-test.yang");
269         final List<InputStream> schemas = new ArrayList<>();
270
271         for (String schemaPath : schemaPaths) {
272             InputStream resourceAsStream = getClass().getResourceAsStream(schemaPath);
273             schemas.add(resourceAsStream);
274         }
275
276         return schemas;
277     }
278
279     private SchemaContext parseSchemas(Collection<InputStream> schemas) throws IOException, YangSyntaxErrorException {
280         final YangParserImpl parser = new YangParserImpl();
281         Collection<ByteSource> sources = BuilderUtils.streamsToByteSources(schemas);
282         return parser.parseSources(sources);
283     }
284 }