Remove use of ThreadPools in sal-netconf-connector
[netconf.git] / netconf / sal-netconf-connector / src / test / java / org / opendaylight / netconf / sal / connect / netconf / NetconfDeviceTest.java
index 318df85c8deb21cf681b24ad742928f145373764..a7e0de26dbd283ee8b2e429e1e8c4df493f9c9d1 100644 (file)
@@ -5,13 +5,13 @@
  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
  * and is available at http://www.eclipse.org/legal/epl-v10.html
  */
-
 package org.opendaylight.netconf.sal.connect.netconf;
 
 import static org.junit.Assert.assertEquals;
 import static org.mockito.Matchers.any;
 import static org.mockito.Matchers.anyCollectionOf;
 import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.after;
 import static org.mockito.Mockito.doAnswer;
 import static org.mockito.Mockito.doNothing;
 import static org.mockito.Mockito.doReturn;
@@ -20,33 +20,33 @@ import static org.mockito.Mockito.timeout;
 import static org.mockito.Mockito.times;
 import static org.mockito.Mockito.verify;
 
-import com.google.common.base.Optional;
 import com.google.common.collect.HashMultimap;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
 import com.google.common.util.concurrent.Futures;
+import com.google.common.util.concurrent.ListeningExecutorService;
+import com.google.common.util.concurrent.MoreExecutors;
+import com.google.common.util.concurrent.SettableFuture;
 import java.io.IOException;
-import java.io.InputStream;
 import java.net.InetSocketAddress;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.HashMap;
-import java.util.List;
 import java.util.Map;
-import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
 import org.junit.Test;
 import org.mockito.ArgumentCaptor;
 import org.mockito.Mockito;
-import org.opendaylight.controller.config.util.xml.XmlUtil;
+import org.opendaylight.controller.md.sal.dom.api.DOMActionService;
 import org.opendaylight.controller.md.sal.dom.api.DOMNotification;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcResult;
 import org.opendaylight.controller.md.sal.dom.api.DOMRpcService;
 import org.opendaylight.controller.md.sal.dom.spi.DefaultDOMRpcResult;
 import org.opendaylight.netconf.api.NetconfMessage;
 import org.opendaylight.netconf.api.xml.XmlNetconfConstants;
+import org.opendaylight.netconf.api.xml.XmlUtil;
 import org.opendaylight.netconf.sal.connect.api.MessageTransformer;
 import org.opendaylight.netconf.sal.connect.api.NetconfDeviceSchemasResolver;
 import org.opendaylight.netconf.sal.connect.api.RemoteDeviceHandler;
@@ -58,10 +58,10 @@ import org.opendaylight.netconf.sal.connect.netconf.util.NetconfMessageTransform
 import org.opendaylight.netconf.sal.connect.util.RemoteDeviceId;
 import org.opendaylight.yang.gen.v1.urn.opendaylight.netconf.node.topology.rev150114.netconf.node.connection.status.available.capabilities.AvailableCapability;
 import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.common.Revision;
 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
-import org.opendaylight.yangtools.yang.model.api.ModuleImport;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
 import org.opendaylight.yangtools.yang.model.repo.api.MissingSchemaSourceException;
@@ -71,10 +71,10 @@ import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaResolutionException;
 import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceRepresentation;
 import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
+import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
 import org.opendaylight.yangtools.yang.model.repo.spi.PotentialSchemaSource;
 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistration;
 import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceRegistry;
-import org.opendaylight.yangtools.yang.parser.util.ASTSchemaSource;
 import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
 import org.xml.sax.SAXException;
 
@@ -105,12 +105,12 @@ public class NetconfDeviceTest {
     public static final String TEST_MODULE = "test-module";
     public static final String TEST_REVISION = "2013-07-22";
     public static final SourceIdentifier TEST_SID =
-            RevisionSourceIdentifier.create(TEST_MODULE, Optional.of(TEST_REVISION));
+            RevisionSourceIdentifier.create(TEST_MODULE, Revision.of(TEST_REVISION));
     public static final String TEST_CAPABILITY =
             TEST_NAMESPACE + "?module=" + TEST_MODULE + "&revision=" + TEST_REVISION;
 
     public static final SourceIdentifier TEST_SID2 =
-            RevisionSourceIdentifier.create(TEST_MODULE + "2", Optional.of(TEST_REVISION));
+            RevisionSourceIdentifier.create(TEST_MODULE + "2", Revision.of(TEST_REVISION));
     public static final String TEST_CAPABILITY2 =
             TEST_NAMESPACE + "?module=" + TEST_MODULE + "2" + "&revision=" + TEST_REVISION;
 
@@ -130,9 +130,9 @@ public class NetconfDeviceTest {
                 new SchemaResolutionException("fail first", TEST_SID, new Throwable("YangTools parser fail"));
         doAnswer(invocation -> {
             if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
-                return Futures.immediateFailedCheckedFuture(schemaResolutionException);
+                return Futures.immediateFailedFuture(schemaResolutionException);
             } else {
-                return Futures.immediateCheckedFuture(schema);
+                return Futures.immediateFuture(schema);
             }
         }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
 
@@ -161,7 +161,8 @@ public class NetconfDeviceTest {
         device.onRemoteSessionUp(sessionCaps, listener);
 
         Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(
-                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class),
+                any(DOMActionService.class));
         Mockito.verify(schemaFactory, times(2)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
     }
 
@@ -178,9 +179,8 @@ public class NetconfDeviceTest {
         // Make fallback attempt to fail due to empty resolved sources
         final SchemaResolutionException schemaResolutionException
                 = new SchemaResolutionException("fail first",
-                Collections.<SourceIdentifier>emptyList(), HashMultimap.<SourceIdentifier, ModuleImport>create());
-        doReturn(Futures.immediateFailedCheckedFuture(
-                schemaResolutionException))
+                Collections.emptyList(), HashMultimap.create());
+        doReturn(Futures.immediateFailedFuture(schemaResolutionException))
                 .when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
 
         final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice
@@ -214,13 +214,13 @@ public class NetconfDeviceTest {
         // Make fallback attempt to fail due to empty resolved sources
         final MissingSchemaSourceException schemaResolutionException =
                 new MissingSchemaSourceException("fail first", TEST_SID);
-        doReturn(Futures.immediateFailedCheckedFuture(schemaResolutionException))
-                .when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(ASTSchemaSource.class));
+        doReturn(Futures.immediateFailedFuture(schemaResolutionException))
+                .when(schemaRepository).getSchemaSource(eq(TEST_SID), eq(YangTextSchemaSource.class));
         doAnswer(invocation -> {
             if (((Collection<?>) invocation.getArguments()[0]).size() == 2) {
-                return Futures.immediateFailedCheckedFuture(schemaResolutionException);
+                return Futures.immediateFailedFuture(schemaResolutionException);
             } else {
-                return Futures.immediateCheckedFuture(schema);
+                return Futures.immediateFuture(schema);
             }
         }).when(schemaFactory).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
 
@@ -249,7 +249,8 @@ public class NetconfDeviceTest {
         device.onRemoteSessionUp(sessionCaps, listener);
 
         Mockito.verify(facade, Mockito.timeout(5000)).onDeviceConnected(
-                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class),
+                any(DOMActionService.class));
         Mockito.verify(schemaFactory, times(1)).createSchemaContext(anyCollectionOf(SourceIdentifier.class));
     }
 
@@ -266,8 +267,8 @@ public class NetconfDeviceTest {
     private static SchemaRepository getSchemaRepository() {
         final SchemaRepository mock = mock(SchemaRepository.class);
         final SchemaSourceRepresentation mockRep = mock(SchemaSourceRepresentation.class);
-        doReturn(Futures.immediateCheckedFuture(mockRep))
-                .when(mock).getSchemaSource(any(SourceIdentifier.class), eq(ASTSchemaSource.class));
+        doReturn(Futures.immediateFuture(mockRep))
+                .when(mock).getSchemaSource(any(SourceIdentifier.class), eq(YangTextSchemaSource.class));
         return mock;
     }
 
@@ -275,9 +276,12 @@ public class NetconfDeviceTest {
     public void testNotificationBeforeSchema() throws Exception {
         final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
         final NetconfDeviceCommunicator listener = getListener();
-
-        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO = new NetconfDevice.SchemaResourcesDTO(
-                getSchemaRegistry(), getSchemaRepository(), getSchemaFactory(), STATE_SCHEMAS_RESOLVER);
+        final SchemaContextFactory schemaContextProviderFactory = mock(SchemaContextFactory.class);
+        final SettableFuture<SchemaContext> schemaFuture = SettableFuture.create();
+        doReturn(schemaFuture).when(schemaContextProviderFactory).createSchemaContext(any(Collection.class));
+        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO =
+                new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(),
+                        schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
         final NetconfDevice device = new NetconfDeviceBuilder()
                 .setReconnectOnSchemasChange(true)
                 .setSchemaResourcesDTO(schemaResourcesDTO)
@@ -286,19 +290,16 @@ public class NetconfDeviceTest {
                 .setSalFacade(facade)
                 .build();
 
-        device.onNotification(NOTIFICATION);
-        device.onNotification(NOTIFICATION);
-
-        verify(facade, times(0)).onNotification(any(DOMNotification.class));
-
         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
                 Lists.newArrayList(TEST_CAPABILITY));
+        device.onRemoteSessionUp(sessionCaps, listener);
 
-        final DOMRpcService deviceRpc = mock(DOMRpcService.class);
-
-        device.handleSalInitializationSuccess(
-                NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false), sessionCaps, deviceRpc);
+        device.onNotification(NOTIFICATION);
+        device.onNotification(NOTIFICATION);
+        verify(facade, times(0)).onNotification(any(DOMNotification.class));
 
+        verify(facade, times(0)).onNotification(any(DOMNotification.class));
+        schemaFuture.set(NetconfToNotificationTest.getNotificationSchemaContext(getClass(), false));
         verify(facade, timeout(10000).times(2)).onNotification(any(DOMNotification.class));
 
         device.onNotification(NOTIFICATION);
@@ -327,7 +328,8 @@ public class NetconfDeviceTest {
 
         verify(schemaContextProviderFactory, timeout(5000)).createSchemaContext(any(Collection.class));
         verify(facade, timeout(5000)).onDeviceConnected(
-                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class),
+                any(DOMActionService.class));
 
         device.onRemoteSessionDown();
         verify(facade, timeout(5000)).onDeviceDisconnected();
@@ -336,7 +338,38 @@ public class NetconfDeviceTest {
 
         verify(schemaContextProviderFactory, timeout(5000).times(2)).createSchemaContext(any(Collection.class));
         verify(facade, timeout(5000).times(2)).onDeviceConnected(
-                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class));
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(DOMRpcService.class),
+                any(DOMActionService.class));
+    }
+
+    @Test
+    public void testNetconfDeviceDisconnectListenerCallCancellation() throws Exception {
+        final RemoteDeviceHandler<NetconfSessionPreferences> facade = getFacade();
+        final NetconfDeviceCommunicator listener = getListener();
+        final SchemaContextFactory schemaContextProviderFactory = mock(SchemaContextFactory.class);
+        final SettableFuture<SchemaContext> schemaFuture = SettableFuture.create();
+        doReturn(schemaFuture).when(schemaContextProviderFactory).createSchemaContext(any(Collection.class));
+        final NetconfDevice.SchemaResourcesDTO schemaResourcesDTO
+                = new NetconfDevice.SchemaResourcesDTO(getSchemaRegistry(), getSchemaRepository(),
+                schemaContextProviderFactory, STATE_SCHEMAS_RESOLVER);
+        final NetconfDevice device = new NetconfDeviceBuilder()
+                .setReconnectOnSchemasChange(true)
+                .setSchemaResourcesDTO(schemaResourcesDTO)
+                .setGlobalProcessingExecutor(getExecutor())
+                .setId(getId())
+                .setSalFacade(facade)
+                .build();
+        final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
+                Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
+        //session up, start schema resolution
+        device.onRemoteSessionUp(sessionCaps, listener);
+        //session closed
+        device.onRemoteSessionDown();
+        verify(facade, timeout(5000)).onDeviceDisconnected();
+        //complete schema setup
+        schemaFuture.set(getSchema());
+        //facade.onDeviceDisconnected() was called, so facade.onDeviceConnected() shouldn't be called anymore
+        verify(facade, after(1000).never()).onDeviceConnected(any(), any(), any(), any(DOMActionService.class));
     }
 
     @Test
@@ -355,22 +388,23 @@ public class NetconfDeviceTest {
                 .setId(getId())
                 .setSalFacade(facade)
                 .build();
-        NetconfDevice netconfSpy = Mockito.spy(device);
+        final NetconfDevice netconfSpy = Mockito.spy(device);
 
         final NetconfSessionPreferences sessionCaps = getSessionCaps(true,
                 Lists.newArrayList(TEST_NAMESPACE + "?module=" + TEST_MODULE + "&amp;revision=" + TEST_REVISION));
-        Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
+        final Map<QName, AvailableCapability.CapabilityOrigin> moduleBasedCaps = new HashMap<>();
         moduleBasedCaps.putAll(sessionCaps.getModuleBasedCapsOrigin());
         moduleBasedCaps
                 .put(QName.create("(test:qname:side:loading)test"), AvailableCapability.CapabilityOrigin.UserDefined);
 
         netconfSpy.onRemoteSessionUp(sessionCaps.replaceModuleCaps(moduleBasedCaps), listener);
 
-        ArgumentCaptor argument = ArgumentCaptor.forClass(NetconfSessionPreferences.class);
-        verify(netconfSpy, timeout(5000)).handleSalInitializationSuccess(
-                any(SchemaContext.class), (NetconfSessionPreferences) argument.capture(), any(DOMRpcService.class));
-        NetconfDeviceCapabilities netconfDeviceCaps =
-                ((NetconfSessionPreferences) argument.getValue()).getNetconfDeviceCapabilities();
+        final ArgumentCaptor<NetconfSessionPreferences> argument =
+                ArgumentCaptor.forClass(NetconfSessionPreferences.class);
+        verify(facade, timeout(5000))
+                .onDeviceConnected(any(SchemaContext.class), argument.capture(), any(DOMRpcService.class),
+                        any(DOMActionService.class));
+        final NetconfDeviceCapabilities netconfDeviceCaps = argument.getValue().getNetconfDeviceCapabilities();
 
         netconfDeviceCaps.getResolvedCapabilities()
                 .forEach(entry -> assertEquals("Builded 'AvailableCapability' schemas should match input capabilities.",
@@ -380,23 +414,21 @@ public class NetconfDeviceTest {
 
     private static SchemaContextFactory getSchemaFactory() throws Exception {
         final SchemaContextFactory schemaFactory = mockClass(SchemaContextFactory.class);
-        doReturn(Futures.immediateCheckedFuture(getSchema()))
+        doReturn(Futures.immediateFuture(getSchema()))
                 .when(schemaFactory).createSchemaContext(any(Collection.class));
         return schemaFactory;
     }
 
-    public static SchemaContext getSchema() throws Exception {
-        final List<InputStream> modelsToParse = Lists.newArrayList(
-                NetconfDeviceTest.class.getResourceAsStream("/schemas/test-module.yang")
-        );
-        return YangParserTestUtils.parseYangStreams(modelsToParse);
+    public static SchemaContext getSchema() {
+        return YangParserTestUtils.parseYangResource("/schemas/test-module.yang");
     }
 
     private static RemoteDeviceHandler<NetconfSessionPreferences> getFacade() throws Exception {
         final RemoteDeviceHandler<NetconfSessionPreferences> remoteDeviceHandler =
                 mockCloseableClass(RemoteDeviceHandler.class);
         doNothing().when(remoteDeviceHandler).onDeviceConnected(
-                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class));
+                any(SchemaContext.class), any(NetconfSessionPreferences.class), any(NetconfDeviceRpc.class),
+                any(DOMActionService.class));
         doNothing().when(remoteDeviceHandler).onDeviceDisconnected();
         doNothing().when(remoteDeviceHandler).onNotification(any(DOMNotification.class));
         return remoteDeviceHandler;
@@ -419,8 +451,8 @@ public class NetconfDeviceTest {
         return new RemoteDeviceId("test-D", InetSocketAddress.createUnresolved("localhost", 22));
     }
 
-    public ExecutorService getExecutor() {
-        return Executors.newSingleThreadExecutor();
+    public ListeningExecutorService getExecutor() {
+        return MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
     }
 
     public MessageTransformer<NetconfMessage> getMessageTransformer() throws Exception {