Fix of build breakage caused by changes in Yangtools
[netconf.git] / netconf / sal-netconf-connector / src / test / java / org / opendaylight / netconf / sal / connect / netconf / NetconfDeviceTest.java
1 /*
2  * Copyright (c) 2014, 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.sal.connect.netconf;
10
11 import static org.mockito.Matchers.any;
12 import static org.mockito.Matchers.anyCollectionOf;
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.Iterables;
24 import com.google.common.collect.Lists;
25 import com.google.common.collect.Sets;
26 import com.google.common.util.concurrent.Futures;
27 import java.io.InputStream;
28 import java.net.InetSocketAddress;
29 import java.util.ArrayList;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.List;
33 import java.util.concurrent.ExecutorService;
34 import java.util.concurrent.Executors;
35 import org.junit.Test;
36 import org.mockito.Mockito;
37 import org.mockito.invocation.InvocationOnMock;
38 import org.mockito.stubbing.Answer;
39 import org.opendaylight.controller.config.util.xml.XmlUtil;
40 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
41 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
42 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
43 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
44 import org.opendaylight.netconf.api.NetconfMessage;
45 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
46 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
47 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
48 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
49 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
50 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
51 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
52 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
53 import org.opendaylight.yangtools.yang.common.QName;
54 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
55 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
56 import org.opendaylight.yangtools.yang.model.api.Module;
57 import org.opendaylight.yangtools.yang.model.api.ModuleImport;
58 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
59 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
60 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
61 import org.opendaylight.yangtools.yang.model.repo.api.RevisionSourceIdentifier;
62 import org.opendaylight.yangtools.yang.model.repo.api.SchemaContextFactory;
63 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
64 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
65 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
66 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
67 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
68 import org.opendaylight.yangtools.yang.parser.spi.meta.ReactorException;
69 import org.opendaylight.yangtools.yang.parser.stmt.reactor.CrossSourceStatementReactor;
70 import org.opendaylight.yangtools.yang.parser.stmt.rfc6020.YangInferencePipeline;
71
72 public class NetconfDeviceTest {
73
74     private static final NetconfMessage notification;
75
76     private static final ContainerNode compositeNode;
77
78     static {
79         try {
80             compositeNode = mockClass(ContainerNode.class);
81         } catch (final Exception e) {
82             throw new RuntimeException(e);
83         }
84         try {
85             notification = new NetconfMessage(XmlUtil.readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
86         } catch (Exception e) {
87             throw new ExceptionInInitializerError(e);
88         }
89     }
90
91     private static final DOMRpcResult rpcResultC = new DefaultDOMRpcResult(compositeNode);
92
93     public static final String TEST_NAMESPACE = "test:namespace";
94     public static final String TEST_MODULE = "test-module";
95     public static final String TEST_REVISION = "2013-07-22";
96     public static final SourceIdentifier TEST_SID =
97             RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
98     public static final String TEST_CAPABILITY = TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
99
100     public static final SourceIdentifier TEST_SID2 =
101             RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
102     public static final String TEST_CAPABILITY2 = TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
103
104     private static final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
105
106         @Override
107         public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
108             return NetconfStateSchemas.EMPTY;
109         }
110     };
111
112     @Test
113     public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
114         final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
115
116         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
117         final NetconfDeviceCommunicator listener = getListener();
118
119         final SchemaContextFactory schemaFactory = getSchemaFactory();
120
121         // Make fallback attempt to fail due to empty resolved sources
122         final SchemaResolutionException schemaResolutionException
123                 = new SchemaResolutionException("fail first",
124                 Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
125         doReturn(Futures.immediateFailedCheckedFuture(
126                 schemaResolutionException))
127                 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
128
129         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
130                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
131         final NetconfDevice device = new NetconfDeviceBuilder()
132                 .setReconnectOnSchemasChange(true)
133                 .setSchemaResourcesDTO(schemaResourcesDTO)
134                 .setGlobalProcessingExecutor(getExecutor())
135                 .setId(getId())
136                 .setSalFacade(facade)
137                 .build();
138
139         // Monitoring not supported
140         final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
141         device.onRemoteSessionUp(sessionCaps, listener);
142
143         Mockito.verify(facade, Mockito.timeout(5000)).onDeviceDisconnected();
144         Mockito.verify(listener, Mockito.timeout(5000)).close();
145         Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
146     }
147
148     @Test
149     public void testNetconfDeviceMissingSource() throws Exception {
150         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
151         final NetconfDeviceCommunicator listener = getListener();
152         final SchemaContext schema = getSchema();
153
154         final SchemaContextFactory schemaFactory = getSchemaFactory();
155
156         // Make fallback attempt to fail due to empty resolved sources
157         final MissingSchemaSourceException schemaResolutionException = new MissingSchemaSourceException("fail first", TEST_SID);
158         doAnswer(new Answer<Object>() {
159             @Override
160             public Object answer(final InvocationOnMock invocation) throws Throwable {
161                 if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
162                     return Futures.immediateFailedCheckedFuture(schemaResolutionException);
163                 } else {
164                     return Futures.immediateCheckedFuture(schema);
165                 }
166             }
167         }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
168
169         final NetconfStateSchemas.NetconfStateSchemasResolver stateSchemasResolver = new NetconfStateSchemas.NetconfStateSchemasResolver() {
170             @Override
171             public NetconfStateSchemas resolve(final NetconfDeviceRpc deviceRpc, final NetconfSessionPreferences remoteSessionCapabilities, final RemoteDeviceId id) {
172                 final Module first = Iterables.getFirst(schema.getModules(), null);
173                 final QName qName = QName.create(first.getQNameModule(), first.getName());
174                 final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
175                 final NetconfStateSchemas.RemoteYangSchema source2 = new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
176                 return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
177             }
178         };
179
180         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
181                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaFactory, stateSchemasResolver);
182
183         final NetconfDevice device = new NetconfDeviceBuilder()
184                 .setReconnectOnSchemasChange(true)
185                 .setSchemaResourcesDTO(schemaResourcesDTO)
186                 .setGlobalProcessingExecutor(getExecutor())
187                 .setId(getId())
188                 .setSalFacade(facade)
189                 .build();
190         // Monitoring supported
191         final NetconfSessionPreferences sessionCaps = getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
192         device.onRemoteSessionUp(sessionCaps, listener);
193
194         Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
195         Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
196     }
197
198     private SchemaSourceRegistry getSchemaRegistry() {
199         final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
200         final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
201         doNothing().when(mockReg).close();
202         doReturn(mockReg).when(mock).registerSchemaSource(any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class), any(PotentialSchemaSource.class));
203         return mock;
204     }
205
206     @Test
207     public void testNotificationBeforeSchema() throws Exception {
208         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
209         final NetconfDeviceCommunicator listener = getListener();
210
211         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
212                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaFactory(), stateSchemasResolver);
213         final NetconfDevice device = new NetconfDeviceBuilder()
214                 .setReconnectOnSchemasChange(true)
215                 .setSchemaResourcesDTO(schemaResourcesDTO)
216                 .setGlobalProcessingExecutor(getExecutor())
217                 .setId(getId())
218                 .setSalFacade(facade)
219                 .build();
220
221         device.onNotification(notification);
222         device.onNotification(notification);
223
224         verify(facade, times(0)).onNotification(any(DOMNotification.class));
225
226         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
227                 Lists.newArrayList(TEST_CAPABILITY));
228
229         final DOMRpcService deviceRpc = mock(DOMRpcService.class);
230
231         device.handleSalInitializationSuccess(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
232
233         verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
234
235         device.onNotification(notification);
236         verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
237     }
238
239     @Test
240     public void testNetconfDeviceReconnect() throws Exception {
241         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
242         final NetconfDeviceCommunicator listener = getListener();
243
244         final SchemaContextFactory schemaContextProviderFactory = getSchemaFactory();
245
246         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
247                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), schemaContextProviderFactory, stateSchemasResolver);
248         final NetconfDevice device = new NetconfDeviceBuilder()
249                 .setReconnectOnSchemasChange(true)
250                 .setSchemaResourcesDTO(schemaResourcesDTO)
251                 .setGlobalProcessingExecutor(getExecutor())
252                 .setId(getId())
253                 .setSalFacade(facade)
254                 .build();
255         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
256                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
257         device.onRemoteSessionUp(sessionCaps, listener);
258
259         verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
260         verify(facade, timeout(5000)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
261
262         device.onRemoteSessionDown();
263         verify(facade, timeout(5000)).onDeviceDisconnected();
264
265         device.onRemoteSessionUp(sessionCaps, listener);
266
267         verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
268         verify(facade, timeout(5000).times(2)).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
269     }
270
271     private SchemaContextFactory getSchemaFactory() {
272         final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
273         doReturn(Futures.immediateCheckedFuture(getSchema())).when(schemaFactory).createSchemaContext(any(Collection.class));
274         return schemaFactory;
275     }
276
277     private static SchemaContext parseYangStreams(final List<InputStream> streams) {
278         CrossSourceStatementReactor.BuildAction reactor = YangInferencePipeline.RFC6020_REACTOR
279                 .newBuild();
280         final SchemaContext schemaContext;
281         try {
282             schemaContext = reactor.buildEffective(streams);
283         } catch (ReactorException e) {
284             throw new RuntimeException("Unable to build schema context from " + streams, e);
285         }
286         return schemaContext;
287     }
288
289     public static SchemaContext getSchema() {
290         final List<InputStream> modelsToParse = Lists.newArrayList(
291                 NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
292         );
293         return parseYangStreams(modelsToParse);
294     }
295
296     private RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
297         final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler = mockCloseableClass(RemoteDeviceHandler.class);
298         doNothing().when(remoteDeviceHandler).onDeviceConnected(any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
299         doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
300         doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
301         return remoteDeviceHandler;
302     }
303
304     private <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass) throws Exception {
305         final T mock = mockClass(remoteDeviceHandlerClass);
306         doNothing().when(mock).close();
307         return mock;
308     }
309
310     private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
311         final T mock = mock(remoteDeviceHandlerClass);
312         Mockito.doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
313         return mock;
314     }
315
316     public RemoteDeviceId getId() {
317         return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
318     }
319
320     public ExecutorService getExecutor() {
321         return Executors.newSingleThreadExecutor();
322     }
323
324     public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
325         final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
326         doReturn(notification).when(messageTransformer).toRpcRequest(any(SchemaPath.class), any(NormalizedNode.class));
327         doReturn(rpcResultC).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(SchemaPath.class));
328         doReturn(compositeNode).when(messageTransformer).toNotification(any(NetconfMessage.class));
329         return messageTransformer;
330     }
331
332     public NetconfSessionPreferences getSessionCaps(final boolean addMonitor, final Collection<String> additionalCapabilities) {
333         final ArrayList<String> capabilities = Lists.newArrayList(
334                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
335                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
336
337         if(addMonitor) {
338             capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
339         }
340
341         capabilities.addAll(additionalCapabilities);
342
343         return NetconfSessionPreferences.fromStrings(
344                 capabilities);
345     }
346
347     public NetconfDeviceCommunicator getListener() throws Exception {
348         final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
349 //        doReturn(Futures.immediateFuture(rpcResult)).when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
350         return remoteDeviceCommunicator;
351     }
352 }