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