BUG-2310 - widen yang model for netconf-node.
[controller.git] / opendaylight / md-sal / sal-netconf-connector / src / test / java / org / opendaylight / controller / sal / connect / netconf / NetconfDeviceTest.java
1 /*
2  * Copyright (c) 2014 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 package org.opendaylight.controller.sal.connect.netconf;
9
10 import static org.mockito.Matchers.any;
11 import static org.mockito.Matchers.anyCollectionOf;
12 import static org.mockito.Matchers.anyString;
13 import static org.mockito.Mockito.doAnswer;
14 import static org.mockito.Mockito.doNothing;
15 import static org.mockito.Mockito.doReturn;
16 import static org.mockito.Mockito.mock;
17 import static org.mockito.Mockito.timeout;
18 import static org.mockito.Mockito.times;
19 import static org.mockito.Mockito.verify;
20
21 import com.google.common.base.Optional;
22 import com.google.common.collect.HashMultimap;
23 import com.google.common.collect.Lists;
24 import com.google.common.util.concurrent.Futures;
25 import java.io.InputStream;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.List;
30 import java.util.Set;
31 import java.util.concurrent.ExecutorService;
32 import java.util.concurrent.Executors;
33 import org.junit.Test;
34 import org.mockito.Mockito;
35 import org.mockito.invocation.InvocationOnMock;
36 import org.mockito.stubbing.Answer;
37 import org.opendaylight.controller.netconf.api.NetconfMessage;
38 import org.opendaylight.controller.netconf.api.xml.XmlNetconfConstants;
39 import org.opendaylight.controller.sal.connect.api.MessageTransformer;
40 import org.opendaylight.controller.sal.connect.api.RemoteDeviceCommunicator;
41 import org.opendaylight.controller.sal.connect.api.RemoteDeviceHandler;
42 import org.opendaylight.controller.sal.connect.api.SchemaSourceProviderFactory;
43 import org.opendaylight.controller.sal.connect.netconf.listener.NetconfSessionPreferences;
44 import org.opendaylight.controller.sal.connect.netconf.sal.NetconfDeviceRpc;
45 import org.opendaylight.controller.sal.connect.netconf.util.NetconfMessageTransformUtil;
46 import org.opendaylight.controller.sal.connect.util.RemoteDeviceId;
47 import org.opendaylight.controller.sal.core.api.RpcImplementation;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.common.RpcResult;
50 import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
51 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
52 import org.opendaylight.yangtools.yang.model.api.Module;
53 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
56 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
57 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
58 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
59 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
60 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
61 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
62 import org.opendaylight.yangtools.yang.model.util.repo.SchemaSourceProvider;
63 import org.opendaylight.yangtools.yang.parser.impl.YangParserImpl;
64
65 public class NetconfDeviceTest {
66
67     private static final NetconfMessage netconfMessage;
68     private static final CompositeNode compositeNode;
69
70     static {
71         try {
72             netconfMessage = mockClass(NetconfMessage.class);
73             compositeNode = mockClass(CompositeNode.class);
74         } catch (final Exception e) {
75             throw new RuntimeException(e);
76         }
77     }
78
79     private static final  RpcResult<NetconfMessage> rpcResult = RpcResultBuilder.success(netconfMessage).build();
80     private static final  RpcResult<CompositeNode> rpcResultC = RpcResultBuilder.success(compositeNode).build();
81
82     public static final String TEST_NAMESPACE = "test:namespace";
83     public static final String TEST_MODULE = "test-module";
84     public static final String TEST_REVISION = "2013-07-22";
85     public static final SourceIdentifier TEST_SID = new SourceIdentifier(TEST_MODULE, Optional.of(TEST_REVISION));
86     public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION;
87
88     public static final SourceIdentifier TEST_SID2 = new SourceIdentifier(TEST_MODULE + "2", Optional.of(TEST_REVISION));
89     public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&amp;revision=" + TEST_REVISION;
90
91     private static final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
92
93         @Override
94         public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
95             return NetconfStateSchemas.EMPTY;
96         }
97     };
98
99     @Test
100     public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
101         final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
102
103         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
104         final RemoteDeviceCommunicator<NetconfMessage> listener = getListener();
105
106         final SchemaContextFactory schemaFactory = getSchemaFactory();
107
108         // Make fallback attempt to fail due to empty resolved sources
109         final SchemaResolutionException schemaResolutionException
110                 = new SchemaResolutionException("fail first",
111                 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
112         doReturn(Futures.immediateFailedCheckedFuture(
113                 schemaResolutionException))
114                 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
115
116         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
117                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
118         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), getMessageTransformer());
119         // Monitoring not supported
120         final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
121         device.onRemoteSessionUp(sessionCaps, listener);
122
123         Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
124         Mockito.verify(listener, Mockito.timeout(5000)).close();
125         Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
126     }
127
128     @Test
129     public void testNetconfDeviceMissingSource() throws Exception {
130         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
131         final RemoteDeviceCommunicator<NetconfMessage> listener = getListener();
132
133         final SchemaContextFactory schemaFactory = getSchemaFactory();
134
135         // Make fallback attempt to fail due to empty resolved sources
136         final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
137         doAnswer(new Answer<Object>() {
138             @Override
139             public Object answer(final InvocationOnMock invocation) throws Throwable {
140                 if(((Collection<?>) invocation.getArguments()[0]).size() == 2) {
141                     return Futures.immediateFailedCheckedFuture(schemaResolutionException);
142                 } else {
143                     return Futures.immediateCheckedFuture(getSchema());
144                 }
145             }
146         }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
147
148         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
149                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
150         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), getMessageTransformer());
151         // Monitoring supported
152         final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
153         device.onRemoteSessionUp(sessionCaps, listener);
154
155         Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(RpcImplementation.class));
156         Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
157     }
158
159     private SchemaSourceRegistry getSchemaRegistry() {
160         final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
161         final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
162         doNothing().when(mockReg).close();
163         doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
164         return mock;
165     }
166
167     @Test
168     public void testNotificationBeforeSchema() throws Exception {
169         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
170         final RemoteDeviceCommunicator<NetconfMessage> listener = getListener();
171
172         final MessageTransformer<NetconfMessage> messageTransformer = getMessageTransformer();
173
174         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
175                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaFactory(), stateSchemasResolver);
176         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), messageTransformer);
177
178         device.onNotification(netconfMessage);
179         device.onNotification(netconfMessage);
180
181         verify(facade, times(0)).onNotification(any(CompositeNode.class));
182
183         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
184                 Lists.newArrayList(TEST_CAPABILITY));
185
186         device.onRemoteSessionUp(sessionCaps, listener);
187
188         verify(messageTransformer, timeout(10000).times(2)).toNotification(netconfMessage);
189         verify(facade, timeout(10000).times(2)).onNotification(compositeNode);
190
191         device.onNotification(netconfMessage);
192         verify(messageTransformer, timeout(10000).times(3)).toNotification(netconfMessage);
193         verify(facade, timeout(10000).times(3)).onNotification(compositeNode);
194     }
195
196     @Test
197     public void testNetconfDeviceReconnect() throws Exception {
198         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
199         final RemoteDeviceCommunicator<NetconfMessage> listener = getListener();
200
201         final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
202         final MessageTransformer<NetconfMessage> messageTransformer = getMessageTransformer();
203
204         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
205                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaContextProviderFactory, stateSchemasResolver);
206         final NetconfDevice device = new NetconfDevice(schemaResourcesDTO, getId(), facade, getExecutor(), messageTransformer);
207         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
208                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
209         device.onRemoteSessionUp(sessionCaps, listener);
210
211         verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
212         verify(messageTransformer, timeout(5000)).onGlobalContextUpdated(any(SchemaContext.class));
213         verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(RpcImplementation.class));
214
215         device.onRemoteSessionDown();
216         verify(facade, timeout(5000)).onDeviceDisconnected();
217
218         device.onRemoteSessionUp(sessionCaps, listener);
219
220         verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
221         verify(messageTransformer, timeout(5000).times(3)).onGlobalContextUpdated(any(SchemaContext.class));
222         verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(RpcImplementation.class));
223     }
224
225     private SchemaContextFactory getSchemaFactory() {
226         final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
227         doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
228         return schemaFactory;
229     }
230
231     public static SchemaContext getSchema() {
232         final YangParserImpl parser = new YangParserImpl();
233         final List<InputStream> modelsToParse = Lists.newArrayList(
234                 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
235         );
236         final Set<Module> models = parser.parseYangModelsFromStreams(modelsToParse);
237         return parser.resolveSchemaContext(models);
238     }
239
240     private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
241         final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
242         doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(RpcImplementation.class));
243         doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
244         doNothing().when(remoteDeviceHandler).onNotification(any(CompositeNode.class));
245         return remoteDeviceHandler;
246     }
247
248     private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
249         final T mock = mockClass(remoteDeviceHandlerClass);
250         doNothing().when(mock).close();
251         return mock;
252     }
253
254     public SchemaSourceProviderFactory<InputStream> getSourceProviderFactory() {
255         final SchemaSourceProviderFactory<InputStream> mock = mockClass(SchemaSourceProviderFactory.class);
256
257         final SchemaSourceProvider<InputStream> schemaSourceProvider = mockClass(SchemaSourceProvider.class);
258         doReturn(Optional.<String>absent()).when(schemaSourceProvider).getSchemaSource(anyString(), any(Optional.class));
259
260         doReturn(schemaSourceProvider).when(mock).createSourceProvider(any(RpcImplementation.class));
261         return mock;
262     }
263
264     private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
265         final T mock = mock(remoteDeviceHandlerClass);
266         Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
267         return mock;
268     }
269
270     public RemoteDeviceId getId() {
271         return new RemoteDeviceId("test-D");
272     }
273
274     public ExecutorService getExecutor() {
275         return Executors.newSingleThreadExecutor();
276     }
277
278     public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
279         final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
280         doReturn(netconfMessage).when(messageTransformer).toRpcRequest(any(QName.class), any(CompositeNode.class));
281         doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(QName.class));
282         doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
283         doNothing().when(messageTransformer).onGlobalContextUpdated(any(SchemaContext.class));
284         return messageTransformer;
285     }
286
287     public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
288         final ArrayList<String> capabilities = Lists.newArrayList(
289                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
290                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
291
292         if(addMonitor) {
293             capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
294         }
295
296         capabilities.addAll(additionalCapabilities);
297
298         return NetconfSessionPreferences.fromStrings(
299                 capabilities);
300     }
301
302     public RemoteDeviceCommunicator<NetconfMessage> getListener() throws Exception {
303         final RemoteDeviceCommunicator<NetconfMessage> remoteDeviceCommunicator = mockCloseableClass(RemoteDeviceCommunicator.class);
304         doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
305         return remoteDeviceCommunicator;
306     }
307 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.