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