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