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