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