Bump upstream versions
[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 package org.opendaylight.netconf.sal.connect.netconf;
9
10 import static org.junit.Assert.assertEquals;
11 import static org.junit.Assert.assertFalse;
12 import static org.junit.Assert.assertTrue;
13 import static org.mockito.ArgumentMatchers.any;
14 import static org.mockito.ArgumentMatchers.anyCollection;
15 import static org.mockito.ArgumentMatchers.eq;
16 import static org.mockito.ArgumentMatchers.isNull;
17 import static org.mockito.Mockito.after;
18 import static org.mockito.Mockito.doAnswer;
19 import static org.mockito.Mockito.doNothing;
20 import static org.mockito.Mockito.doReturn;
21 import static org.mockito.Mockito.mock;
22 import static org.mockito.Mockito.spy;
23 import static org.mockito.Mockito.timeout;
24 import static org.mockito.Mockito.times;
25 import static org.mockito.Mockito.verify;
26
27 import com.google.common.collect.HashMultimap;
28 import com.google.common.collect.Iterables;
29 import com.google.common.collect.Lists;
30 import com.google.common.collect.Sets;
31 import com.google.common.util.concurrent.Futures;
32 import com.google.common.util.concurrent.ListeningExecutorService;
33 import com.google.common.util.concurrent.MoreExecutors;
34 import com.google.common.util.concurrent.SettableFuture;
35 import java.io.IOException;
36 import java.net.InetSocketAddress;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.Collection;
40 import java.util.Collections;
41 import java.util.HashMap;
42 import java.util.List;
43 import java.util.Map;
44 import java.util.Set;
45 import java.util.concurrent.Executors;
46 import org.junit.Test;
47 import org.mockito.ArgumentCaptor;
48 import org.opendaylight.mdsal.dom.api.DOMActionService;
49 import org.opendaylight.mdsal.dom.api.DOMNotification;
50 import org.opendaylight.mdsal.dom.api.DOMRpcResult;
51 import org.opendaylight.mdsal.dom.api.DOMRpcService;
52 import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
53 import org.opendaylight.netconf.api.NetconfMessage;
54 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
55 import org.opendaylight.netconf.api.xml.XmlUtil;
56 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
57 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
58 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
59 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCapabilities;
60 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfDeviceCommunicator;
61 import org.opendaylight.netconf.sal.connect.netconf.listener.NetconfSessionPreferences;
62 import org.opendaylight.netconf.sal.connect.netconf.sal.NetconfDeviceRpc;
63 import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransformUtil;
64 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
65 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
66 import org.opendaylight.yangtools.rfc8528.data.api.MountPointContext;
67 import org.opendaylight.yangtools.yang.common.QName;
68 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
69 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
70 import org.opendaylight.yangtools.yang.model.api.Module;
71 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
72 import org.opendaylight.yangtools.yang.model.repo.api.EffectiveModelContextFactory;
73 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
74 import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
75 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
76 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
77 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
78 import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
79 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
80 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
81 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
82 import org.xml.sax.SAXException;
83
84 public class NetconfDeviceTest extends AbstractTestModelTest {
85
86     private static final NetconfMessage NOTIFICATION;
87
88     private static final ContainerNode COMPOSITE_NODE = mockClass(ContainerNode.class);
89
90     static {
91         try {
92             NOTIFICATION = new NetconfMessage(XmlUtil
93                     .readXmlToDocument(NetconfDeviceTest.class.getResourceAsStream("/notification-payload.xml")));
94         } catch (SAXException | IOException e) {
95             throw new ExceptionInInitializerError(e);
96         }
97     }
98
99     private static final DOMRpcResult RPC_RESULT = new DefaultDOMRpcResult(COMPOSITE_NODE);
100
101     public static final String TEST_NAMESPACE = "test:namespace";
102     public static final String TEST_MODULE = "test-module";
103     public static final String TEST_REVISION = "2013-07-22";
104     public static final SourceIdentifier TEST_SID = new SourceIdentifier(TEST_MODULE, TEST_REVISION);
105     public static final String TEST_CAPABILITY =
106             TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
107
108     public static final SourceIdentifier TEST_SID2 = new SourceIdentifier(TEST_MODULE + "2", TEST_REVISION);
109     public static final String TEST_CAPABILITY2 =
110             TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
111
112     private static final NetconfDeviceSchemasResolver STATE_SCHEMAS_RESOLVER =
113         (deviceRpc, remoteSessionCapabilities, id, schemaContext) -> NetconfStateSchemas.EMPTY;
114
115
116     @Test
117     public void testNetconfDeviceFlawedModelFailedResolution() throws Exception {
118         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
119         final NetconfDeviceCommunicator listener = getListener();
120
121         final EffectiveModelContextFactory schemaFactory = getSchemaFactory();
122         final SchemaRepository schemaRepository = getSchemaRepository();
123
124         final SchemaResolutionException schemaResolutionException =
125                 new SchemaResolutionException("fail first", TEST_SID, new Throwable("YangTools parser fail"));
126         doAnswer(invocation -> {
127             if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
128                 return Futures.immediateFailedFuture(schemaResolutionException);
129             } else {
130                 return Futures.immediateFuture(SCHEMA_CONTEXT);
131             }
132         }).when(schemaFactory).createEffectiveModelContext(anyCollection());
133
134         final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id,
135                 schemaContext) -> {
136             final Module first = Iterables.getFirst(SCHEMA_CONTEXT.getModules(), null);
137             final QName qName = QName.create(first.getQNameModule(), first.getName());
138             final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
139             final NetconfStateSchemas.RemoteYangSchema source2 =
140                     new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
141             return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
142         };
143
144         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
145                 .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
146
147         final NetconfDevice device = new NetconfDeviceBuilder()
148                 .setReconnectOnSchemasChange(true)
149                 .setSchemaResourcesDTO(schemaResourcesDTO)
150                 .setGlobalProcessingExecutor(getExecutor())
151                 .setId(getId())
152                 .setSalFacade(facade)
153                 .setBaseSchemas(BASE_SCHEMAS)
154                 .build();
155         // Monitoring supported
156         final NetconfSessionPreferences sessionCaps =
157                 getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
158         device.onRemoteSessionUp(sessionCaps, listener);
159
160         verify(facade, timeout(5000)).onDeviceConnected(any(MountPointContext.class),
161             any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class), isNull());
162         verify(schemaFactory, times(2)).createEffectiveModelContext(anyCollection());
163     }
164
165     @Test
166     public void testNetconfDeviceFailFirstSchemaFailSecondEmpty() throws Exception {
167         final ArrayList<String> capList = Lists.newArrayList(TEST_CAPABILITY);
168
169         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
170         final NetconfDeviceCommunicator listener = getListener();
171
172         final EffectiveModelContextFactory schemaFactory = getSchemaFactory();
173         final SchemaRepository schemaRepository = getSchemaRepository();
174
175         // Make fallback attempt to fail due to empty resolved sources
176         final SchemaResolutionException schemaResolutionException
177                 = new SchemaResolutionException("fail first",
178                 Collections.emptyList(), HashMultimap.create());
179         doReturn(Futures.immediateFailedFuture(schemaResolutionException))
180                 .when(schemaFactory).createEffectiveModelContext(anyCollection());
181
182         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
183                 .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, STATE_SCHEMAS_RESOLVER);
184         final NetconfDevice device = new NetconfDeviceBuilder()
185                 .setReconnectOnSchemasChange(true)
186                 .setSchemaResourcesDTO(schemaResourcesDTO)
187                 .setGlobalProcessingExecutor(getExecutor())
188                 .setId(getId())
189                 .setSalFacade(facade)
190                 .setBaseSchemas(BASE_SCHEMAS)
191                 .build();
192
193         // Monitoring not supported
194         final NetconfSessionPreferences sessionCaps = getSessionCaps(false, capList);
195         device.onRemoteSessionUp(sessionCaps, listener);
196
197         verify(facade, timeout(5000)).onDeviceDisconnected();
198         verify(listener, timeout(5000)).close();
199         verify(schemaFactory, times(1)).createEffectiveModelContext(anyCollection());
200     }
201
202     @Test
203     public void testNetconfDeviceMissingSource() throws Exception {
204         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
205         final NetconfDeviceCommunicator listener = getListener();
206
207         final EffectiveModelContextFactory schemaFactory = getSchemaFactory();
208         final SchemaRepository schemaRepository = getSchemaRepository();
209
210         // Make fallback attempt to fail due to empty resolved sources
211         final MissingSchemaSourceException schemaResolutionException =
212                 new MissingSchemaSourceException("fail first", TEST_SID);
213         doReturn(Futures.immediateFailedFuture(schemaResolutionException))
214                 .when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(YangTextSchemaSource.class));
215         doAnswer(invocation -> {
216             if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
217                 return Futures.immediateFailedFuture(schemaResolutionException);
218             } else {
219                 return Futures.immediateFuture(SCHEMA_CONTEXT);
220             }
221         }).when(schemaFactory).createEffectiveModelContext(anyCollection());
222
223         final NetconfDeviceSchemasResolver stateSchemasResolver = (deviceRpc, remoteSessionCapabilities, id,
224             schemaContext) -> {
225             final Module first = Iterables.getFirst(SCHEMA_CONTEXT.getModules(), null);
226             final QName qName = QName.create(first.getQNameModule(), first.getName());
227             final NetconfStateSchemas.RemoteYangSchema source1 = new NetconfStateSchemas.RemoteYangSchema(qName);
228             final NetconfStateSchemas.RemoteYangSchema source2 =
229                     new NetconfStateSchemas.RemoteYangSchema(QName.create(first.getQNameModule(), "test-module2"));
230             return new NetconfStateSchemas(Sets.newHashSet(source1, source2));
231         };
232
233         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
234                 .SchemaResourcesDTO(getSchemaRegistry(), schemaRepository, schemaFactory, stateSchemasResolver);
235
236         final NetconfDevice device = new NetconfDeviceBuilder()
237                 .setReconnectOnSchemasChange(true)
238                 .setSchemaResourcesDTO(schemaResourcesDTO)
239                 .setGlobalProcessingExecutor(getExecutor())
240                 .setBaseSchemas(BASE_SCHEMAS)
241                 .setId(getId())
242                 .setSalFacade(facade)
243                 .build();
244         // Monitoring supported
245         final NetconfSessionPreferences sessionCaps =
246                 getSessionCaps(true, Lists.newArrayList(TEST_CAPABILITY, TEST_CAPABILITY2));
247         device.onRemoteSessionUp(sessionCaps, listener);
248
249         verify(facade, timeout(5000)).onDeviceConnected(any(MountPointContext.class),
250             any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class), isNull());
251         verify(schemaFactory, times(1)).createEffectiveModelContext(anyCollection());
252     }
253
254     private static SchemaSourceRegistry getSchemaRegistry() {
255         final SchemaSourceRegistry mock = mock(SchemaSourceRegistry.class);
256         final SchemaSourceRegistration<?> mockReg = mock(SchemaSourceRegistration.class);
257         doNothing().when(mockReg).close();
258         doReturn(mockReg).when(mock).registerSchemaSource(
259                 any(org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider.class),
260                 any(PotentialSchemaSource.class));
261         return mock;
262     }
263
264     private static SchemaRepository getSchemaRepository() {
265         final SchemaRepository mock = mock(SchemaRepository.class);
266         final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
267         doReturn(Futures.immediateFuture(mockRep))
268                 .when(mock).getSchemaSource(any(SourceIdentifier.class), eq(YangTextSchemaSource.class));
269         return mock;
270     }
271
272     @Test
273     public void testNotificationBeforeSchema() throws Exception {
274         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
275         final NetconfDeviceCommunicator listener = getListener();
276         final EffectiveModelContextFactory schemaContextProviderFactory = mock(EffectiveModelContextFactory.class);
277         final SettableFuture<SchemaContext> schemaFuture = SettableFuture.create();
278         doReturn(schemaFuture).when(schemaContextProviderFactory).createEffectiveModelContext(any(Collection.class));
279         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO =
280                 new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(),
281                         schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
282         final NetconfDevice device = new NetconfDeviceBuilder()
283                 .setReconnectOnSchemasChange(true)
284                 .setSchemaResourcesDTO(schemaResourcesDTO)
285                 .setGlobalProcessingExecutor(getExecutor())
286                 .setId(getId())
287                 .setSalFacade(facade)
288                 .setBaseSchemas(BASE_SCHEMAS)
289                 .build();
290
291         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
292                 Lists.newArrayList(TEST_CAPABILITY));
293         device.onRemoteSessionUp(sessionCaps, listener);
294
295         device.onNotification(NOTIFICATION);
296         device.onNotification(NOTIFICATION);
297         verify(facade, times(0)).onNotification(any(DOMNotification.class));
298
299         verify(facade, times(0)).onNotification(any(DOMNotification.class));
300         schemaFuture.set(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false));
301         verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
302
303         device.onNotification(NOTIFICATION);
304         verify(facade, timeout(10000).times(3)).onNotification(any(DOMNotification.class));
305     }
306
307     @Test
308     public void testNetconfDeviceReconnect() throws Exception {
309         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
310         final NetconfDeviceCommunicator listener = getListener();
311
312         final EffectiveModelContextFactory schemaContextProviderFactory = getSchemaFactory();
313
314         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
315                 getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
316         final NetconfDevice device = new NetconfDeviceBuilder()
317                 .setReconnectOnSchemasChange(true)
318                 .setSchemaResourcesDTO(schemaResourcesDTO)
319                 .setGlobalProcessingExecutor(getExecutor())
320                 .setId(getId())
321                 .setSalFacade(facade)
322                 .setBaseSchemas(BASE_SCHEMAS)
323                 .build();
324         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
325                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
326         device.onRemoteSessionUp(sessionCaps, listener);
327
328         verify(schemaContextProviderFactory, timeout(5000)).createEffectiveModelContext(any(Collection.class));
329         verify(facade, timeout(5000)).onDeviceConnected(
330                 any(MountPointContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class),
331                 isNull());
332
333         device.onRemoteSessionDown();
334         verify(facade, timeout(5000)).onDeviceDisconnected();
335
336         device.onRemoteSessionUp(sessionCaps, listener);
337
338         verify(schemaContextProviderFactory, timeout(5000).times(2)).createEffectiveModelContext(any(Collection.class));
339         verify(facade, timeout(5000).times(2)).onDeviceConnected(
340                 any(MountPointContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class),
341                 isNull());
342     }
343
344     @Test
345     public void testNetconfDeviceDisconnectListenerCallCancellation() throws Exception {
346         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
347         final NetconfDeviceCommunicator listener = getListener();
348         final EffectiveModelContextFactory schemaContextProviderFactory = mock(EffectiveModelContextFactory.class);
349         final SettableFuture<SchemaContext> schemaFuture = SettableFuture.create();
350         doReturn(schemaFuture).when(schemaContextProviderFactory).createEffectiveModelContext(any(Collection.class));
351         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
352                 = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(),
353                 schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
354         final NetconfDevice device = new NetconfDeviceBuilder()
355                 .setReconnectOnSchemasChange(true)
356                 .setSchemaResourcesDTO(schemaResourcesDTO)
357                 .setGlobalProcessingExecutor(getExecutor())
358                 .setId(getId())
359                 .setSalFacade(facade)
360                 .setBaseSchemas(BASE_SCHEMAS)
361                 .build();
362         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
363                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
364         //session up, start schema resolution
365         device.onRemoteSessionUp(sessionCaps, listener);
366         //session closed
367         device.onRemoteSessionDown();
368         verify(facade, timeout(5000)).onDeviceDisconnected();
369         //complete schema setup
370         schemaFuture.set(SCHEMA_CONTEXT);
371         //facade.onDeviceDisconnected() was called, so facade.onDeviceConnected() shouldn't be called anymore
372         verify(facade, after(1000).never()).onDeviceConnected(any(), any(), any(), any(DOMActionService.class));
373     }
374
375     @Test
376     public void testNetconfDeviceAvailableCapabilitiesBuilding() throws Exception {
377         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
378         final NetconfDeviceCommunicator listener = getListener();
379
380         final EffectiveModelContextFactory schemaContextProviderFactory = getSchemaFactory();
381
382         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
383                 getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
384         final NetconfDevice device = new NetconfDeviceBuilder()
385                 .setReconnectOnSchemasChange(true)
386                 .setSchemaResourcesDTO(schemaResourcesDTO)
387                 .setGlobalProcessingExecutor(getExecutor())
388                 .setId(getId())
389                 .setSalFacade(facade)
390                 .setBaseSchemas(BASE_SCHEMAS)
391                 .build();
392         final NetconfDevice netconfSpy = spy(device);
393
394         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
395                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
396         final Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
397         moduleBasedCaps.putAll(sessionCaps.getModuleBasedCapsOrigin());
398         moduleBasedCaps
399                 .put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
400
401         netconfSpy.onRemoteSessionUp(sessionCaps.replaceModuleCaps(moduleBasedCaps), listener);
402
403         final ArgumentCaptor<NetconfSessionPreferences> argument =
404                 ArgumentCaptor.forClass(NetconfSessionPreferences.class);
405         verify(facade, timeout(5000)).onDeviceConnected(any(MountPointContext.class), argument.capture(),
406             any(DOMRpcService.class), isNull());
407         final NetconfDeviceCapabilities netconfDeviceCaps = argument.getValue().getNetconfDeviceCapabilities();
408
409         netconfDeviceCaps.getResolvedCapabilities()
410                 .forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
411                         moduleBasedCaps.get(
412                                 QName.create(entry.getCapability())).getName(), entry.getCapabilityOrigin().getName()));
413     }
414
415     @Test
416     public void testNetconfDeviceNotificationsModelNotPresentWithCapability() throws Exception {
417         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
418         final NetconfDeviceCommunicator listener = getListener();
419         final EffectiveModelContextFactory schemaContextProviderFactory = getSchemaFactory();
420
421         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
422                 getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
423         final NetconfDevice device = new NetconfDeviceBuilder()
424                 .setSchemaResourcesDTO(schemaResourcesDTO)
425                 .setGlobalProcessingExecutor(getExecutor())
426                 .setId(getId())
427                 .setSalFacade(facade)
428                 .setBaseSchemas(BASE_SCHEMAS)
429                 .build();
430         final NetconfDevice netconfSpy = spy(device);
431
432         final NetconfSessionPreferences sessionCaps = getSessionCaps(false,
433                 Lists.newArrayList(XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_CAPABILITY_NOTIFICATION_1_0));
434
435         netconfSpy.onRemoteSessionUp(sessionCaps, listener);
436
437         final ArgumentCaptor<NetconfSessionPreferences> argument =
438                 ArgumentCaptor.forClass(NetconfSessionPreferences.class);
439         verify(facade, timeout(5000)).onDeviceConnected(any(MountPointContext.class), argument.capture(),
440                 any(DOMRpcService.class), isNull());
441
442         List<String> notificationModulesName = Arrays.asList(
443                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
444                         .$YangModuleInfoImpl.getInstance().getName().toString(),
445                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
446                         .$YangModuleInfoImpl.getInstance().getName().toString());
447
448         final Set<AvailableCapability> resolvedCapabilities = argument.getValue().getNetconfDeviceCapabilities()
449                 .getResolvedCapabilities();
450
451         assertEquals(2, resolvedCapabilities.size());
452         assertTrue(resolvedCapabilities.stream().anyMatch(entry -> notificationModulesName
453                 .contains(entry.getCapability())));
454     }
455
456     @Test
457     public void testNetconfDeviceNotificationsCapabilityIsNotPresent() throws Exception {
458         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
459         final NetconfDeviceCommunicator listener = getListener();
460         final EffectiveModelContextFactory schemaContextProviderFactory = getSchemaFactory();
461
462         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
463                 getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
464         final NetconfDevice device = new NetconfDeviceBuilder()
465                 .setSchemaResourcesDTO(schemaResourcesDTO)
466                 .setGlobalProcessingExecutor(getExecutor())
467                 .setId(getId())
468                 .setSalFacade(facade)
469                 .setBaseSchemas(BASE_SCHEMAS)
470                 .build();
471         final NetconfDevice netconfSpy = spy(device);
472
473         final NetconfSessionPreferences sessionCaps = getSessionCaps(false,
474                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
475
476         netconfSpy.onRemoteSessionUp(sessionCaps, listener);
477
478         final ArgumentCaptor<NetconfSessionPreferences> argument =
479                 ArgumentCaptor.forClass(NetconfSessionPreferences.class);
480         verify(facade, timeout(5000)).onDeviceConnected(any(MountPointContext.class), argument.capture(),
481                 any(DOMRpcService.class), isNull());
482         final NetconfDeviceCapabilities netconfDeviceCaps = argument.getValue().getNetconfDeviceCapabilities();
483
484         List<String> notificationModulesName = Arrays.asList(
485                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
486                         .$YangModuleInfoImpl.getInstance().getName().toString(),
487                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
488                         .$YangModuleInfoImpl.getInstance().getName().toString());
489
490         assertFalse(netconfDeviceCaps.getResolvedCapabilities().stream().anyMatch(entry -> notificationModulesName
491                 .contains(entry.getCapability())));
492     }
493
494     @Test
495     public void testNetconfDeviceNotificationsModelIsPresent() throws Exception {
496         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
497         final NetconfDeviceCommunicator listener = getListener();
498         final EffectiveModelContextFactory schemaContextProviderFactory = getSchemaFactory();
499
500         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
501                 getSchemaRegistry(), getSchemaRepository(), schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
502         final NetconfDevice device = new NetconfDeviceBuilder()
503                 .setSchemaResourcesDTO(schemaResourcesDTO)
504                 .setGlobalProcessingExecutor(getExecutor())
505                 .setId(getId())
506                 .setSalFacade(facade)
507                 .setBaseSchemas(BASE_SCHEMAS)
508                 .build();
509         final NetconfDevice netconfSpy = spy(device);
510
511         final NetconfSessionPreferences sessionCaps = getSessionCaps(false, Collections.emptyList());
512
513         final Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
514         moduleBasedCaps.put(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
515                         .$YangModuleInfoImpl.getInstance().getName(),
516                 AvailableCapability.CapabilityOrigin.DeviceAdvertised);
517         moduleBasedCaps.put(org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
518                         .$YangModuleInfoImpl.getInstance().getName(),
519                 AvailableCapability.CapabilityOrigin.DeviceAdvertised);
520
521
522         netconfSpy.onRemoteSessionUp(sessionCaps.replaceModuleCaps(moduleBasedCaps), listener);
523
524         final ArgumentCaptor<NetconfSessionPreferences> argument =
525                 ArgumentCaptor.forClass(NetconfSessionPreferences.class);
526         verify(facade, timeout(5000)).onDeviceConnected(any(MountPointContext.class), argument.capture(),
527                 any(DOMRpcService.class), isNull());
528         final Set<AvailableCapability> resolvedCapabilities = argument.getValue().getNetconfDeviceCapabilities()
529                 .getResolvedCapabilities();
530
531         List<String> notificationModulesName = Arrays.asList(
532                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.netconf.notification._1._0.rev080714
533                         .$YangModuleInfoImpl.getInstance().getName().toString(),
534                 org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715
535                         .$YangModuleInfoImpl.getInstance().getName().toString());
536
537         assertEquals(2, resolvedCapabilities.size());
538         assertTrue(resolvedCapabilities.stream().anyMatch(entry -> notificationModulesName
539                 .contains(entry.getCapability())));
540     }
541
542     private static EffectiveModelContextFactory getSchemaFactory() throws Exception {
543         final EffectiveModelContextFactory schemaFactory = mockClass(EffectiveModelContextFactory.class);
544         doReturn(Futures.immediateFuture(SCHEMA_CONTEXT))
545                 .when(schemaFactory).createEffectiveModelContext(any(Collection.class));
546         return schemaFactory;
547     }
548
549     private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
550         final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler =
551                 mockCloseableClass(RemoteDeviceHandler.class);
552         doNothing().when(remoteDeviceHandler).onDeviceConnected(
553                 any(MountPointContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class),
554                 any(DOMActionService.class));
555         doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
556         doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
557         return remoteDeviceHandler;
558     }
559
560     private static <T extends AutoCloseable> T mockCloseableClass(final Class<T> remoteDeviceHandlerClass)
561             throws Exception {
562         final T mock = mockClass(remoteDeviceHandlerClass);
563         doNothing().when(mock).close();
564         return mock;
565     }
566
567     private static <T> T mockClass(final Class<T> remoteDeviceHandlerClass) {
568         final T mock = mock(remoteDeviceHandlerClass);
569         doReturn(remoteDeviceHandlerClass.getSimpleName()).when(mock).toString();
570         return mock;
571     }
572
573     public RemoteDeviceId getId() {
574         return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
575     }
576
577     public ListeningExecutorService getExecutor() {
578         return MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
579     }
580
581     public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {
582         final MessageTransformer<NetconfMessage> messageTransformer = mockClass(MessageTransformer.class);
583         doReturn(NOTIFICATION).when(messageTransformer).toRpcRequest(any(QName.class), any(NormalizedNode.class));
584         doReturn(RPC_RESULT).when(messageTransformer).toRpcResult(any(NetconfMessage.class), any(QName.class));
585         doReturn(COMPOSITE_NODE).when(messageTransformer).toNotification(any(NetconfMessage.class));
586         return messageTransformer;
587     }
588
589     public NetconfSessionPreferences getSessionCaps(final boolean addMonitor,
590                                                     final Collection<String> additionalCapabilities) {
591         final ArrayList<String> capabilities = Lists.newArrayList(
592                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_0,
593                 XmlNetconfConstants.URN_IETF_PARAMS_NETCONF_BASE_1_1);
594
595         if (addMonitor) {
596             capabilities.add(NetconfMessageTransformUtil.IETF_NETCONF_MONITORING.getNamespace().toString());
597         }
598
599         capabilities.addAll(additionalCapabilities);
600
601         return NetconfSessionPreferences.fromStrings(
602                 capabilities);
603     }
604
605     public NetconfDeviceCommunicator getListener() throws Exception {
606         final NetconfDeviceCommunicator remoteDeviceCommunicator = mockCloseableClass(NetconfDeviceCommunicator.class);
607 //        doReturn(Futures.immediateFuture(rpcResult))
608 //                .when(remoteDeviceCommunicator).sendRequest(any(NetconfMessage.class), any(QName.class));
609         return remoteDeviceCommunicator;
610     }
611 }