Merge "Migrate restconf to mockito ArgumentMatchers"
[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.mdsal.dom.api.DOMSchemaService;
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.findModules(type.getLastComponent().getNamespace()).stream()
130                 .findFirst().orElse(null);
131             final RpcDefinition rpcDefinition = getRpcDefinitionFromModule(
132                 module, module.getNamespace(), type.getLastComponent().getLocalName());
133             final ContainerSchemaNode outputSchemaNode = rpcDefinition.getOutput();
134             final ContainerNode node = ImmutableContainerNodeBuilder.create()
135                     .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(outputSchemaNode.getQName()))
136                     .withValue(children).build();
137
138             return Futures.immediateCheckedFuture(new DefaultDOMRpcResult(node));
139         }
140
141         @Nonnull
142         @Override
143         public <T extends DOMRpcAvailabilityListener> ListenerRegistration<T> registerRpcListener(
144                 @Nonnull final T lsnr) {
145             return null;
146         }
147     };
148
149     private SchemaContext schemaContext = null;
150     private CurrentSchemaContext currentSchemaContext = null;
151
152     @Mock
153     private DOMSchemaService schemaService;
154     @Mock
155     private SchemaContextListener listener;
156     @Mock
157     private ListenerRegistration<?> registration;
158     @Mock
159     private SchemaSourceProvider<YangTextSchemaSource> sourceProvider;
160
161     @Before
162     public void setUp() throws Exception {
163         initMocks(this);
164         doNothing().when(registration).close();
165         doReturn(listener).when(registration).getInstance();
166         doReturn(schemaContext).when(schemaService).getGlobalContext();
167         doReturn(schemaContext).when(schemaService).getSessionContext();
168         doAnswer(invocationOnMock -> {
169             ((SchemaContextListener) invocationOnMock.getArguments()[0]).onGlobalContextUpdated(schemaContext);
170             return registration;
171         }).when(schemaService).registerSchemaContextListener(any(SchemaContextListener.class));
172
173         XMLUnit.setIgnoreWhitespace(true);
174         XMLUnit.setIgnoreAttributeOrder(true);
175
176         doAnswer(invocationOnMock -> {
177             final SourceIdentifier sId = (SourceIdentifier) invocationOnMock.getArguments()[0];
178             final YangTextSchemaSource yangTextSchemaSource =
179                     YangTextSchemaSource.delegateForByteSource(sId, ByteSource.wrap("module test".getBytes()));
180             return Futures.immediateCheckedFuture(yangTextSchemaSource);
181
182         }).when(sourceProvider).getSource(any(SourceIdentifier.class));
183
184         this.schemaContext = YangParserTestUtils.parseYangResource("/yang/mdsal-netconf-rpc-test.yang");
185         this.currentSchemaContext = new CurrentSchemaContext(schemaService, sourceProvider);
186     }
187
188     @Test
189     public void testVoidOutputRpc() throws Exception {
190         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
191
192         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-output.xml");
193         final HandlingPriority priority = rpc.canHandle(rpcDocument);
194         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
195
196         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
197
198         verifyResponse(response, RPC_REPLY_OK);
199     }
200
201     @Test
202     public void testSuccesfullNonVoidInvocation() throws Exception {
203         final RuntimeRpc rpc = new RuntimeRpc(
204             SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
205
206         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
207         final HandlingPriority priority = rpc.canHandle(rpcDocument);
208         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
209
210         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
211         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid-control.xml"));
212     }
213
214     @Test
215     public void testSuccesfullContainerInvocation() throws Exception {
216         final RuntimeRpc rpc = new RuntimeRpc(
217             SESSION_ID_FOR_REPORTING, currentSchemaContext, rpcServiceSuccessfulInvocation);
218
219         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container.xml");
220         final HandlingPriority priority = rpc.canHandle(rpcDocument);
221         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
222
223         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
224         verifyResponse(response, XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-container-control.xml"));
225     }
226
227     @Test
228     public void testFailedInvocation() throws Exception {
229         final RuntimeRpc rpc = new RuntimeRpc(
230             SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_FAILED_INVOCATION);
231
232         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-nonvoid.xml");
233         final HandlingPriority priority = rpc.canHandle(rpcDocument);
234         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
235
236         try {
237             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
238             fail("should have failed with rpc invocation not implemented yet");
239         } catch (final DocumentedException e) {
240             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
241             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
242             assertTrue(e.getErrorTag() == ErrorTag.OPERATION_FAILED);
243         }
244     }
245
246     @Test
247     public void testVoidInputOutputRpc() throws Exception {
248         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
249
250         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-void-input-output.xml");
251         final HandlingPriority priority = rpc.canHandle(rpcDocument);
252         Preconditions.checkState(priority != HandlingPriority.CANNOT_HANDLE);
253
254         final Document response = rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
255
256         verifyResponse(response, RPC_REPLY_OK);
257     }
258
259     @Test
260     public void testBadNamespaceInRpc() throws Exception {
261         final RuntimeRpc rpc = new RuntimeRpc(SESSION_ID_FOR_REPORTING, currentSchemaContext, RPC_SERVICE_VOID_INVOKER);
262         final Document rpcDocument = XmlFileLoader.xmlFileToDocument("messages/mapping/rpcs/rpc-bad-namespace.xml");
263
264         try {
265             rpc.handle(rpcDocument, NetconfOperationChainedExecution.EXECUTION_TERMINATION_POINT);
266             fail("Should have failed, rpc has bad namespace");
267         } catch (final DocumentedException e) {
268             assertTrue(e.getErrorSeverity() == ErrorSeverity.ERROR);
269             assertTrue(e.getErrorTag() == ErrorTag.BAD_ELEMENT);
270             assertTrue(e.getErrorType() == ErrorType.APPLICATION);
271         }
272     }
273
274     private static void verifyResponse(final Document response, final Document template) {
275         final DetailedDiff dd = new DetailedDiff(new Diff(response, template));
276         dd.overrideElementQualifier(new RecursiveElementNameAndTextQualifier());
277         //we care about order so response has to be identical
278         assertTrue(dd.identical());
279     }
280
281     private static RpcDefinition getRpcDefinitionFromModule(final Module module, final URI namespaceURI,
282             final String name) {
283         for (final RpcDefinition rpcDef : module.getRpcs()) {
284             if (rpcDef.getQName().getNamespace().equals(namespaceURI)
285                     && rpcDef.getQName().getLocalName().equals(name)) {
286                 return rpcDef;
287             }
288         }
289
290         return null;
291     }
292 }