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