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