Repository: mina-sshd Updated Branches: refs/heads/master b5bb002f0 -> ae8d1c995
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractCheckFileExtensionTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractCheckFileExtensionTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractCheckFileExtensionTest.java index a47e5d2..9ddeb30 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractCheckFileExtensionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractCheckFileExtensionTest.java @@ -32,7 +32,6 @@ import java.util.LinkedList; import java.util.List; import java.util.concurrent.TimeUnit; -import org.apache.sshd.client.SshClient; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.client.subsystem.sftp.AbstractSftpClientTestSupport; import org.apache.sshd.client.subsystem.sftp.SftpClient; @@ -52,7 +51,6 @@ import org.apache.sshd.common.util.Pair; import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.Utils; -import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -125,11 +123,6 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor setupServer(); } - @After - public void tearDown() throws Exception { - tearDownServer(); - } - @Test public void testCheckFileExtension() throws Exception { testCheckFileExtension(algorithm, dataSize, blockSize); @@ -169,7 +162,7 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor Path srcFile = assertHierarchyTargetFolderExists(lclSftp).resolve(factory.getName() + "-data-" + data.length + "-" + hashBlockSize + ".txt"); Files.write(srcFile, data, IoUtils.EMPTY_OPEN_OPTIONS); - List<String> algorithms = new ArrayList<String>(BuiltinDigests.VALUES.size()); + List<String> algorithms = new ArrayList<>(BuiltinDigests.VALUES.size()); // put the selected algorithm 1st and then the rest algorithms.add(factory.getName()); for (NamedFactory<? extends Digest> f : BuiltinDigests.VALUES) { @@ -183,40 +176,33 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor Path parentPath = targetPath.getParent(); String srcPath = Utils.resolveRelativeRemotePath(parentPath, srcFile); String srcFolder = Utils.resolveRelativeRemotePath(parentPath, srcFile.getParent()); + try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { + session.addPasswordIdentity(getCurrentTestName()); + session.auth().verify(5L, TimeUnit.SECONDS); + + try (SftpClient sftp = session.createSftpClient()) { + CheckFileNameExtension file = assertExtensionCreated(sftp, CheckFileNameExtension.class); + try { + Pair<String, ?> result = file.checkFileName(srcFolder, algorithms, 0L, 0L, hashBlockSize); + fail("Unexpected success to hash folder=" + srcFolder + ": " + result.getFirst()); + } catch (IOException e) { // expected - not allowed to hash a folder + assertTrue("Not an SftpException", e instanceof SftpException); + } - try (SshClient client = setupTestClient()) { - client.start(); - - try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { - session.addPasswordIdentity(getCurrentTestName()); - session.auth().verify(5L, TimeUnit.SECONDS); - - try (SftpClient sftp = session.createSftpClient()) { - CheckFileNameExtension file = assertExtensionCreated(sftp, CheckFileNameExtension.class); + CheckFileHandleExtension hndl = assertExtensionCreated(sftp, CheckFileHandleExtension.class); + try (CloseableHandle dirHandle = sftp.openDir(srcFolder)) { try { - Pair<String, ?> result = file.checkFileName(srcFolder, algorithms, 0L, 0L, hashBlockSize); - fail("Unexpected success to hash folder=" + srcFolder + ": " + result.getFirst()); + Pair<String, ?> result = hndl.checkFileHandle(dirHandle, algorithms, 0L, 0L, hashBlockSize); + fail("Unexpected handle success on folder=" + srcFolder + ": " + result.getFirst()); } catch (IOException e) { // expected - not allowed to hash a folder assertTrue("Not an SftpException", e instanceof SftpException); } + } - CheckFileHandleExtension hndl = assertExtensionCreated(sftp, CheckFileHandleExtension.class); - try (CloseableHandle dirHandle = sftp.openDir(srcFolder)) { - try { - Pair<String, ?> result = hndl.checkFileHandle(dirHandle, algorithms, 0L, 0L, hashBlockSize); - fail("Unexpected handle success on folder=" + srcFolder + ": " + result.getFirst()); - } catch (IOException e) { // expected - not allowed to hash a folder - assertTrue("Not an SftpException", e instanceof SftpException); - } - } - - validateHashResult(file, file.checkFileName(srcPath, algorithms, 0L, 0L, hashBlockSize), algorithms.get(0), expectedHash); - try (CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Read)) { - validateHashResult(hndl, hndl.checkFileHandle(fileHandle, algorithms, 0L, 0L, hashBlockSize), algorithms.get(0), expectedHash); - } + validateHashResult(file, file.checkFileName(srcPath, algorithms, 0L, 0L, hashBlockSize), algorithms.get(0), expectedHash); + try (CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Read)) { + validateHashResult(hndl, hndl.checkFileHandle(fileHandle, algorithms, 0L, 0L, hashBlockSize), algorithms.get(0), expectedHash); } - } finally { - client.stop(); } } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractMD5HashExtensionTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractMD5HashExtensionTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractMD5HashExtensionTest.java index f39bf12..6c63b6f 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractMD5HashExtensionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/AbstractMD5HashExtensionTest.java @@ -30,7 +30,6 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; -import org.apache.sshd.client.SshClient; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.client.subsystem.sftp.AbstractSftpClientTestSupport; import org.apache.sshd.client.subsystem.sftp.SftpClient; @@ -45,7 +44,6 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.Utils; -import org.junit.After; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; @@ -92,11 +90,6 @@ public class AbstractMD5HashExtensionTest extends AbstractSftpClientTestSupport setupServer(); } - @After - public void tearDown() throws Exception { - tearDownServer(); - } - @Test public void testMD5HashExtension() throws Exception { testMD5HashExtension(size); @@ -138,50 +131,43 @@ public class AbstractMD5HashExtensionTest extends AbstractSftpClientTestSupport Path parentPath = targetPath.getParent(); String srcPath = Utils.resolveRelativeRemotePath(parentPath, srcFile); String srcFolder = Utils.resolveRelativeRemotePath(parentPath, srcFile.getParent()); + try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { + session.addPasswordIdentity(getCurrentTestName()); + session.auth().verify(5L, TimeUnit.SECONDS); + + try (SftpClient sftp = session.createSftpClient()) { + MD5FileExtension file = assertExtensionCreated(sftp, MD5FileExtension.class); + try { + byte[] actual = file.getHash(srcFolder, 0L, 0L, quickHash); + fail("Unexpected file success on folder=" + srcFolder + ": " + BufferUtils.toHex(':', actual)); + } catch (IOException e) { // expected - not allowed to hash a folder + assertTrue("Not an SftpException for file hash on " + srcFolder, e instanceof SftpException); + } - try (SshClient client = setupTestClient()) { - client.start(); - - try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { - session.addPasswordIdentity(getCurrentTestName()); - session.auth().verify(5L, TimeUnit.SECONDS); - - try (SftpClient sftp = session.createSftpClient()) { - MD5FileExtension file = assertExtensionCreated(sftp, MD5FileExtension.class); + MD5HandleExtension hndl = assertExtensionCreated(sftp, MD5HandleExtension.class); + try (CloseableHandle dirHandle = sftp.openDir(srcFolder)) { try { - byte[] actual = file.getHash(srcFolder, 0L, 0L, quickHash); - fail("Unexpected file success on folder=" + srcFolder + ": " + BufferUtils.toHex(':', actual)); + byte[] actual = hndl.getHash(dirHandle, 0L, 0L, quickHash); + fail("Unexpected handle success on folder=" + srcFolder + ": " + BufferUtils.toHex(':', actual)); } catch (IOException e) { // expected - not allowed to hash a folder - assertTrue("Not an SftpException for file hash on " + srcFolder, e instanceof SftpException); - } - - MD5HandleExtension hndl = assertExtensionCreated(sftp, MD5HandleExtension.class); - try (CloseableHandle dirHandle = sftp.openDir(srcFolder)) { - try { - byte[] actual = hndl.getHash(dirHandle, 0L, 0L, quickHash); - fail("Unexpected handle success on folder=" + srcFolder + ": " + BufferUtils.toHex(':', actual)); - } catch (IOException e) { // expected - not allowed to hash a folder - assertTrue("Not an SftpException for handle hash on " + srcFolder, e instanceof SftpException); - } + assertTrue("Not an SftpException for handle hash on " + srcFolder, e instanceof SftpException); } + } - try (CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Read)) { - for (byte[] qh : new byte[][]{GenericUtils.EMPTY_BYTE_ARRAY, quickHash}) { - for (boolean useFile : new boolean[]{true, false}) { - byte[] actualHash = useFile ? file.getHash(srcPath, 0L, 0L, qh) : hndl.getHash(fileHandle, 0L, 0L, qh); - String type = useFile ? file.getClass().getSimpleName() : hndl.getClass().getSimpleName(); - if (!Arrays.equals(expectedHash, actualHash)) { - fail("Mismatched hash for quick=" + BufferUtils.toHex(':', qh) - + " using " + type + " on " + srcFile - + ": expected=" + BufferUtils.toHex(':', expectedHash) - + ", actual=" + BufferUtils.toHex(':', actualHash)); - } + try (CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Read)) { + for (byte[] qh : new byte[][]{GenericUtils.EMPTY_BYTE_ARRAY, quickHash}) { + for (boolean useFile : new boolean[]{true, false}) { + byte[] actualHash = useFile ? file.getHash(srcPath, 0L, 0L, qh) : hndl.getHash(fileHandle, 0L, 0L, qh); + String type = useFile ? file.getClass().getSimpleName() : hndl.getClass().getSimpleName(); + if (!Arrays.equals(expectedHash, actualHash)) { + fail("Mismatched hash for quick=" + BufferUtils.toHex(':', qh) + + " using " + type + " on " + srcFile + + ": expected=" + BufferUtils.toHex(':', expectedHash) + + ", actual=" + BufferUtils.toHex(':', actualHash)); } } } } - } finally { - client.stop(); } } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyDataExtensionImplTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyDataExtensionImplTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyDataExtensionImplTest.java index 2ae45a4..e2ba00d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyDataExtensionImplTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyDataExtensionImplTest.java @@ -34,7 +34,6 @@ import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; -import org.apache.sshd.client.SshClient; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.client.subsystem.sftp.AbstractSftpClientTestSupport; import org.apache.sshd.client.subsystem.sftp.SftpClient; @@ -45,7 +44,6 @@ import org.apache.sshd.common.random.Random; import org.apache.sshd.common.subsystem.sftp.SftpConstants; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.Utils; -import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -111,11 +109,6 @@ public class CopyDataExtensionImplTest extends AbstractSftpClientTestSupport { setupServer(); } - @After - public void tearDown() throws Exception { - tearDownServer(); - } - @Test public void testCopyDataExtension() throws Exception { testCopyDataExtension(size, srcOffset, length, dstOffset); @@ -151,37 +144,30 @@ public class CopyDataExtensionImplTest extends AbstractSftpClientTestSupport { Files.delete(dstFile); } String dstPath = Utils.resolveRelativeRemotePath(parentPath, dstFile); - - try (SshClient client = setupTestClient()) { - client.start(); - - if (writeOffset > 0L) { - Factory<? extends Random> factory = client.getRandomFactory(); - Random randomizer = factory.create(); - long totalLength = writeOffset + readLength; - byte[] workBuf = new byte[(int) Math.min(totalLength, IoUtils.DEFAULT_COPY_SIZE)]; - try (OutputStream output = Files.newOutputStream(dstFile, IoUtils.EMPTY_OPEN_OPTIONS)) { - while (totalLength > 0L) { - randomizer.fill(workBuf); - output.write(workBuf); - totalLength -= workBuf.length; - } + if (writeOffset > 0L) { + Factory<? extends Random> factory = client.getRandomFactory(); + Random randomizer = factory.create(); + long totalLength = writeOffset + readLength; + byte[] workBuf = new byte[(int) Math.min(totalLength, IoUtils.DEFAULT_COPY_SIZE)]; + try (OutputStream output = Files.newOutputStream(dstFile, IoUtils.EMPTY_OPEN_OPTIONS)) { + while (totalLength > 0L) { + randomizer.fill(workBuf); + output.write(workBuf); + totalLength -= workBuf.length; } } + } - try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { - session.addPasswordIdentity(getCurrentTestName()); - session.auth().verify(5L, TimeUnit.SECONDS); + try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { + session.addPasswordIdentity(getCurrentTestName()); + session.auth().verify(5L, TimeUnit.SECONDS); - try (SftpClient sftp = session.createSftpClient()) { - CopyDataExtension ext = assertExtensionCreated(sftp, CopyDataExtension.class); - try (CloseableHandle readHandle = sftp.open(srcPath, SftpClient.OpenMode.Read); - CloseableHandle writeHandle = sftp.open(dstPath, SftpClient.OpenMode.Write, SftpClient.OpenMode.Create)) { - ext.copyData(readHandle, readOffset, readLength, writeHandle, writeOffset); - } + try (SftpClient sftp = session.createSftpClient()) { + CopyDataExtension ext = assertExtensionCreated(sftp, CopyDataExtension.class); + try (CloseableHandle readHandle = sftp.open(srcPath, SftpClient.OpenMode.Read); + CloseableHandle writeHandle = sftp.open(dstPath, SftpClient.OpenMode.Write, SftpClient.OpenMode.Create)) { + ext.copyData(readHandle, readOffset, readLength, writeHandle, writeOffset); } - } finally { - client.stop(); } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyFileExtensionImplTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyFileExtensionImplTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyFileExtensionImplTest.java index e929f47..f1acc08 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyFileExtensionImplTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/CopyFileExtensionImplTest.java @@ -26,7 +26,6 @@ import java.nio.file.LinkOption; import java.nio.file.Path; import java.util.concurrent.TimeUnit; -import org.apache.sshd.client.SshClient; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.client.subsystem.sftp.AbstractSftpClientTestSupport; import org.apache.sshd.client.subsystem.sftp.SftpClient; @@ -35,7 +34,6 @@ import org.apache.sshd.common.subsystem.sftp.SftpConstants; import org.apache.sshd.common.subsystem.sftp.SftpException; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.Utils; -import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -55,11 +53,6 @@ public class CopyFileExtensionImplTest extends AbstractSftpClientTestSupport { setupServer(); } - @After - public void tearDown() throws Exception { - tearDownServer(); - } - @Test public void testCopyFileExtension() throws Exception { Path targetPath = detectTargetFolder(); @@ -78,31 +71,25 @@ public class CopyFileExtensionImplTest extends AbstractSftpClientTestSupport { LinkOption[] options = IoUtils.getLinkOptions(false); assertFalse("Destination file unexpectedly exists", Files.exists(dstFile, options)); - try (SshClient client = setupTestClient()) { - client.start(); + try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { + session.addPasswordIdentity(getCurrentTestName()); + session.auth().verify(5L, TimeUnit.SECONDS); - try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { - session.addPasswordIdentity(getCurrentTestName()); - session.auth().verify(5L, TimeUnit.SECONDS); + try (SftpClient sftp = session.createSftpClient()) { + CopyFileExtension ext = assertExtensionCreated(sftp, CopyFileExtension.class); + ext.copyFile(srcPath, dstPath, false); + assertTrue("Source file not preserved", Files.exists(srcFile, options)); + assertTrue("Destination file not created", Files.exists(dstFile, options)); - try (SftpClient sftp = session.createSftpClient()) { - CopyFileExtension ext = assertExtensionCreated(sftp, CopyFileExtension.class); - ext.copyFile(srcPath, dstPath, false); - assertTrue("Source file not preserved", Files.exists(srcFile, options)); - assertTrue("Destination file not created", Files.exists(dstFile, options)); + byte[] actual = Files.readAllBytes(dstFile); + assertArrayEquals("Mismatched copied data", data, actual); - byte[] actual = Files.readAllBytes(dstFile); - assertArrayEquals("Mismatched copied data", data, actual); - - try { - ext.copyFile(srcPath, dstPath, false); - fail("Unexpected success to overwrite existing destination: " + dstFile); - } catch (IOException e) { - assertTrue("Not an SftpException", e instanceof SftpException); - } + try { + ext.copyFile(srcPath, dstPath, false); + fail("Unexpected success to overwrite existing destination: " + dstFile); + } catch (IOException e) { + assertTrue("Not an SftpException", e instanceof SftpException); } - } finally { - client.stop(); } } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/SpaceAvailableExtensionImplTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/SpaceAvailableExtensionImplTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/SpaceAvailableExtensionImplTest.java index e8affed..ef1cb61 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/SpaceAvailableExtensionImplTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/helpers/SpaceAvailableExtensionImplTest.java @@ -25,9 +25,9 @@ import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.Path; import java.util.Arrays; +import java.util.List; import java.util.concurrent.TimeUnit; -import org.apache.sshd.client.SshClient; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.client.subsystem.sftp.AbstractSftpClientTestSupport; import org.apache.sshd.client.subsystem.sftp.SftpClient; @@ -39,7 +39,6 @@ import org.apache.sshd.server.Command; import org.apache.sshd.server.subsystem.sftp.SftpSubsystem; import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory; import org.apache.sshd.util.test.Utils; -import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -59,11 +58,6 @@ public class SpaceAvailableExtensionImplTest extends AbstractSftpClientTestSuppo setupServer(); } - @After - public void tearDown() throws Exception { - tearDownServer(); - } - @Test public void testFileStoreReport() throws Exception { Path targetPath = detectTargetFolder(); @@ -72,6 +66,8 @@ public class SpaceAvailableExtensionImplTest extends AbstractSftpClientTestSuppo FileStore store = Files.getFileStore(lclSftp.getRoot()); final String queryPath = Utils.resolveRelativeRemotePath(parentPath, lclSftp); final SpaceAvailableExtensionInfo expected = new SpaceAvailableExtensionInfo(store); + + List<NamedFactory<Command>> factories = sshd.getSubsystemFactories(); sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory() { @Override public Command create() { @@ -88,21 +84,17 @@ public class SpaceAvailableExtensionImplTest extends AbstractSftpClientTestSuppo } })); - try (SshClient client = setupTestClient()) { - client.start(); - - try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { - session.addPasswordIdentity(getCurrentTestName()); - session.auth().verify(5L, TimeUnit.SECONDS); + try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { + session.addPasswordIdentity(getCurrentTestName()); + session.auth().verify(5L, TimeUnit.SECONDS); - try (SftpClient sftp = session.createSftpClient()) { - SpaceAvailableExtension ext = assertExtensionCreated(sftp, SpaceAvailableExtension.class); - SpaceAvailableExtensionInfo actual = ext.available(queryPath); - assertEquals("Mismatched information", expected, actual); - } - } finally { - client.stop(); + try (SftpClient sftp = session.createSftpClient()) { + SpaceAvailableExtension ext = assertExtensionCreated(sftp, SpaceAvailableExtension.class); + SpaceAvailableExtensionInfo actual = ext.available(queryPath); + assertEquals("Mismatched information", expected, actual); } + } finally { + sshd.setSubsystemFactories(factories); } } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/openssh/helpers/OpenSSHExtensionsTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/openssh/helpers/OpenSSHExtensionsTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/openssh/helpers/OpenSSHExtensionsTest.java index 7a6223c..d69813e 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/openssh/helpers/OpenSSHExtensionsTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/openssh/helpers/OpenSSHExtensionsTest.java @@ -54,7 +54,6 @@ import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.server.subsystem.sftp.SftpSubsystem; import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory; import org.apache.sshd.util.test.Utils; -import org.junit.After; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; @@ -74,11 +73,6 @@ public class OpenSSHExtensionsTest extends AbstractSftpClientTestSupport { setupServer(); } - @After - public void tearDown() throws Exception { - tearDownServer(); - } - @Test public void testFsync() throws IOException { Path targetPath = detectTargetFolder(); @@ -88,25 +82,19 @@ public class OpenSSHExtensionsTest extends AbstractSftpClientTestSupport { Path parentPath = targetPath.getParent(); String srcPath = Utils.resolveRelativeRemotePath(parentPath, srcFile); - try (SshClient client = setupTestClient()) { - client.start(); - - try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { - session.addPasswordIdentity(getCurrentTestName()); - session.auth().verify(5L, TimeUnit.SECONDS); - - try (SftpClient sftp = session.createSftpClient()) { - OpenSSHFsyncExtension fsync = assertExtensionCreated(sftp, OpenSSHFsyncExtension.class); - try (CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Write, SftpClient.OpenMode.Create)) { - sftp.write(fileHandle, 0L, expected); - fsync.fsync(fileHandle); - - byte[] actual = Files.readAllBytes(srcFile); - assertArrayEquals("Mismatched written data", expected, actual); - } + try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { + session.addPasswordIdentity(getCurrentTestName()); + session.auth().verify(5L, TimeUnit.SECONDS); + + try (SftpClient sftp = session.createSftpClient()) { + OpenSSHFsyncExtension fsync = assertExtensionCreated(sftp, OpenSSHFsyncExtension.class); + try (CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Write, SftpClient.OpenMode.Create)) { + sftp.write(fileHandle, 0L, expected); + fsync.fsync(fileHandle); + + byte[] actual = Files.readAllBytes(srcFile); + assertArrayEquals("Mismatched written data", expected, actual); } - } finally { - client.stop(); } } } @@ -120,7 +108,7 @@ public class OpenSSHExtensionsTest extends AbstractSftpClientTestSupport { Path parentPath = targetPath.getParent(); String srcPath = Utils.resolveRelativeRemotePath(parentPath, srcFile); - final AtomicReference<String> extensionHolder = new AtomicReference<String>(null); + final AtomicReference<String> extensionHolder = new AtomicReference<>(null); final OpenSSHStatExtensionInfo expected = new OpenSSHStatExtensionInfo(); expected.f_bavail = Short.MAX_VALUE; expected.f_bfree = Integer.MAX_VALUE; @@ -142,7 +130,7 @@ public class OpenSSHExtensionsTest extends AbstractSftpClientTestSupport { protected List<OpenSSHExtension> resolveOpenSSHExtensions(ServerSession session) { List<OpenSSHExtension> original = super.resolveOpenSSHExtensions(session); int numOriginal = GenericUtils.size(original); - List<OpenSSHExtension> result = new ArrayList<OpenSSHExtension>(numOriginal + 2); + List<OpenSSHExtension> result = new ArrayList<>(numOriginal + 2); if (numOriginal > 0) { result.addAll(original); } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java b/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java index d47019b..36883cc 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java @@ -39,6 +39,7 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.JSchLogger; import org.apache.sshd.util.test.SimpleUserInfo; import org.apache.sshd.util.test.Utils; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.BeforeClass; import org.junit.FixMethodOrder; @@ -87,6 +88,8 @@ public class CipherTest extends BaseTestSupport { }); private static final String CRYPT_NAMES = NamedResource.Utils.getNames(TEST_CIPHERS); + private static SshServer sshd; + private static int port; private final Random random = Utils.getRandomizerInstance(); private final BuiltinCiphers builtInCipher; @@ -105,26 +108,31 @@ public class CipherTest extends BaseTestSupport { } @BeforeClass - public static void jschInit() { + public static void setupClientAndServer() throws Exception { JSchLogger.init(); + sshd = Utils.setupTestServer(CipherTest.class); + sshd.start(); + port = sshd.getPort(); } - @Test - public void testBuiltinCipherSession() throws Exception { - Assume.assumeTrue("No internal support for " + builtInCipher.getName(), builtInCipher.isSupported() && checkCipher(jschCipher.getName())); - - try (SshServer sshd = setupTestServer()) { - sshd.setCipherFactories(Collections.<NamedFactory<org.apache.sshd.common.cipher.Cipher>>singletonList(builtInCipher)); - sshd.start(); - + @AfterClass + public static void tearDownClientAndServer() throws Exception { + if (sshd != null) { try { - runJschTest(sshd.getPort()); - } finally { sshd.stop(true); + } finally { + sshd = null; } } } + @Test + public void testBuiltinCipherSession() throws Exception { + Assume.assumeTrue("No internal support for " + builtInCipher.getName(), builtInCipher.isSupported() && checkCipher(jschCipher.getName())); + sshd.setCipherFactories(Collections.<NamedFactory<org.apache.sshd.common.cipher.Cipher>>singletonList(builtInCipher)); + runJschTest(port); + } + private void runJschTest(int port) throws Exception { JSch sch = new JSch(); JSch.setConfig("cipher.s2c", CRYPT_NAMES); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java b/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java index 4ded562..59f2af9 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/compression/CompressionTest.java @@ -32,13 +32,16 @@ import com.jcraft.jsch.JSch; import org.apache.sshd.common.NamedFactory; import org.apache.sshd.common.channel.Channel; import org.apache.sshd.common.kex.KexProposalOption; +import org.apache.sshd.common.mac.MacTest; import org.apache.sshd.common.session.Session; import org.apache.sshd.common.session.SessionListener; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.JSchLogger; import org.apache.sshd.util.test.SimpleUserInfo; +import org.apache.sshd.util.test.Utils; import org.junit.After; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; @@ -60,11 +63,26 @@ public class CompressionTest extends BaseTestSupport { private static final Collection<KexProposalOption> COMPRESSION_OPTIONS = Collections.unmodifiableSet(EnumSet.of(KexProposalOption.C2SCOMP, KexProposalOption.S2CCOMP)); - private final CompressionFactory factory; - private SshServer sshd; + private static SshServer sshd; + private static int port; + private final CompressionFactory factory; + private final SessionListener listener; public CompressionTest(CompressionFactory factory) { this.factory = factory; + listener = new SessionListener() { + @Override + @SuppressWarnings("synthetic-access") + public void sessionEvent(Session session, Event event) { + if (Event.KeyEstablished.equals(event)) { + String expected = factory.getName(); + for (KexProposalOption option : COMPRESSION_OPTIONS) { + String actual = session.getNegotiatedKexParameter(KexProposalOption.C2SCOMP); + assertEquals("Mismatched value for " + option, expected, actual); + } + } + } + }; } @Parameters(name = "factory={0}") @@ -73,28 +91,30 @@ public class CompressionTest extends BaseTestSupport { } @BeforeClass - public static void jschInit() { + public static void setupClientAndServer() throws Exception { JSchLogger.init(); + + sshd = Utils.setupTestServer(MacTest.class); + sshd.setKeyPairProvider(Utils.createTestHostKeyProvider(MacTest.class)); + sshd.start(); + port = sshd.getPort(); + } + + @AfterClass + public static void tearDownClientAndServer() throws Exception { + if (sshd != null) { + try { + sshd.stop(true); + } finally { + sshd = null; + } + } } @Before public void setUp() throws Exception { - sshd = setupTestServer(); sshd.setCompressionFactories(Arrays.<NamedFactory<org.apache.sshd.common.compression.Compression>>asList(factory)); - sshd.addSessionListener(new SessionListener() { - @Override - @SuppressWarnings("synthetic-access") - public void sessionEvent(Session session, Event event) { - if (Event.KeyEstablished.equals(event)) { - String expected = factory.getName(); - for (KexProposalOption option : COMPRESSION_OPTIONS) { - String actual = session.getNegotiatedKexParameter(KexProposalOption.C2SCOMP); - assertEquals("Mismatched value for " + option, expected, actual); - } - } - } - }); - sshd.start(); + sshd.addSessionListener(listener); String name = factory.getName(); JSch.setConfig("compression.s2c", name); @@ -106,7 +126,7 @@ public class CompressionTest extends BaseTestSupport { @After public void tearDown() throws Exception { if (sshd != null) { - sshd.stop(true); + sshd.removeSessionListener(listener); } JSch.setConfig("compression.s2c", "none"); JSch.setConfig("compression.c2s", "none"); @@ -117,7 +137,7 @@ public class CompressionTest extends BaseTestSupport { Assume.assumeTrue("Skip unsupported compression " + factory, factory.isSupported()); JSch sch = new JSch(); - com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()); + com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port); s.setUserInfo(new SimpleUserInfo(getCurrentTestName())); s.connect(); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingLoadTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingLoadTest.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingLoadTest.java index 86786a4..c788596 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingLoadTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingLoadTest.java @@ -127,6 +127,7 @@ public class PortForwardingLoadTest extends BaseTestSupport { log.info("tornDownDynamicTunnel(session={}, address={}, reason={})", session, address, reason); } }; + private SshServer sshd; private int sshPort; private IoAcceptor acceptor; http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingTest.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingTest.java index 8aae6e2..cba1951 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingTest.java @@ -66,12 +66,12 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.JSchLogger; import org.apache.sshd.util.test.SimpleUserInfo; import org.apache.sshd.util.test.Utils; -import org.junit.After; -import org.junit.Before; +import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; +import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** @@ -79,10 +79,9 @@ import org.slf4j.LoggerFactory; */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class PortForwardingTest extends BaseTestSupport { - - private final org.slf4j.Logger log = LoggerFactory.getLogger(getClass()); @SuppressWarnings("checkstyle:anoninnerlength") - private final PortForwardingEventListener serverSideListener = new PortForwardingEventListener() { + private static final PortForwardingEventListener SERVER_SIDE_LISTENER = new PortForwardingEventListener() { + private final org.slf4j.Logger log = LoggerFactory.getLogger(PortForwardingEventListener.class); @Override public void establishingExplicitTunnel(org.apache.sshd.common.session.Session session, SshdSocketAddress local, @@ -137,34 +136,31 @@ public class PortForwardingTest extends BaseTestSupport { } }; - private final BlockingQueue<String> requestsQ = new LinkedBlockingDeque<>(); - - private SshServer sshd; - private int sshPort; - private int echoPort; - private IoAcceptor acceptor; - private SshClient client; + private static final BlockingQueue<String> REQUESTS_QUEUE = new LinkedBlockingDeque<>(); + private static SshServer sshd; + private static int sshPort; + private static int echoPort; + private static IoAcceptor acceptor; + private static SshClient client; + private final Logger log = LoggerFactory.getLogger(getClass()); public PortForwardingTest() { super(); } @BeforeClass - public static void jschInit() { + public static void setUpTestEnvironment() throws Exception { JSchLogger.init(); - } - - @Before - public void setUp() throws Exception { - sshd = setupTestServer(); + sshd = Utils.setupTestServer(PortForwardingTest.class); PropertyResolverUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 2048); PropertyResolverUtils.updateProperty(sshd, FactoryManager.MAX_PACKET_SIZE, 256); sshd.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE); - sshd.addPortForwardingEventListener(serverSideListener); + sshd.addPortForwardingEventListener(SERVER_SIDE_LISTENER); sshd.start(); + sshPort = sshd.getPort(); - if (!requestsQ.isEmpty()) { - requestsQ.clear(); + if (!REQUESTS_QUEUE.isEmpty()) { + REQUESTS_QUEUE.clear(); } final TcpipForwarderFactory factory = ValidateUtils.checkNotNull(sshd.getTcpipForwarderFactory(), "No TcpipForwarderFactory"); @@ -186,6 +182,8 @@ public class PortForwardingTest extends BaseTestSupport { final TcpipForwarder forwarder = factory.create(service); return (TcpipForwarder) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() { + private final org.slf4j.Logger log = LoggerFactory.getLogger(TcpipForwarder.class); + @SuppressWarnings("synthetic-access") @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { @@ -193,7 +191,7 @@ public class PortForwardingTest extends BaseTestSupport { String name = method.getName(); String request = method2req.get(name); if (GenericUtils.length(request) > 0) { - if (requestsQ.offer(request)) { + if (REQUESTS_QUEUE.offer(request)) { log.info("Signal " + request); } else { log.error("Failed to offer request=" + request); @@ -204,7 +202,6 @@ public class PortForwardingTest extends BaseTestSupport { }); } }); - sshPort = sshd.getPort(); NioSocketAcceptor acceptor = new NioSocketAcceptor(); acceptor.setHandler(new IoHandlerAdapter() { @@ -220,13 +217,28 @@ public class PortForwardingTest extends BaseTestSupport { acceptor.setReuseAddress(true); acceptor.bind(new InetSocketAddress(0)); echoPort = acceptor.getLocalAddress().getPort(); - this.acceptor = acceptor; + + client = Utils.setupTestClient(PortForwardingTest.class); + client.start(); + } + + @AfterClass + public static void tearDownTestEnvironment() throws Exception { + if (sshd != null) { + sshd.stop(true); + } + if (acceptor != null) { + acceptor.dispose(true); + } + if (client != null) { + client.stop(); + } } private void waitForForwardingRequest(String expected, long timeout) throws InterruptedException { for (long remaining = timeout; remaining > 0L;) { long waitStart = System.currentTimeMillis(); - String actual = requestsQ.poll(remaining, TimeUnit.MILLISECONDS); + String actual = REQUESTS_QUEUE.poll(remaining, TimeUnit.MILLISECONDS); long waitEnd = System.currentTimeMillis(); if (GenericUtils.isEmpty(actual)) { throw new IllegalStateException("Failed to retrieve request=" + expected); @@ -243,19 +255,6 @@ public class PortForwardingTest extends BaseTestSupport { throw new IllegalStateException("Timeout while waiting to retrieve request=" + expected); } - @After - public void tearDown() throws Exception { - if (sshd != null) { - sshd.stop(true); - } - if (acceptor != null) { - acceptor.dispose(true); - } - if (client != null) { - client.stop(); - } - } - @Test public void testRemoteForwarding() throws Exception { Session session = createSession(); @@ -800,14 +799,12 @@ public class PortForwardingTest extends BaseTestSupport { } protected ClientSession createNativeSession(PortForwardingEventListener listener) throws Exception { - client = setupTestClient(); PropertyResolverUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 2048); PropertyResolverUtils.updateProperty(client, FactoryManager.MAX_PACKET_SIZE, 256); client.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE); if (listener != null) { client.addPortForwardingEventListener(listener); } - client.start(); ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshPort).verify(7L, TimeUnit.SECONDS).getSession(); session.addPasswordIdentity(getCurrentTestName()); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/kex/KexFactoryManagerTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/kex/KexFactoryManagerTest.java b/sshd-core/src/test/java/org/apache/sshd/common/kex/KexFactoryManagerTest.java index ed2f9e3..b2a9682 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/kex/KexFactoryManagerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/kex/KexFactoryManagerTest.java @@ -49,7 +49,7 @@ public class KexFactoryManagerTest extends BaseTestSupport { @Test public void testDefaultCompressionFactoriesMethods() { - KexFactoryManager manager = new TestKexFactoryManager(); + KexFactoryManager manager = new TestKexFactoryManager(); assertEquals("Mismatched empty factories name list", "", manager.getCompressionFactoriesNameList()); String expected = NamedResource.Utils.getNames(BuiltinCompressions.VALUES); @@ -66,7 +66,7 @@ public class KexFactoryManagerTest extends BaseTestSupport { @Test public void testDefaultCipherFactoriesMethods() { - KexFactoryManager manager = new TestKexFactoryManager(); + KexFactoryManager manager = new TestKexFactoryManager(); assertEquals("Mismatched empty factories name list", "", manager.getCipherFactoriesNameList()); String expected = NamedResource.Utils.getNames(BuiltinCiphers.VALUES); @@ -83,7 +83,7 @@ public class KexFactoryManagerTest extends BaseTestSupport { @Test public void testDefaultMacFactoriesMethods() { - KexFactoryManager manager = new TestKexFactoryManager(); + KexFactoryManager manager = new TestKexFactoryManager(); assertEquals("Mismatched empty factories name list", "", manager.getMacFactoriesNameList()); String expected = NamedResource.Utils.getNames(BuiltinMacs.VALUES); @@ -100,7 +100,7 @@ public class KexFactoryManagerTest extends BaseTestSupport { @Test public void testDefaultSignatureFactoriesMethods() { - KexFactoryManager manager = new TestKexFactoryManager(); + KexFactoryManager manager = new TestKexFactoryManager(); assertEquals("Mismatched empty factories name list", "", manager.getSignatureFactoriesNameList()); String expected = NamedResource.Utils.getNames(BuiltinSignatures.VALUES); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java b/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java index 89081ae..20e5c69 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/mac/MacTest.java @@ -39,7 +39,8 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.JSchLogger; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.After; +import org.apache.sshd.util.test.Utils; +import org.junit.AfterClass; import org.junit.Assume; import org.junit.Before; import org.junit.BeforeClass; @@ -75,10 +76,11 @@ public class MacTest extends BaseTestSupport { } }); + private static SshServer sshd; + private static int port; + private final MacFactory factory; private final String jschMacClass; - private SshServer sshd; - private int port; public MacTest(MacFactory factory, String jschMacClass) { this.factory = factory; @@ -119,27 +121,33 @@ public class MacTest extends BaseTestSupport { return ret; } + @BeforeClass - public static void jschnit() { + public static void setupClientAndServer() throws Exception { JSchLogger.init(); - } - @Before - public void setUp() throws Exception { - sshd = setupTestServer(); - sshd.setKeyPairProvider(createTestHostKeyProvider()); - sshd.setMacFactories(Arrays.<NamedFactory<Mac>>asList(factory)); + sshd = Utils.setupTestServer(MacTest.class); + sshd.setKeyPairProvider(Utils.createTestHostKeyProvider(MacTest.class)); sshd.start(); port = sshd.getPort(); } - @After - public void tearDown() throws Exception { + @AfterClass + public static void tearDownClientAndServer() throws Exception { if (sshd != null) { - sshd.stop(true); + try { + sshd.stop(true); + } finally { + sshd = null; + } } } + @Before + public void setUp() throws Exception { + sshd.setMacFactories(Arrays.<NamedFactory<Mac>>asList(factory)); + } + @Test public void testWithJSCH() throws Exception { String macName = factory.getName(); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java deleted file mode 100644 index 0979a6c..0000000 --- a/sshd-core/src/test/java/org/apache/sshd/common/signature/AbstractSignatureFactoryTestSupport.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sshd.common.signature; - -import java.security.KeyPair; -import java.util.Collections; -import java.util.List; -import java.util.concurrent.TimeUnit; - -import org.apache.sshd.client.SshClient; -import org.apache.sshd.client.session.ClientSession; -import org.apache.sshd.common.Factory; -import org.apache.sshd.common.NamedFactory; -import org.apache.sshd.common.RuntimeSshException; -import org.apache.sshd.common.config.keys.PublicKeyEntryDecoder; -import org.apache.sshd.common.keyprovider.AbstractKeyPairProvider; -import org.apache.sshd.common.keyprovider.KeyPairProvider; -import org.apache.sshd.common.util.ValidateUtils; -import org.apache.sshd.server.SshServer; -import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; - -/** - * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> - */ -public abstract class AbstractSignatureFactoryTestSupport extends BaseTestSupport { - private SshServer sshd; - private SshClient client; - private int port; - - private final String keyType; - private final int keySize; - - protected AbstractSignatureFactoryTestSupport(String keyType, int keySize) { - this.keyType = ValidateUtils.checkNotNullAndNotEmpty(keyType, "No key type specified"); - ValidateUtils.checkTrue(keySize > 0, "Invalid key size: %d", keySize); - this.keySize = keySize; - } - - public final int getKeySize() { - return keySize; - } - - public final String getKeyType() { - return keyType; - } - - @Before - public void setUp() throws Exception { - sshd = setupTestServer(); - } - - @After - public void tearDown() throws Exception { - if (sshd != null) { - sshd.stop(true); - } - if (client != null) { - client.stop(); - } - } - - protected void testKeyPairProvider(PublicKeyEntryDecoder<?, ?> decoder, List<NamedFactory<Signature>> signatures) throws Exception { - testKeyPairProvider(getKeyType(), getKeySize(), decoder, signatures); - } - - protected void testKeyPairProvider( - final String keyName, final int keySize, final PublicKeyEntryDecoder<?, ?> decoder, List<NamedFactory<Signature>> signatures) - throws Exception { - testKeyPairProvider(keyName, new Factory<Iterable<KeyPair>>() { - @Override - public Iterable<KeyPair> create() { - try { - KeyPair kp = decoder.generateKeyPair(keySize); - outputDebugMessage("Generated key pair for %s - key size=%d", keyName, keySize); - return Collections.singletonList(kp); - } catch (Exception e) { - throw new RuntimeSshException(e); - } - } - }, signatures); - } - - protected void testKeyPairProvider( - final String keyName, final Factory<Iterable<KeyPair>> factory, List<NamedFactory<Signature>> signatures) - throws Exception { - final Iterable<KeyPair> iter = factory.create(); - testKeyPairProvider(new AbstractKeyPairProvider() { - @Override - public Iterable<KeyPair> loadKeys() { - return iter; - } - }, signatures); - } - - protected void testKeyPairProvider(KeyPairProvider provider, List<NamedFactory<Signature>> signatures) throws Exception { - sshd.setKeyPairProvider(provider); - sshd.start(); - port = sshd.getPort(); - - client = setupTestClient(); - client.setSignatureFactories(signatures); - client.start(); - try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { - s.addPasswordIdentity(getCurrentTestName()); - // allow a rather long timeout since generating some keys may take some time - s.auth().verify(30L, TimeUnit.SECONDS); - } finally { - client.stop(); - } - } -} http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureDSSFactoryTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureDSSFactoryTest.java b/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureDSSFactoryTest.java deleted file mode 100644 index 949dcd4..0000000 --- a/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureDSSFactoryTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sshd.common.signature; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.apache.sshd.common.NamedFactory; -import org.apache.sshd.common.config.keys.DSSPublicKeyEntryDecoder; -import org.apache.sshd.common.keyprovider.KeyPairProvider; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -/** - * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -public class SignatureDSSFactoryTest extends AbstractSignatureFactoryTestSupport { - private static final List<NamedFactory<Signature>> FACTORIES = - Collections.unmodifiableList(Collections.<NamedFactory<Signature>>singletonList(BuiltinSignatures.dsa)); - - public SignatureDSSFactoryTest(int keySize) { - super(KeyPairProvider.SSH_DSS, keySize); - } - - @Parameters(name = "keySize={0}") - public static Collection<Object[]> parameters() { - return parameterize(DSS_SIZES); - } - - @Test - public void testDSSPublicKeyAuth() throws Exception { - testKeyPairProvider(DSSPublicKeyEntryDecoder.INSTANCE, FACTORIES); - } -} http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureECDSAFactoryTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureECDSAFactoryTest.java b/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureECDSAFactoryTest.java deleted file mode 100644 index 5958f40..0000000 --- a/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureECDSAFactoryTest.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ -package org.apache.sshd.common.signature; - -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.apache.sshd.common.NamedFactory; -import org.apache.sshd.common.cipher.ECCurves; -import org.apache.sshd.common.config.keys.ECDSAPublicKeyEntryDecoder; -import org.apache.sshd.common.util.SecurityUtils; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -/** - * Makes sure that all the available {@link Signature} implementations are tested - * - * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -public class SignatureECDSAFactoryTest extends AbstractSignatureFactoryTestSupport { - private static final List<NamedFactory<Signature>> FACTORIES = - Collections.unmodifiableList( - Arrays.<NamedFactory<Signature>>asList( - BuiltinSignatures.nistp256, - BuiltinSignatures.nistp384, - BuiltinSignatures.nistp521 - )); - - public SignatureECDSAFactoryTest(ECCurves curve) { - super(curve.getName(), curve.getKeySize()); - } - - @Parameters(name = "keySize={0}") - public static Collection<Object[]> parameters() { - return parameterize(ECCurves.VALUES); - } - - @Test - public void testECDSAPublicKeyAuth() throws Exception { - Assume.assumeTrue("ECC not supported", SecurityUtils.hasEcc()); - testKeyPairProvider(ECDSAPublicKeyEntryDecoder.INSTANCE, FACTORIES); - } -} http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureFactoriesTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureFactoriesTest.java b/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureFactoriesTest.java new file mode 100644 index 0000000..4896c5e --- /dev/null +++ b/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureFactoriesTest.java @@ -0,0 +1,184 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.sshd.common.signature; + +import java.security.KeyPair; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.TimeUnit; + +import org.apache.sshd.client.SshClient; +import org.apache.sshd.client.session.ClientSession; +import org.apache.sshd.common.Factory; +import org.apache.sshd.common.NamedFactory; +import org.apache.sshd.common.RuntimeSshException; +import org.apache.sshd.common.cipher.ECCurves; +import org.apache.sshd.common.config.keys.DSSPublicKeyEntryDecoder; +import org.apache.sshd.common.config.keys.ECDSAPublicKeyEntryDecoder; +import org.apache.sshd.common.config.keys.PublicKeyEntryDecoder; +import org.apache.sshd.common.config.keys.RSAPublicKeyDecoder; +import org.apache.sshd.common.keyprovider.AbstractKeyPairProvider; +import org.apache.sshd.common.keyprovider.KeyPairProvider; +import org.apache.sshd.common.util.SecurityUtils; +import org.apache.sshd.common.util.ValidateUtils; +import org.apache.sshd.server.SshServer; +import org.apache.sshd.util.test.BaseTestSupport; +import org.apache.sshd.util.test.Utils; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.FixMethodOrder; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.MethodSorters; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +/** + * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> + */ +@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +public class SignatureFactoriesTest extends BaseTestSupport { + private static SshServer sshd; + private static SshClient client; + private static int port; + + private final String keyType; + private final int keySize; + private final NamedFactory<Signature> factory; + private final PublicKeyEntryDecoder<?, ?> pubKeyDecoder; + + public SignatureFactoriesTest(String keyType, NamedFactory<Signature> factory, int keySize, PublicKeyEntryDecoder<?, ?> decoder) { + this.keyType = ValidateUtils.checkNotNullAndNotEmpty(keyType, "No key type specified"); + this.factory = Objects.requireNonNull(factory, "No signature factory provided"); + ValidateUtils.checkTrue(keySize > 0, "Invalid key size: %d", keySize); + this.keySize = keySize; + this.pubKeyDecoder = Objects.requireNonNull(decoder, "No public key decoder provided"); + } + + @Parameters(name = "type={0}, size={2}") + public static List<Object[]> parameters() { + return Collections.unmodifiableList(new ArrayList<Object[]>() { + // Not serializing it + private static final long serialVersionUID = 1L; + + { + addTests(KeyPairProvider.SSH_DSS, BuiltinSignatures.dsa, DSS_SIZES, DSSPublicKeyEntryDecoder.INSTANCE); + addTests(KeyPairProvider.SSH_RSA, BuiltinSignatures.rsa, RSA_SIZES, RSAPublicKeyDecoder.INSTANCE); + if (SecurityUtils.hasEcc()) { + for (ECCurves curve : ECCurves.VALUES) { + BuiltinSignatures factory = BuiltinSignatures.fromFactoryName(curve.getKeyType()); + addTests(curve.getName(), factory, Collections.singletonList(curve.getKeySize()), ECDSAPublicKeyEntryDecoder.INSTANCE); + } + } + } + + private void addTests(String keyType, NamedFactory<Signature> factory, Collection<Integer> sizes, PublicKeyEntryDecoder<?, ?> decoder) { + for (Integer keySize : sizes) { + add(new Object[]{keyType, factory, keySize, decoder}); + } + } + }); + } + + @BeforeClass + public static void setupClientAndServer() throws Exception { + sshd = Utils.setupTestServer(SignatureFactoriesTest.class); + sshd.start(); + port = sshd.getPort(); + + client = Utils.setupTestClient(SignatureFactoriesTest.class); + client.start(); + } + + @AfterClass + public static void tearDownClientAndServer() throws Exception { + if (sshd != null) { + try { + sshd.stop(true); + } finally { + sshd = null; + } + } + + if (client != null) { + try { + client.stop(); + } finally { + client = null; + } + } + } + + public final int getKeySize() { + return keySize; + } + + public final String getKeyType() { + return keyType; + } + + @Test + public void testPublicKeyAuth() throws Exception { + testKeyPairProvider(getKeyType(), getKeySize(), pubKeyDecoder, Collections.singletonList(factory)); + } + + protected void testKeyPairProvider( + final String keyName, final int keySize, final PublicKeyEntryDecoder<?, ?> decoder, List<NamedFactory<Signature>> signatures) + throws Exception { + testKeyPairProvider(keyName, new Factory<Iterable<KeyPair>>() { + @Override + public Iterable<KeyPair> create() { + try { + KeyPair kp = decoder.generateKeyPair(keySize); + outputDebugMessage("Generated key pair for %s - key size=%d", keyName, keySize); + return Collections.singletonList(kp); + } catch (Exception e) { + throw new RuntimeSshException(e); + } + } + }, signatures); + } + + protected void testKeyPairProvider( + final String keyName, final Factory<Iterable<KeyPair>> keyPairFactory, List<NamedFactory<Signature>> signatures) + throws Exception { + final Iterable<KeyPair> iter = keyPairFactory.create(); + testKeyPairProvider(new AbstractKeyPairProvider() { + @Override + public Iterable<KeyPair> loadKeys() { + return iter; + } + }, signatures); + } + + protected void testKeyPairProvider(KeyPairProvider provider, List<NamedFactory<Signature>> signatures) throws Exception { + sshd.setKeyPairProvider(provider); + client.setSignatureFactories(signatures); + try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(7L, TimeUnit.SECONDS).getSession()) { + s.addPasswordIdentity(getCurrentTestName()); + // allow a rather long timeout since generating some keys may take some time + s.auth().verify(30L, TimeUnit.SECONDS); + } + } +} http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureRSAFactoryTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureRSAFactoryTest.java b/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureRSAFactoryTest.java deleted file mode 100644 index 33960ce..0000000 --- a/sshd-core/src/test/java/org/apache/sshd/common/signature/SignatureRSAFactoryTest.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -package org.apache.sshd.common.signature; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import org.apache.sshd.common.NamedFactory; -import org.apache.sshd.common.config.keys.RSAPublicKeyDecoder; -import org.apache.sshd.common.keyprovider.KeyPairProvider; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; - -/** - * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> - */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -public class SignatureRSAFactoryTest extends AbstractSignatureFactoryTestSupport { - private static final List<NamedFactory<Signature>> FACTORIES = - Collections.unmodifiableList(Collections.<NamedFactory<Signature>>singletonList(BuiltinSignatures.rsa)); - - public SignatureRSAFactoryTest(int keySize) { - super(KeyPairProvider.SSH_RSA, keySize); - } - - @Parameters(name = "keySize={0}") - public static Collection<Object[]> parameters() { - return parameterize(RSA_SIZES); - } - - @Test - public void testRSAPublicKeyAuth() throws Exception { - testKeyPairProvider(RSAPublicKeyDecoder.INSTANCE, FACTORIES); - } -} http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/server/ServerSessionListenerTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerSessionListenerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerSessionListenerTest.java index 4b13e8a..5fcaba2 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/ServerSessionListenerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerSessionListenerTest.java @@ -47,8 +47,9 @@ import org.apache.sshd.server.auth.password.PasswordAuthenticator; import org.apache.sshd.server.auth.password.PasswordChangeRequiredException; import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; +import org.apache.sshd.util.test.Utils; +import org.junit.AfterClass; +import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @@ -60,29 +61,40 @@ import org.slf4j.LoggerFactory; */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class ServerSessionListenerTest extends BaseTestSupport { - private SshServer sshd; - private SshClient client; - private int port; + private static SshServer sshd; + private static int port; + private static SshClient client; public ServerSessionListenerTest() { super(); } - @Before - public void setUp() throws Exception { - sshd = setupTestServer(); + + @BeforeClass + public static void setupClientAndServer() throws Exception { + sshd = Utils.setupTestServer(ServerSessionListenerTest.class); sshd.start(); port = sshd.getPort(); - client = setupTestClient(); + client = Utils.setupTestClient(ServerSessionListenerTest.class); + client.start(); } - @After - public void tearDown() throws Exception { + @AfterClass + public static void tearDownClientAndServer() throws Exception { if (sshd != null) { - sshd.stop(true); + try { + sshd.stop(true); + } finally { + sshd = null; + } } + if (client != null) { - client.stop(); + try { + client.stop(); + } finally { + client = null; + } } } @@ -90,7 +102,7 @@ public class ServerSessionListenerTest extends BaseTestSupport { public void testServerStillListensIfSessionListenerThrowsException() throws Exception { final Map<String, SocketAddress> eventsMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); final Logger log = LoggerFactory.getLogger(getClass()); - sshd.addSessionListener(new SessionListener() { + SessionListener listener = new SessionListener() { @Override public void sessionCreated(Session session) { throwException("SessionCreated", session); @@ -119,36 +131,38 @@ public class ServerSessionListenerTest extends BaseTestSupport { log.info(e.getMessage()); throw e; } - }); - - client.start(); + }; + sshd.addSessionListener(listener); int curCount = 0; - for (int retryCount = 0; retryCount < Byte.SIZE; retryCount++) { - synchronized (eventsMap) { - curCount = eventsMap.size(); - if (curCount >= 3) { - return; + try { + for (int retryCount = 0; retryCount < Byte.SIZE; retryCount++) { + synchronized (eventsMap) { + curCount = eventsMap.size(); + if (curCount >= 3) { + return; + } } - } - try { - try (ClientSession s = createTestClientSession()) { - log.info("Retry #" + retryCount + " successful"); - } + try { + try (ClientSession s = createTestClientSession()) { + log.info("Retry #" + retryCount + " successful"); + } - synchronized (eventsMap) { - assertTrue("Unexpected premature success at retry # " + retryCount + ": " + eventsMap, eventsMap.size() >= 3); - } - } catch (IOException e) { - // expected - ignored - synchronized (eventsMap) { - int nextCount = eventsMap.size(); - assertTrue("No session event generated at retry #" + retryCount, nextCount > curCount); + synchronized (eventsMap) { + assertTrue("Unexpected premature success at retry # " + retryCount + ": " + eventsMap, eventsMap.size() >= 3); + } + } catch (IOException e) { + // expected - ignored + synchronized (eventsMap) { + int nextCount = eventsMap.size(); + assertTrue("No session event generated at retry #" + retryCount, nextCount > curCount); + } } } + } finally { + sshd.removeSessionListener(listener); } - fail("No success to authenticate"); } @@ -159,7 +173,7 @@ public class ServerSessionListenerTest extends BaseTestSupport { kexParams.put(KexProposalOption.S2CENC, getLeastFavorite(Cipher.class, sshd.getCipherFactories())); kexParams.put(KexProposalOption.S2CMAC, getLeastFavorite(Mac.class, sshd.getMacFactories())); - sshd.addSessionListener(new SessionListener() { + SessionListener listener = new SessionListener() { @Override @SuppressWarnings("unchecked") public void sessionCreated(Session session) { @@ -167,9 +181,9 @@ public class ServerSessionListenerTest extends BaseTestSupport { session.setCipherFactories(Collections.singletonList((NamedFactory<Cipher>) kexParams.get(KexProposalOption.S2CENC))); session.setMacFactories(Collections.singletonList((NamedFactory<Mac>) kexParams.get(KexProposalOption.S2CMAC))); } - }); + }; + sshd.addSessionListener(listener); - client.start(); try (ClientSession session = createTestClientSession()) { for (Map.Entry<KexProposalOption, ? extends NamedResource> ke : kexParams.entrySet()) { KexProposalOption option = ke.getKey(); @@ -178,7 +192,7 @@ public class ServerSessionListenerTest extends BaseTestSupport { assertEquals("Mismatched values for KEX=" + option, expected, actual); } } finally { - client.stop(); + sshd.removeSessionListener(listener); } } @@ -193,7 +207,7 @@ public class ServerSessionListenerTest extends BaseTestSupport { return defaultPassAuth.authenticate(username, password, session); } }; - sshd.addSessionListener(new SessionListener() { + SessionListener listener = new SessionListener() { @Override public void sessionCreated(Session session) { if ((!session.isAuthenticated()) && (session instanceof ServerSession)) { @@ -204,15 +218,15 @@ public class ServerSessionListenerTest extends BaseTestSupport { ServerAuthenticationManager.Utils.DEFAULT_USER_AUTH_PASSWORD_FACTORY)); } } - }); + }; + sshd.addSessionListener(listener); - client.start(); try (ClientSession session = createTestClientSession()) { assertNotSame("Mismatched default password authenticator", passAuth, sshd.getPasswordAuthenticator()); assertNotSame("Mismatched default kb authenticator", KeyboardInteractiveAuthenticator.NONE, sshd.getKeyboardInteractiveAuthenticator()); assertEquals("Authenticator override not invoked", 1, passCount.get()); } finally { - client.stop(); + sshd.removeSessionListener(listener); } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java index 957c0a6..7f75b01 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java @@ -87,8 +87,6 @@ import org.junit.runners.MethodSorters; import org.slf4j.LoggerFactory; /** - * TODO Add javadoc - * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/ae8d1c99/sshd-core/src/test/java/org/apache/sshd/server/auth/WelcomeBannerTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/auth/WelcomeBannerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/auth/WelcomeBannerTest.java index 7f824ad..f54e7f2 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/auth/WelcomeBannerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/auth/WelcomeBannerTest.java @@ -53,11 +53,11 @@ public class WelcomeBannerTest extends BaseTestSupport { @BeforeClass public static void setupClientAndServer() throws Exception { - sshd = Utils.setupTestServer(WelcomeBannerPhaseTest.class); + sshd = Utils.setupTestServer(WelcomeBannerTest.class); sshd.start(); port = sshd.getPort(); - client = Utils.setupTestClient(WelcomeBannerPhaseTest.class); + client = Utils.setupTestClient(WelcomeBannerTest.class); client.start(); }
