From a9504ba8ffd7ee52532304c51da7dcd4486fd355 Mon Sep 17 00:00:00 2001 From: Guillaume Nodet Date: Thu, 25 Jul 2024 19:20:48 +0200 Subject: [PATCH] Switch to JUnit 5 --- pom.xml | 38 +- sshd-benchmarks/pom.xml | 9 - .../benchmarks/sftp/upload/CatBenchmark.java | 4 +- sshd-checkstyle-suppressions.xml | 5 + sshd-cli/pom.xml | 11 +- ...iSupportSplitCommandLineArgumentsTest.java | 38 +- sshd-common/pom.xml | 14 +- .../PasswordIdentityProviderTest.java | 19 +- .../ConfigFileHostEntryResolverTest.java | 45 +- .../config/hosts/HostConfigEntryTest.java | 139 ++--- .../config/hosts/KnownHostHashEntryTest.java | 58 +- .../config/hosts/KnownHostHashValueTest.java | 66 +- .../BuiltinClientIdentitiesWatcherTest.java | 30 +- .../keys/ClientIdentityFileWatcherTest.java | 25 +- .../config/keys/ClientIdentityTest.java | 29 +- .../keys/LazyClientIdentityIteratorTest.java | 22 +- .../PropertyResolverCommonValuesTest.java | 19 +- .../PropertyResolverParseBooleanTest.java | 44 +- .../org/apache/sshd/common/PropertyTest.java | 72 ++- .../apache/sshd/common/SshConstantsTest.java | 41 +- .../sshd/common/VersionPropertiesTest.java | 19 +- .../sshd/common/channel/PtyModeTest.java | 24 +- .../sshd/common/channel/PtyModeValueTest.java | 60 +- .../sshd/common/channel/SttySupportTest.java | 32 +- .../sshd/common/cipher/AES128GCMTest.java | 4 +- .../sshd/common/cipher/AES192CTRTest.java | 10 +- .../sshd/common/cipher/AES256CBCTest.java | 10 +- .../sshd/common/cipher/AES256GCMTest.java | 4 +- .../sshd/common/cipher/ARCFOUR128Test.java | 10 +- .../sshd/common/cipher/ARCFOUR256Test.java | 10 +- .../cipher/BaseAuthenticatedCipherTest.java | 4 + .../common/cipher/BaseCipherResetTest.java | 58 +- .../sshd/common/cipher/BaseCipherTest.java | 21 +- .../common/cipher/ChaCha20CipherTest.java | 6 +- .../sshd/common/cipher/ECCurvesTest.java | 45 +- .../compression/BuiltinCompressionsTest.java | 75 ++- .../common/config/TimeValueConfigTest.java | 19 +- ...thorizedKeyEntryLoginOptionsParseTest.java | 60 +- .../config/keys/BuiltinIdentitiesTest.java | 83 +-- .../keys/EcdsaPublicKeyEntryDecoderTest.java | 36 +- .../common/config/keys/KeyRandomArtTest.java | 55 +- .../common/config/keys/KeyUtilsCloneTest.java | 52 +- ...eyUtilsFingerprintCaseSensitivityTest.java | 40 +- .../KeyUtilsFingerprintGenerationTest.java | 50 +- .../sshd/common/config/keys/KeyUtilsTest.java | 94 +-- .../keys/OpenSshCertificateValuesTest.java | 30 +- .../config/keys/PublicKeyEntryTest.java | 22 +- .../loader/AESPrivateKeyObfuscatorTest.java | 51 +- .../OpenSSHKeyPairResourceParserAEADTest.java | 39 +- ...nSSHKeyPairResourceParserDecodingTest.java | 49 +- ...nSSHKeyPairResourceParserPasswordTest.java | 69 +-- ...enSSHKeyPairResourceParserTestSupport.java | 24 +- .../OpenSSHMaxBCryptRoundsSettingTest.java | 46 +- .../PKCS8PEMResourceKeyPairParserTest.java | 77 +-- ...sh2PublicKeyEntryDecoderByKeyTypeTest.java | 36 +- .../ssh2/Ssh2PublicKeyEntryDecoderTest.java | 23 +- .../OpenSSHKeyPairResourceWriterTest.java | 184 +++--- .../common/digest/BuiltinDigestsTest.java | 27 +- .../nonefs/NoneFileSystemFactoryTest.java | 17 +- .../sshd/common/file/root/AssertableFile.java | 14 +- .../root/RootedFileSystemProviderTest.java | 205 ++++--- .../sshd/common/file/util/BasePathTest.java | 112 ++-- .../common/future/DefaultSshFutureTest.java | 56 +- .../common/kex/KexProposalOptionTest.java | 46 +- .../KeyIdentityProviderResolutionTest.java | 39 +- .../keyprovider/KeyPairProviderTest.java | 29 +- .../MultiKeyIdentityProviderTest.java | 26 +- .../sshd/common/mac/BuiltinMacsTest.java | 78 +-- .../sshd/common/mac/MacVectorsTest.java | 45 +- .../sshd/common/random/RandomFactoryTest.java | 36 +- .../signature/BuiltinSignaturesTest.java | 70 ++- .../signature/RSASignatureVariantsTest.java | 42 +- .../common/signature/SignatureDSATest.java | 17 +- .../signature/SignatureRSASHA1Test.java | 51 +- .../signature/SignatureSkECDSATest.java | 23 +- .../signature/SignatureSkED25519Test.java | 23 +- .../SignatureVariantTestSupport.java | 25 +- .../signature/SignaturesDevelopment.java | 4 +- .../common/util/EventListenerUtilsTest.java | 58 +- .../util/ExceptionUtilsAndroidPeelTest.java | 34 +- .../sshd/common/util/GenericUtilsTest.java | 91 +-- .../sshd/common/util/Int2IntFunctionTest.java | 51 +- .../sshd/common/util/NumberUtilsTest.java | 47 +- .../apache/sshd/common/util/OsUtilsTest.java | 36 +- .../common/util/PathsConcatentionTest.java | 38 +- .../sshd/common/util/SelectorUtilsTest.java | 50 +- .../sshd/common/util/ThreadUtilsTest.java | 39 +- .../sshd/common/util/ValidateUtilsTest.java | 25 +- .../sshd/common/util/VersionInfoTest.java | 23 +- .../sshd/common/util/buffer/BufferTest.java | 49 +- .../common/util/buffer/BufferUtilsTest.java | 31 +- .../util/closeable/CloseableUtilsTest.java | 29 +- .../helper/LazyIterablesConcatenatorTest.java | 10 +- .../helper/LazyMatchingTypeIteratorTest.java | 17 +- .../common/util/io/DirectoryScannerTest.java | 17 +- .../sshd/common/util/io/IoUtilsTest.java | 59 +- .../util/io/ModifiableFileWatcherTest.java | 128 ++-- .../sshd/common/util/io/PathUtilsTest.java | 24 +- .../common/util/io/der/ASN1ClassTest.java | 42 +- .../sshd/common/util/io/der/ASN1TypeTest.java | 42 +- .../common/util/io/der/DERParserTest.java | 17 +- .../common/util/io/der/DERWriterTest.java | 17 +- .../util/io/input/EmptyInputStreamTest.java | 60 +- .../util/io/input/LimitInputStreamTest.java | 42 +- .../util/io/input/NoCloseInputStreamTest.java | 22 +- .../util/io/input/NoCloseReaderTest.java | 22 +- .../util/io/input/NullInputStreamTest.java | 34 +- .../util/io/output/LineOutputStreamTest.java | 32 +- .../io/output/NoCloseOutputStreamTest.java | 17 +- .../util/io/output/NoCloseWriterTest.java | 17 +- .../util/io/output/NullOutputStreamTest.java | 31 +- .../util/net/SshdSocketIpv6AddressTest.java | 34 +- ...curityProviderRegistrarCipherNameTest.java | 36 +- .../SecurityProviderRegistrarTestSupport.java | 4 +- .../SecurityUtilsDHGEXGroupKeySizeTest.java | 79 +-- .../util/security/SecurityUtilsTest.java | 64 +- .../security/SecurityUtilsTestSupport.java | 8 +- ...ncyCastleGeneratorHostKeyProviderTest.java | 41 +- .../security/eddsa/EDDSAProviderTest.java | 69 ++- .../security/eddsa/Ed25519VectorsTest.java | 88 +-- .../EdDSASecurityProviderRegistrarTest.java | 41 +- .../AbstractGeneratorHostKeyProviderTest.java | 21 +- .../PEMGeneratorHostKeyProviderTest.java | 56 +- .../SimpleGeneratorHostKeyProviderTest.java | 60 +- .../shell/TtyFilterInputStreamTest.java | 61 +- .../shell/TtyFilterOutputStreamTest.java | 54 +- .../test/JUnit4ClassRunnerWithParameters.java | 48 -- ...Unit4ClassRunnerWithParametersFactory.java | 60 -- .../test/JUnit4SingleInstanceClassRunner.java | 54 -- .../sshd/util/test/JUnitTestSupport.java | 112 ++-- ...> readGlobalHostsConfigEntries.config.txt} | 0 ...xt => readMultipleHostPatterns.config.txt} | 0 ...> readSimpleHostsConfigEntries.config.txt} | 0 sshd-contrib/pom.xml | 14 +- ...teractivePasswordIdentityProviderTest.java | 33 +- .../ThrottlingChannelStreamWriterTest.java | 87 +-- .../common/signature/LegacyDSASignerTest.java | 62 +- ...mpleAccessControlScpEventListenerTest.java | 27 +- .../ProxyProtocolV2AcceptorTest.java | 44 +- ...pleAccessControlSftpEventListenerTest.java | 48 +- sshd-core/pom.xml | 17 +- .../apache/sshd/DefaultSetupTestSupport.java | 37 +- .../java/org/apache/sshd/KeepAliveTest.java | 76 +-- .../org/apache/sshd/KeyReExchangeTest.java | 90 +-- .../test/java/org/apache/sshd/LoadTest.java | 33 +- .../test/java/org/apache/sshd/ProxyTest.java | 61 +- .../org/apache/sshd/WindowAdjustTest.java | 33 +- .../java/org/apache/sshd/agent/AgentTest.java | 39 +- .../org/apache/sshd/agent/AgentUnitTest.java | 27 +- .../GenerateOpenSSHClientCertificateTest.java | 37 +- ...ateOpenSshClientCertificateOracleTest.java | 37 +- .../OpenSSHCertificateParserTest.java | 33 +- .../ClientAuthenticationManagerTest.java | 52 +- .../sshd/client/ClientDeadlockTest.java | 29 +- .../sshd/client/ClientDefaultSetupTest.java | 6 +- .../client/ClientSessionListenerTest.java | 43 +- .../org/apache/sshd/client/ClientTest.java | 504 +++++++-------- .../org/apache/sshd/client/ProxyTest.java | 46 +- .../auth/BuiltinUserAuthFactoriesTest.java | 74 +-- .../auth/pubkey/HostBoundPubKeyAuthTest.java | 32 +- .../auth/pubkey/InvalidRsaKeyAuthTest.java | 16 +- .../client/auth/pubkey/MultiAuthTest.java | 24 +- .../pubkey/RSAVariantsAuthPublicKeyTest.java | 49 +- .../sshd/client/channel/ChannelExecTest.java | 33 +- .../hosts/HostConfigEntryResolverTest.java | 42 +- .../org/apache/sshd/client/kex/KexTest.java | 50 +- .../KnownHostsServerKeyVerifierTest.java | 137 +++-- .../StaticServerKeyVerifierTest.java | 21 +- .../ClientOpenSSHCertificatesTest.java | 35 +- .../client/session/ClientSessionTest.java | 124 ++-- .../simple/SimpleSessionClientTest.java | 31 +- .../sshd/common/AttributeStoreTest.java | 51 +- .../common/PropertyResolverUtilsTest.java | 93 +-- .../apache/sshd/common/SshBuilderTest.java | 28 +- .../sshd/common/auth/AuthenticationTest.java | 50 +- .../auth/AuthenticationTestSupport.java | 20 +- .../auth/HostBasedAuthenticationTest.java | 27 +- ...KeyboardInteractiveAuthenticationTest.java | 74 +-- .../auth/PasswordAuthenticationTest.java | 105 ++-- .../auth/PublicKeyAuthenticationTest.java | 81 +-- .../common/auth/SinglePublicKeyAuthTest.java | 64 +- .../channel/ChannelAsyncOutputStreamTest.java | 29 +- .../channel/ChannelPipedInputStreamTest.java | 35 +- .../channel/ChannelPipedOutputStreamTest.java | 36 +- .../sshd/common/channel/WindowInitTest.java | 32 +- .../sshd/common/channel/WindowTest.java | 53 +- .../common/channel/WindowTimeoutTest.java | 50 +- .../common/cipher/BuiltinCiphersTest.java | 99 +-- .../apache/sshd/common/cipher/CipherTest.java | 71 +-- .../sshd/common/cipher/OpenSshCipherTest.java | 47 +- .../common/compression/CompressionTest.java | 101 ++- .../config/SshConfigFileReaderTest.java | 174 +++--- .../config/keys/AuthorizedKeyEntryTest.java | 43 +- .../keys/AuthorizedKeysTestSupport.java | 5 +- .../AbstractServerCloseTestSupport.java | 42 +- .../forward/ApacheServerApacheClientTest.java | 34 +- .../forward/ApacheServerJSchClientTest.java | 34 +- .../forward/ConcurrentConnectionTest.java | 54 +- ...rwardingEntryCombinedBoundAddressTest.java | 63 +- .../forward/LocalForwardingEntryTest.java | 38 +- .../common/forward/NoServerNoClientTest.java | 6 +- .../forward/PortForwardingLoadTest.java | 53 +- .../common/forward/PortForwardingTest.java | 188 +++--- .../PortForwardingWithOpenSshTest.java | 55 +- .../sshd/common/forward/Sshd1033Test.java | 31 +- .../global/OpenSshHostKeysHandlerTest.java | 33 +- .../BuiltinIoServiceFactoryFactoriesTest.java | 26 +- .../DefaultIoServiceFactoryFactoryTest.java | 18 +- .../sshd/common/io/nio2/Nio2ServiceTest.java | 19 +- .../sshd/common/kex/AbstractDHTest.java | 26 +- .../common/kex/BuiltinDHFactoriesTest.java | 86 +-- .../sshd/common/kex/DHGroupDataParseTest.java | 50 +- .../common/kex/KexFactoryManagerTest.java | 56 +- .../sshd/common/kex/KeyExchangeTest.java | 27 +- .../extension/KexExtensionHandlerTest.java | 28 +- .../StrictKexInteroperabilityTest.java | 37 +- .../common/kex/extension/StrictKexTest.java | 68 ++- .../FileHostKeyCertificateProviderTest.java | 13 +- .../sshd/common/mac/EncryptThenMacTest.java | 52 +- .../sshd/common/mac/MacCompatibilityTest.java | 66 +- .../common/session/GlobalRequestTest.java | 87 +-- .../ReservedSessionMessagesHandlerTest.java | 45 +- .../session/helpers/AbstractSessionTest.java | 163 ++--- .../signature/OpenSSHCertificateTest.java | 85 +-- .../signature/SignatureFactoriesTest.java | 56 +- .../server/PasswordAuthenticatorTest.java | 21 +- .../server/PublickeyAuthenticatorTest.java | 21 +- .../ServerAuthenticationManagerTest.java | 30 +- .../sshd/server/ServerDefaultSetupTest.java | 6 +- .../sshd/server/ServerProxyAcceptorTest.java | 39 +- .../server/ServerSessionListenerTest.java | 53 +- .../org/apache/sshd/server/ServerTest.java | 226 +++---- .../org/apache/sshd/server/SshServerTest.java | 20 +- .../sshd/server/StandardEnvironmentTest.java | 19 +- .../server/auth/AsyncAuthInteractiveTest.java | 12 +- .../sshd/server/auth/AsyncAuthTest.java | 12 +- .../sshd/server/auth/AsyncAuthTestBase.java | 26 +- .../auth/BuiltinUserAuthFactoriesTest.java | 76 +-- .../server/auth/WelcomeBannerPhaseTest.java | 46 +- .../sshd/server/auth/WelcomeBannerTest.java | 70 ++- .../server/channel/ChannelSessionTest.java | 69 ++- .../command/CommandFactorySplitterTest.java | 34 +- .../keys/AuthorizedKeysAuthenticatorTest.java | 43 +- ...efaultAuthorizedKeysAuthenticatorTest.java | 10 +- .../config/keys/ServerIdentityTest.java | 29 +- .../server/forward/ForwardingFilterTest.java | 21 +- .../jaas/JaasPasswordAuthenticatorTest.java | 36 +- .../apache/sshd/server/kex/ModuliTest.java | 51 +- .../shell/InvertedShellWrapperTest.java | 43 +- .../apache/sshd/spring/SpringConfigTest.java | 28 +- .../sshd/util/test/BaseTestSupport.java | 32 +- .../sshd/util/test/TestChannelListener.java | 15 +- .../simple/BaseSimpleClientTestSupport.java | 8 +- sshd-git/pom.xml | 11 +- .../sshd/git/pack/GitPackCommandTest.java | 37 +- .../sshd/git/pgm/GitPgmCommandTest.java | 17 +- sshd-ldap/pom.xml | 26 +- .../sshd/ldap/BaseAuthenticatorTest.java | 31 +- .../ldap/LdapPasswordAuthenticatorTest.java | 34 +- .../ldap/LdapPublickeyAuthenticatorTest.java | 31 +- sshd-mina/pom.xml | 7 +- .../org/apache/sshd/mina/MinaSessionTest.java | 20 +- sshd-netty/pom.xml | 12 +- .../java/org/apache/sshd/netty/NettyTest.java | 31 + sshd-openpgp/pom.xml | 18 +- .../openpgp/PGPKeyPairResourceParserTest.java | 62 +- .../openpgp/PGPPublicRingWatcherTest.java | 24 +- .../openpgp/PGPUtilsKeyFingerprintTest.java | 102 ++-- sshd-putty/pom.xml | 14 +- .../sshd/putty/AbstractPuttyTestSupport.java | 28 +- .../apache/sshd/putty/PuttyKeyUtilsTest.java | 102 ++-- .../sshd/putty/PuttySpecialKeysTest.java | 22 +- sshd-scp/pom.xml | 19 +- .../scp/client/AbstractScpTestSupport.java | 8 +- .../sshd/scp/client/ScpCharsetTest.java | 42 +- .../ScpRemote2RemoteTransferHelperTest.java | 70 +-- .../org/apache/sshd/scp/client/ScpTest.java | 159 ++--- .../sshd/scp/client/SimpleScpClientTest.java | 32 +- .../scp/common/ScpLocationParsingTest.java | 50 +- .../AbstractScpCommandDetailsTest.java | 46 +- .../scp/server/ScpCommandFactoryTest.java | 46 +- .../ScpReceiveDirCommandDetailsTest.java | 24 +- sshd-sftp/pom.xml | 17 +- .../client/AbstractSftpClientTestSupport.java | 17 +- .../apache/sshd/sftp/client/ClientTest.java | 80 +-- .../client/DefaultCloseableHandleTest.java | 31 +- .../sshd/sftp/client/SftpPerformanceTest.java | 10 +- .../org/apache/sshd/sftp/client/SftpTest.java | 573 ++++++++++-------- .../sshd/sftp/client/SftpTransferTest.java | 33 +- .../sftp/client/SftpVersionResolverTest.java | 53 +- .../sftp/client/SftpVersionSelectorTest.java | 47 +- .../sshd/sftp/client/SftpVersionsTest.java | 140 +++-- .../sftp/client/SimpleSftpClientTest.java | 40 +- .../BuiltinSftpClientExtensionsTest.java | 37 +- .../client/extensions/SftpExtensionsTest.java | 29 +- .../client/extensions/VersionParserTest.java | 13 +- .../AbstractCheckFileExtensionTest.java | 52 +- .../helpers/AbstractMD5HashExtensionTest.java | 50 +- .../helpers/CopyDataExtensionImplTest.java | 38 +- .../helpers/CopyFileExtensionImplTest.java | 31 +- .../SpaceAvailableExtensionImplTest.java | 20 +- .../helpers/OpenSSHExtensionsTest.java | 39 +- .../fs/AbstractSftpFilesSystemSupport.java | 47 +- .../client/fs/SftpDirectoryScannersTest.java | 97 +-- .../sftp/client/fs/SftpFileSystemTest.java | 259 ++++---- .../sftp/client/fs/SftpFileSystemURITest.java | 67 +- .../impl/SftpRemotePathChannelTest.java | 97 +-- .../sshd/sftp/client/impl/SftpStatusTest.java | 55 +- .../sshd/sftp/common/SftpConstantsTest.java | 32 +- .../sshd/sftp/common/SftpHelperTest.java | 41 +- .../SftpUniversalOwnerAndGroupTest.java | 31 +- .../apache/sshd/sftp/server/HandleTest.java | 17 +- .../sshd/sftp/server/SftpServerTest.java | 72 +-- .../sftp/server/SftpSubsystemFactoryTest.java | 40 +- sshd-spring-sftp/pom.xml | 7 +- .../ApacheSshdSftpSessionFactoryTest.java | 62 +- 316 files changed, 8009 insertions(+), 7161 deletions(-) delete mode 100644 sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4ClassRunnerWithParameters.java delete mode 100644 sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4ClassRunnerWithParametersFactory.java delete mode 100644 sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4SingleInstanceClassRunner.java rename sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/{testReadGlobalHostsConfigEntries.config.txt => readGlobalHostsConfigEntries.config.txt} (100%) rename sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/{testReadMultipleHostPatterns.config.txt => readMultipleHostPatterns.config.txt} (100%) rename sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/{testReadSimpleHostsConfigEntries.config.txt => readSimpleHostsConfigEntries.config.txt} (100%) create mode 100644 sshd-netty/src/test/java/org/apache/sshd/netty/NettyTest.java diff --git a/pom.xml b/pom.xml index e1d4a062c..b309e286a 100644 --- a/pom.xml +++ b/pom.xml @@ -116,9 +116,8 @@ 5.3.37 5.13.3.202401111512-r - 4.13.2 1.14.18 - 1.16.2 + 1.20.1 1.65.1 5.8.0 @@ -554,12 +553,6 @@ import - - junit - junit - ${junit.version} - - org.mockito mockito-core @@ -667,6 +660,16 @@ org.apache.servicemix.bundles.not-yet-commons-ssl 0.3.11_1 + + org.junit.jupiter + junit-jupiter + 5.10.3 + + + org.mockito + mockito-junit-jupiter + 3.12.4 + @@ -698,11 +701,6 @@ logback-classic test - - junit - junit - test - org.mockito mockito-core @@ -941,6 +939,7 @@ target/generated-sources/annotations target/generated-sources/java + src/test/java @@ -1345,24 +1344,11 @@ ${sshd.tests.rerun.count} - - - junit - junit - ${junit.version} - - - - org.apache.maven.surefire - surefire-junit47 - ${version.maven-surefire} - - dummy diff --git a/sshd-benchmarks/pom.xml b/sshd-benchmarks/pom.xml index 2c3cf6ef5..f3e1e908f 100644 --- a/sshd-benchmarks/pom.xml +++ b/sshd-benchmarks/pom.xml @@ -118,15 +118,6 @@ com.github.mwiede jsch - - - junit - junit - provided - diff --git a/sshd-benchmarks/src/main/java/org/apache/sshd/benchmarks/sftp/upload/CatBenchmark.java b/sshd-benchmarks/src/main/java/org/apache/sshd/benchmarks/sftp/upload/CatBenchmark.java index 32ba6ae3a..045d4f2ce 100644 --- a/sshd-benchmarks/src/main/java/org/apache/sshd/benchmarks/sftp/upload/CatBenchmark.java +++ b/sshd-benchmarks/src/main/java/org/apache/sshd/benchmarks/sftp/upload/CatBenchmark.java @@ -140,13 +140,13 @@ public void catUpload() throws Exception { offset += n; length -= n; if (length == 0) { - out.writeBuffer(new ByteArrayBuffer(buffer)).verify(1000); + out.writeBuffer(new ByteArrayBuffer(buffer)).verify(5000); offset = 0; length = buffer.length; } } if (offset > 0) { - out.writeBuffer(new ByteArrayBuffer(buffer, 0, offset)).verify(1000); + out.writeBuffer(new ByteArrayBuffer(buffer, 0, offset)).verify(5000); } out.close(false); } diff --git a/sshd-checkstyle-suppressions.xml b/sshd-checkstyle-suppressions.xml index e8b09a181..528cfa5cb 100644 --- a/sshd-checkstyle-suppressions.xml +++ b/sshd-checkstyle-suppressions.xml @@ -6,6 +6,11 @@ + + + + + diff --git a/sshd-cli/pom.xml b/sshd-cli/pom.xml index d37fdfe41..7c248bab4 100644 --- a/sshd-cli/pom.xml +++ b/sshd-cli/pom.xml @@ -55,14 +55,14 @@ sshd-putty ${project.version} - + net.i2p.crypto eddsa true - + org.apache.sshd sshd-core @@ -77,7 +77,7 @@ test-jar test - + org.apache.sshd sshd-mina @@ -90,6 +90,11 @@ ${project.version} test + + org.junit.jupiter + junit-jupiter + test + com.github.mwiede diff --git a/sshd-cli/src/test/java/org/apache/sshd/cli/CliSupportSplitCommandLineArgumentsTest.java b/sshd-cli/src/test/java/org/apache/sshd/cli/CliSupportSplitCommandLineArgumentsTest.java index dcdd29bd0..65bf5549f 100644 --- a/sshd-cli/src/test/java/org/apache/sshd/cli/CliSupportSplitCommandLineArgumentsTest.java +++ b/sshd-cli/src/test/java/org/apache/sshd/cli/CliSupportSplitCommandLineArgumentsTest.java @@ -24,35 +24,24 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -public class CliSupportSplitCommandLineArgumentsTest extends BaseTestSupport { - private final String line; - private final String[] expected; +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") +class CliSupportSplitCommandLineArgumentsTest extends BaseTestSupport { - public CliSupportSplitCommandLineArgumentsTest(String line, String[] expected) { - this.line = line; - this.expected = expected; + CliSupportSplitCommandLineArgumentsTest() { + super(); } - @Parameters(name = "{0}") - public static List parameters() { + static List parameters() { return new ArrayList() { // not serializing it private static final long serialVersionUID = 1L; @@ -86,8 +75,9 @@ private void addTestCase(String line, String... expected) { }; } - @Test - public void testSplitCommandLineArguments() { + @MethodSource("parameters") + @ParameterizedTest(name = "<{0}>") + void splitCommandLineArguments(String line, String[] expected) { String[] actual = CliSupport.splitCommandLineArguments(line); assertArrayEquals(expected, actual); } diff --git a/sshd-common/pom.xml b/sshd-common/pom.xml index d6beeaeee..7ac9ed026 100644 --- a/sshd-common/pom.xml +++ b/sshd-common/pom.xml @@ -47,19 +47,29 @@ true - + net.i2p.crypto eddsa true - + org.apache.servicemix.bundles org.apache.servicemix.bundles.not-yet-commons-ssl test + + org.junit.jupiter + junit-jupiter + test + + + org.mockito + mockito-junit-jupiter + test + diff --git a/sshd-common/src/test/java/org/apache/sshd/client/auth/password/PasswordIdentityProviderTest.java b/sshd-common/src/test/java/org/apache/sshd/client/auth/password/PasswordIdentityProviderTest.java index 679f515bb..dd87a0975 100644 --- a/sshd-common/src/test/java/org/apache/sshd/client/auth/password/PasswordIdentityProviderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/client/auth/password/PasswordIdentityProviderTest.java @@ -29,24 +29,25 @@ import java.util.List; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PasswordIdentityProviderTest extends JUnitTestSupport { public PasswordIdentityProviderTest() { super(); } @Test - public void testMultiProvider() throws IOException, GeneralSecurityException { + void multiProvider() throws IOException, GeneralSecurityException { String[][] values = { { getClass().getSimpleName(), getCurrentTestName() }, { new Date(System.currentTimeMillis()).toString() }, @@ -69,7 +70,7 @@ public void testMultiProvider() throws IOException, GeneralSecurityException { private static void assertProviderContents(String message, PasswordIdentityProvider p, Iterable expected) throws IOException, GeneralSecurityException { - assertNotNull(message + ": no provider", p); + assertNotNull(p, message + ": no provider"); assertEquals(message, expected, p.loadPasswords(null)); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/ConfigFileHostEntryResolverTest.java b/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/ConfigFileHostEntryResolverTest.java index 902192f19..5a0be1464 100644 --- a/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/ConfigFileHostEntryResolverTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/ConfigFileHostEntryResolverTest.java @@ -35,24 +35,30 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ConfigFileHostEntryResolverTest extends JUnitTestSupport { public ConfigFileHostEntryResolverTest() { super(); } @Test - public void testIdentityFilePaths() throws IOException { + void identityFilePaths() throws IOException { final String config = "IdentityFile ~/.ssh/%r.key0\n" // + "Host foo\n" // + "IdentityFile ~/.ssh/%r.key1\n" // @@ -84,7 +90,7 @@ public void testIdentityFilePaths() throws IOException { } @Test - public void testConfigFileReload() throws IOException { + void configFileReload() throws IOException { Path dir = getTempTargetRelativeFile(getClass().getSimpleName()); AtomicInteger reloadCount = new AtomicInteger(); ConfigFileHostEntryResolver resolver = new ConfigFileHostEntryResolver( @@ -159,22 +165,21 @@ private static void testConfigFileReload( null); if (entries == null) { - assertEquals(phase + "[" + index + "]: mismatched reload count", 0, reloadCount.get()); + assertEquals(0, reloadCount.get(), phase + "[" + index + "]: mismatched reload count"); } else { - assertEquals(phase + "[" + index + "]: mismatched reload count", 1, reloadCount.get()); + assertEquals(1, reloadCount.get(), phase + "[" + index + "]: mismatched reload count"); } if (expected == null) { - assertNull(phase + "[" + index + "]: Unexpected success for " + query, actual); + assertNull(actual, phase + "[" + index + "]: Unexpected success for " + query); } else { - assertNotNull(phase + "[" + index + "]: No result for " + query, actual); - assertNotSame(phase + "[" + index + "]: No cloned result for " + query, expected, actual); - assertEquals(phase + "[" + index + "]: Mismatched host for " + query, - expected.getHostName(), actual.getHostName()); - assertEquals(phase + "[" + index + "]: Mismatched port for " + query, - expected.getPort(), actual.getPort()); - assertEquals(phase + "[" + index + "]: Mismatched user for " + query, - expected.getUsername(), actual.getUsername()); + assertNotNull(actual, phase + "[" + index + "]: No result for " + query); + assertNotSame(expected, actual, phase + "[" + index + "]: No cloned result for " + query); + assertEquals(expected.getHostName(), actual.getHostName(), + phase + "[" + index + "]: Mismatched host for " + query); + assertEquals(expected.getPort(), actual.getPort(), phase + "[" + index + "]: Mismatched port for " + query); + assertEquals(expected.getUsername(), actual.getUsername(), + phase + "[" + index + "]: Mismatched user for " + query); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/HostConfigEntryTest.java b/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/HostConfigEntryTest.java index 4ee7e2c47..c53fd518d 100644 --- a/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/HostConfigEntryTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/HostConfigEntryTest.java @@ -31,21 +31,23 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class HostConfigEntryTest extends JUnitTestSupport { - public HostConfigEntryTest() { - super(); - } private void expect(String hostname, int port, String username, HostConfigEntry resolved) throws Exception { assertEquals(hostname, resolved.getHostName()); @@ -57,7 +59,7 @@ private void expect(String hostname, int port, String username, HostConfigEntry } @Test - public void testSetTwice() throws Exception { + void setTwice() throws Exception { HostConfigEntry entry = new HostConfigEntry("foo", "foo.example.com", 22, "test"); entry.setProperties(null); entry.setHost("bar"); @@ -70,7 +72,7 @@ public void testSetTwice() throws Exception { } @Test - public void testArgumentsOverrideConfig() throws Exception { + void argumentsOverrideConfig() throws Exception { HostConfigEntry entry = new HostConfigEntry("foo.example.com", null, 22, "test"); HostConfigEntry resolved = HostConfigEntry.toHostConfigEntryResolver(Collections.singleton(entry)) .resolveEffectiveHost("foo.example.com", 2022, null, "testuser", null, null); @@ -78,7 +80,7 @@ public void testArgumentsOverrideConfig() throws Exception { } @Test - public void testConfigSetsHostname() throws Exception { + void configSetsHostname() throws Exception { HostConfigEntry entry = new HostConfigEntry("foo.example.com", "bar.example.com", 22, "test"); HostConfigEntry resolved = HostConfigEntry.toHostConfigEntryResolver(Collections.singleton(entry)) .resolveEffectiveHost("foo.example.com", 2022, null, "testuser", null, null); @@ -86,7 +88,7 @@ public void testConfigSetsHostname() throws Exception { } @Test - public void testWildcardHostname() throws Exception { + void wildcardHostname() throws Exception { HostConfigEntry entry = new HostConfigEntry("foo*", null, 22, "test"); HostConfigEntry resolved = HostConfigEntry.toHostConfigEntryResolver(Collections.singleton(entry)) .resolveEffectiveHost("foo.example.com", 2022, null, "testuser", null, null); @@ -94,7 +96,7 @@ public void testWildcardHostname() throws Exception { } @Test - public void testDefaults() throws Exception { + void defaults() throws Exception { HostConfigEntry entry = new HostConfigEntry("foo*", "bar.example.com", 22, "test"); HostConfigEntry resolved = HostConfigEntry.toHostConfigEntryResolver(Collections.singleton(entry)) .resolveEffectiveHost("foo", 0, null, "", null, null); @@ -102,7 +104,7 @@ public void testDefaults() throws Exception { } @Test - public void testDefaultDefaults() throws Exception { + void defaultDefaults() throws Exception { HostConfigEntry entry = new HostConfigEntry(); entry.setHost("foo*"); entry.setUsername("test"); @@ -112,7 +114,7 @@ public void testDefaultDefaults() throws Exception { } @Test - public void testCoalescing() throws Exception { + void coalescing() throws Exception { HostConfigEntry first = new HostConfigEntry(); first.setHost("foo*"); first.setHostName("bar.example.com"); @@ -132,7 +134,7 @@ public void testCoalescing() throws Exception { } @Test - public void testCoalescingFirstValue() throws Exception { + void coalescingFirstValue() throws Exception { HostConfigEntry first = new HostConfigEntry(); first.setHost("fo*"); first.setHostName("bar.example.com"); @@ -146,7 +148,7 @@ public void testCoalescingFirstValue() throws Exception { } @Test - public void testCoalescingIdentityFile() throws Exception { + void coalescingIdentityFile() throws Exception { HostConfigEntry first = new HostConfigEntry(); first.setHost("fo*"); first.setHostName("bar.example.com"); @@ -166,8 +168,9 @@ public void testCoalescingIdentityFile() throws Exception { assertEquals("xFile,dFile", resolved.getProperty(HostConfigEntry.IDENTITY_FILE_CONFIG_PROP)); } - @Test // See GH-351 - public void testProxyJump() throws Exception { + // See GH-351 + @Test + void proxyJump() throws Exception { HostConfigEntry bastion = new HostConfigEntry(); bastion.setHost("bastion"); bastion.setHostName("1.2.3.4"); @@ -180,9 +183,9 @@ public void testProxyJump() throws Exception { HostConfigEntry resolved = resolver.resolveEffectiveHost("server1", 0, null, "someone", null, null); expect("server1", 22, "someone", resolved); Collection identities = resolved.getIdentities(); - assertTrue("Unexpected configured identities " + identities, identities == null || identities.isEmpty()); + assertTrue(identities == null || identities.isEmpty(), "Unexpected configured identities " + identities); String identityProp = resolved.getProperty(HostConfigEntry.IDENTITY_FILE_CONFIG_PROP); - assertNull("Unexpected IdentityFile property", identityProp); + assertNull(identityProp, "Unexpected IdentityFile property"); // Same handling as in SshClient.parseProxyJumps() String proxy = resolved.getProperty(HostConfigEntry.PROXY_JUMP_CONFIG_PROP); assertEquals("bastion", proxy); @@ -190,15 +193,15 @@ public void testProxyJump() throws Exception { resolved = resolver.resolveEffectiveHost(uri.getHost(), uri.getPort(), null, uri.getUserInfo(), null, null); expect("1.2.3.4", 22, "username", resolved); identities = resolved.getIdentities(); - assertNotNull("Should have identities", identities); + assertNotNull(identities, "Should have identities"); assertEquals("[yFile]", identities.toString()); identityProp = resolved.getProperty(HostConfigEntry.IDENTITY_FILE_CONFIG_PROP); - assertNotNull("Should have IdentityFile property", identityProp); + assertNotNull(identityProp, "Should have IdentityFile property"); assertEquals("yFile", identityProp); } @Test - public void testNegatingPatternOverridesAll() { + void negatingPatternOverridesAll() { String testHost = "37.77.34.7"; String[] elements = GenericUtils.split(testHost, '.'); StringBuilder sb = new StringBuilder(testHost.length() + Byte.SIZE); @@ -224,13 +227,13 @@ public void testNegatingPatternOverridesAll() { } for (int index = 0; index < patterns.size(); index++) { - assertFalse("Unexpected match for " + patterns, HostPatternsHolder.isHostMatch(testHost, 0, patterns)); + assertFalse(HostPatternsHolder.isHostMatch(testHost, 0, patterns), "Unexpected match for " + patterns); Collections.shuffle(patterns); } } @Test - public void testHostWildcardPatternMatching() { + void hostWildcardPatternMatching() { String pkgName = getClass().getPackage().getName(); String[] elements = GenericUtils.split(pkgName, '.'); StringBuilder sb = new StringBuilder(pkgName.length() + Long.SIZE + 1).append(HostPatternsHolder.WILDCARD_PATTERN); @@ -256,7 +259,7 @@ public void testHostWildcardPatternMatching() { } @Test - public void testIPAddressWildcardPatternMatching() { + void iPAddressWildcardPatternMatching() { StringBuilder sb = new StringBuilder().append("10.0.0."); int sbLen = sb.length(); @@ -266,12 +269,12 @@ public void testIPAddressWildcardPatternMatching() { sb.append(v); String address = sb.toString(); - assertTrue("No match for " + address, HostPatternsHolder.isHostMatch(address, pattern)); + assertTrue(HostPatternsHolder.isHostMatch(address, pattern), "No match for " + address); } } @Test - public void testHostSingleCharPatternMatching() { + void hostSingleCharPatternMatching() { String value = getCurrentTestName(); StringBuilder sb = new StringBuilder(value); for (boolean restoreOriginal : new boolean[] { true, false }) { @@ -286,7 +289,7 @@ public void testHostSingleCharPatternMatching() { } @Test - public void testIPAddressSingleCharPatternMatching() { + void iPAddressSingleCharPatternMatching() { StringBuilder sb = new StringBuilder().append("10.0.0."); int sbLen = sb.length(); @@ -302,13 +305,13 @@ public void testIPAddressSingleCharPatternMatching() { String pattern = sb.toString(); HostPatternValue pp = HostPatternsHolder.toPattern(pattern); - assertTrue("No match for " + address + " on pattern=" + pattern, - HostPatternsHolder.isHostMatch(address, 0, Collections.singletonList(pp))); + assertTrue(HostPatternsHolder.isHostMatch(address, 0, Collections.singletonList(pp)), + "No match for " + address + " on pattern=" + pattern); } } @Test - public void testIPv6AddressSingleCharPatternMatching() { + void iPv6AddressSingleCharPatternMatching() { StringBuilder sb = new StringBuilder().append("fe80::7780:db3:a57:6a9"); int sbLen = sb.length(); @@ -324,33 +327,33 @@ public void testIPv6AddressSingleCharPatternMatching() { String pattern = sb.toString(); HostPatternValue pp = HostPatternsHolder.toPattern(pattern); - assertTrue("No match for " + address + " on pattern=" + pattern, - HostPatternsHolder.isHostMatch(address, 0, Collections.singletonList(pp))); + assertTrue(HostPatternsHolder.isHostMatch(address, 0, Collections.singletonList(pp)), + "No match for " + address + " on pattern=" + pattern); } } @Test - public void testIsValidPatternChar() { + void isValidPatternChar() { for (char ch = '\0'; ch <= ' '; ch++) { - assertFalse("Unexpected valid character (0x" + Integer.toHexString(ch & 0xFF) + ")", - HostPatternsHolder.isValidPatternChar(ch)); + assertFalse(HostPatternsHolder.isValidPatternChar(ch), + "Unexpected valid character (0x" + Integer.toHexString(ch & 0xFF) + ")"); } for (char ch = 'a'; ch <= 'z'; ch++) { - assertTrue("Valid character not recognized: " + Character.toString(ch), HostPatternsHolder.isValidPatternChar(ch)); + assertTrue(HostPatternsHolder.isValidPatternChar(ch), "Valid character not recognized: " + Character.toString(ch)); } for (char ch = 'A'; ch <= 'Z'; ch++) { - assertTrue("Valid character not recognized: " + Character.toString(ch), HostPatternsHolder.isValidPatternChar(ch)); + assertTrue(HostPatternsHolder.isValidPatternChar(ch), "Valid character not recognized: " + Character.toString(ch)); } for (char ch = '0'; ch <= '9'; ch++) { - assertTrue("Valid character not recognized: " + Character.toString(ch), HostPatternsHolder.isValidPatternChar(ch)); + assertTrue(HostPatternsHolder.isValidPatternChar(ch), "Valid character not recognized: " + Character.toString(ch)); } for (char ch : new char[] { '-', '_', '.', HostPatternsHolder.SINGLE_CHAR_PATTERN, HostPatternsHolder.WILDCARD_PATTERN }) { - assertTrue("Valid character not recognized: " + Character.toString(ch), HostPatternsHolder.isValidPatternChar(ch)); + assertTrue(HostPatternsHolder.isValidPatternChar(ch), "Valid character not recognized: " + Character.toString(ch)); } for (char ch : new char[] { @@ -358,68 +361,68 @@ public void testIsValidPatternChar() { '#', '$', '^', '&', '~', '<', '>', ',', '/', '\\', '\'', '"', ';' }) { - assertFalse("Unexpected valid character: " + Character.toString(ch), HostPatternsHolder.isValidPatternChar(ch)); + assertFalse(HostPatternsHolder.isValidPatternChar(ch), "Unexpected valid character: " + Character.toString(ch)); } for (char ch = 0x7E; ch <= 0xFF; ch++) { - assertFalse("Unexpected valid character (0x" + Integer.toHexString(ch & 0xFF) + ")", - HostPatternsHolder.isValidPatternChar(ch)); + assertFalse(HostPatternsHolder.isValidPatternChar(ch), + "Unexpected valid character (0x" + Integer.toHexString(ch & 0xFF) + ")"); } } @Test - public void testReadSimpleHostsConfigEntries() throws IOException { + void readSimpleHostsConfigEntries() throws IOException { validateHostConfigEntries(readHostConfigEntries()); } @Test - public void testReadGlobalHostsConfigEntries() throws IOException { + void readGlobalHostsConfigEntries() throws IOException { List entries = validateHostConfigEntries(readHostConfigEntries()); - assertTrue("Not enough entries read", GenericUtils.size(entries) > 1); + assertTrue(GenericUtils.size(entries) > 1, "Not enough entries read"); // global entry MUST be 1st one HostConfigEntry globalEntry = entries.get(0); - assertEquals("Mismatched global entry pattern", HostPatternsHolder.ALL_HOSTS_PATTERN, globalEntry.getHost()); + assertEquals(HostPatternsHolder.ALL_HOSTS_PATTERN, globalEntry.getHost(), "Mismatched global entry pattern"); for (int index = 1; index < entries.size(); index++) { HostConfigEntry entry = entries.get(index); - assertFalse("No properties for " + entry, MapEntryUtils.isEmpty(entry.getProperties())); + assertFalse(MapEntryUtils.isEmpty(entry.getProperties()), "No properties for " + entry); boolean noHostName = GenericUtils.isEmpty(entry.getHostName()); boolean noPort = entry.getPort() <= 0; boolean noUsername = GenericUtils.isEmpty(entry.getUsername()); boolean noIdentities = GenericUtils.isEmpty(entry.getIdentities()); if (index == 1) { - assertFalse("No username for " + entry, noUsername); + assertFalse(noUsername, "No username for " + entry); } else { - assertTrue("Unexpected username for " + entry, noUsername); + assertTrue(noUsername, "Unexpected username for " + entry); } if (index == 2) { - assertFalse("No target port for " + entry, noPort); + assertFalse(noPort, "No target port for " + entry); } else { - assertTrue("Unexpected target port for " + entry, noPort); + assertTrue(noPort, "Unexpected target port for " + entry); } if (index == 3) { - assertFalse("No target host for " + entry, noHostName); + assertFalse(noHostName, "No target host for " + entry); } else { - assertTrue("Unexpected target host for " + entry, noHostName); + assertTrue(noHostName, "Unexpected target host for " + entry); } if (index == 4) { - assertFalse("No identities for " + entry, noIdentities); + assertFalse(noIdentities, "No identities for " + entry); } else { - assertTrue("Unexpected identity for " + entry, noIdentities); + assertTrue(noIdentities, "Unexpected identity for " + entry); } } } @Test - public void testReadMultipleHostPatterns() throws IOException { + void readMultipleHostPatterns() throws IOException { List entries = validateHostConfigEntries(readHostConfigEntries()); - assertEquals("Mismatched number of entries", 1, GenericUtils.size(entries)); - assertEquals("Mismatched number of patterns", 3, GenericUtils.size(entries.get(0).getPatterns())); + assertEquals(1, GenericUtils.size(entries), "Mismatched number of entries"); + assertEquals(3, GenericUtils.size(entries.get(0).getPatterns()), "Mismatched number of patterns"); } @Test - public void testResolveIdentityFilePath() throws Exception { + void resolveIdentityFilePath() throws Exception { final String hostValue = getClass().getSimpleName(); final int portValue = 7365; final String userValue = getCurrentTestName(); @@ -449,11 +452,11 @@ public void testResolveIdentityFilePath() throws Exception { } private static > C validateHostConfigEntries(C entries) { - assertFalse("No entries", GenericUtils.isEmpty(entries)); + assertFalse(GenericUtils.isEmpty(entries), "No entries"); for (HostConfigEntry entry : entries) { - assertFalse("No pattern for " + entry, GenericUtils.isEmpty(entry.getHost())); - assertFalse("No extra properties for " + entry, MapEntryUtils.isEmpty(entry.getProperties())); + assertFalse(GenericUtils.isEmpty(entry.getHost()), "No pattern for " + entry); + assertFalse(MapEntryUtils.isEmpty(entry.getProperties()), "No extra properties for " + entry); } return entries; @@ -465,7 +468,7 @@ private List readHostConfigEntries() throws IOException { private List readHostConfigEntries(String resourceName) throws IOException { URL url = getClass().getResource(resourceName); - assertNotNull("Missing resource " + resourceName, url); + assertNotNull(url, "Missing resource " + resourceName); return HostConfigEntry.readHostConfigEntries(url); } diff --git a/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/KnownHostHashEntryTest.java b/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/KnownHostHashEntryTest.java index 4abbd045d..7f26bb1ec 100644 --- a/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/KnownHostHashEntryTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/KnownHostHashEntryTest.java @@ -24,41 +24,38 @@ import org.apache.sshd.common.SshConstants; import org.apache.sshd.common.util.GenericUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class KnownHostHashEntryTest extends JUnitTestSupport { - private final String host; - private final int port; - private final String comment; - private final String line; + private String host; + private int port; + private String comment; + private String line; - public KnownHostHashEntryTest(String host, int port, String hashValue, String keyType, String keyData, String comment) { + public void initKnownHostHashEntryTest( + String host, int port, String hashValue, String keyType, String keyData, String comment) { this.host = host; this.port = port; this.comment = comment; this.line = GenericUtils.join(new Object[] { hashValue, keyType, keyData, comment }, ' '); } - @Parameters(name = "{5}") public static List parameters() { return Arrays.asList( // line generated `ssh xenon@localhost hostname` (SSH-2.0-OpenSSH_7.5) @@ -77,20 +74,29 @@ public static List parameters() { }); } - @Test - public void testHostHashMatchOnSamePort() { + @MethodSource("parameters") + @ParameterizedTest(name = "{5}") + public void hostHashMatchOnSamePort( + String host, int port, String hashValue, String keyType, String keyData, String comment) { + initKnownHostHashEntryTest(host, port, hashValue, keyType, keyData, comment); KnownHostEntry entry = KnownHostEntry.parseKnownHostEntry(line); assertTrue(entry.isHostMatch(host, port)); } - @Test - public void testHostHashNotMatchOnDifferentPort() { + @MethodSource("parameters") + @ParameterizedTest(name = "{5}") + public void hostHashNotMatchOnDifferentPort( + String host, int port, String hashValue, String keyType, String keyData, String comment) { + initKnownHostHashEntryTest(host, port, hashValue, keyType, keyData, comment); KnownHostEntry entry = KnownHostEntry.parseKnownHostEntry(line); assertFalse(entry.isHostMatch(host, port / 2)); } - @Test - public void testHostHashMatchOnDefaultPort() { + @MethodSource("parameters") + @ParameterizedTest(name = "{5}") + public void hostHashMatchOnDefaultPort( + String host, int port, String hashValue, String keyType, String keyData, String comment) { + initKnownHostHashEntryTest(host, port, hashValue, keyType, keyData, comment); KnownHostEntry entry = KnownHostEntry.parseKnownHostEntry(line); assertEquals(port == SshConstants.DEFAULT_PORT, entry.isHostMatch(host, 0)); } diff --git a/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/KnownHostHashValueTest.java b/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/KnownHostHashValueTest.java index 0293f0e90..71a0e7158 100644 --- a/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/KnownHostHashValueTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/client/config/hosts/KnownHostHashValueTest.java @@ -23,39 +23,37 @@ import java.util.Collection; import org.apache.sshd.common.SshConstants; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class KnownHostHashValueTest extends JUnitTestSupport { - private final String hostName; - private final int port; - private final String hashValue; - private final KnownHostHashValue hash; + private String hostName; + private int port; + private String hashValue; + private KnownHostHashValue hash; - public KnownHostHashValueTest(String hostName, int port, String hashValue) { + public void initKnownHostHashValueTest(String hostName, int port, String hashValue) { this.hostName = hostName; this.port = port; this.hashValue = hashValue; this.hash = KnownHostHashValue.parse(hashValue); } - @Parameters(name = "host={0}, port={1}, hash={2}") public static Collection parameters() { return Arrays.asList( // line generated `ssh xenon@localhost -p 10022 hostname` (SSH-2.0-OpenSSH_7.5) @@ -71,24 +69,30 @@ public static Collection parameters() { "|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg=" }); } - @Test - public void testDecodeEncode() { - assertSame("Mismatched digester", KnownHostHashValue.DEFAULT_DIGEST, hash.getDigester()); - assertEquals("Mismatched encoded form", hashValue, hash.toString()); + @MethodSource("parameters") + @ParameterizedTest(name = "host={0}, port={1}, hash={2}") + public void decodeEncode(String hostName, int port, String hashValue) { + initKnownHostHashValueTest(hostName, port, hashValue); + assertSame(KnownHostHashValue.DEFAULT_DIGEST, hash.getDigester(), "Mismatched digester"); + assertEquals(hashValue, hash.toString(), "Mismatched encoded form"); } - @Test - public void testHostMatch() { - assertTrue("Specified host does not match", hash.isHostMatch(hostName, port)); - assertFalse("Unexpected host match", hash.isHostMatch(getCurrentTestName(), port)); + @MethodSource("parameters") + @ParameterizedTest(name = "host={0}, port={1}, hash={2}") + public void hostMatch(String hostName, int port, String hashValue) { + initKnownHostHashValueTest(hostName, port, hashValue); + assertTrue(hash.isHostMatch(hostName, port), "Specified host does not match"); + assertFalse(hash.isHostMatch(getCurrentTestName(), port), "Unexpected host match"); } - @Test - public void testCalculateHashValue() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "host={0}, port={1}, hash={2}") + public void calculateHashValue(String hostName, int port, String hashValue) throws Exception { + initKnownHostHashValueTest(hostName, port, hashValue); byte[] expected = hash.getDigestValue(); byte[] actual = KnownHostHashValue.calculateHashValue( hostName, port, hash.getDigester(), hash.getSaltValue()); - assertArrayEquals("Mismatched hash value", expected, actual); + assertArrayEquals(expected, actual, "Mismatched hash value"); } @Override diff --git a/sshd-common/src/test/java/org/apache/sshd/client/config/keys/BuiltinClientIdentitiesWatcherTest.java b/sshd-common/src/test/java/org/apache/sshd/client/config/keys/BuiltinClientIdentitiesWatcherTest.java index 2a3944c0a..4f4601e11 100644 --- a/sshd-common/src/test/java/org/apache/sshd/client/config/keys/BuiltinClientIdentitiesWatcherTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/client/config/keys/BuiltinClientIdentitiesWatcherTest.java @@ -48,24 +48,28 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class BuiltinClientIdentitiesWatcherTest extends JUnitTestSupport { public BuiltinClientIdentitiesWatcherTest() { super(); } @Test - public void testMultipleFilesWatch() throws Exception { + void multipleFilesWatch() throws Exception { KeyPair identity = CommonTestSupportUtils.getFirstKeyPair(createTestHostKeyProvider()); String keyType = ValidateUtils.checkNotNullAndNotEmpty(KeyUtils.getKeyType(identity), "Cannot determine identity key type"); @@ -76,8 +80,8 @@ public void testMultipleFilesWatch() throws Exception { for (BuiltinIdentities id : BuiltinIdentities.VALUES) { Path idFile = dir.resolve(ClientIdentity.getIdentityFileName(id)); Files.deleteIfExists(idFile); - assertNull("Multiple file mappings for " + id, locationsMap.put(id, idFile)); - assertNull("Multiple identity mappings for " + id, idsMap.put(id, KeyUtils.cloneKeyPair(keyType, identity))); + assertNull(locationsMap.put(id, idFile), "Multiple file mappings for " + id); + assertNull(idsMap.put(id, KeyUtils.cloneKeyPair(keyType, identity)), "Multiple identity mappings for " + id); } ClientIdentityLoader loader = new ClientIdentityLoader() { @@ -86,7 +90,7 @@ public Iterable loadClientIdentities( SessionContext session, NamedResource location, FilePasswordProvider provider) throws IOException, GeneralSecurityException { BuiltinIdentities id = findIdentity(location); - assertNotNull("Invalid location: " + location, id); + assertNotNull(id, "Invalid location: " + location); KeyPair kp = idsMap.get(id); return (kp == null) ? null : Collections.singletonList(kp); } @@ -160,11 +164,11 @@ private static void testMultipleFilesWatch( for (KeyPair kp : keys) { actual.add(kp); } - assertEquals(phase + ": mismatched sizes", GenericUtils.size(expected), GenericUtils.size(actual)); + assertEquals(GenericUtils.size(expected), GenericUtils.size(actual), phase + ": mismatched sizes"); if (!GenericUtils.isEmpty(expected)) { for (KeyPair kp : expected) { - assertTrue(phase + ": missing key", actual.contains(kp)); + assertTrue(actual.contains(kp), phase + ": missing key"); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/client/config/keys/ClientIdentityFileWatcherTest.java b/sshd-common/src/test/java/org/apache/sshd/client/config/keys/ClientIdentityFileWatcherTest.java index 6f48db577..cabfd368f 100644 --- a/sshd-common/src/test/java/org/apache/sshd/client/config/keys/ClientIdentityFileWatcherTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/client/config/keys/ClientIdentityFileWatcherTest.java @@ -42,24 +42,27 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ClientIdentityFileWatcherTest extends JUnitTestSupport { public ClientIdentityFileWatcherTest() { super(); } @Test - public void testIdentityReload() throws Exception { + void identityReload() throws Exception { Path dir = assertHierarchyTargetFolderExists(getTempTargetRelativeFile(getClass().getSimpleName())); Path idFile = dir.resolve(getCurrentTestName() + ".pem"); KeyPair identity = CommonTestSupportUtils.getFirstKeyPair(createTestHostKeyProvider()); @@ -68,7 +71,7 @@ public void testIdentityReload() throws Exception { public Iterable loadClientIdentities( SessionContext session, NamedResource location, FilePasswordProvider provider) throws IOException, GeneralSecurityException { - assertTrue("Invalid location: " + location, isValidLocation(location)); + assertTrue(isValidLocation(location), "Invalid location: " + location); return Collections.singletonList(identity); } @@ -126,7 +129,7 @@ private static void testIdentityReload( throws Exception { Iterable ids = provider.getClientIdentities(null); KeyPair actualIdentity = GenericUtils.head(ids); - assertSame(phase + ": mismatched identity", expectedIdentity, actualIdentity); - assertEquals(phase + ": mismatched re-load count", expectedCount, reloadCount.intValue()); + assertSame(expectedIdentity, actualIdentity, phase + ": mismatched identity"); + assertEquals(expectedCount, reloadCount.intValue(), phase + ": mismatched re-load count"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/client/config/keys/ClientIdentityTest.java b/sshd-common/src/test/java/org/apache/sshd/client/config/keys/ClientIdentityTest.java index 260afb73c..15573bcee 100644 --- a/sshd-common/src/test/java/org/apache/sshd/client/config/keys/ClientIdentityTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/client/config/keys/ClientIdentityTest.java @@ -35,24 +35,27 @@ import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ClientIdentityTest extends JUnitTestSupport { public ClientIdentityTest() { super(); } @Test - public void testLoadClientIdentities() throws Exception { + void loadClientIdentities() throws Exception { Path resFolder = getTestResourcesFolder(); LinkOption[] options = IoUtils.getLinkOptions(true); Collection expected = EnumSet.noneOf(BuiltinIdentities.class); @@ -77,25 +80,25 @@ public void testLoadClientIdentities() throws Exception { false, // don't be strict null, // none of the files is password protected options); - assertEquals("Mismatched loaded ids count", GenericUtils.size(expected), MapEntryUtils.size(ids)); + assertEquals(GenericUtils.size(expected), MapEntryUtils.size(ids), "Mismatched loaded ids count"); Collection pairs = new ArrayList<>(ids.size()); for (BuiltinIdentities type : BuiltinIdentities.VALUES) { if (expected.contains(type)) { KeyPair kp = ids.get(type.getName()); - assertNotNull("No key pair loaded for " + type, kp); + assertNotNull(kp, "No key pair loaded for " + type); pairs.add(kp); } } KeyIdentityProvider provider = IdentityUtils.createKeyPairProvider(ids, true /* supported only */); - assertNotNull("No provider generated", provider); + assertNotNull(provider, "No provider generated"); Iterable keys = provider.loadKeys(null); for (KeyPair kp : keys) { - assertTrue("Unexpected loaded key: " + kp, pairs.remove(kp)); + assertTrue(pairs.remove(kp), "Unexpected loaded key: " + kp); } - assertEquals("Not all pairs listed", 0, pairs.size()); + assertEquals(0, pairs.size(), "Not all pairs listed"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/client/config/keys/LazyClientIdentityIteratorTest.java b/sshd-common/src/test/java/org/apache/sshd/client/config/keys/LazyClientIdentityIteratorTest.java index 1bd58b990..9e9200a23 100644 --- a/sshd-common/src/test/java/org/apache/sshd/client/config/keys/LazyClientIdentityIteratorTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/client/config/keys/LazyClientIdentityIteratorTest.java @@ -29,24 +29,28 @@ import org.apache.sshd.common.session.SessionContext; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class LazyClientIdentityIteratorTest extends JUnitTestSupport { public LazyClientIdentityIteratorTest() { super(); } @Test - public void testLazyKeysLoader() { + void lazyKeysLoader() { List providers = new ArrayList<>(); for (int index = 1; index <= Byte.SIZE; index++) { PublicKey pub = Mockito.mock(PublicKey.class); @@ -66,14 +70,14 @@ public void testLazyKeysLoader() { for (int index = 0, count = providers.size(); index < count; index++) { CountingClientIdentityProvider p = providers.get(index); - assertEquals("Mismatched provider #" + index + " pre-fetch load count", 0, p.getLoadCount()); + assertEquals(0, p.getLoadCount(), "Mismatched provider #" + index + " pre-fetch load count"); KeyPair expected = p.getKeyPair(); - assertTrue("No more keys after " + index + " values", keys.hasNext()); + assertTrue(keys.hasNext(), "No more keys after " + index + " values"); KeyPair actual = keys.next(); - assertSame("Mismatched identity after " + index + " values", expected, actual); - assertEquals("Mismatched provider #" + index + " post-fetch load count", 1, p.getLoadCount()); + assertSame(expected, actual, "Mismatched identity after " + index + " values"); + assertEquals(1, p.getLoadCount(), "Mismatched provider #" + index + " post-fetch load count"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/PropertyResolverCommonValuesTest.java b/sshd-common/src/test/java/org/apache/sshd/common/PropertyResolverCommonValuesTest.java index d24e63386..0720946f0 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/PropertyResolverCommonValuesTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/PropertyResolverCommonValuesTest.java @@ -24,24 +24,25 @@ import java.util.concurrent.TimeUnit; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PropertyResolverCommonValuesTest extends JUnitTestSupport { public PropertyResolverCommonValuesTest() { super(); } @Test - public void testToBooleanOnNonBooleanValues() { + void toBooleanOnNonBooleanValues() { for (Object v : new Object[] { 1, 2L, 3.0f, 4.0d, new Date(), Calendar.class, TimeUnit.DAYS }) { try { Boolean result = PropertyResolverUtils.toBoolean(v); @@ -53,7 +54,7 @@ public void testToBooleanOnNonBooleanValues() { } @Test - public void testParseBooleanOnNonBooleanValues() { + void parseBooleanOnNonBooleanValues() { for (String v : new String[] { getCurrentTestName(), "0", "1" }) { try { Boolean result = PropertyResolverUtils.parseBoolean(v); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/PropertyResolverParseBooleanTest.java b/sshd-common/src/test/java/org/apache/sshd/common/PropertyResolverParseBooleanTest.java index 20526a132..cee00aa57 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/PropertyResolverParseBooleanTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/PropertyResolverParseBooleanTest.java @@ -23,35 +23,29 @@ import java.util.List; import org.apache.sshd.common.util.GenericUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class PropertyResolverParseBooleanTest extends JUnitTestSupport { - private final String value; - private final Boolean expected; + private String value; + private Boolean expected; - public PropertyResolverParseBooleanTest(String value, Boolean expected) { + public void initPropertyResolverParseBooleanTest(String value, Boolean expected) { this.value = value; this.expected = expected; } - @Parameters(name = "value={0}, expected={1}") public static List parameters() { List result = new ArrayList<>(); result.add(new Object[] { null, null }); @@ -66,20 +60,24 @@ public static List parameters() { return result; } - @Test - public void testSimpleParseBoolean() { + @MethodSource("parameters") + @ParameterizedTest(name = "value={0}, expected={1}") + public void simpleParseBoolean(String value, Boolean expected) { + initPropertyResolverParseBooleanTest(value, expected); Boolean actual = PropertyResolverUtils.parseBoolean(value); assertSame(expected, actual); } - @Test - public void testCaseInsensitiveParseBoolean() { + @MethodSource("parameters") + @ParameterizedTest(name = "value={0}, expected={1}") + public void caseInsensitiveParseBoolean(String value, Boolean expected) { + initPropertyResolverParseBooleanTest(value, expected); if (!GenericUtils.isEmpty(value)) { String v = value; for (int index = 1, count = v.length(); index <= (2 * count); index++) { v = shuffleCase(v); Boolean actual = PropertyResolverUtils.parseBoolean(v); - assertSame("Mismatched result for '" + v + "'", expected, actual); + assertSame(expected, actual, "Mismatched result for '" + v + "'"); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/PropertyTest.java b/sshd-common/src/test/java/org/apache/sshd/common/PropertyTest.java index 094bdbf8c..303191380 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/PropertyTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/PropertyTest.java @@ -26,33 +26,30 @@ import java.util.Map; import java.util.Optional; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @param Type of property being tested * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class PropertyTest extends JUnitTestSupport { - private final Class propType; - private final T defaultValue; - private final Property prop; + private Class propType; + private T defaultValue; + private Property prop; @SuppressWarnings("unchecked") - public PropertyTest(Class propType, T defaultValue) throws Exception { + public void initPropertyTest(Class propType, T defaultValue) throws Exception { this.propType = propType; this.defaultValue = defaultValue; @@ -62,7 +59,6 @@ public PropertyTest(Class propType, T defaultValue) throws Exception { prop = (Property) ctor.newInstance(propClass.getSimpleName() + "Test", defaultValue); } - @Parameters(name = "type={0}, default={1}") public static Collection parameters() { Collection testCases = new LinkedList<>(); testCases.add(new Object[] { Integer.class, null }); @@ -76,43 +72,55 @@ public static Collection parameters() { return testCases; } - @Test - public void testPropertyType() { + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}, default={1}") + public void propertyType(Class propType, T defaultValue) throws Exception { + initPropertyTest(propType, defaultValue); assertSame(propType, prop.getType()); } - @Test - public void testDefaultValue() { + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}, default={1}") + public void defaultValue(Class propType, T defaultValue) throws Exception { + initPropertyTest(propType, defaultValue); Optional actual = prop.get(null); if (defaultValue == null) { - assertFalse("Unexpected value: " + actual, actual.isPresent()); + assertFalse(actual.isPresent(), "Unexpected value: " + actual); } else { assertSame(defaultValue, actual.get()); } } - @Test - public void testGetOrNullIfNoValueResolved() { + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}, default={1}") + public void getOrNullIfNoValueResolved(Class propType, T defaultValue) throws Exception { + initPropertyTest(propType, defaultValue); T actual = prop.getOrNull(PropertyResolver.EMPTY); assertNull(actual); } - @Test - public void testGetOrNullIfNoValueExists() { + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}, default={1}") + public void getOrNullIfNoValueExists(Class propType, T defaultValue) throws Exception { + initPropertyTest(propType, defaultValue); T expected = getNonDefaultValue(); T actual = prop.getOrNull(asPropertyResolver(expected)); assertSame(expected, actual); } - @Test - public void testGetOrCustomDefaultIfNoValueResolved() { + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}, default={1}") + public void getOrCustomDefaultIfNoValueResolved(Class propType, T defaultValue) throws Exception { + initPropertyTest(propType, defaultValue); T expected = getCustomValue(); T actual = prop.getOrCustomDefault(PropertyResolver.EMPTY, expected); assertSame(expected, actual); } - @Test - public void testGetOrCustomDefaultIfValueExists() { + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}, default={1}") + public void getOrCustomDefaultIfValueExists(Class propType, T defaultValue) throws Exception { + initPropertyTest(propType, defaultValue); T expected = getNonDefaultValue(); T actual = prop.getOrCustomDefault(asPropertyResolver(expected), getCustomValue()); assertSame(expected, actual); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/SshConstantsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/SshConstantsTest.java index 37b9b3f1e..8b30b6405 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/SshConstantsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/SshConstantsTest.java @@ -23,58 +23,61 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SshConstantsTest extends JUnitTestSupport { public SshConstantsTest() { super(); } @Test - public void testGetDisconnectReason() { + void getDisconnectReason() { for (int reason = SshConstants.SSH2_DISCONNECT_HOST_NOT_ALLOWED_TO_CONNECT; reason <= SshConstants.SSH2_DISCONNECT_ILLEGAL_USER_NAME; reason++) { String name = SshConstants.getDisconnectReasonName(reason); - assertTrue("Mismatched name for reason=" + reason + ": " + name, name.startsWith("SSH2_DISCONNECT_")); + assertTrue(name.startsWith("SSH2_DISCONNECT_"), "Mismatched name for reason=" + reason + ": " + name); } } @Test - public void testGetOpenErrorName() { + void getOpenErrorName() { for (int code = SshConstants.SSH_OPEN_ADMINISTRATIVELY_PROHIBITED; code <= SshConstants.SSH_OPEN_RESOURCE_SHORTAGE; code++) { String name = SshConstants.getOpenErrorCodeName(code); - assertTrue("Mismatched name for code=" + code + ": " + name, name.startsWith("SSH_OPEN_")); + assertTrue(name.startsWith("SSH_OPEN_"), "Mismatched name for code=" + code + ": " + name); } } @Test - public void testAmbiguousOpcodes() throws Exception { + void ambiguousOpcodes() throws Exception { int[] knownAmbiguities = { 30, 31, 60 }; Collection opcodes = SshConstants.getAmbiguousOpcodes(); - assertTrue("Not enough ambiguities found", GenericUtils.size(opcodes) >= knownAmbiguities.length); + assertTrue(GenericUtils.size(opcodes) >= knownAmbiguities.length, "Not enough ambiguities found"); for (int cmd : knownAmbiguities) { - assertEquals("Mismatched mnemonic for known ambiguity=" + cmd, Integer.toString(cmd), - SshConstants.getCommandMessageName(cmd)); - assertTrue("Known ambiguity not reported as such: " + cmd, SshConstants.isAmbiguousOpcode(cmd)); - assertTrue("Known ambiguity=" + cmd + " not listed: " + opcodes, opcodes.contains(cmd)); + assertEquals(Integer.toString(cmd), + SshConstants.getCommandMessageName(cmd), + "Mismatched mnemonic for known ambiguity=" + cmd); + assertTrue(SshConstants.isAmbiguousOpcode(cmd), "Known ambiguity not reported as such: " + cmd); + assertTrue(opcodes.contains(cmd), "Known ambiguity=" + cmd + " not listed: " + opcodes); } for (Integer cmd : opcodes) { - assertEquals("Mismatched mnemonic for " + cmd, cmd.toString(), SshConstants.getCommandMessageName(cmd)); - assertTrue("Opcode not detected as ambiguous: " + cmd, SshConstants.isAmbiguousOpcode(cmd)); + assertEquals(cmd.toString(), SshConstants.getCommandMessageName(cmd), "Mismatched mnemonic for " + cmd); + assertTrue(SshConstants.isAmbiguousOpcode(cmd), "Opcode not detected as ambiguous: " + cmd); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/VersionPropertiesTest.java b/sshd-common/src/test/java/org/apache/sshd/common/VersionPropertiesTest.java index e49b36250..f5cd49c92 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/VersionPropertiesTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/VersionPropertiesTest.java @@ -25,30 +25,31 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class VersionPropertiesTest extends JUnitTestSupport { public VersionPropertiesTest() { super(); } @Test - public void testNonEmptyProperties() { + void nonEmptyProperties() { Map props = VersionProperties.getVersionProperties(); assertTrue(MapEntryUtils.isNotEmpty(props)); } @Test - public void testReportedVersionAvailable() { + void reportedVersionAvailable() { Map props = VersionProperties.getVersionProperties(); String version = props.get(VersionProperties.REPORTED_VERSION); assertTrue(GenericUtils.isNotEmpty(version)); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/channel/PtyModeTest.java b/sshd-common/src/test/java/org/apache/sshd/common/channel/PtyModeTest.java index 3eb7fd21a..124ab21a5 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/channel/PtyModeTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/channel/PtyModeTest.java @@ -25,35 +25,37 @@ import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PtyModeTest extends JUnitTestSupport { public PtyModeTest() { super(); } @Test - public void testOpcodeExtractorOnNull() { + void opcodeExtractorOnNull() { assertEquals(-1, PtyMode.OPCODE_EXTRACTOR.applyAsInt(null)); } @Test - public void testEnabledOptions() { + void enabledOptions() { Set expected = EnumSet.of(PtyMode.ECHO, PtyMode.CS8, PtyMode.ICANON); Map modes = PtyMode.createEnabledOptions(expected); - assertEquals("Mismatched modes size", expected.size(), MapEntryUtils.size(modes)); + assertEquals(expected.size(), MapEntryUtils.size(modes), "Mismatched modes size"); for (PtyMode m : expected) { - assertSame("Mismatched setting for " + m, PtyMode.TRUE_SETTING, modes.get(m)); + assertSame(PtyMode.TRUE_SETTING, modes.get(m), "Mismatched setting for " + m); } Set actual = PtyMode.resolveEnabledOptions(modes, expected); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/channel/PtyModeValueTest.java b/sshd-common/src/test/java/org/apache/sshd/common/channel/PtyModeValueTest.java index 94f16c850..b29bc1844 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/channel/PtyModeValueTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/channel/PtyModeValueTest.java @@ -23,71 +23,75 @@ import java.util.List; import java.util.Map; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class PtyModeValueTest extends JUnitTestSupport { - private final PtyMode expected; + private PtyMode expected; - public PtyModeValueTest(PtyMode expected) { + public void initPtyModeValueTest(PtyMode expected) { this.expected = expected; } - @Parameters(name = "{0}") public static List parameters() { return parameterize(PtyMode.MODES); } - @Test - public void testOpcodeExtractor() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void opcodeExtractor(PtyMode expected) { + initPtyModeValueTest(expected); assertEquals(expected.toInt(), PtyMode.OPCODE_EXTRACTOR.applyAsInt(expected)); } - @Test - public void testByOpcodeComparator() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void byOpcodeComparator(PtyMode expected) { + initPtyModeValueTest(expected); int v1 = expected.toInt(); for (PtyMode actual : PtyMode.MODES) { int v2 = actual.toInt(); int cmpExpected = Integer.signum(Integer.compare(v1, v2)); int cmpActual = Integer.signum(PtyMode.BY_OPCODE.compare(expected, actual)); - assertEquals(expected + " vs. " + actual, cmpExpected, cmpActual); + assertEquals(cmpExpected, cmpActual, expected + " vs. " + actual); } } - @Test - public void testFromName() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fromName(PtyMode expected) { + initPtyModeValueTest(expected); String name = expected.name(); for (int index = 0; index < Byte.SIZE; index++) { PtyMode actual = PtyMode.fromName(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); name = shuffleCase(name); } } - @Test + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") @SuppressWarnings("unchecked") - public void testGetBooleanSettingValueOnNullOrEmptyValues() { + public void getBooleanSettingValueOnNullOrEmptyValues(PtyMode expected) { + initPtyModeValueTest(expected); for (Map modes : new Map[] { null, Collections.emptyMap() }) { String s = (modes == null) ? "null" : "empty"; - assertFalse("Map is " + s, PtyMode.getBooleanSettingValue(modes, expected)); + assertFalse(PtyMode.getBooleanSettingValue(modes, expected), "Map is " + s); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/channel/SttySupportTest.java b/sshd-common/src/test/java/org/apache/sshd/common/channel/SttySupportTest.java index 74e7da9af..4cfc4cfb1 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/channel/SttySupportTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/channel/SttySupportTest.java @@ -27,39 +27,33 @@ import java.util.Map; import org.apache.sshd.common.util.ValidateUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class SttySupportTest extends JUnitTestSupport { - private final String resourceName; + private String resourceName; - public SttySupportTest(String resourceName) { + public void initSttySupportTest(String resourceName) { this.resourceName = resourceName; } - @Parameters(name = "{0}") public static List parameters() { return parameterize(Arrays.asList("stty-output-1.txt", "stty-output-2.txt")); } - @Test - public void testParseSttyOutput() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void parseSttyOutput(String resourceName) throws Exception { + initSttySupportTest(resourceName); String stty; try (InputStream s = ValidateUtils.checkNotNull( getClass().getResourceAsStream(resourceName), "Missing %s", resourceName); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES128GCMTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES128GCMTest.java index 217ba3541..d52b21c7f 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES128GCMTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES128GCMTest.java @@ -19,7 +19,7 @@ package org.apache.sshd.common.cipher; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AES128GCMTest extends BaseAuthenticatedCipherTest { @@ -28,7 +28,7 @@ public AES128GCMTest() { } @Test - public void testEncryptDecrypt() throws Exception { + void encryptDecrypt() throws Exception { ensureFullCipherInformationSupported(BuiltinCiphers.aes128gcm); testAuthenticatedEncryptDecrypt(BuiltinCiphers.aes128gcm); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES192CTRTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES192CTRTest.java index bdd220a52..f9267e137 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES192CTRTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES192CTRTest.java @@ -19,21 +19,21 @@ package org.apache.sshd.common.cipher; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class AES192CTRTest extends BaseCipherTest { public AES192CTRTest() { super(); } @Test - public void testEncryptDecrypt() throws Exception { + void encryptDecrypt() throws Exception { // for AES 256 bits we need the JCE unlimited strength policy ensureFullCipherInformationSupported(BuiltinCiphers.aes192ctr); testEncryptDecrypt(BuiltinCiphers.aes192ctr); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256CBCTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256CBCTest.java index 6503b23bd..8e336acfc 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256CBCTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256CBCTest.java @@ -19,21 +19,21 @@ package org.apache.sshd.common.cipher; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class AES256CBCTest extends BaseCipherTest { public AES256CBCTest() { super(); } @Test - public void testEncryptDecrypt() throws Exception { + void encryptDecrypt() throws Exception { // for AES 256 bits we need the JCE unlimited strength policy ensureFullCipherInformationSupported(BuiltinCiphers.aes256cbc); testEncryptDecrypt(BuiltinCiphers.aes256cbc); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256GCMTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256GCMTest.java index 5a8f23ac0..73de431f5 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256GCMTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256GCMTest.java @@ -19,7 +19,7 @@ package org.apache.sshd.common.cipher; -import org.junit.Test; +import org.junit.jupiter.api.Test; public class AES256GCMTest extends BaseAuthenticatedCipherTest { @@ -28,7 +28,7 @@ public AES256GCMTest() { } @Test - public void testEncryptDecrypt() throws Exception { + void encryptDecrypt() throws Exception { ensureFullCipherInformationSupported(BuiltinCiphers.aes256gcm); testAuthenticatedEncryptDecrypt(BuiltinCiphers.aes256gcm); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR128Test.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR128Test.java index 9f1fef3a4..d0f951d2e 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR128Test.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR128Test.java @@ -19,14 +19,14 @@ package org.apache.sshd.common.cipher; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ARCFOUR128Test extends BaseCipherTest { public ARCFOUR128Test() { super(); @@ -34,7 +34,7 @@ public ARCFOUR128Test() { @Test @SuppressWarnings("deprecation") - public void testEncryptDecrypt() throws Exception { + void encryptDecrypt() throws Exception { testEncryptDecrypt(BuiltinCiphers.arcfour128); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR256Test.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR256Test.java index 682b3403e..11150d252 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR256Test.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR256Test.java @@ -19,14 +19,14 @@ package org.apache.sshd.common.cipher; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ARCFOUR256Test extends BaseCipherTest { public ARCFOUR256Test() { super(); @@ -34,7 +34,7 @@ public ARCFOUR256Test() { @Test @SuppressWarnings("deprecation") - public void testEncryptDecrypt() throws Exception { + void encryptDecrypt() throws Exception { // for RC4 256 bits we need the JCE unlimited strength policy ensureCipherInformationKeySizeSupported(BuiltinCiphers.arcfour256); testEncryptDecrypt(BuiltinCiphers.arcfour256); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseAuthenticatedCipherTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseAuthenticatedCipherTest.java index dd2028755..14cfeed38 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseAuthenticatedCipherTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseAuthenticatedCipherTest.java @@ -25,6 +25,10 @@ import org.apache.sshd.common.NamedFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; + public abstract class BaseAuthenticatedCipherTest extends BaseCipherTest { protected BaseAuthenticatedCipherTest() { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherResetTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherResetTest.java index 54772d168..25e0d832c 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherResetTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherResetTest.java @@ -32,27 +32,26 @@ import org.apache.sshd.common.cipher.Cipher.Mode; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; -@Category({ NoIoTestCase.class }) -@RunWith(Parameterized.class) +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; + +@Tag("NoIoTestCase") public class BaseCipherResetTest extends JUnitTestSupport { private static final Random RND = new SecureRandom(); - private final String providerName; + private String providerName; - private final BuiltinCiphers builtIn; + private BuiltinCiphers builtIn; - public BaseCipherResetTest(String providerName, BuiltinCiphers builtIn, String name) { + public void initBaseCipherResetTest(String providerName, BuiltinCiphers builtIn, String name) { this.providerName = providerName; this.builtIn = builtIn; if ("BC".equals(providerName)) { @@ -66,7 +65,6 @@ private static void registerBouncyCastleProviderIfNecessary() { } } - @Parameters(name = "{2} - {0}") public static List getParameters() { List items = new ArrayList<>(); for (BuiltinCiphers c : BuiltinCiphers.values()) { @@ -79,14 +77,14 @@ public static List getParameters() { return items; } - @Before - public void changeCipher() { + @BeforeEach + void changeCipher() { BaseCipher.factory = t -> javax.crypto.Cipher.getInstance(t, providerName); BaseCipher.alwaysReInit = true; } - @After - public void resetCipher() { + @AfterEach + void resetCipher() { BaseCipher.factory = SecurityUtils::getCipher; BaseCipher.alwaysReInit = false; } @@ -94,11 +92,13 @@ public void resetCipher() { private void checkBuffer(byte[] data, int index, byte[] front, byte[] back) { byte[] expected = front.clone(); System.arraycopy(back, index, expected, index, back.length - index); - assertArrayEquals("Mismatched bytes at " + index, expected, data); + assertArrayEquals(expected, data, "Mismatched bytes at " + index); } - @Test - public void testReset() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "{2} - {0}") + public void reset(String providerName, BuiltinCiphers builtIn, String name) throws Exception { + initBaseCipherResetTest(providerName, builtIn, name); byte[] plaintext = new byte[builtIn.getCipherBlockSize() * 30]; for (int i = 0; i < plaintext.length; i++) { plaintext[i] = (byte) (' ' + i); @@ -119,13 +119,13 @@ public void testReset() throws Exception { javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance(builtIn.getTransformation(), providerName); cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, secretKey, param); byte[] encrypted = cipher.doFinal(plaintext); - assertEquals("Mismatched length", plaintext.length, encrypted.length); + assertEquals(plaintext.length, encrypted.length, "Mismatched length"); Cipher sshCipher = builtIn.create(); sshCipher.init(Mode.Encrypt, key, iv); byte[] sshText = plaintext.clone(); // Encrypt it all sshCipher.update(sshText); - assertArrayEquals("Mismatched encrypted bytes", encrypted, sshText); + assertArrayEquals(encrypted, sshText, "Mismatched encrypted bytes"); // Same, but encrypt block by block sshCipher = builtIn.create(); sshCipher.init(Mode.Encrypt, key, iv); @@ -135,7 +135,7 @@ public void testReset() throws Exception { sshCipher.update(sshText, i, blockSize); checkBuffer(sshText, i + blockSize, encrypted, plaintext); } - assertArrayEquals("Mismatched encrypted bytes", encrypted, sshText); + assertArrayEquals(encrypted, sshText, "Mismatched encrypted bytes"); // Same, but encrypt six times five blocks sshCipher = builtIn.create(); sshCipher.init(Mode.Encrypt, key, iv); @@ -145,16 +145,16 @@ public void testReset() throws Exception { sshCipher.update(sshText, i, blockSize); checkBuffer(sshText, i + blockSize, encrypted, plaintext); } - assertArrayEquals("Mismatched encrypted bytes", encrypted, sshText); + assertArrayEquals(encrypted, sshText, "Mismatched encrypted bytes"); // Decrypt in all three ways: should be equal to the original plaintext cipher.init(javax.crypto.Cipher.DECRYPT_MODE, secretKey, param); byte[] decrypted = cipher.doFinal(encrypted); - assertArrayEquals("Mismatched encrypted bytes", plaintext, decrypted); + assertArrayEquals(plaintext, decrypted, "Mismatched encrypted bytes"); sshCipher = builtIn.create(); sshCipher.init(Mode.Decrypt, key, iv); byte[] data = encrypted.clone(); sshCipher.update(data); - assertArrayEquals("Mismatched encrypted bytes", plaintext, data); + assertArrayEquals(plaintext, data, "Mismatched encrypted bytes"); sshCipher = builtIn.create(); sshCipher.init(Mode.Decrypt, key, iv); data = encrypted.clone(); @@ -163,7 +163,7 @@ public void testReset() throws Exception { sshCipher.update(data, i, blockSize); checkBuffer(data, i + blockSize, plaintext, encrypted); } - assertArrayEquals("Mismatched encrypted bytes", plaintext, data); + assertArrayEquals(plaintext, data, "Mismatched encrypted bytes"); sshCipher = builtIn.create(); sshCipher.init(Mode.Decrypt, key, iv); data = encrypted.clone(); @@ -172,6 +172,6 @@ public void testReset() throws Exception { sshCipher.update(data, i, blockSize); checkBuffer(data, i + blockSize, plaintext, encrypted); } - assertArrayEquals("Mismatched encrypted bytes", plaintext, data); + assertArrayEquals(plaintext, data, "Mismatched encrypted bytes"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java index 0203c07a9..f05ebcc02 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java @@ -33,14 +33,15 @@ import org.apache.sshd.common.cipher.Cipher.Mode; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.Tag; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; /** * @author Apache MINA SSHD Project */ -@Category({ NoIoTestCase.class }) +@Tag("NoIoTestCase") public abstract class BaseCipherTest extends JUnitTestSupport { protected BaseCipherTest() { super(); @@ -60,7 +61,7 @@ protected void ensureKeySizeSupported(int bsize, String algorithm, String transf cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, new SecretKeySpec(key, algorithm)); } catch (GeneralSecurityException e) { if (e instanceof InvalidKeyException) { // NOTE: assumption violations are NOT test failures... - Assume.assumeTrue(algorithm + "/" + transformation + "[" + bsize + "] N/A", false); + Assumptions.assumeTrue(false, algorithm + "/" + transformation + "[" + bsize + "] N/A"); } throw e; @@ -91,10 +92,10 @@ protected void ensureKeySizeSupported( params); } catch (GeneralSecurityException e) { if (e instanceof InvalidKeyException) { - Assume.assumeTrue(algorithm + "/" + transformation + "[" + bsize + "/" + ivsize + "]", false /* - * force - * exception - */); + Assumptions.assumeTrue(false, algorithm + "/" + transformation + "[" + bsize + "/" + ivsize + "]" /* + * force + * exception + */); } throw e; @@ -127,6 +128,6 @@ protected void testEncryptDecrypt(NamedFactory factory) throws Exception byte[] actBytes = workBuf.clone(); // need to clone since the cipher works in-line dec.update(actBytes, 0, actBytes.length); - assertArrayEquals(facName, expBytes, actBytes); + assertArrayEquals(expBytes, actBytes, facName); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ChaCha20CipherTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ChaCha20CipherTest.java index 92b8725b3..0cae83b87 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ChaCha20CipherTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ChaCha20CipherTest.java @@ -23,7 +23,9 @@ import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.Test; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; public class ChaCha20CipherTest extends JUnitTestSupport { public ChaCha20CipherTest() { @@ -31,7 +33,7 @@ public ChaCha20CipherTest() { } @Test - public void testEncryptDecrypt() throws Exception { + void encryptDecrypt() throws Exception { ChaCha20Cipher cipher = new ChaCha20Cipher(); byte[] key = new byte[cipher.getKdfSize()]; for (int i = 0; i < key.length; i++) { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ECCurvesTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ECCurvesTest.java index 2294606c1..123a97236 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ECCurvesTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ECCurvesTest.java @@ -23,83 +23,86 @@ import java.util.Set; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ECCurvesTest extends JUnitTestSupport { public ECCurvesTest() { super(); } @Test - public void testFromName() { + void fromName() { for (ECCurves expected : ECCurves.VALUES) { String name = expected.getName(); for (int index = 0; index < name.length(); index++) { ECCurves actual = ECCurves.fromCurveName(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); name = shuffleCase(name); } } } @Test - public void testAllNamesListed() { + void allNamesListed() { Set listed = EnumSet.noneOf(ECCurves.class); for (String name : ECCurves.NAMES) { ECCurves c = ECCurves.fromCurveName(name); - assertNotNull("No curve for listed name=" + name, c); - assertTrue("Duplicated listed name: " + name, listed.add(c)); + assertNotNull(c, "No curve for listed name=" + name); + assertTrue(listed.add(c), "Duplicated listed name: " + name); } assertEquals("Mismatched listed vs. values", ECCurves.VALUES, listed); } @Test - public void testFromKeySize() { + void fromKeySize() { for (ECCurves expected : ECCurves.VALUES) { String name = expected.getName(); ECCurves actual = ECCurves.fromCurveSize(expected.getKeySize()); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testFromCurveParameters() { + void fromCurveParameters() { for (ECCurves expected : ECCurves.VALUES) { String name = expected.getName(); ECCurves actual = ECCurves.fromCurveParameters(expected.getParameters()); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testFromKeyType() { + void fromKeyType() { for (ECCurves expected : ECCurves.VALUES) { String keyType = expected.getKeyType(); for (int index = 0; index < keyType.length(); index++) { ECCurves actual = ECCurves.fromKeyType(keyType); - assertSame(keyType, expected, actual); + assertSame(expected, actual, keyType); keyType = shuffleCase(keyType); } } } @Test - public void testAllKeyTypesListed() { + void allKeyTypesListed() { Set listed = EnumSet.noneOf(ECCurves.class); for (String name : ECCurves.KEY_TYPES) { ECCurves c = ECCurves.fromKeyType(name); - assertNotNull("No curve for listed key type=" + name, c); - assertTrue("Duplicated listed key type: " + name, listed.add(c)); + assertNotNull(c, "No curve for listed key type=" + name); + assertTrue(listed.add(c), "Duplicated listed key type: " + name); } assertEquals("Mismatched listed vs. values", ECCurves.VALUES, listed); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/compression/BuiltinCompressionsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/compression/BuiltinCompressionsTest.java index c3c6f3327..c86baf0ec 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/compression/BuiltinCompressionsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/compression/BuiltinCompressionsTest.java @@ -33,52 +33,59 @@ import org.apache.sshd.common.compression.BuiltinCompressions.ParseResult; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class BuiltinCompressionsTest extends JUnitTestSupport { public BuiltinCompressionsTest() { super(); } @Test - public void testFromFactoryName() { + void fromFactoryName() { for (BuiltinCompressions expected : BuiltinCompressions.VALUES) { String name = expected.getName(); for (int index = 0; index < name.length(); index++) { BuiltinCompressions actual = BuiltinCompressions.fromFactoryName(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); name = shuffleCase(name); } } } @Test - public void testAllConstantsCovered() throws Exception { + void allConstantsCovered() throws Exception { Set avail = EnumSet.noneOf(BuiltinCompressions.class); Field[] fields = BuiltinCompressions.Constants.class.getFields(); for (Field f : fields) { String name = (String) f.get(null); BuiltinCompressions value = BuiltinCompressions.fromFactoryName(name); - assertNotNull("No match found for " + name, value); - assertTrue(name + " re-specified", avail.add(value)); + assertNotNull(value, "No match found for " + name); + assertTrue(avail.add(value), name + " re-specified"); } assertEquals("Incomplete coverage", BuiltinCompressions.VALUES, avail); } @Test - public void testParseCompressionsList() { + void parseCompressionsList() { List builtin = NamedResource.getNameList(BuiltinCompressions.VALUES); List unknown = Arrays.asList(getClass().getPackage().getName(), getClass().getSimpleName(), getCurrentTestName()); @@ -115,16 +122,16 @@ public void testParseCompressionsList() { } @Test - public void testResolveFactoryOnBuiltinValues() { + void resolveFactoryOnBuiltinValues() { for (NamedFactory expected : BuiltinCompressions.VALUES) { String name = expected.getName(); NamedFactory actual = BuiltinCompressions.resolveFactory(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testNotAllowedToRegisterBuiltinFactories() { + void notAllowedToRegisterBuiltinFactories() { for (CompressionFactory expected : BuiltinCompressions.VALUES) { try { BuiltinCompressions.registerExtension(expected); @@ -135,38 +142,40 @@ public void testNotAllowedToRegisterBuiltinFactories() { } } - @Test(expected = IllegalArgumentException.class) - public void testNotAllowedToOverrideRegisteredFactories() { - CompressionFactory expected = Mockito.mock(CompressionFactory.class); - Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); + @Test + void notAllowedToOverrideRegisteredFactories() { + assertThrows(IllegalArgumentException.class, () -> { + CompressionFactory expected = Mockito.mock(CompressionFactory.class); + Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); - String name = expected.getName(); - try { - for (int index = 1; index <= Byte.SIZE; index++) { - BuiltinCompressions.registerExtension(expected); - assertEquals("Unexpected success at attempt #" + index, 1, index); + String name = expected.getName(); + try { + for (int index = 1; index <= Byte.SIZE; index++) { + BuiltinCompressions.registerExtension(expected); + assertEquals(1, index, "Unexpected success at attempt #" + index); + } + } finally { + BuiltinCompressions.unregisterExtension(name); } - } finally { - BuiltinCompressions.unregisterExtension(name); - } + }); } @Test - public void testResolveFactoryOnRegisteredExtension() { + void resolveFactoryOnRegisteredExtension() { CompressionFactory expected = Mockito.mock(CompressionFactory.class); Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); String name = expected.getName(); try { - assertNull("Extension already registered", BuiltinCompressions.resolveFactory(name)); + assertNull(BuiltinCompressions.resolveFactory(name), "Extension already registered"); BuiltinCompressions.registerExtension(expected); NamedFactory actual = BuiltinCompressions.resolveFactory(name); - assertSame("Mismatched resolved instance", expected, actual); + assertSame(expected, actual, "Mismatched resolved instance"); } finally { NamedFactory actual = BuiltinCompressions.unregisterExtension(name); - assertSame("Mismatched unregistered instance", expected, actual); - assertNull("Extension not un-registered", BuiltinCompressions.resolveFactory(name)); + assertSame(expected, actual, "Mismatched unregistered instance"); + assertNull(BuiltinCompressions.resolveFactory(name), "Extension not un-registered"); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/TimeValueConfigTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/TimeValueConfigTest.java index 985cb0100..30d1b6594 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/TimeValueConfigTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/TimeValueConfigTest.java @@ -22,24 +22,25 @@ import java.util.concurrent.TimeUnit; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class TimeValueConfigTest extends JUnitTestSupport { public TimeValueConfigTest() { super(); } @Test - public void testDurationOf() { + void durationOf() { Object[] values = { "600", TimeUnit.SECONDS.toMillis(600L), "10m", TimeUnit.MINUTES.toMillis(10L), @@ -51,7 +52,7 @@ public void testDurationOf() { String s = (String) values[index]; Number expected = (Number) values[index + 1]; long actual = TimeValueConfig.durationOf(s); - assertEquals(s, expected.longValue(), actual); + assertEquals(expected.longValue(), actual, s); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/AuthorizedKeyEntryLoginOptionsParseTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/AuthorizedKeyEntryLoginOptionsParseTest.java index c506da04f..7c1d6ca3f 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/AuthorizedKeyEntryLoginOptionsParseTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/AuthorizedKeyEntryLoginOptionsParseTest.java @@ -24,40 +24,36 @@ import java.util.Map; import org.apache.sshd.common.util.GenericUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class AuthorizedKeyEntryLoginOptionsParseTest extends JUnitTestSupport { - private final String value; - private final String loginPart; - private final String keyPart; - private final Map options; + private String value; + private String loginPart; + private String keyPart; + private Map options; - public AuthorizedKeyEntryLoginOptionsParseTest(String value, String loginPart, String keyPart, - Map options) { + public void initAuthorizedKeyEntryLoginOptionsParseTest( + String value, String loginPart, String keyPart, + Map options) { this.value = value; this.loginPart = loginPart; this.keyPart = keyPart; this.options = options; } - @Parameters(name = "{0}") public static List parameters() { List params = new ArrayList<>(); addData(params, "ssh-rsa AAAAB2...19Q==", "john@example.net", "from=\"*.sales.example.net,!pc.sales.example.net\""); @@ -103,22 +99,26 @@ private static void addData(List params, String keyData, String commen params.add(new Object[] { value, value.substring(0, pos), value.substring(pos + 1), optionsMap }); } - @Test - public void testResolveEntryComponents() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void resolveEntryComponents(String value, String loginPart, String keyPart, Map options) { + initAuthorizedKeyEntryLoginOptionsParseTest(value, loginPart, keyPart, options); Map.Entry actual = AuthorizedKeyEntry.resolveEntryComponents(value); - assertNotNull(value, actual); - assertEquals("login(" + value + ")", loginPart, actual.getKey()); - assertEquals("remainder(" + value + ")", keyPart, actual.getValue()); + assertNotNull(actual, value); + assertEquals(loginPart, actual.getKey(), "login(" + value + ")"); + assertEquals(keyPart, actual.getValue(), "remainder(" + value + ")"); } - @Test - public void testParseLoginOptions() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void parseLoginOptions(String value, String loginPart, String keyPart, Map options) { + initAuthorizedKeyEntryLoginOptionsParseTest(value, loginPart, keyPart, options); Map parsed = AuthorizedKeyEntry.parseLoginOptions(loginPart); options.forEach((key, expected) -> { String actual = parsed.get(key); - assertEquals(key, expected, actual); + assertEquals(expected, actual, key); }); - assertEquals("Mismatched size", options.size(), parsed.size()); + assertEquals(options.size(), parsed.size(), "Mismatched size"); } @Override diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/BuiltinIdentitiesTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/BuiltinIdentitiesTest.java index b5aeb9530..59c9534d8 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/BuiltinIdentitiesTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/BuiltinIdentitiesTest.java @@ -31,41 +31,38 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.functors.UnaryEquator; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class BuiltinIdentitiesTest extends JUnitTestSupport { - private final BuiltinIdentities expected; + private BuiltinIdentities expected; - public BuiltinIdentitiesTest(BuiltinIdentities expected) { + public void initBuiltinIdentitiesTest(BuiltinIdentities expected) { this.expected = expected; } - @Parameters(name = "{0}") public static List parameters() { return parameterize(BuiltinIdentities.VALUES); } - @BeforeClass // Dirty hack around the parameterized run - public static void testAllConstantsCovered() throws Exception { + @BeforeAll // Dirty hack around the parameterized run + static void testAllConstantsCovered() throws Exception { Field[] fields = BuiltinIdentities.Constants.class.getFields(); for (Field f : fields) { int mods = f.getModifiers(); @@ -85,46 +82,56 @@ public static void testAllConstantsCovered() throws Exception { String name = f.getName(); String value = (String) f.get(null); BuiltinIdentities id = BuiltinIdentities.fromName(value); - assertNotNull("No match found for field " + name + "=" + value, id); + assertNotNull(id, "No match found for field " + name + "=" + value); } } - @Test - public void testFromName() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fromName(BuiltinIdentities expected) { + initBuiltinIdentitiesTest(expected); String name = expected.getName(); for (int index = 0, count = name.length(); index < count; index++) { - assertSame(name, expected, BuiltinIdentities.fromName(name)); + assertSame(expected, BuiltinIdentities.fromName(name), name); name = shuffleCase(name); } } - @Test - public void testFromAlgorithm() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fromAlgorithm(BuiltinIdentities expected) { + initBuiltinIdentitiesTest(expected); String algorithm = expected.getAlgorithm(); for (int index = 0, count = algorithm.length(); index < count; index++) { - assertSame(algorithm, expected, BuiltinIdentities.fromAlgorithm(algorithm)); + assertSame(expected, BuiltinIdentities.fromAlgorithm(algorithm), algorithm); algorithm = shuffleCase(algorithm); } } - @Test - public void testFromKey() throws GeneralSecurityException { - Assume.assumeTrue("Unsupported built-in identity", expected.isSupported()); + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fromKey(BuiltinIdentities expected) throws GeneralSecurityException { + initBuiltinIdentitiesTest(expected); + Assumptions.assumeTrue(expected.isSupported(), "Unsupported built-in identity"); KeyPairGenerator gen = SecurityUtils.getKeyPairGenerator(expected.getAlgorithm()); KeyPair kp = gen.generateKeyPair(); outputDebugMessage("Checking built-in identity: %s", expected); - assertSame(expected + "[pair]", expected, BuiltinIdentities.fromKeyPair(kp)); - assertSame(expected + "[public]", expected, BuiltinIdentities.fromKey(kp.getPublic())); - assertSame(expected + "[private]", expected, BuiltinIdentities.fromKey(kp.getPrivate())); + assertSame(expected, BuiltinIdentities.fromKeyPair(kp), expected + "[pair]"); + assertSame(expected, BuiltinIdentities.fromKey(kp.getPublic()), expected + "[public]"); + assertSame(expected, BuiltinIdentities.fromKey(kp.getPrivate()), expected + "[private]"); } - @Test - public void testNonEmptySupportedKeyTypeNames() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void nonEmptySupportedKeyTypeNames(BuiltinIdentities expected) { + initBuiltinIdentitiesTest(expected); assertTrue(GenericUtils.isNotEmpty(expected.getSupportedKeyTypes())); } - @Test - public void testNoOverlappingKeyTypeNamesWithOtherIdentities() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void noOverlappingKeyTypeNamesWithOtherIdentities(BuiltinIdentities expected) { + initBuiltinIdentitiesTest(expected); Collection current = expected.getSupportedKeyTypes(); for (BuiltinIdentities identity : BuiltinIdentities.VALUES) { if (UnaryEquator.isSameReference(expected, identity)) { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/EcdsaPublicKeyEntryDecoderTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/EcdsaPublicKeyEntryDecoderTest.java index 713cc5aac..bb189237e 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/EcdsaPublicKeyEntryDecoderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/EcdsaPublicKeyEntryDecoderTest.java @@ -28,44 +28,38 @@ import org.apache.sshd.common.cipher.ECCurves; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class EcdsaPublicKeyEntryDecoderTest extends JUnitTestSupport { public static final int TESTS_COUNT = Integer.parseInt(System.getProperty(EcdsaPublicKeyEntryDecoderTest.class.getName(), "500")); - private final ECCurves curve; + private ECCurves curve; - public EcdsaPublicKeyEntryDecoderTest(ECCurves curve) { + public void initEcdsaPublicKeyEntryDecoderTest(ECCurves curve) { this.curve = curve; } - @Parameters(name = "{0}") public static List parameters() { return parameterize(ECCurves.VALUES); } - @Test // see SSHD-934 - public void testEncodeDecodePublicKey() throws Exception { - Assume.assumeTrue("ECC not supported", SecurityUtils.isECCSupported()); + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") // see SSHD-934 + public void encodeDecodePublicKey(ECCurves curve) throws Exception { + initEcdsaPublicKeyEntryDecoderTest(curve); + Assumptions.assumeTrue(SecurityUtils.isECCSupported(), "ECC not supported"); int keySize = curve.getKeySize(); String keyType = curve.getKeyType(); for (int index = 1; index <= TESTS_COUNT; index++) { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyRandomArtTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyRandomArtTest.java index 5108a12c3..0c13575a0 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyRandomArtTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyRandomArtTest.java @@ -29,41 +29,36 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.AfterClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class KeyRandomArtTest extends JUnitTestSupport { private static final Collection KEYS = new LinkedList<>(); - private final String algorithm; - private final int keySize; - private final KeyPair keyPair; + private String algorithm; + private int keySize; + private KeyPair keyPair; - public KeyRandomArtTest(String algorithm, int keySize) throws Exception { + public void initKeyRandomArtTest(String algorithm, int keySize) throws Exception { this.algorithm = algorithm; this.keySize = keySize; this.keyPair = CommonTestSupportUtils.generateKeyPair(algorithm, keySize); KEYS.add(this.keyPair); } - @Parameters(name = "algorithm={0}, key-size={1}") public static List parameters() { List params = new ArrayList<>(); for (int keySize : RSA_SIZES) { @@ -88,20 +83,22 @@ public static List parameters() { return params; } - @AfterClass - public static void dumpAllArts() throws Exception { + @AfterAll + static void dumpAllArts() throws Exception { KeyRandomArt.combine(null, System.out, ' ', session -> KEYS); } - @Test - public void testRandomArtString() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "algorithm={0}, key-size={1}") + public void randomArtString(String algorithm, int keySize) throws Exception { + initKeyRandomArtTest(algorithm, keySize); KeyRandomArt art = new KeyRandomArt(keyPair.getPublic()); - assertEquals("Mismatched algorithm", algorithm, art.getAlgorithm()); - assertEquals("Mismatched key size", keySize, art.getKeySize()); + assertEquals(algorithm, art.getAlgorithm(), "Mismatched algorithm"); + assertEquals(keySize, art.getKeySize(), "Mismatched key size"); String s = art.toString(); String[] lines = GenericUtils.split(s, '\n'); - assertEquals("Mismatched lines count", KeyRandomArt.FLDSIZE_Y + 2, lines.length); + assertEquals(KeyRandomArt.FLDSIZE_Y + 2, lines.length, "Mismatched lines count"); for (int index = 0; index < lines.length; index++) { String l = lines[index]; @@ -111,8 +108,8 @@ public void testRandomArtString() throws Exception { } System.out.append('\t').println(l); - assertTrue("Mismatched line length #" + (index + 1) + ": " + l.length(), - l.length() >= (KeyRandomArt.FLDSIZE_X + 2)); + assertTrue(l.length() >= (KeyRandomArt.FLDSIZE_X + 2), + "Mismatched line length #" + (index + 1) + ": " + l.length()); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsCloneTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsCloneTest.java index 5b3e9e61f..31b5c2454 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsCloneTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsCloneTest.java @@ -32,35 +32,31 @@ import org.apache.sshd.common.keyprovider.KeyPairProvider; import org.apache.sshd.common.util.ValidateUtils; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class KeyUtilsCloneTest extends JUnitTestSupport { - private final String keyType; - private final int keySize; + private String keyType; + private int keySize; - public KeyUtilsCloneTest(String keyType, int keySize) { + public void initKeyUtilsCloneTest(String keyType, int keySize) { this.keyType = ValidateUtils.checkNotNullAndNotEmpty(keyType, "No key type specified"); this.keySize = keySize; } - @Parameters(name = "type={0}, size={1}") public static List parameters() { List list = new ArrayList<>(); addTests(list, KeyPairProvider.SSH_DSS, DSS_SIZES); @@ -85,9 +81,11 @@ private static void addTests(List list, String keyType, CollectionApache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class KeyUtilsFingerprintCaseSensitivityTest extends JUnitTestSupport { // CHECKSTYLE:OFF @@ -68,18 +63,17 @@ public class KeyUtilsFingerprintCaseSensitivityTest extends JUnitTestSupport { private String expected; private String test; - public KeyUtilsFingerprintCaseSensitivityTest(String expected, String test) { + public void initKeyUtilsFingerprintCaseSensitivityTest(String expected, String test) { this.expected = expected; this.test = test; } - @BeforeClass - public static void beforeClass() throws GeneralSecurityException, IOException { + @BeforeAll + static void beforeClass() throws GeneralSecurityException, IOException { PublicKeyEntry keyEntry = PublicKeyEntry.parsePublicKeyEntry(KEY_STRING); key = keyEntry.resolvePublicKey(null, Collections.emptyMap(), PublicKeyEntryResolver.FAILING); } - @Parameters(name = "expected={0}, test={1}") public static Collection parameters() { return Arrays.asList( new Object[] { MD5_FULL, MD5_FULL }, @@ -94,8 +88,10 @@ public static Collection parameters() { new Object[] { SHA1_FULL, SHA1_PREFIX.toLowerCase() + SHA1 }); } - @Test - public void testCase() throws Exception { - assertEquals("Check failed", new SimpleImmutableEntry<>(true, expected), KeyUtils.checkFingerPrint(test, key)); + @MethodSource("parameters") + @ParameterizedTest(name = "expected={0}, test={1}") + public void testCase(String expected, String test) throws Exception { + initKeyUtilsFingerprintCaseSensitivityTest(expected, test); + assertEquals(new SimpleImmutableEntry<>(true, expected), KeyUtils.checkFingerPrint(test, key), "Check failed"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsFingerprintGenerationTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsFingerprintGenerationTest.java index a131b87e9..37a7ecf42 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsFingerprintGenerationTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsFingerprintGenerationTest.java @@ -33,37 +33,31 @@ import org.apache.sshd.common.digest.BuiltinDigests; import org.apache.sshd.common.digest.DigestFactory; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class KeyUtilsFingerprintGenerationTest extends JUnitTestSupport { - private final PublicKey key; - private final DigestFactory digestFactory; - private final String expected; + private PublicKey key; + private DigestFactory digestFactory; + private String expected; - public KeyUtilsFingerprintGenerationTest(PublicKey key, DigestFactory digestFactory, String expected) { + public void initKeyUtilsFingerprintGenerationTest(PublicKey key, DigestFactory digestFactory, String expected) { this.key = key; this.digestFactory = digestFactory; this.expected = expected; } - @Parameters(name = "key={0}, digestFactory={1}, expected={2}") public static Collection parameters() throws IOException, GeneralSecurityException { List>>> keyEntries = Collections.unmodifiableList(Arrays.asList( @@ -135,20 +129,22 @@ public static Collection parameters() throws IOException, GeneralSecur return ret; } - @Test - public void testFingerprint() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "key={0}, digestFactory={1}, expected={2}") + public void fingerprint(PublicKey key, DigestFactory digestFactory, String expected) throws Exception { + initKeyUtilsFingerprintGenerationTest(key, digestFactory, expected); String name = digestFactory.getName(); assertEquals( - String.format("Fingerprint does not match for digest %s", name), expected, - KeyUtils.getFingerPrint(digestFactory, key)); + KeyUtils.getFingerPrint(digestFactory, key), + String.format("Fingerprint does not match for digest %s", name)); assertEquals( - String.format("Fingerprint check failed for digest %s", name), new SimpleImmutableEntry<>(true, expected), - KeyUtils.checkFingerPrint(expected, digestFactory, key)); + KeyUtils.checkFingerPrint(expected, digestFactory, key), + String.format("Fingerprint check failed for digest %s", name)); assertEquals( - String.format("Fingerprint check succeeded for invalid digest %s", name), new SimpleImmutableEntry<>(false, expected), - KeyUtils.checkFingerPrint(expected + "A", digestFactory, key)); + KeyUtils.checkFingerPrint(expected + "A", digestFactory, key), + String.format("Fingerprint check succeeded for invalid digest %s", name)); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsTest.java index ad5e0adb2..6ba2fd84a 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/KeyUtilsTest.java @@ -20,6 +20,7 @@ package org.apache.sshd.common.config.keys; import java.io.ByteArrayInputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -45,31 +46,35 @@ import org.apache.sshd.common.util.OsUtils; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.TemporaryFolder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.io.TempDir; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class KeyUtilsTest extends JUnitTestSupport { - @Rule - public TemporaryFolder testDir = new TemporaryFolder(); + @TempDir + protected File testDir; public KeyUtilsTest() { super(); } @Test - public void testGenerateFingerPrintOnException() { + void generateFingerPrintOnException() { for (DigestFactory info : BuiltinDigests.VALUES) { if (!info.isSupported()) { System.out.println("Skip unsupported digest: " + info.getAlgorithm()); @@ -110,14 +115,14 @@ public Digest create() { } }, getCurrentTestName()); String expected = thrown.getClass().getSimpleName(); - assertEquals("Mismatched fingerprint for " + thrown.getMessage(), expected, actual); + assertEquals(expected, actual, "Mismatched fingerprint for " + thrown.getMessage()); } } @Test - public void testGenerateDefaultFingerprintDigest() { + void generateDefaultFingerprintDigest() { DigestFactory defaultValue = KeyUtils.getDefaultFingerPrintFactory(); - assertNotNull("No current default fingerprint digest factory", defaultValue); + assertNotNull(defaultValue, "No current default fingerprint digest factory"); try { for (DigestFactory f : BuiltinDigests.VALUES) { if (!f.isSupported()) { @@ -130,20 +135,21 @@ public void testGenerateDefaultFingerprintDigest() { String data = getClass().getName() + "#" + getCurrentTestName() + "(" + f.getName() + ")"; String expected = KeyUtils.getFingerPrint(f, data); String actual = KeyUtils.getFingerPrint(data); - assertEquals("Mismatched fingerprint for digest=" + f.getName(), expected, actual); + assertEquals(expected, actual, "Mismatched fingerprint for digest=" + f.getName()); } } finally { KeyUtils.setDefaultFingerPrintFactory(defaultValue); // restore the original } } - @Test // see SSHD-606 - public void testValidateStrictKeyFilePermissions() throws IOException { - Assume.assumeTrue("Test does not always work on Windows", !OsUtils.isWin32()); + // see SSHD-606 + @Test + void validateStrictKeyFilePermissions() throws IOException { + Assumptions.assumeTrue(!OsUtils.isWin32(), "Test does not always work on Windows"); Path file = getTempTargetRelativeFile(getClass().getSimpleName(), getCurrentTestName()); outputDebugMessage("%s deletion result=%s", file, Files.deleteIfExists(file)); - assertNull("Unexpected violation for non-existent file: " + file, KeyUtils.validateStrictKeyFilePermissions(file)); + assertNull(KeyUtils.validateStrictKeyFilePermissions(file), "Unexpected violation for non-existent file: " + file); assertHierarchyTargetFolderExists(file.getParent()); try (OutputStream output = Files.newOutputStream(file)) { @@ -153,40 +159,42 @@ public void testValidateStrictKeyFilePermissions() throws IOException { Collection perms = IoUtils.getPermissions(file); if (GenericUtils.isEmpty(perms)) { - assertNull("Unexpected violation for no permissions file: " + file, - KeyUtils.validateStrictKeyFilePermissions(file)); + assertNull(KeyUtils.validateStrictKeyFilePermissions(file), + "Unexpected violation for no permissions file: " + file); } else if (OsUtils.isUNIX()) { Map.Entry violation = null; for (PosixFilePermission p : KeyUtils.STRICTLY_PROHIBITED_FILE_PERMISSION) { if (perms.contains(p)) { violation = KeyUtils.validateStrictKeyFilePermissions(file); - assertNotNull("Unexpected success for permission=" + p + " of file " + file + " permissions=" + perms, - violation); + assertNotNull(violation, + "Unexpected success for permission=" + p + " of file " + file + " permissions=" + perms); break; } } if (violation == null) { // we expect a failure since the parent does not have the necessary permissions - assertNotNull("Unexpected UNIX success for file " + file + " permissions=" + perms, - KeyUtils.validateStrictKeyFilePermissions(file)); + assertNotNull(KeyUtils.validateStrictKeyFilePermissions(file), + "Unexpected UNIX success for file " + file + " permissions=" + perms); } } else { - assertNull("Unexpected Windows violation for file " + file + " permissions=" + perms, - KeyUtils.validateStrictKeyFilePermissions(file)); + assertNull(KeyUtils.validateStrictKeyFilePermissions(file), + "Unexpected Windows violation for file " + file + " permissions=" + perms); } } - @Test // see SSHD-895 - public void testRSAKeyTypeAliases() { + // see SSHD-895 + @Test + void rsaKeyTypeAliases() { for (String alias : new String[] { KeyUtils.RSA_SHA256_KEY_TYPE_ALIAS, KeyUtils.RSA_SHA512_KEY_TYPE_ALIAS }) { - assertEquals("Mismatched canonical name for " + alias, KeyPairProvider.SSH_RSA, - KeyUtils.getCanonicalKeyType(alias)); + assertEquals(KeyPairProvider.SSH_RSA, + KeyUtils.getCanonicalKeyType(alias), + "Mismatched canonical name for " + alias); } } @Test - public void testLoadPublicKey() throws Exception { - Path testFile = testDir.newFile().toPath(); + void loadPublicKey() throws Exception { + Path testFile = File.createTempFile("junit", null, testDir).toPath(); try (InputStream testContent = this.getClass().getClassLoader().getResourceAsStream( this.getClass().getPackage().getName().replace('.', '/') + "/loader/openssh/RSA-KeyPair.pub")) { Files.copy(testContent, testFile, StandardCopyOption.REPLACE_EXISTING); @@ -197,22 +205,22 @@ public void testLoadPublicKey() throws Exception { } @Test - public void testLoadPublicKeyNonExisting() throws Exception { - Path testFile = testDir.getRoot().toPath().resolve("does_not_exist"); + void loadPublicKeyNonExisting() throws Exception { + Path testFile = testDir.toPath().resolve("does_not_exist"); assertFalse(Files.exists(testFile, LinkOption.NOFOLLOW_LINKS)); assertThrows(IOException.class, () -> KeyUtils.loadPublicKey(testFile)); } @Test - public void testLoadPublicKeyEmpty() throws Exception { - Path testFile = testDir.newFile().toPath(); + void loadPublicKeyEmpty() throws Exception { + Path testFile = File.createTempFile("junit", null, testDir).toPath(); PublicKey key = KeyUtils.loadPublicKey(testFile); assertNull(key); } @Test - public void testLoadPublicKeyMultiple() throws Exception { - Path testFile = testDir.newFile().toPath(); + void loadPublicKeyMultiple() throws Exception { + Path testFile = File.createTempFile("junit", null, testDir).toPath(); byte[] data; try (InputStream testContent = this.getClass().getClassLoader().getResourceAsStream( this.getClass().getPackage().getName().replace('.', '/') + "/loader/openssh/RSA-KeyPair.pub")) { @@ -229,8 +237,8 @@ public void testLoadPublicKeyMultiple() throws Exception { } @Test - public void testLoadPublicKeyCorrupt() throws Exception { - Path testFile = testDir.newFile().toPath(); + void loadPublicKeyCorrupt() throws Exception { + Path testFile = File.createTempFile("junit", null, testDir).toPath(); byte[] data = new byte[42]; Arrays.fill(data, (byte) 'a'); Files.write(testFile, data); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/OpenSshCertificateValuesTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/OpenSshCertificateValuesTest.java index 732c56557..564aaf812 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/OpenSshCertificateValuesTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/OpenSshCertificateValuesTest.java @@ -21,11 +21,13 @@ import java.time.Instant; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestMethodOrder(MethodName.class) public class OpenSshCertificateValuesTest { public OpenSshCertificateValuesTest() { @@ -33,24 +35,28 @@ public OpenSshCertificateValuesTest() { } @Test - public void testValidAfterMinMaxSuccess() { + void validAfterMinMaxSuccess() { new OpenSshCertificateImpl().setValidAfter(OpenSshCertificate.MIN_EPOCH); new OpenSshCertificateImpl().setValidAfter(OpenSshCertificate.INFINITY); } @Test - public void testValidBeforeMinMaxSuccess() { + void validBeforeMinMaxSuccess() { new OpenSshCertificateImpl().setValidBefore(OpenSshCertificate.MIN_EPOCH); new OpenSshCertificateImpl().setValidBefore(OpenSshCertificate.INFINITY); } - @Test(expected = IllegalArgumentException.class) - public void testValidAfterOutOfBounds() { - new OpenSshCertificateImpl().setValidAfter(Instant.EPOCH.minusSeconds(1L)); + @Test + void validAfterOutOfBounds() { + assertThrows(IllegalArgumentException.class, () -> { + new OpenSshCertificateImpl().setValidAfter(Instant.EPOCH.minusSeconds(1L)); + }); } - @Test(expected = IllegalArgumentException.class) - public void testValidBeforeOutOfBounds() { - new OpenSshCertificateImpl().setValidBefore(Instant.EPOCH.minusSeconds(1L)); + @Test + void validBeforeOutOfBounds() { + assertThrows(IllegalArgumentException.class, () -> { + new OpenSshCertificateImpl().setValidBefore(Instant.EPOCH.minusSeconds(1L)); + }); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/PublicKeyEntryTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/PublicKeyEntryTest.java index 32d3c62a2..c83a3e3a9 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/PublicKeyEntryTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/PublicKeyEntryTest.java @@ -27,24 +27,26 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PublicKeyEntryTest extends JUnitTestSupport { public PublicKeyEntryTest() { super(); } @Test - public void testFallbackResolver() throws Exception { + void fallbackResolver() throws Exception { PublicKeyEntry entry = PublicKeyEntry.parsePublicKeyEntry( GenericUtils.join( Arrays.asList(getCurrentTestName(), "AAAA", getClass().getSimpleName()), ' ')); @@ -52,8 +54,8 @@ public void testFallbackResolver() throws Exception { null, PublicKeyEntryResolver.FAILING, PublicKeyEntryResolver.IGNORING }) { try { PublicKey key = entry.resolvePublicKey(null, Collections.emptyMap(), resolver); - assertSame("Mismatched successful resolver", PublicKeyEntryResolver.IGNORING, resolver); - assertNull("Unexpected success for resolver=" + resolver + ": " + KeyUtils.getFingerPrint(key), key); + assertSame(PublicKeyEntryResolver.IGNORING, resolver, "Mismatched successful resolver"); + assertNull(key, "Unexpected success for resolver=" + resolver + ": " + KeyUtils.getFingerPrint(key)); } catch (GeneralSecurityException e) { assertObjectInstanceOf("Mismatched thrown exception for resolver=" + resolver, InvalidKeySpecException.class, e); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/AESPrivateKeyObfuscatorTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/AESPrivateKeyObfuscatorTest.java index df0c7f785..bf9f3ebec 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/AESPrivateKeyObfuscatorTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/AESPrivateKeyObfuscatorTest.java @@ -32,42 +32,39 @@ import org.apache.sshd.common.cipher.CipherInformation; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class AESPrivateKeyObfuscatorTest extends JUnitTestSupport { - private final int keyLength; + private int keyLength; - public AESPrivateKeyObfuscatorTest(int keyLength) { + public void initAESPrivateKeyObfuscatorTest(int keyLength) { this.keyLength = keyLength; } - @Parameters(name = "keyLength={0}") public static List parameters() { List lengths = AESPrivateKeyObfuscator.getAvailableKeyLengths(); - assertFalse("No lengths available", GenericUtils.isEmpty(lengths)); + assertFalse(GenericUtils.isEmpty(lengths), "No lengths available"); return parameterize(lengths); } - @Test - public void testAvailableKeyLengthExists() throws GeneralSecurityException { - assertEquals("Not a BYTE size multiple", 0, keyLength % Byte.SIZE); + @MethodSource("parameters") + @ParameterizedTest(name = "keyLength={0}") + public void availableKeyLengthExists(int keyLength) throws GeneralSecurityException { + initAESPrivateKeyObfuscatorTest(keyLength); + assertEquals(0, keyLength % Byte.SIZE, "Not a BYTE size multiple"); PrivateKeyEncryptionContext encContext = new PrivateKeyEncryptionContext(); encContext.setCipherName(AESPrivateKeyObfuscator.CIPHER_NAME); @@ -75,25 +72,27 @@ public void testAvailableKeyLengthExists() throws GeneralSecurityException { encContext.setCipherType(Integer.toString(keyLength)); int actual = AESPrivateKeyObfuscator.INSTANCE.resolveKeyLength(encContext); - assertEquals("Mismatched resolved key length", keyLength, actual); + assertEquals(keyLength, actual, "Mismatched resolved key length"); // see SSHD-987 byte[] iv = AESPrivateKeyObfuscator.INSTANCE.generateInitializationVector(encContext); - assertEquals("Mismatched IV size", 16 /* TODO change this if GCM allowed */, iv.length); + assertEquals(16 /* TODO change this if GCM allowed */, iv.length, "Mismatched IV size"); Key key = new SecretKeySpec(iv, AESPrivateKeyObfuscator.CIPHER_NAME); Cipher c = SecurityUtils.getCipher(AESPrivateKeyObfuscator.CIPHER_NAME); c.init(Cipher.DECRYPT_MODE, key); } - @Test - public void testSingleCipherMatch() { + @MethodSource("parameters") + @ParameterizedTest(name = "keyLength={0}") + public void singleCipherMatch(int keyLength) { + initAESPrivateKeyObfuscatorTest(keyLength); Predicate selector = AESPrivateKeyObfuscator.createCipherSelector( keyLength, PrivateKeyEncryptionContext.DEFAULT_CIPHER_MODE); Collection matches = BuiltinCiphers.VALUES.stream() .filter(selector) .collect(Collectors.toList()); - assertEquals("Mismatched matching ciphers: " + matches, 1, GenericUtils.size(matches)); + assertEquals(1, GenericUtils.size(matches), "Mismatched matching ciphers: " + matches); } @Override diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserAEADTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserAEADTest.java index 1dac4687b..11205074c 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserAEADTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserAEADTest.java @@ -24,20 +24,20 @@ import org.apache.sshd.common.config.keys.KeyUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests reading an ed25519 private key in OpenSSH format AES encrypted and encrypted with AEAD ciphers (AES-GCM and * chacha20-poly1305@openssh.com). */ -@RunWith(Parameterized.class) -@Category({ NoIoTestCase.class }) +@Tag("NoIoTestCase") public class OpenSSHKeyPairResourceParserAEADTest extends JUnitTestSupport { private static final String BASE = "ed25519_priv"; @@ -46,32 +46,33 @@ public class OpenSSHKeyPairResourceParserAEADTest extends JUnitTestSupport { private KeyPair unencrypted; - public OpenSSHKeyPairResourceParserAEADTest(String fileName) { + public void initOpenSSHKeyPairResourceParserAEADTest(String fileName) { testFileName = fileName; } - @Parameters(name = "{0}") public static String[] parameters() { return new String[] { BASE + ".aes", BASE + ".cha", BASE + ".gcm" }; } private KeyPair load(String fileName) throws Exception { URL url = getClass().getResource(fileName); - assertNotNull("Missing test resource " + fileName, url); + assertNotNull(url, "Missing test resource " + fileName); Collection pairs = OpenSSHKeyPairResourceParser.INSTANCE.loadKeyPairs(null, url, (s, r, i) -> "test"); - assertEquals("Unexpected number of keys", 1, pairs.size()); + assertEquals(1, pairs.size(), "Unexpected number of keys"); KeyPair result = pairs.iterator().next(); - assertNotNull("No unencrypted key pair", result); + assertNotNull(result, "No unencrypted key pair"); return result; } - @Before - public void loadUnencrypted() throws Exception { + @BeforeEach + void loadUnencrypted() throws Exception { unencrypted = load(BASE); } - @Test - public void testDecrypt() throws Exception { - assertTrue("Unequal keys", KeyUtils.compareKeyPairs(unencrypted, load(testFileName))); + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void decrypt(String fileName) throws Exception { + initOpenSSHKeyPairResourceParserAEADTest(fileName); + assertTrue(KeyUtils.compareKeyPairs(unencrypted, load(testFileName)), "Unequal keys"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserDecodingTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserDecodingTest.java index a41cd9387..151fea36d 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserDecodingTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserDecodingTest.java @@ -28,41 +28,42 @@ import org.apache.sshd.common.config.keys.KeyUtils; import org.apache.sshd.common.config.keys.PrivateKeyEntryDecoder; import org.apache.sshd.common.util.GenericUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class OpenSSHKeyPairResourceParserDecodingTest extends OpenSSHKeyPairResourceParserTestSupport { - public OpenSSHKeyPairResourceParserDecodingTest(BuiltinIdentities identity) { - super(identity); + + public void initOpenSSHKeyPairResourceParserDecodingTest(BuiltinIdentities identity) { + setIdentity(identity); } - @Parameters(name = "type={0}") public static List parameters() { return parameterize(BuiltinIdentities.VALUES); } - @Test - public void testLoadUnencryptedKeyPairs() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}") + public void loadUnencryptedKeyPairs(BuiltinIdentities identity) throws Exception { + initOpenSSHKeyPairResourceParserDecodingTest(identity); testLoadKeyPairs(false, null); } - @Test - public void testLoadEncryptedKeyPairs() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}") + public void loadEncryptedKeyPairs(BuiltinIdentities identity) throws Exception { + initOpenSSHKeyPairResourceParserDecodingTest(identity); testLoadKeyPairs(true, DEFAULT_PASSWORD_PROVIDER); } @@ -70,7 +71,7 @@ public void testLoadEncryptedKeyPairs() throws Exception { protected void testLoadKeyPairs( boolean encrypted, String resourceKey, Collection pairs, PublicKey pubEntry) throws Exception { - assertEquals("Mismatched pairs count", 1, GenericUtils.size(pairs)); + assertEquals(1, GenericUtils.size(pairs), "Mismatched pairs count"); Class pubType = identity.getPublicKeyType(); Class prvType = identity.getPrivateKeyType(); @@ -85,7 +86,7 @@ protected void testLoadKeyPairs( String pubName = KeyUtils.getKeyType(pubKey); String prvName = KeyUtils.getKeyType(prvKey); - assertEquals("Mismatched reported key type names", pubName, prvName); + assertEquals(pubName, prvName, "Mismatched reported key type names"); if (!supportedTypeNames.contains(pubName)) { fail("Unsupported key type name (" + pubName + "): " + supportedTypeNames); @@ -95,7 +96,7 @@ protected void testLoadKeyPairs( @SuppressWarnings("rawtypes") PrivateKeyEntryDecoder decoder = OpenSSHKeyPairResourceParser.getPrivateKeyEntryDecoder(prvKey); - assertNotNull("No private key decoder", decoder); + assertNotNull(decoder, "No private key decoder"); if (decoder.isPublicKeyRecoverySupported()) { @SuppressWarnings("unchecked") diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserPasswordTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserPasswordTest.java index 0bac2aa76..a47facb86 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserPasswordTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserPasswordTest.java @@ -34,34 +34,33 @@ import org.apache.sshd.common.config.keys.FilePasswordProvider.ResourceDecodeResult; import org.apache.sshd.common.session.SessionContext; import org.apache.sshd.common.util.GenericUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class OpenSSHKeyPairResourceParserPasswordTest extends OpenSSHKeyPairResourceParserTestSupport { private static final int MAX_RETRIES = 3; - private final ResourceDecodeResult decodeResult; + private ResourceDecodeResult decodeResult; private final AtomicInteger retriesCount = new AtomicInteger(0); - private final FilePasswordProvider passwordProvider; + private FilePasswordProvider passwordProvider; - public OpenSSHKeyPairResourceParserPasswordTest(BuiltinIdentities identity, ResourceDecodeResult reportedResult) { - super(identity); + public void initOpenSSHKeyPairResourceParserPasswordTest(BuiltinIdentities identity, ResourceDecodeResult reportedResult) { + setIdentity(identity); this.decodeResult = reportedResult; this.passwordProvider = new FilePasswordProvider() { @Override @@ -89,17 +88,17 @@ public ResourceDecodeResult handleDecodeAttemptResult( switch (reportedResult) { case IGNORE: case TERMINATE: - assertNotNull("No error reported", err); - assertEquals("Mismatched retry index", 0, retryIndex); + assertNotNull(err, "No error reported"); + assertEquals(0, retryIndex, "Mismatched retry index"); break; case RETRY: if (err != null) { @SuppressWarnings("synthetic-access") int curRetry = retriesCount.getAndIncrement(); - assertEquals("Mismatched retry index", curRetry, retryIndex); - assertTrue("Too many retries: " + retryIndex, retryIndex < MAX_RETRIES); + assertEquals(curRetry, retryIndex, "Mismatched retry index"); + assertTrue(retryIndex < MAX_RETRIES, "Too many retries: " + retryIndex); } else { - assertEquals("Mismatched success retries count", MAX_RETRIES, retryIndex); + assertEquals(MAX_RETRIES, retryIndex, "Mismatched success retries count"); } break; default: @@ -111,7 +110,6 @@ public ResourceDecodeResult handleDecodeAttemptResult( }; } - @Parameters(name = "{0} / {1}") public static List parameters() { return new ArrayList() { // Not serializing it @@ -127,16 +125,19 @@ public static List parameters() { }; } - @Before - public void setUp() { + @BeforeEach + void setUp() { retriesCount.set(0); } - @Test - public void testLoadEncryptedFileWithPasswordRetry() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0} / {1}") + public void loadEncryptedFileWithPasswordRetry(BuiltinIdentities identity, ResourceDecodeResult reportedResult) + throws Exception { + initOpenSSHKeyPairResourceParserPasswordTest(identity, reportedResult); try { testLoadKeyPairs(true, passwordProvider); - assertNotSame("Unexpected success", ResourceDecodeResult.TERMINATE, decodeResult); + assertNotSame(ResourceDecodeResult.TERMINATE, decodeResult, "Unexpected success"); } catch (Exception e) { if (decodeResult != ResourceDecodeResult.TERMINATE) { throw e; @@ -155,13 +156,13 @@ protected void testLoadKeyPairs( throws Exception { switch (decodeResult) { case IGNORE: - assertTrue("Unexpected key pairs recovered", GenericUtils.isEmpty(pairs)); - assertEquals("Mismatched retries count", 0, retriesCount.getAndSet(0)); + assertTrue(GenericUtils.isEmpty(pairs), "Unexpected key pairs recovered"); + assertEquals(0, retriesCount.getAndSet(0), "Mismatched retries count"); break; case RETRY: - assertEquals("Mismatched pairs count", 1, GenericUtils.size(pairs)); - assertEquals("Mismatched retries count", MAX_RETRIES, retriesCount.getAndSet(0)); + assertEquals(1, GenericUtils.size(pairs), "Mismatched pairs count"); + assertEquals(MAX_RETRIES, retriesCount.getAndSet(0), "Mismatched retries count"); validateKeyPairSignable(resourceKey, GenericUtils.head(pairs)); break; diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserTestSupport.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserTestSupport.java index 24a071a7f..1a6c4b98b 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserTestSupport.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHKeyPairResourceParserTestSupport.java @@ -34,7 +34,10 @@ import org.apache.sshd.common.config.keys.PublicKeyEntryResolver; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.Assume; +import org.junit.jupiter.api.Assumptions; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * TODO Add javadoc @@ -47,14 +50,14 @@ public abstract class OpenSSHKeyPairResourceParserTestSupport extends JUnitTestS protected static final FilePasswordProvider DEFAULT_PASSWORD_PROVIDER = FilePasswordProvider.of(PASSWORD); protected static final String ENCRYPTED_RESOURCE_PREFIX = "encrypted"; - protected final BuiltinIdentities identity; + protected BuiltinIdentities identity; - protected OpenSSHKeyPairResourceParserTestSupport(BuiltinIdentities identity) { + protected void setIdentity(BuiltinIdentities identity) { this.identity = identity; } protected void testLoadKeyPairs(boolean encrypted, FilePasswordProvider passwordProvider) throws Exception { - Assume.assumeTrue(identity + " not supported", identity.isSupported()); + Assumptions.assumeTrue(identity.isSupported(), identity + " not supported"); String resourceKey = identity.getName().toUpperCase() + "-" + KeyPair.class.getSimpleName(); if (encrypted) { @@ -63,10 +66,11 @@ protected void testLoadKeyPairs(boolean encrypted, FilePasswordProvider password URL urlKeyPair = getClass().getResource(resourceKey); if (encrypted) { - Assume.assumeTrue(identity + " no encrypted test data", urlKeyPair != null); - Assume.assumeTrue(BuiltinCiphers.aes256cbc.getTransformation() + " N/A", BuiltinCiphers.aes256cbc.isSupported()); + Assumptions.assumeTrue(urlKeyPair != null, identity + " no encrypted test data"); + Assumptions.assumeTrue(BuiltinCiphers.aes256cbc.isSupported(), + BuiltinCiphers.aes256cbc.getTransformation() + " N/A"); } else { - assertNotNull("Missing key-pair resource: " + resourceKey, urlKeyPair); + assertNotNull(urlKeyPair, "Missing key-pair resource: " + resourceKey); } Collection pairs; @@ -82,15 +86,15 @@ protected void testLoadKeyPairs(boolean encrypted, FilePasswordProvider password } URL urlPubKey = getClass().getResource(resourceKey + PublicKeyEntry.PUBKEY_FILE_SUFFIX); - assertNotNull("Missing public key resource: " + resourceKey, urlPubKey); + assertNotNull(urlPubKey, "Missing public key resource: " + resourceKey); List entries = AuthorizedKeyEntry.readAuthorizedKeys(urlPubKey); - assertEquals("Mismatched public keys count", 1, GenericUtils.size(entries)); + assertEquals(1, GenericUtils.size(entries), "Mismatched public keys count"); AuthorizedKeyEntry entry = entries.get(0); PublicKey pubEntry = entry.resolvePublicKey( null, Collections.emptyMap(), PublicKeyEntryResolver.FAILING); - assertNotNull("Cannot retrieve public key", pubEntry); + assertNotNull(pubEntry, "Cannot retrieve public key"); testLoadKeyPairs(encrypted, resourceKey, pairs, pubEntry); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHMaxBCryptRoundsSettingTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHMaxBCryptRoundsSettingTest.java index 6c02de38b..d604dfcd9 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHMaxBCryptRoundsSettingTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/openssh/OpenSSHMaxBCryptRoundsSettingTest.java @@ -28,48 +28,44 @@ import org.apache.sshd.common.config.keys.BuiltinIdentities; import org.apache.sshd.common.config.keys.loader.openssh.kdf.BCryptKdfOptions; import org.apache.sshd.common.config.keys.loader.openssh.kdf.BCryptKdfOptions.BCryptBadRoundsException; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class OpenSSHMaxBCryptRoundsSettingTest extends OpenSSHKeyPairResourceParserTestSupport { - public OpenSSHMaxBCryptRoundsSettingTest(BuiltinIdentities identity) { - super(identity); + public void initOpenSSHMaxBCryptRoundsSettingTest(BuiltinIdentities identity) { + setIdentity(identity); } - @Parameters(name = "type={0}") public static List parameters() { return parameterize(BuiltinIdentities.VALUES); } - @Before - public void setUp() { + @BeforeEach + void setUp() { BCryptKdfOptions.setMaxAllowedRounds(1); // we know all our test cases use 16 } - @After - public void tearDown() { + @AfterEach + void tearDown() { BCryptKdfOptions.setMaxAllowedRounds(BCryptKdfOptions.DEFAULT_MAX_ROUNDS); } - @Test - public void testMaxRoundsSettingFailure() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}") + public void maxRoundsSettingFailure(BuiltinIdentities identity) throws Exception { + initOpenSSHMaxBCryptRoundsSettingTest(identity); testLoadKeyPairs(true, DEFAULT_PASSWORD_PROVIDER); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/pem/PKCS8PEMResourceKeyPairParserTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/pem/PKCS8PEMResourceKeyPairParserTest.java index 577f744aa..3ede7af27 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/pem/PKCS8PEMResourceKeyPairParserTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/pem/PKCS8PEMResourceKeyPairParserTest.java @@ -38,38 +38,33 @@ import org.apache.sshd.common.config.keys.KeyUtils; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PKCS8PEMResourceKeyPairParserTest extends JUnitTestSupport { - private final String algorithm; - private final int keySize; + private String algorithm; + private int keySize; - public PKCS8PEMResourceKeyPairParserTest(String algorithm, int keySize) { + public void initPKCS8PEMResourceKeyPairParserTest(String algorithm, int keySize) { this.algorithm = algorithm; this.keySize = keySize; } - @Parameters(name = "{0}-{1}") public static List parameters() { List params = new ArrayList<>(); for (Integer ks : RSA_SIZES) { @@ -94,8 +89,10 @@ public static List parameters() { return params; } - @Test // see SSHD-760 - public void testLocallyGeneratedPkcs8() throws IOException, GeneralSecurityException { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}-{1}") // see SSHD-760 + public void locallyGeneratedPkcs8(String algorithm, int keySize) throws IOException, GeneralSecurityException { + initPKCS8PEMResourceKeyPairParserTest(algorithm, keySize); KeyPairGenerator generator = SecurityUtils.getKeyPairGenerator(algorithm); if (keySize > 0) { generator.initialize(keySize); @@ -114,7 +111,7 @@ public void testLocallyGeneratedPkcs8() throws IOException, GeneralSecurityExcep Iterable ids = SecurityUtils.loadKeyPairIdentities( null, NamedResource.ofName(getCurrentTestName()), bais, null); KeyPair kp2 = GenericUtils.head(ids); - assertNotNull("No identity loaded", kp2); + assertNotNull(kp2, "No identity loaded"); assertKeyEquals("Mismatched public key", kp.getPublic(), kp2.getPublic()); assertKeyEquals("Mismatched private key", prv1, kp2.getPrivate()); } @@ -135,15 +132,17 @@ public void testLocallyGeneratedPkcs8() throws IOException, GeneralSecurityExcep * * openssl genpkey -algorithm ed25519 -out pkcs8-ed25519.pem openssl asn1parse -inform PEM -in ...file... -dump */ - @Test // see SSHD-989 - public void testPKCS8FileParsing() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}-{1}") // see SSHD-989 + public void pkcs8FileParsing(String algorithm, int keySize) throws Exception { + initPKCS8PEMResourceKeyPairParserTest(algorithm, keySize); String baseName = "pkcs8-" + algorithm.toLowerCase(); String resourceKey = baseName + ((keySize > 0) ? "-" + keySize : "") + ".pem"; URL url = getClass().getResource(resourceKey); - assertNotNull("No test file=" + resourceKey, url); + assertNotNull(url, "No test file=" + resourceKey); Collection pairs = PKCS8PEMResourceKeyPairParser.INSTANCE.loadKeyPairs(null, url, null); - assertEquals("Mismatched extract keys count", 1, GenericUtils.size(pairs)); + assertEquals(1, GenericUtils.size(pairs), "Mismatched extract keys count"); validateKeyPairSignable(algorithm + "/" + keySize, GenericUtils.head(pairs)); // Check for an encrypted key } @@ -153,25 +152,27 @@ public void testPKCS8FileParsing() throws Exception { * * openssl [rsa|dsa|ec] -in .pem -out .enc -aes-128-cbc */ - @Test - public void testTraditionalEncryptedPEMParsing() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}-{1}") + public void traditionalEncryptedPEMParsing(String algorithm, int keySize) throws Exception { + initPKCS8PEMResourceKeyPairParserTest(algorithm, keySize); String baseName = "pkcs8-" + algorithm.toLowerCase(); String resourceKey = baseName + ((keySize > 0) ? "-" + keySize : "") + ".enc"; URL url = getClass().getResource(resourceKey); - assertNotNull("No encrypted test file=" + resourceKey, url); + assertNotNull(url, "No encrypted test file=" + resourceKey); // The eddsa (ed25519) PEM file with RFC 1421 traditional encryption comes from // https://github.com/bcgit/bc-java/issues/1238#issuecomment-1263162809 and has a // different password. Unknown how it was generated; openssl always writes the // RFC 5958 EncryptedPrivateKeyInfo. String password = "eddsa".equalsIgnoreCase(algorithm) ? "Vjvyhfngz0MCUs$kwOF0" : "test"; Collection pairs = PEMResourceParserUtils.PROXY.loadKeyPairs(null, url, (s, r, i) -> password); - assertEquals("Mismatched extract keys count", 1, GenericUtils.size(pairs)); + assertEquals(1, GenericUtils.size(pairs), "Mismatched extract keys count"); validateKeyPairSignable(algorithm + "/" + keySize, GenericUtils.head(pairs)); // Try again using the standard key pair parser try (InputStream in = url.openStream()) { pairs = SecurityUtils.getKeyPairResourceParser().loadKeyPairs(null, NamedResource.ofName(getCurrentTestName()), (s, r, i) -> password, in); - assertEquals("Mismatched extract keys count", 1, GenericUtils.size(pairs)); + assertEquals(1, GenericUtils.size(pairs), "Mismatched extract keys count"); validateKeyPairSignable(algorithm + "/" + keySize, GenericUtils.head(pairs)); } } @@ -181,22 +182,24 @@ public void testTraditionalEncryptedPEMParsing() throws Exception { * * openssl pkcs8 -in .pem -out .enc2 -topk8 */ - @Test - public void testEncryptedPEMParsing() throws Exception { - Assume.assumeTrue(SecurityUtils.isBouncyCastleRegistered()); + @MethodSource("parameters") + @ParameterizedTest(name = "{0}-{1}") + public void encryptedPEMParsing(String algorithm, int keySize) throws Exception { + initPKCS8PEMResourceKeyPairParserTest(algorithm, keySize); + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered()); String baseName = "pkcs8-" + algorithm.toLowerCase(); String resourceKey = baseName + ((keySize > 0) ? "-" + keySize : "") + ".enc2"; URL url = getClass().getResource(resourceKey); - assertNotNull("No encrypted test file=" + resourceKey, url); + assertNotNull(url, "No encrypted test file=" + resourceKey); String password = "test"; Collection pairs = PEMResourceParserUtils.PROXY.loadKeyPairs(null, url, (s, r, i) -> password); - assertEquals("Mismatched extract keys count", 1, GenericUtils.size(pairs)); + assertEquals(1, GenericUtils.size(pairs), "Mismatched extract keys count"); validateKeyPairSignable(algorithm + "/" + keySize, GenericUtils.head(pairs)); // Try again using the standard key pair parser try (InputStream in = url.openStream()) { pairs = SecurityUtils.getKeyPairResourceParser().loadKeyPairs(null, NamedResource.ofName(getCurrentTestName()), (s, r, i) -> password, in); - assertEquals("Mismatched extract keys count", 1, GenericUtils.size(pairs)); + assertEquals(1, GenericUtils.size(pairs), "Mismatched extract keys count"); validateKeyPairSignable(algorithm + "/" + keySize, GenericUtils.head(pairs)); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/ssh2/Ssh2PublicKeyEntryDecoderByKeyTypeTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/ssh2/Ssh2PublicKeyEntryDecoderByKeyTypeTest.java index 2c1e28550..2436388ae 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/ssh2/Ssh2PublicKeyEntryDecoderByKeyTypeTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/ssh2/Ssh2PublicKeyEntryDecoderByKeyTypeTest.java @@ -33,33 +33,27 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.ValidateUtils; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class Ssh2PublicKeyEntryDecoderByKeyTypeTest extends JUnitTestSupport { - private final String keyType; + private String keyType; - public Ssh2PublicKeyEntryDecoderByKeyTypeTest(String keyType) { + public void initSsh2PublicKeyEntryDecoderByKeyTypeTest(String keyType) { this.keyType = keyType; } - @Parameters(name = "{0}") public static List parameters() { return new ArrayList() { // Not serializing it @@ -87,13 +81,15 @@ private void addKey(String k) { }; } - @Test - public void testDecodePublicKey() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void decodePublicKey(String keyType) throws Exception { + initSsh2PublicKeyEntryDecoderByKeyTypeTest(keyType); PublicKey expected; try (InputStream keyData = getPublicKeyDataStream("pub")) { Collection entries = AuthorizedKeyEntry.readAuthorizedKeys(keyData, true); List keys = PublicKeyEntry.resolvePublicKeyEntries(null, entries, null); - assertEquals("Mismatched expected public entries count", 1, GenericUtils.size(keys)); + assertEquals(1, GenericUtils.size(keys), "Mismatched expected public entries count"); expected = keys.get(0); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/ssh2/Ssh2PublicKeyEntryDecoderTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/ssh2/Ssh2PublicKeyEntryDecoderTest.java index 439926a4b..5d8514255 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/ssh2/Ssh2PublicKeyEntryDecoderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/loader/ssh2/Ssh2PublicKeyEntryDecoderTest.java @@ -25,29 +25,30 @@ import org.apache.sshd.common.config.keys.KeyUtils; import org.apache.sshd.common.util.ValidateUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class Ssh2PublicKeyEntryDecoderTest extends JUnitTestSupport { public Ssh2PublicKeyEntryDecoderTest() { super(); } @Test - public void testMultiLineComment() throws Exception { + void multiLineComment() throws Exception { testDecoder("rfc4716-multi-line-comment.ssh2"); } @Test - public void testMultipleHeaders() throws Exception { + void multipleHeaders() throws Exception { testDecoder("rfc4716-multiple-headers.ssh2"); } @@ -57,10 +58,10 @@ private PublicKey testDecoder(String resourceName) throws Exception { getClass().getResourceAsStream(resourceName), "Missing test resource: %s", resourceName)) { key = Ssh2PublicKeyEntryDecoder.INSTANCE.readPublicKey(null, () -> resourceName, stream); } - assertNotNull("No key loaded from " + resourceName, key); + assertNotNull(key, "No key loaded from " + resourceName); String keyType = KeyUtils.getKeyType(key); - assertNotNull("Unknown key type loaded from " + resourceName, keyType); + assertNotNull(keyType, "Unknown key type loaded from " + resourceName); return key; } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/writer/openssh/OpenSSHKeyPairResourceWriterTest.java b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/writer/openssh/OpenSSHKeyPairResourceWriterTest.java index e25567d1a..80651159d 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/config/keys/writer/openssh/OpenSSHKeyPairResourceWriterTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/config/keys/writer/openssh/OpenSSHKeyPairResourceWriterTest.java @@ -48,33 +48,31 @@ import org.apache.sshd.common.util.io.output.SecureByteArrayOutputStream; import org.apache.sshd.common.util.io.resource.PathResource; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class OpenSSHKeyPairResourceWriterTest extends JUnitTestSupport { - private final TestData data; + private TestData data; private KeyPair testKey; - public OpenSSHKeyPairResourceWriterTest(TestData data) { + public void initOpenSSHKeyPairResourceWriterTest(TestData data) throws Exception { this.data = data; + setUp(); } - @Parameters(name = "{0}") public static Collection parameters() { List result = new ArrayList<>(); result.add(new TestData("RSA", 1024, null)); @@ -107,8 +105,7 @@ public static Collection parameters() { return parameterize(result); } - @Before - public void setUp() throws Exception { + void setUp() throws Exception { KeyPairGenerator generator; if (data.provider == null) { generator = KeyPairGenerator.getInstance(data.algorithm); @@ -142,8 +139,10 @@ private static void writeToFile(Path file, byte[] sensitiveData) } } - @Test - public void testFileRoundtripNoEncryption() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fileRoundtripNoEncryption(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (SecureByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyPairResourceWriter.INSTANCE.writePrivateKey(testKey, "a comment", null, out); @@ -152,9 +151,9 @@ public void testFileRoundtripNoEncryption() throws Exception { try (InputStream in = Files.newInputStream(tmp)) { KeyPair key = SecurityUtils.loadKeyPairIdentities(null, new PathResource(tmp), in, null).iterator().next(); - assertNotNull("No key pair parsed", key); + assertNotNull(key, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key); - assertTrue("Keys should be equal", compare(key, testKey)); + assertTrue(compare(key, testKey), "Keys should be equal"); Path tmp2 = getTemporaryOutputFile("again"); try (SecureByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyPairResourceWriter.INSTANCE.writePrivateKey(key, "a comment", null, out); @@ -163,18 +162,20 @@ public void testFileRoundtripNoEncryption() throws Exception { try (InputStream in2 = Files.newInputStream(tmp2)) { KeyPair key2 = SecurityUtils.loadKeyPairIdentities(null, new PathResource(tmp2), in2, null).iterator().next(); - assertNotNull("No key pair parsed", key2); + assertNotNull(key2, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key2); - assertTrue("Keys should be equal", compare(key2, testKey)); + assertTrue(compare(key2, testKey), "Keys should be equal"); assertKeyPairEquals("Mismatched recovered keys", key, key2); - assertTrue("Keys should be equal", compare(key2, key)); + assertTrue(compare(key2, key), "Keys should be equal"); } } } - @Test - public void testFileRoundtripWithEncryption() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fileRoundtripWithEncryption(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); OpenSSHKeyEncryptionContext options = new OpenSSHKeyEncryptionContext(); options.setPassword("nonsense"); @@ -190,9 +191,9 @@ public void testFileRoundtripWithEncryption() throws Exception { try (InputStream in = Files.newInputStream(tmp)) { KeyPair key = SecurityUtils.loadKeyPairIdentities(null, new PathResource(tmp), in, FilePasswordProvider.of("nonsense")).iterator().next(); - assertNotNull("No key pair parsed", key); + assertNotNull(key, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key); - assertTrue("Keys should be equal", compare(key, testKey)); + assertTrue(compare(key, testKey), "Keys should be equal"); Path tmp2 = getTemporaryOutputFile("again"); try (ByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyPairResourceWriter.INSTANCE.writePrivateKey(key, "a comment", options, out); @@ -201,18 +202,20 @@ public void testFileRoundtripWithEncryption() throws Exception { try (InputStream in2 = Files.newInputStream(tmp2)) { KeyPair key2 = SecurityUtils.loadKeyPairIdentities(null, new PathResource(tmp2), in2, FilePasswordProvider.of("nonsense")).iterator().next(); - assertNotNull("No key pair parsed", key2); + assertNotNull(key2, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key2); - assertTrue("Keys should be equal", compare(key2, testKey)); + assertTrue(compare(key2, testKey), "Keys should be equal"); assertKeyPairEquals("Mismatched recovered keys", key, key2); - assertTrue("Keys should be equal", compare(key2, key)); + assertTrue(compare(key2, key), "Keys should be equal"); } } } - @Test - public void testFileRoundtripAsymmetric() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fileRoundtripAsymmetric(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); // Write first unencrypted, then encrypted. read both and compare. Path tmp = getTemporaryOutputFile(); try (ByteArrayOutputStream out = new SecureByteArrayOutputStream()) { @@ -222,9 +225,9 @@ public void testFileRoundtripAsymmetric() throws Exception { try (InputStream in = Files.newInputStream(tmp)) { KeyPair key = SecurityUtils.loadKeyPairIdentities(null, new PathResource(tmp), in, null).iterator().next(); - assertNotNull("No key pair parsed", key); + assertNotNull(key, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key); - assertTrue("Keys should be equal", compare(key, testKey)); + assertTrue(compare(key, testKey), "Keys should be equal"); Path tmp2 = getTemporaryOutputFile("again"); try (ByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyEncryptionContext options = new OpenSSHKeyEncryptionContext(); @@ -238,18 +241,20 @@ public void testFileRoundtripAsymmetric() throws Exception { try (InputStream in2 = Files.newInputStream(tmp2)) { KeyPair key2 = SecurityUtils.loadKeyPairIdentities(null, new PathResource(tmp2), in2, FilePasswordProvider.of("nonsense")).iterator().next(); - assertNotNull("No key pair parsed", key2); + assertNotNull(key2, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key2); - assertTrue("Keys should be equal", compare(key2, testKey)); + assertTrue(compare(key2, testKey), "Keys should be equal"); assertKeyPairEquals("Mismatched recovered keys", key, key2); - assertTrue("Keys should be equal", compare(key2, key)); + assertTrue(compare(key2, key), "Keys should be equal"); } } } - @Test - public void testWritePrivateKeyNoEncryption() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePrivateKeyNoEncryption(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (ByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyPairResourceWriter.INSTANCE.writePrivateKey(testKey, "a comment", null, out); @@ -258,14 +263,16 @@ public void testWritePrivateKeyNoEncryption() throws Exception { try (InputStream in = Files.newInputStream(tmp)) { KeyPair key = SecurityUtils.loadKeyPairIdentities(null, new PathResource(tmp), in, null).iterator().next(); - assertNotNull("No key pair parsed", key); + assertNotNull(key, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key); - assertTrue("Keys should be equal", compare(key, testKey)); + assertTrue(compare(key, testKey), "Keys should be equal"); } } - @Test - public void testWritePrivateKeyNoPassword() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePrivateKeyNoPassword(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (ByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyEncryptionContext options = new OpenSSHKeyEncryptionContext(); @@ -275,14 +282,16 @@ public void testWritePrivateKeyNoPassword() throws Exception { try (InputStream in = Files.newInputStream(tmp)) { KeyPair key = SecurityUtils.loadKeyPairIdentities(null, new PathResource(tmp), in, null).iterator().next(); - assertNotNull("No key pair parsed", key); + assertNotNull(key, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key); - assertTrue("Keys should be equal", compare(key, testKey)); + assertTrue(compare(key, testKey), "Keys should be equal"); } } - @Test - public void testWritePrivateKeyEncryptedAesCbc128() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePrivateKeyEncryptedAesCbc128(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (ByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyEncryptionContext options = new OpenSSHKeyEncryptionContext(); @@ -298,14 +307,16 @@ public void testWritePrivateKeyEncryptedAesCbc128() throws Exception { .loadKeyPairIdentities(null, new PathResource(tmp), in, FilePasswordProvider.of("nonsense")) .iterator().next(); - assertNotNull("No key pair parsed", key); + assertNotNull(key, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key); - assertTrue("Keys should be equal", compare(key, testKey)); + assertTrue(compare(key, testKey), "Keys should be equal"); } } - @Test - public void testWritePrivateKeyEncryptedAesCtr256() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePrivateKeyEncryptedAesCtr256(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (ByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyEncryptionContext options = new OpenSSHKeyEncryptionContext(); @@ -321,14 +332,16 @@ public void testWritePrivateKeyEncryptedAesCtr256() throws Exception { .loadKeyPairIdentities(null, new PathResource(tmp), in, FilePasswordProvider.of("nonsense")) .iterator().next(); - assertNotNull("No key pair parsed", key); + assertNotNull(key, "No key pair parsed"); assertKeyPairEquals("Mismatched recovered keys", testKey, key); - assertTrue("Keys should be equal", compare(key, testKey)); + assertTrue(compare(key, testKey), "Keys should be equal"); } } - @Test - public void testWritePrivateKeyEncryptedWrongPassword() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePrivateKeyEncryptedWrongPassword(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (ByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyEncryptionContext options = new OpenSSHKeyEncryptionContext(); @@ -349,8 +362,10 @@ public void testWritePrivateKeyEncryptedWrongPassword() throws Exception { } } - @Test - public void testWritePrivateKeyEncryptedNoPassword() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePrivateKeyEncryptedNoPassword(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (ByteArrayOutputStream out = new SecureByteArrayOutputStream()) { OpenSSHKeyEncryptionContext options = new OpenSSHKeyEncryptionContext(); @@ -370,22 +385,24 @@ public void testWritePrivateKeyEncryptedNoPassword() throws Exception { private void checkPublicKey(Path tmp, String comment) throws Exception { List keysRead = AuthorizedKeyEntry.readAuthorizedKeys(tmp); - assertEquals("Unexpected list size", 1, keysRead.size()); + assertEquals(1, keysRead.size(), "Unexpected list size"); AuthorizedKeyEntry entry = keysRead.get(0); String readComment = entry.getComment(); if (comment == null || comment.isEmpty()) { - assertTrue("Unexpected comment: " + readComment, readComment == null || readComment.isEmpty()); + assertTrue(readComment == null || readComment.isEmpty(), "Unexpected comment: " + readComment); } else { - assertEquals("Unexpected comment", comment, readComment); + assertEquals(comment, readComment, "Unexpected comment"); } PublicKey pubKey = entry.resolvePublicKey(null, PublicKeyEntryResolver.IGNORING); - assertTrue("keys don't match", - KeyUtils.compareKeys(testKey.getPublic(), pubKey)); + assertTrue(KeyUtils.compareKeys(testKey.getPublic(), pubKey), + "keys don't match"); } - @Test - public void testWritePublicKeyWithComment() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePublicKeyWithComment(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (OutputStream out = Files.newOutputStream(tmp)) { OpenSSHKeyPairResourceWriter.INSTANCE.writePublicKey(testKey, "a comment", out); @@ -393,20 +410,25 @@ public void testWritePublicKeyWithComment() throws Exception { checkPublicKey(tmp, "a comment"); } - @Test - public void testWritePublicKeyWithMultilineComment() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePublicKeyWithMultilineComment(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (OutputStream out = Files.newOutputStream(tmp)) { OpenSSHKeyPairResourceWriter.INSTANCE.writePublicKey(testKey, "a comment" + System.lineSeparator() + "second line", out); } - assertEquals("Unexpected number of lines", 1, - Files.readAllLines(tmp).size()); + assertEquals(1, + Files.readAllLines(tmp).size(), + "Unexpected number of lines"); checkPublicKey(tmp, "a comment"); } - @Test - public void testWritePublicKeyNoComment() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePublicKeyNoComment(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (OutputStream out = Files.newOutputStream(tmp)) { OpenSSHKeyPairResourceWriter.INSTANCE.writePublicKey(testKey, null, out); @@ -414,8 +436,10 @@ public void testWritePublicKeyNoComment() throws Exception { checkPublicKey(tmp, null); } - @Test - public void testWritePublicKeyEmptyComment() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void writePublicKeyEmptyComment(TestData data) throws Exception { + initOpenSSHKeyPairResourceWriterTest(data); Path tmp = getTemporaryOutputFile(); try (OutputStream out = Files.newOutputStream(tmp)) { OpenSSHKeyPairResourceWriter.INSTANCE.writePublicKey(testKey, "", out); @@ -457,12 +481,14 @@ private static class TestData { public final AlgorithmParameterSpec spec; - TestData(String algorithm, int keySize, + TestData( + String algorithm, int keySize, AlgorithmParameterSpec spec) { this(algorithm, null, keySize, spec); } - TestData(String algorithm, String provider, int keySize, + TestData( + String algorithm, String provider, int keySize, AlgorithmParameterSpec spec) { this.algorithm = algorithm; this.provider = provider; diff --git a/sshd-common/src/test/java/org/apache/sshd/common/digest/BuiltinDigestsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/digest/BuiltinDigestsTest.java index 9ec928b23..946ec8e55 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/digest/BuiltinDigestsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/digest/BuiltinDigestsTest.java @@ -24,40 +24,43 @@ import java.util.Set; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class BuiltinDigestsTest extends JUnitTestSupport { public BuiltinDigestsTest() { super(); } @Test - public void testFromName() { + void fromName() { for (BuiltinDigests expected : BuiltinDigests.VALUES) { String name = expected.getName(); BuiltinDigests actual = BuiltinDigests.fromFactoryName(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testAllConstantsCovered() throws Exception { + void allConstantsCovered() throws Exception { Set avail = EnumSet.noneOf(BuiltinDigests.class); Field[] fields = BuiltinDigests.Constants.class.getFields(); for (Field f : fields) { String name = (String) f.get(null); BuiltinDigests value = BuiltinDigests.fromFactoryName(name); - assertNotNull("No match found for " + name, value); - assertTrue(name + " re-specified", avail.add(value)); + assertNotNull(value, "No match found for " + name); + assertTrue(avail.add(value), name + " re-specified"); } assertEquals("Incomplete coverage", BuiltinDigests.VALUES, avail); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/file/nonefs/NoneFileSystemFactoryTest.java b/sshd-common/src/test/java/org/apache/sshd/common/file/nonefs/NoneFileSystemFactoryTest.java index 854de5a80..38a870024 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/file/nonefs/NoneFileSystemFactoryTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/file/nonefs/NoneFileSystemFactoryTest.java @@ -24,28 +24,31 @@ import java.nio.file.spi.FileSystemProvider; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class NoneFileSystemFactoryTest extends JUnitTestSupport { public NoneFileSystemFactoryTest() { super(); } @Test - public void testFileSystemCreation() throws IOException { + void fileSystemCreation() throws IOException { FileSystem fs = NoneFileSystemFactory.INSTANCE.createFileSystem(null); FileSystemProvider provider = fs.provider(); - assertEquals("Mismatched provider scheme", NoneFileSystemProvider.SCHEME, provider.getScheme()); + assertEquals(NoneFileSystemProvider.SCHEME, provider.getScheme(), "Mismatched provider scheme"); } @Test - public void testUserHomeDirectory() throws IOException { + void userHomeDirectory() throws IOException { assertNull(NoneFileSystemFactory.INSTANCE.getUserHomeDir(null)); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/file/root/AssertableFile.java b/sshd-common/src/test/java/org/apache/sshd/common/file/root/AssertableFile.java index 8a2aeb030..83b2a7517 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/file/root/AssertableFile.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/file/root/AssertableFile.java @@ -25,6 +25,8 @@ import org.apache.sshd.common.util.NumberUtils; import org.apache.sshd.util.test.JUnitTestSupport; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * TODO upgrade to default methods in JDK 8 * @@ -37,37 +39,37 @@ protected AssertableFile() { public static boolean notExists(Path p) { boolean cond = !Files.exists(p); - assertTrue(p + " does not exist", cond); + assertTrue(cond, p + " does not exist"); return cond; } public static boolean exists(Path p) { boolean cond = Files.exists(p); - assertTrue(p + " exists", cond); + assertTrue(cond, p + " exists"); return cond; } public static boolean isDir(Path p) { boolean cond = Files.isDirectory(p); - assertTrue(p + " is directory", cond); + assertTrue(cond, p + " is directory"); return cond; } public static boolean isReadable(Path p) { boolean cond = Files.isReadable(p); - assertTrue(p + " is readable by user", cond); + assertTrue(cond, p + " is readable by user"); return cond; } public static boolean isNonEmpty(byte[] bytes) { boolean cond = !NumberUtils.isEmpty(bytes); - assertTrue("bytes are non empty", cond); + assertTrue(cond, "bytes are non empty"); return cond; } public static boolean isRootedAt(Path root, Path check) { boolean cond = check.toAbsolutePath().normalize().startsWith(root.toAbsolutePath().normalize()); - assertTrue(check + " is subpath of parent " + root, cond); + assertTrue(cond, check + " is subpath of parent " + root); return cond; } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/file/root/RootedFileSystemProviderTest.java b/sshd-common/src/test/java/org/apache/sshd/common/file/root/RootedFileSystemProviderTest.java index ee38b2c33..e36ebb48f 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/file/root/RootedFileSystemProviderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/file/root/RootedFileSystemProviderTest.java @@ -48,13 +48,18 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.OsUtils; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests the RootedFileSystemProvider implementation of {@link java.nio.file.spi.FileSystemProvider} checking that @@ -65,8 +70,8 @@ * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class RootedFileSystemProviderTest extends AssertableFile { private static final String SKIP_ON_WINDOWS = "Test fails due to windows normalizing paths before opening them, " + "allowing one to open a file like \"C:\\directory_doesnt_exist\\..\\myfile.txt\" whereas this is blocked in unix"; @@ -87,17 +92,17 @@ public RootedFileSystemProviderTest() throws Exception { } @Test - public void testRoot() { + void root() { Path root = fileSystem.getRoot(); - assertTrue("Exists? " + root, exists(root)); - assertTrue("Dir? " + root, isDir(root)); - assertTrue("Readable? " + root, isReadable(root)); - assertTrue(root + " rooted at " + rootSandbox + " ?", isRootedAt(rootSandbox, root)); + assertTrue(exists(root), "Exists? " + root); + assertTrue(isDir(root), "Dir? " + root); + assertTrue(isReadable(root), "Readable? " + root); + assertTrue(isRootedAt(rootSandbox, root), root + " rooted at " + rootSandbox + " ?"); } /* mkdir */ @Test - public void testMkdir() throws IOException { + void mkdir() throws IOException { Path created = fileHelper.createDirectory(fileSystem.getPath(getCurrentTestName())); try { assertTrue(exists(created) && isDir(created) && isReadable(created)); @@ -107,31 +112,34 @@ public void testMkdir() throws IOException { } @Test - public void testMkdirInvalid() { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void mkdirInvalid() { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); String parent = DOESNT_EXIST + getCurrentTestName(); - assertThrows(String.format("Unexpected success in creating directory %s", parent), NoSuchFileException.class, - () -> fileHelper.createDirectory(fileSystem.getPath(parent))); + assertThrows(NoSuchFileException.class, + () -> fileHelper.createDirectory(fileSystem.getPath(parent)), + String.format("Unexpected success in creating directory %s", parent)); } /* rmdir */ @Test - public void testRmdir() throws IOException { + void rmdir() throws IOException { Path created = fileHelper.createDirectory(fileSystem.getPath(getCurrentTestName())); Path deleted = fileHelper.deleteDirectory(created); notExists(deleted); } - @Test(expected = NoSuchFileException.class) - public void testRmdirInvalid() throws IOException { - Path deleted = fileHelper.deleteDirectory(fileSystem.getPath(DOESNT_EXIST + getCurrentTestName())); - fail(String.format("Unexpected success in removing directory %s", deleted.toString())); + @Test + void rmdirInvalid() throws IOException { + assertThrows(NoSuchFileException.class, () -> { + Path deleted = fileHelper.deleteDirectory(fileSystem.getPath(DOESNT_EXIST + getCurrentTestName())); + fail(String.format("Unexpected success in removing directory %s", deleted.toString())); + }); } /* chdir */ @Test - public void testChdir() throws IOException { + void chdir() throws IOException { Path created = fileHelper.createDirectory(fileSystem.getPath(getCurrentTestName())); Path createdFile = fileHelper.createFile(created.resolve(getCurrentTestName())); try { @@ -142,7 +150,7 @@ public void testChdir() throws IOException { fileSystem.getPath(created.getFileName() + "/" + p.getFileName())); } } - assertTrue(createdFile + " found in ch directory", hasFile); + assertTrue(hasFile, createdFile + " found in ch directory"); } finally { Files.delete(createdFile); Files.delete(created); @@ -151,51 +159,56 @@ public void testChdir() throws IOException { /* write */ @Test - public void testWriteFile() throws IOException { + void writeFile() throws IOException { Path created = fileHelper.createFile(fileSystem.getPath(getCurrentTestName())); assertTrue(exists(created) && isReadable(created)); } @Test - public void testWriteFileInvalid() { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void writeFileInvalid() { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); String written = DOESNT_EXIST + getCurrentTestName(); - assertThrows(String.format("Unexpected success in writing file %s", written), NoSuchFileException.class, - () -> fileHelper.createFile(fileSystem.getPath(written))); + assertThrows(NoSuchFileException.class, + () -> fileHelper.createFile(fileSystem.getPath(written)), + String.format("Unexpected success in writing file %s", written)); } /* read */ @Test - public void testReadFile() throws IOException { + void readFile() throws IOException { Path created = fileHelper.createFile(fileSystem.getPath(getCurrentTestName())); isNonEmpty(fileHelper.readFile(created)); } - @Test(expected = NoSuchFileException.class) - public void testReadFileInvalid() throws IOException { - Path read = fileSystem.getPath(DOESNT_EXIST + getCurrentTestName()); - fileHelper.readFile(read); - fail(String.format("Unexpected success in reading file %s", read.toString())); + @Test + void readFileInvalid() throws IOException { + assertThrows(NoSuchFileException.class, () -> { + Path read = fileSystem.getPath(DOESNT_EXIST + getCurrentTestName()); + fileHelper.readFile(read); + fail(String.format("Unexpected success in reading file %s", read.toString())); + }); } /* rm */ @Test - public void testDeleteFile() throws IOException { + void deleteFile() throws IOException { Path created = fileHelper.createFile(fileSystem.getPath(getCurrentTestName())); Path deleted = fileHelper.deleteFile(created); notExists(deleted); } - @Test(expected = NoSuchFileException.class) - public void testDeleteFileInvalid() throws IOException { - Path deleted = fileHelper.deleteFile(fileSystem.getPath(DOESNT_EXIST + getCurrentTestName())); - fail(String.format("Unexpected success in deleting file %s", deleted.toString())); + @Test + void deleteFileInvalid() throws IOException { + assertThrows(NoSuchFileException.class, () -> { + Path deleted = fileHelper.deleteFile(fileSystem.getPath(DOESNT_EXIST + getCurrentTestName())); + fail(String.format("Unexpected success in deleting file %s", deleted.toString())); + }); } /* cp */ @Test - public void testCopyFile() throws IOException { + void copyFile() throws IOException { Path created = fileHelper.createFile(fileSystem.getPath(getCurrentTestName())); Path destination = fileSystem.getPath(getCurrentTestName() + "dest"); try { @@ -208,19 +221,19 @@ public void testCopyFile() throws IOException { } @Test - public void testCopyFileInvalid() throws IOException { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void copyFileInvalid() throws IOException { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); Path created = fileHelper.createFile(fileSystem.getPath(getCurrentTestName())); String copy = DOESNT_EXIST + getCurrentTestName(); - assertThrows(String.format("Unexpected success in copying file to %s", copy), - NoSuchFileException.class, - () -> fileHelper.copyFile(created, fileSystem.getPath(copy))); + assertThrows(NoSuchFileException.class, + () -> fileHelper.copyFile(created, fileSystem.getPath(copy)), + String.format("Unexpected success in copying file to %s", copy)); } /* mv */ @Test - public void testMoveFile() throws IOException { + void moveFile() throws IOException { Path created = fileHelper.createFile(fileSystem.getPath(getCurrentTestName())); Path destination = fileSystem.getPath(getCurrentTestName() + "dest"); fileHelper.moveFile(created, destination); @@ -228,18 +241,19 @@ public void testMoveFile() throws IOException { } @Test - public void testMoveFileInvalid() throws IOException { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void moveFileInvalid() throws IOException { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); Path created = fileHelper.createFile(fileSystem.getPath(getCurrentTestName())); String moved = DOESNT_EXIST + getCurrentTestName(); - assertThrows(String.format("Unexpected success in moving file to %s", moved), NoSuchFileException.class, - () -> fileHelper.moveFile(created, fileSystem.getPath(moved))); + assertThrows(NoSuchFileException.class, + () -> fileHelper.moveFile(created, fileSystem.getPath(moved)), + String.format("Unexpected success in moving file to %s", moved)); } /* link */ @Test - public void testCreateLink() throws IOException { + void createLink() throws IOException { Path existing = fileHelper.createFile(fileSystem.getPath(getCurrentTestName())); Path link = fileSystem.getPath(getCurrentTestName() + "link"); try { @@ -252,37 +266,37 @@ public void testCreateLink() throws IOException { } @Test - public void testJailbreakLink() { + void jailbreakLink() { testJailbreakLink("../"); } @Test - public void testJailbreakLink2() { + void jailbreakLink2() { testJailbreakLink("../test/"); } @Test - public void testJailbreakLink3() { + void jailbreakLink3() { testJailbreakLink("/.."); } @Test - public void testJailbreakLink4() { + void jailbreakLink4() { testJailbreakLink("/./.."); } @Test - public void testJailbreakLink5() { + void jailbreakLink5() { testJailbreakLink("/./../"); } @Test - public void testJailbreakLink6() { + void jailbreakLink6() { testJailbreakLink("./../"); } @Test - public void testJailbreakLink7() { + void jailbreakLink7() { String fileName = "/testdir/testdir2/../../.."; testJailbreakLink(fileName); } @@ -290,33 +304,34 @@ public void testJailbreakLink7() { private void testJailbreakLink(String jailbrokenTarget) { Path target = fileSystem.getPath(jailbrokenTarget); Path linkPath = fileSystem.getPath("/testLink"); - Assert.assertThrows(InvalidPathException.class, () -> fileSystem.provider().createSymbolicLink(linkPath, target)); - Assert.assertFalse(Files.exists(linkPath)); + assertThrows(InvalidPathException.class, () -> fileSystem.provider().createSymbolicLink(linkPath, target)); + assertFalse(Files.exists(linkPath)); } @Test - public void testCreateLinkInvalid() throws IOException { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void createLinkInvalid() throws IOException { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); Path existing = fileHelper.createFile(fileSystem.getPath(getCurrentTestName())); String link = DOESNT_EXIST + getCurrentTestName() + "link"; - assertThrows(String.format("Unexpected success in linking file %s", link), NoSuchFileException.class, - () -> fileHelper.createLink(fileSystem.getPath(link), existing)); + assertThrows(NoSuchFileException.class, + () -> fileHelper.createLink(fileSystem.getPath(link), existing), + String.format("Unexpected success in linking file %s", link)); } @Test - public void testNewByteChannelProviderMismatchException() throws IOException { + void newByteChannelProviderMismatchException() throws IOException { RootedFileSystemProvider provider = new RootedFileSystemProvider(); Path tempFolder = getTempTargetFolder(); Path file = Files.createTempFile(tempFolder, getCurrentTestName(), ".txt"); try (FileSystem fs = provider.newFileSystem(tempFolder, Collections.emptyMap()); Channel channel = provider.newByteChannel(fs.getPath(file.getFileName().toString()), Collections.emptySet())) { - assertTrue("Channel not open", channel.isOpen()); + assertTrue(channel.isOpen(), "Channel not open"); } } @Test - public void testResolveRoot() throws IOException { + void resolveRoot() throws IOException { Path root = GenericUtils.head(fileSystem.getRootDirectories()); Path dir = root.resolve("tsd"); fileHelper.createDirectory(dir); @@ -326,7 +341,7 @@ public void testResolveRoot() throws IOException { try (DirectoryStream ds = Files.newDirectoryStream(dir)) { f2 = ds.iterator().next(); } - assertTrue("Unrooted path found", f2 instanceof RootedPath); + assertTrue(f2 instanceof RootedPath, "Unrooted path found"); assertEquals(f1, f2); } finally { fileHelper.deleteFile(f1); @@ -335,37 +350,37 @@ public void testResolveRoot() throws IOException { } @Test - public void testBreakOutOfChroot1() throws IOException { + void breakOutOfChroot1() throws IOException { String fileName = "../" + getCurrentTestName(); testBreakOutOfChroot(fileName, fileName); } @Test - public void testBreakOutOfChroot2() throws IOException { + void breakOutOfChroot2() throws IOException { String fileName = "./../" + getCurrentTestName(); testBreakOutOfChroot(fileName, fileName); } @Test - public void testBreakOutOfChroot3() throws IOException { + void breakOutOfChroot3() throws IOException { String fileName = "/../" + getCurrentTestName(); testBreakOutOfChroot(fileName, fileName); } @Test - public void testBreakOutOfChroot4() throws IOException { + void breakOutOfChroot4() throws IOException { String fileName = "/.././" + getCurrentTestName(); testBreakOutOfChroot(fileName, fileName); } @Test - public void testBreakOutOfChroot5() throws IOException { + void breakOutOfChroot5() throws IOException { String fileName = "/./../" + getCurrentTestName(); testBreakOutOfChroot(fileName, fileName); } @Test - public void testBreakOutOfChroot6() throws IOException { + void breakOutOfChroot6() throws IOException { String fileName = "//../" + getCurrentTestName(); testBreakOutOfChroot(fileName, "/../" + getCurrentTestName()); } @@ -381,7 +396,7 @@ private void testBreakOutOfChroot(String fileName, String expected) throws IOExc RootedPath breakoutAttempt = fileSystem.getPath(fileName); // make sure that our rooted fs behaves like a proper unix fs - Assert.assertEquals(expected, breakoutAttempt.toString()); + assertEquals(expected, breakoutAttempt.toString()); Path expectedDir = fileSystem.getRoot().resolve(getCurrentTestName()); Path newDir = fileHelper.createDirectory(breakoutAttempt); @@ -408,36 +423,36 @@ private void testBreakOutOfChroot(String fileName, String expected) throws IOExc } @Test - public void testValidSymlink1() throws IOException { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void validSymlink1() throws IOException { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); String fileName = "/testdir/../"; testValidSymlink(fileName, true); } @Test - public void testValidSymlink2() throws IOException { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void validSymlink2() throws IOException { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); String fileName = "/testdir/testdir2/../"; testValidSymlink(fileName, true); } @Test - public void testValidSymlink3() throws IOException { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void validSymlink3() throws IOException { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); String fileName = "/testdir/../testdir3/"; testValidSymlink(fileName, true); } @Test - public void testValidSymlink4() throws IOException { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void validSymlink4() throws IOException { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); String fileName = "testdir/../testdir3/../"; testValidSymlink(fileName, true); } @Test - public void testValidSymlink5() throws IOException { - Assume.assumeFalse(SKIP_ON_WINDOWS, OsUtils.isWin32()); + void validSymlink5() throws IOException { + Assumptions.assumeFalse(OsUtils.isWin32(), SKIP_ON_WINDOWS); String fileName = "testdir/../testdir3/../testfile"; testValidSymlink(fileName, false); } @@ -451,13 +466,13 @@ public void testValidSymlink(String symlink, boolean targetIsDirectory) throws I toDelete.add(linkPath); // ensure that nothing processed the symlink. - Assert.assertEquals(Paths.get(symlink).toString(), + assertEquals(Paths.get(symlink).toString(), fileSystem.provider().readSymbolicLink(linkPath).toString()); - Assert.assertFalse(Files.exists(target)); - Assert.assertEquals(Files.exists(linkPath), Files.exists(target)); + assertFalse(Files.exists(target)); + assertEquals(Files.exists(linkPath), Files.exists(target)); // If we don't follow the link, we simply check that the link exists, which it does as we created it. - Assert.assertTrue(Files.exists(linkPath, LinkOption.NOFOLLOW_LINKS)); + assertTrue(Files.exists(linkPath, LinkOption.NOFOLLOW_LINKS)); createParentDirs(targetIsDirectory ? target : target.getParent(), toDelete); @@ -466,7 +481,7 @@ public void testValidSymlink(String symlink, boolean targetIsDirectory) throws I toDelete.add(target); } - Assert.assertTrue(Files.exists(linkPath)); + assertTrue(Files.exists(linkPath)); } finally { for (int i = toDelete.size() - 1; i >= 0; i--) { Path path = toDelete.get(i); @@ -491,7 +506,7 @@ private static void createParentDirs(Path target, List toDelete) throws IO } @Test - public void testFileNamedSlashOnUnixBasedOS() throws IOException { + void fileNamedSlashOnUnixBasedOS() throws IOException { // skip ths test on Win32 if (!"\\".equals(File.separator)) { Path slashFile = fileSystem.getPath("\\"); @@ -505,7 +520,7 @@ public void testFileNamedSlashOnUnixBasedOS() throws IOException { } @Test - public void testStreams() throws IOException { + void streams() throws IOException { byte[] data = "This is test data".getBytes(StandardCharsets.UTF_8); RootedPath testPath = fileSystem.getPath("testfile.txt"); try (OutputStream is = Files.newOutputStream(testPath)) { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java b/sshd-common/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java index da8383aff..37f54c6a5 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java @@ -34,16 +34,22 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") @SuppressWarnings("checkstyle:MethodCount") public class BasePathTest extends JUnitTestSupport { private TestFileSystem fileSystem; @@ -52,13 +58,13 @@ public BasePathTest() { super(); } - @Before - public void setUp() { + @BeforeEach + void setUp() { fileSystem = new TestFileSystem(Mockito.mock(FileSystemProvider.class)); } @Test - public void testBasicPathParsing() { + void basicPathParsing() { assertPathEquals("/", "/"); assertPathEquals("/foo", "/foo"); assertPathEquals("/foo", "/", "foo"); @@ -73,7 +79,7 @@ public void testBasicPathParsing() { } @Test - public void testPathParsingWithExtraSeparators() { + void pathParsingWithExtraSeparators() { assertPathEquals("/foo/bar", "///foo/bar"); assertPathEquals("/foo/bar", "/foo///bar//"); assertPathEquals("/foo/bar/baz", "/foo", "/bar", "baz/"); @@ -81,14 +87,14 @@ public void testPathParsingWithExtraSeparators() { } @Test - public void testRootPath() { + void rootPath() { new PathTester(fileSystem, "/") .root("/") .test("/"); } @Test - public void testRelativePathSingleName() { + void relativePathSingleName() { new PathTester(fileSystem, "test") .names("test") .test("test"); @@ -98,21 +104,21 @@ public void testRelativePathSingleName() { } @Test - public void testRelativePathTwoNames() { + void relativePathTwoNames() { new PathTester(fileSystem, "foo/bar") .names("foo", "bar") .test("foo/bar"); } @Test - public void testRelativePathFourNames() { + void relativePathFourNames() { new PathTester(fileSystem, "foo/bar/baz/test") .names("foo", "bar", "baz", "test") .test("foo/bar/baz/test"); } @Test - public void testAbsolutePathSingleName() { + void absolutePathSingleName() { new PathTester(fileSystem, "/foo") .root("/") .names("foo") @@ -120,7 +126,7 @@ public void testAbsolutePathSingleName() { } @Test - public void testAbsolutePathTwoNames() { + void absolutePathTwoNames() { new PathTester(fileSystem, "/foo/bar") .root("/") .names("foo", "bar") @@ -128,7 +134,7 @@ public void testAbsolutePathTwoNames() { } @Test - public void testAbsoluteMultiNamePathFourNames() { + void absoluteMultiNamePathFourNames() { new PathTester(fileSystem, "/foo/bar/baz/test") .root("/") .names("foo", "bar", "baz", "test") @@ -136,7 +142,7 @@ public void testAbsoluteMultiNamePathFourNames() { } @Test - public void testResolveFromRoot() { + void resolveFromRoot() { Path root = parsePath("/"); assertResolvedPathEquals("/foo", root, "foo"); assertResolvedPathEquals("/foo/bar", root, "foo/bar"); @@ -146,7 +152,7 @@ public void testResolveFromRoot() { } @Test - public void testResolveFromAbsolute() { + void resolveFromAbsolute() { Path path = parsePath("/foo"); assertResolvedPathEquals("/foo/bar", path, "bar"); assertResolvedPathEquals("/foo/bar/baz/test", path, "bar/baz/test"); @@ -155,7 +161,7 @@ public void testResolveFromAbsolute() { } @Test - public void testResolveFromRelative() { + void resolveFromRelative() { Path path = parsePath("foo"); assertResolvedPathEquals("foo/bar", path, "bar"); assertResolvedPathEquals("foo/bar/baz/test", path, "bar/baz/test"); @@ -164,7 +170,7 @@ public void testResolveFromRelative() { } @Test - public void testResolveWithThisAndParentDirNames() { + void resolveWithThisAndParentDirNames() { Path path = parsePath("/foo"); assertResolvedPathEquals("/foo/bar/../baz", path, "bar/../baz"); assertResolvedPathEquals("/foo/bar/../baz", path, "bar", "..", "baz"); @@ -173,24 +179,24 @@ public void testResolveWithThisAndParentDirNames() { } @Test - public void testResolveGivenAbsolutePath() { + void resolveGivenAbsolutePath() { assertResolvedPathEquals("/test", parsePath("/foo"), "/test"); assertResolvedPathEquals("/test", parsePath("foo"), "/test"); } @Test - public void testResolveGivenEmptyPath() { + void resolveGivenEmptyPath() { assertResolvedPathEquals("/foo", parsePath("/foo"), ""); assertResolvedPathEquals("foo", parsePath("foo"), ""); } @Test - public void testResolveAgainstEmptyPath() { + void resolveAgainstEmptyPath() { assertResolvedPathEquals("foo/bar", parsePath(""), "foo/bar"); } @Test - public void testResolveSiblingGivenEmptyPath() { + void resolveSiblingGivenEmptyPath() { Path path = parsePath("foo/bar"); Path resolved = path.resolveSibling(""); assertPathEquals("foo", resolved); @@ -201,7 +207,7 @@ public void testResolveSiblingGivenEmptyPath() { } @Test - public void testResolveSiblingAgainstEmptyPath() { + void resolveSiblingAgainstEmptyPath() { Path path = parsePath(""); Path resolved = path.resolveSibling("foo"); assertPathEquals("foo", resolved); @@ -212,24 +218,24 @@ public void testResolveSiblingAgainstEmptyPath() { } @Test - public void testRelativizeBothAbsolute() { + void relativizeBothAbsolute() { assertRelativizedPathEquals("b/c", parsePath("/a"), "/a/b/c"); assertRelativizedPathEquals("c/d", parsePath("/a/b"), "/a/b/c/d"); } @Test - public void testRelativizeBothRelative() { + void relativizeBothRelative() { assertRelativizedPathEquals("b/c", parsePath("a"), "a/b/c"); assertRelativizedPathEquals("d", parsePath("a/b/c"), "a/b/c/d"); } @Test - public void testRelativizeAgainstEmptyPath() { + void relativizeAgainstEmptyPath() { assertRelativizedPathEquals("foo/bar", parsePath(""), "foo/bar"); } @Test - public void testRelativizeOneAbsoluteOneRelative() { + void relativizeOneAbsoluteOneRelative() { try { Path result = parsePath("/foo/bar").relativize(parsePath("foo")); fail("Unexpected 2-level result: " + result); @@ -246,34 +252,34 @@ public void testRelativizeOneAbsoluteOneRelative() { } @Test - public void testNormalizeWithParentDirName() { + void normalizeWithParentDirName() { assertNormalizedPathEquals("/foo/baz", "/foo/bar/../baz"); assertNormalizedPathEquals("/foo/baz", "/foo", "bar", "..", "baz"); } @Test - public void testNormalizeWithThisDirName() { + void normalizeWithThisDirName() { assertNormalizedPathEquals("/foo/bar/baz", "/foo/bar/./baz"); assertNormalizedPathEquals("/foo/bar/baz", "/foo", "bar", ".", "baz"); } @Test - public void testNormalizeWithThisAndParentDirNames() { + void normalizeWithThisAndParentDirNames() { assertNormalizedPathEquals("foo/test", "foo/./bar/../././baz/../test"); } @Test - public void testNormalizeWithLeadingParentDirNames() { + void normalizeWithLeadingParentDirNames() { assertNormalizedPathEquals("../../foo/baz", "../../foo/bar/../baz"); } @Test - public void testNormalizeWithLeadingThisAndParentDirNames() { + void normalizeWithLeadingThisAndParentDirNames() { assertNormalizedPathEquals("../../foo/baz", "./.././.././foo/bar/../baz"); } @Test - public void testNormalizeWithExtraParentDirNamesAtRoot() { + void normalizeWithExtraParentDirNamesAtRoot() { assertNormalizedPathEquals("/", "/.."); assertNormalizedPathEquals("/", "/../../.."); assertNormalizedPathEquals("/", "/foo/../../.."); @@ -281,7 +287,7 @@ public void testNormalizeWithExtraParentDirNamesAtRoot() { } @Test - public void testPathWithExtraSlashes() { + void pathWithExtraSlashes() { assertPathEquals("/foo/bar/baz", parsePath("/foo/bar/baz/")); assertPathEquals("/foo/bar/baz", parsePath("/foo//bar///baz")); assertPathEquals("/foo/bar/baz", parsePath("///foo/bar/baz")); @@ -410,7 +416,7 @@ public void test(String first, String... more) { } public void test(Path path) { - assertEquals("Mismatched path value", string, path.toString()); + assertEquals(string, path.toString(), "Mismatched path value"); testRoot(path); testNames(path); @@ -422,23 +428,23 @@ public void test(Path path) { protected void testRoot(Path path) { if (root != null) { - assertTrue(path + ".isAbsolute() ?", path.isAbsolute()); - assertNotNull(path + ".getRoot() <> null ?", path.getRoot()); - assertEquals("Mismatched root path value", root, path.getRoot().toString()); + assertTrue(path.isAbsolute(), path + ".isAbsolute() ?"); + assertNotNull(path.getRoot(), path + ".getRoot() <> null ?"); + assertEquals(root, path.getRoot().toString(), "Mismatched root path value"); } else { - assertFalse(path + ".is(Not)Absolute() ?", path.isAbsolute()); - assertNull(path + ".getRoot() == null ?", path.getRoot()); + assertFalse(path.isAbsolute(), path + ".is(Not)Absolute() ?"); + assertNull(path.getRoot(), path + ".getRoot() == null ?"); } } protected void testNames(Path path) { - assertEquals("Mismatched names count", names.size(), path.getNameCount()); + assertEquals(names.size(), path.getNameCount(), "Mismatched names count"); assertListEquals("Mismatched path names", names, names(path)); for (int i = 0; i < names.size(); i++) { String nameAtIndex = names.get(i); Path pathAtIndex = path.getName(i); - assertEquals("Mismatched component name at index=" + i, nameAtIndex, pathAtIndex.toString()); + assertEquals(nameAtIndex, pathAtIndex.toString(), "Mismatched component name at index=" + i); // don't test individual names if this is an individual name if (names.size() > 1) { new PathTester(fileSystem, nameAtIndex) @@ -449,7 +455,7 @@ protected void testNames(Path path) { if (names.size() > 0) { String fileName = names.get(names.size() - 1); - assertEquals("Mismatched last component name", fileName, path.getFileName().toString()); + assertEquals(fileName, path.getFileName().toString(), "Mismatched last component name"); // don't test individual names if this is an individual name if (names.size() > 1) { new PathTester(fileSystem, fileName) @@ -462,7 +468,7 @@ protected void testNames(Path path) { protected void testParents(Path path) { Path parent = path.getParent(); if (((root != null) && (names.size() >= 1)) || (names.size() > 1)) { - assertNotNull("No parent", parent); + assertNotNull(parent, "No parent"); } if (parent != null) { @@ -506,8 +512,8 @@ protected void testStartsWith(Path path) { if ((root != null) || (!names.isEmpty())) { Path other = path; while (other != null) { - assertTrue(path + ".startsWith(" + other + ")[path] ?", path.startsWith(other)); - assertTrue(path + ".startsWith(" + other + ")[string] ?", path.startsWith(other.toString())); + assertTrue(path.startsWith(other), path + ".startsWith(" + other + ")[path] ?"); + assertTrue(path.startsWith(other.toString()), path + ".startsWith(" + other + ")[string] ?"); other = other.getParent(); } } @@ -518,8 +524,8 @@ protected void testEndsWith(Path path) { if ((root != null) || (!names.isEmpty())) { Path other = path; while (other != null) { - assertTrue(path + ".endsWith(" + other + ")[path] ?", path.endsWith(other)); - assertTrue(path + ".endsWith(" + other + ")[string] ?", path.endsWith(other.toString())); + assertTrue(path.endsWith(other), path + ".endsWith(" + other + ")[path] ?"); + assertTrue(path.endsWith(other.toString()), path + ".endsWith(" + other + ")[string] ?"); int otherNameCount = other.getNameCount(); if ((other.getRoot() != null) && (otherNameCount > 0)) { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/future/DefaultSshFutureTest.java b/sshd-common/src/test/java/org/apache/sshd/common/future/DefaultSshFutureTest.java index 05e3df2ff..67dfa0782 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/future/DefaultSshFutureTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/future/DefaultSshFutureTest.java @@ -22,18 +22,20 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class DefaultSshFutureTest extends JUnitTestSupport { public DefaultSshFutureTest() { super(); @@ -41,7 +43,7 @@ public DefaultSshFutureTest() { @Test @SuppressWarnings("rawtypes") - public void testAwaitUninterrupted() { + void awaitUninterrupted() { DefaultSshFuture future = new DefaultSshFuture(getCurrentTestName(), null); Object expected = new Object(); new Thread() { @@ -57,18 +59,18 @@ public void run() { }.start(); future.awaitUninterruptibly(); - assertSame("Mismatched signalled value", expected, future.getValue()); + assertSame(expected, future.getValue(), "Mismatched signalled value"); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) - public void testNotifyMultipleListeners() { + void notifyMultipleListeners() { DefaultSshFuture future = new DefaultSshFuture(getCurrentTestName(), null); AtomicInteger listenerCount = new AtomicInteger(0); Object expected = new Object(); SshFutureListener listener = f -> { - assertSame("Mismatched future instance", future, f); - assertSame("Mismatched value object", expected, future.getValue()); + assertSame(future, f, "Mismatched future instance"); + assertSame(expected, future.getValue(), "Mismatched value object"); listenerCount.incrementAndGet(); }; @@ -78,60 +80,60 @@ public void testNotifyMultipleListeners() { } future.setValue(expected); - assertEquals("Mismatched listeners invocation count", numListeners, listenerCount.get()); + assertEquals(numListeners, listenerCount.get(), "Mismatched listeners invocation count"); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) - public void testListenerInvokedDirectlyAfterResultSet() { + void listenerInvokedDirectlyAfterResultSet() { DefaultSshFuture future = new DefaultSshFuture(getCurrentTestName(), null); AtomicInteger listenerCount = new AtomicInteger(0); Object expected = new Object(); SshFutureListener listener = f -> { - assertSame("Mismatched future instance", future, f); - assertSame("Mismatched value object", expected, future.getValue()); + assertSame(future, f, "Mismatched future instance"); + assertSame(expected, future.getValue(), "Mismatched value object"); listenerCount.incrementAndGet(); }; future.setValue(expected); future.addListener(listener); - assertEquals("Mismatched number of registered listeners", 0, future.getNumRegisteredListeners()); - assertEquals("Listener not invoked", 1, listenerCount.get()); + assertEquals(0, future.getNumRegisteredListeners(), "Mismatched number of registered listeners"); + assertEquals(1, listenerCount.get(), "Listener not invoked"); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) - public void testAddAndRemoveRegisteredListenersBeforeResultSet() { + void addAndRemoveRegisteredListenersBeforeResultSet() { DefaultSshFuture future = new DefaultSshFuture(getCurrentTestName(), null); SshFutureListener listener = Mockito.mock(SshFutureListener.class); for (int index = 1; index <= Byte.SIZE; index++) { future.addListener(listener); - assertEquals("Mismatched number of added listeners", index, future.getNumRegisteredListeners()); + assertEquals(index, future.getNumRegisteredListeners(), "Mismatched number of added listeners"); } for (int index = future.getNumRegisteredListeners() - 1; index >= 0; index--) { future.removeListener(listener); - assertEquals("Mismatched number of remaining listeners", index, future.getNumRegisteredListeners()); + assertEquals(index, future.getNumRegisteredListeners(), "Mismatched number of remaining listeners"); } } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) - public void testListenerNotRemovedIfResultSet() { + void listenerNotRemovedIfResultSet() { DefaultSshFuture future = new DefaultSshFuture(getCurrentTestName(), null); AtomicInteger listenerCount = new AtomicInteger(0); Object expected = new Object(); SshFutureListener listener = f -> { - assertSame("Mismatched future instance", future, f); - assertSame("Mismatched value object", expected, future.getValue()); + assertSame(future, f, "Mismatched future instance"); + assertSame(expected, future.getValue(), "Mismatched value object"); listenerCount.incrementAndGet(); }; future.addListener(listener); future.setValue(expected); - assertEquals("Mismatched number of registered listeners", 1, future.getNumRegisteredListeners()); - assertEquals("Listener not invoked", 1, listenerCount.get()); + assertEquals(1, future.getNumRegisteredListeners(), "Mismatched number of registered listeners"); + assertEquals(1, listenerCount.get(), "Listener not invoked"); future.removeListener(listener); - assertEquals("Mismatched number of remaining listeners", 1, future.getNumRegisteredListeners()); + assertEquals(1, future.getNumRegisteredListeners(), "Mismatched number of remaining listeners"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java b/sshd-common/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java index 230777a26..3f261502f 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java @@ -27,62 +27,66 @@ import org.apache.sshd.common.kex.KexProposalOption.Constants; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class KexProposalOptionTest extends JUnitTestSupport { public KexProposalOptionTest() { super(); } @Test - public void testFromUnmatchedName() { + void fromUnmatchedName() { for (String n : new String[] { null, "", getCurrentTestName() }) { KexProposalOption o = KexProposalOption.fromName(n); - assertNull("Unexpected value for name='" + n + "'", o); + assertNull(o, "Unexpected value for name='" + n + "'"); } } @Test - public void testFromMatchedName() { + void fromMatchedName() { for (KexProposalOption expected : KexProposalOption.VALUES) { String n = expected.name(); for (int index = 0; index < n.length(); index++) { KexProposalOption actual = KexProposalOption.fromName(n); - assertSame("Mismatched option for name=" + n, expected, actual); + assertSame(expected, actual, "Mismatched option for name=" + n); n = shuffleCase(n); // prepare for next iteration } } } @Test - public void testFromUnmatchedProposalIndex() { + void fromUnmatchedProposalIndex() { for (int index : new int[] { -1, KexProposalOption.VALUES.size() }) { KexProposalOption o = KexProposalOption.fromProposalIndex(index); - assertNull("Unexpected value for index=" + index, o); + assertNull(o, "Unexpected value for index=" + index); } } @Test - public void testFromMatchedProposalIndex() { + void fromMatchedProposalIndex() { for (KexProposalOption expected : KexProposalOption.VALUES) { int index = expected.getProposalIndex(); KexProposalOption actual = KexProposalOption.fromProposalIndex(index); - assertSame("Mismatched values for index=" + index, expected, actual); + assertSame(expected, actual, "Mismatched values for index=" + index); } } @Test - public void testByProposalIndexSortOrder() { + void byProposalIndexSortOrder() { for (int index = 0; index < KexProposalOption.VALUES.size(); index++) { if (index < 1) { continue; @@ -93,12 +97,12 @@ public void testByProposalIndexSortOrder() { int i1 = o1.getProposalIndex(); int i2 = o2.getProposalIndex(); - assertTrue("Non increasing index for " + o1 + "[" + i1 + "] vs. " + o2 + "[" + i2 + "]", i1 < i2); + assertTrue(i1 < i2, "Non increasing index for " + o1 + "[" + i1 + "] vs. " + o2 + "[" + i2 + "]"); } } @Test - public void testAllConstantsCovered() throws Exception { + void allConstantsCovered() throws Exception { Field[] fields = Constants.class.getFields(); Collection options = EnumSet.allOf(KexProposalOption.class); @@ -115,10 +119,10 @@ public void testAllConstantsCovered() throws Exception { int index = f.getInt(null); KexProposalOption o = KexProposalOption.fromProposalIndex(index); - assertNotNull("No matching option for index=" + index, o); - assertTrue("Option not in known options: " + o, options.remove(o)); + assertNotNull(o, "No matching option for index=" + index); + assertTrue(options.remove(o), "Option not in known options: " + o); } - assertTrue("Not all options covered: " + options, GenericUtils.isEmpty(options)); + assertTrue(GenericUtils.isEmpty(options), "Not all options covered: " + options); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/KeyIdentityProviderResolutionTest.java b/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/KeyIdentityProviderResolutionTest.java index 71286f310..d7d9842f0 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/KeyIdentityProviderResolutionTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/KeyIdentityProviderResolutionTest.java @@ -22,40 +22,35 @@ import java.util.ArrayList; import java.util.List; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class KeyIdentityProviderResolutionTest extends JUnitTestSupport { - private final KeyIdentityProvider p1; - private final KeyIdentityProvider p2; - private final KeyIdentityProvider expected; + private KeyIdentityProvider p1; + private KeyIdentityProvider p2; + private KeyIdentityProvider expected; - public KeyIdentityProviderResolutionTest(KeyIdentityProvider p1, KeyIdentityProvider p2, KeyIdentityProvider expected) { + public void initKeyIdentityProviderResolutionTest( + KeyIdentityProvider p1, KeyIdentityProvider p2, KeyIdentityProvider expected) { this.p1 = p1; this.p2 = p2; this.expected = expected; } - @Parameters(name = "p1={0}, p2={1}, expected={2}") public static List parameters() { return new ArrayList() { // Not serializing it @@ -84,8 +79,10 @@ private KeyIdentityProvider createKeyIdentityProvider(String name) { }; } - @Test - public void testResolveKeyIdentityProvider() { + @MethodSource("parameters") + @ParameterizedTest(name = "p1={0}, p2={1}, expected={2}") + public void resolveKeyIdentityProvider(KeyIdentityProvider p1, KeyIdentityProvider p2, KeyIdentityProvider expected) { + initKeyIdentityProviderResolutionTest(p1, p2, expected); assertSame(expected, KeyIdentityProvider.resolveKeyIdentityProvider(p1, p2)); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/KeyPairProviderTest.java b/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/KeyPairProviderTest.java index 18d534b58..b17846f16 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/KeyPairProviderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/KeyPairProviderTest.java @@ -31,36 +31,39 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class KeyPairProviderTest extends JUnitTestSupport { public KeyPairProviderTest() { super(); } @Test - public void testEmptyKeyProvider() throws IOException, GeneralSecurityException { + void emptyKeyProvider() throws IOException, GeneralSecurityException { KeyPairProvider provider = KeyPairProvider.EMPTY_KEYPAIR_PROVIDER; - assertTrue("Non empty loaded keys", GenericUtils.isEmpty(provider.loadKeys(null))); - assertTrue("Non empty key type", GenericUtils.isEmpty(provider.getKeyTypes(null))); + assertTrue(GenericUtils.isEmpty(provider.loadKeys(null)), "Non empty loaded keys"); + assertTrue(GenericUtils.isEmpty(provider.getKeyTypes(null)), "Non empty key type"); for (String keyType : new String[] { null, "", getCurrentTestName() }) { - assertNull("Unexpected key-pair loaded for type='" + keyType + "'", provider.loadKey(null, keyType)); + assertNull(provider.loadKey(null, keyType), "Unexpected key-pair loaded for type='" + keyType + "'"); } } @Test - public void testMapToKeyPairProvider() throws IOException, GeneralSecurityException { + void mapToKeyPairProvider() throws IOException, GeneralSecurityException { PublicKey pubKey = Mockito.mock(PublicKey.class); PrivateKey prvKey = Mockito.mock(PrivateKey.class); String[] testKeys = { getCurrentTestName(), getClass().getSimpleName() }; @@ -78,7 +81,7 @@ public void testMapToKeyPairProvider() throws IOException, GeneralSecurityExcept String keyType = pe.getKey(); KeyPair expected = pe.getValue(); KeyPair actual = provider.loadKey(null, keyType); - assertSame(keyType, expected, actual); + assertSame(expected, actual, keyType); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProviderTest.java b/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProviderTest.java index c8bb07157..079bf0025 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProviderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/keyprovider/MultiKeyIdentityProviderTest.java @@ -32,24 +32,30 @@ import org.apache.sshd.common.session.SessionContext; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class MultiKeyIdentityProviderTest extends JUnitTestSupport { public MultiKeyIdentityProviderTest() { super(); } - @Test // see SSHD-860 - public void testLazyKeyIdentityMultiProvider() throws IOException, GeneralSecurityException { + // see SSHD-860 + @Test + void lazyKeyIdentityMultiProvider() throws IOException, GeneralSecurityException { List expected = new ArrayList<>(); for (int index = 1; index <= Short.SIZE; index++) { PublicKey pub = Mockito.mock(PublicKey.class); @@ -73,13 +79,13 @@ public void testLazyKeyIdentityMultiProvider() throws IOException, GeneralSecuri Iterator iter = keys.iterator(); for (int index = 0, count = expected.size(); index < count; index++) { KeyPair kpExpected = expected.get(index); - assertTrue("Premature keys exhaustion after " + index + " iterations", iter.hasNext()); + assertTrue(iter.hasNext(), "Premature keys exhaustion after " + index + " iterations"); KeyPair kpActual = iter.next(); - assertSame("Mismatched key at index=" + index, kpExpected, kpActual); - assertEquals("Mismatched requested lazy key position", index + 1, position.get()); + assertSame(kpExpected, kpActual, "Mismatched key at index=" + index); + assertEquals(index + 1, position.get(), "Mismatched requested lazy key position"); } - assertFalse("Not all keys exhausted", iter.hasNext()); + assertFalse(iter.hasNext(), "Not all keys exhausted"); } private static KeyIdentityProvider wrapKeyPairs(AtomicInteger position, Iterable keys) { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/mac/BuiltinMacsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/mac/BuiltinMacsTest.java index f56785eda..b00c3b791 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/mac/BuiltinMacsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/mac/BuiltinMacsTest.java @@ -32,48 +32,54 @@ import org.apache.sshd.common.mac.BuiltinMacs.ParseResult; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class BuiltinMacsTest extends JUnitTestSupport { public BuiltinMacsTest() { super(); } @Test - public void testFromName() { + void fromName() { for (BuiltinMacs expected : BuiltinMacs.VALUES) { String name = expected.getName(); BuiltinMacs actual = BuiltinMacs.fromFactoryName(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testAllConstantsCovered() throws Exception { + void allConstantsCovered() throws Exception { Set avail = EnumSet.noneOf(BuiltinMacs.class); Field[] fields = BuiltinMacs.Constants.class.getFields(); for (Field f : fields) { String name = (String) f.get(null); BuiltinMacs value = BuiltinMacs.fromFactoryName(name); - assertNotNull("No match found for " + name, value); - assertTrue(name + " re-specified", avail.add(value)); + assertNotNull(value, "No match found for " + name); + assertTrue(avail.add(value), name + " re-specified"); } assertEquals("Incomplete coverage", BuiltinMacs.VALUES, avail); } @Test - public void testParseMacsList() { + void parseMacsList() { List builtin = NamedResource.getNameList(BuiltinMacs.VALUES); List unknown = Arrays.asList(getClass().getPackage().getName(), getClass().getSimpleName(), getCurrentTestName()); @@ -110,52 +116,54 @@ public void testParseMacsList() { } @Test - public void testResolveFactoryOnBuiltinValues() { + void resolveFactoryOnBuiltinValues() { for (MacFactory expected : BuiltinMacs.VALUES) { String name = expected.getName(); MacFactory actual = BuiltinMacs.resolveFactory(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testNotAllowedToRegisterBuiltinFactories() { - BuiltinMacs.VALUES.forEach(expected -> assertThrows("Unexpected success for " + expected.getName(), - IllegalArgumentException.class, () -> BuiltinMacs.registerExtension(expected))); + void notAllowedToRegisterBuiltinFactories() { + BuiltinMacs.VALUES.forEach(expected -> assertThrows(IllegalArgumentException.class, + () -> BuiltinMacs.registerExtension(expected), "Unexpected success for " + expected.getName())); } - @Test(expected = IllegalArgumentException.class) - public void testNotAllowedToOverrideRegisteredFactories() { - MacFactory expected = Mockito.mock(MacFactory.class); - Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); + @Test + void notAllowedToOverrideRegisteredFactories() { + assertThrows(IllegalArgumentException.class, () -> { + MacFactory expected = Mockito.mock(MacFactory.class); + Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); - String name = expected.getName(); - try { - for (int index = 1; index <= Byte.SIZE; index++) { - BuiltinMacs.registerExtension(expected); - assertEquals("Unexpected success at attempt #" + index, 1, index); + String name = expected.getName(); + try { + for (int index = 1; index <= Byte.SIZE; index++) { + BuiltinMacs.registerExtension(expected); + assertEquals(1, index, "Unexpected success at attempt #" + index); + } + } finally { + BuiltinMacs.unregisterExtension(name); } - } finally { - BuiltinMacs.unregisterExtension(name); - } + }); } @Test - public void testResolveFactoryOnRegisteredExtension() { + void resolveFactoryOnRegisteredExtension() { MacFactory expected = Mockito.mock(MacFactory.class); Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); String name = expected.getName(); try { - assertNull("Extension already registered", BuiltinMacs.resolveFactory(name)); + assertNull(BuiltinMacs.resolveFactory(name), "Extension already registered"); BuiltinMacs.registerExtension(expected); MacFactory actual = BuiltinMacs.resolveFactory(name); - assertSame("Mismatched resolved instance", expected, actual); + assertSame(expected, actual, "Mismatched resolved instance"); } finally { MacFactory actual = BuiltinMacs.unregisterExtension(name); - assertSame("Mismatched unregistered instance", expected, actual); - assertNull("Extension not un-registered", BuiltinMacs.resolveFactory(name)); + assertSame(expected, actual, "Mismatched unregistered instance"); + assertNull(BuiltinMacs.resolveFactory(name), "Extension not un-registered"); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/mac/MacVectorsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/mac/MacVectorsTest.java index b52e334b7..6a794a6e4 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/mac/MacVectorsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/mac/MacVectorsTest.java @@ -33,38 +33,32 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.ValidateUtils; import org.apache.sshd.common.util.buffer.BufferUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; /** * @see RFC 4321 * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class MacVectorsTest extends JUnitTestSupport { - private final VectorSeed seed; - private final Factory macFactory; - private final byte[] expected; + private VectorSeed seed; + private Factory macFactory; + private byte[] expected; - public MacVectorsTest(VectorSeed seed, String factoryName, String expected) { + public void initMacVectorsTest(VectorSeed seed, String factoryName, String expected) { this.seed = Objects.requireNonNull(seed, "No seed"); this.macFactory = ValidateUtils.checkNotNull(BuiltinMacs.fromFactoryName(factoryName), "Unknown MAC: %s", factoryName); this.expected = BufferUtils.decodeHex(BufferUtils.EMPTY_HEX_SEPARATOR, expected); } - @Parameters(name = "factory={1}, expected={2}, seed={0}") @SuppressWarnings("checkstyle:MethodLength") public static Collection parameters() { List ret = new ArrayList<>(); @@ -255,16 +249,18 @@ public static Collection parameters() { return ret; } - @Test - public void testStandardVectorMac() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "factory={1}, expected={2}, seed={0}") + public void standardVectorMac(VectorSeed seed, String factoryName, String expected) throws Exception { + initMacVectorsTest(seed, factoryName, expected); Mac mac = macFactory.create(); mac.init(seed.getKey()); mac.update(seed.getData()); byte[] actual = new byte[mac.getBlockSize()]; mac.doFinal(actual); - assertArrayEquals("Mismatched results for actual=" + BufferUtils.toHex(BufferUtils.EMPTY_HEX_SEPARATOR, actual), - expected, actual); + assertArrayEquals(this.expected, actual, + "Mismatched results for actual=" + BufferUtils.toHex(BufferUtils.EMPTY_HEX_SEPARATOR, actual)); } private static class VectorSeed { @@ -337,7 +333,8 @@ private static class VectorTestData extends VectorSeed { this.results = results; } - VectorTestData(String key, boolean useKeyString, String data, boolean useDataString, + VectorTestData( + String key, boolean useKeyString, String data, boolean useDataString, Collection> results) { super(key, useKeyString, data, useDataString); this.results = results; diff --git a/sshd-common/src/test/java/org/apache/sshd/common/random/RandomFactoryTest.java b/sshd-common/src/test/java/org/apache/sshd/common/random/RandomFactoryTest.java index 3f5e541af..d6a077823 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/random/RandomFactoryTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/random/RandomFactoryTest.java @@ -23,34 +23,26 @@ import java.util.concurrent.TimeUnit; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class RandomFactoryTest extends JUnitTestSupport { - private final RandomFactory factory; + private RandomFactory factory; - public RandomFactoryTest(RandomFactory factory) { + public void initRandomFactoryTest(RandomFactory factory) { this.factory = factory; } - @Parameters(name = "type={0}") public static Collection parameters() { Collection testCases = new LinkedList<>(); testCases.add(JceRandomFactory.INSTANCE); @@ -63,9 +55,11 @@ public static Collection parameters() { return parameterize(testCases); } - @Test - public void testRandomFactory() { - Assume.assumeTrue("Skip unsupported factory: " + factory.getName(), factory.isSupported()); + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}") + public void randomFactory(RandomFactory factory) { + initRandomFactoryTest(factory); + Assumptions.assumeTrue(factory.isSupported(), "Skip unsupported factory: " + factory.getName()); long t = testRandom(factory.create()); System.out.println(factory.getName() + " duration: " + t + " " + TimeUnit.MICROSECONDS); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/signature/BuiltinSignaturesTest.java b/sshd-common/src/test/java/org/apache/sshd/common/signature/BuiltinSignaturesTest.java index 6fd1b4884..36d9ebcd3 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/signature/BuiltinSignaturesTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/signature/BuiltinSignaturesTest.java @@ -29,34 +29,38 @@ import org.apache.sshd.common.signature.BuiltinSignatures.ParseResult; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class BuiltinSignaturesTest extends JUnitTestSupport { public BuiltinSignaturesTest() { super(); } @Test - public void testFromName() { + void fromName() { for (BuiltinSignatures expected : BuiltinSignatures.VALUES) { String name = expected.getName(); BuiltinSignatures actual = BuiltinSignatures.fromFactoryName(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testParseSignaturesList() { + void parseSignaturesList() { List builtin = NamedResource.getNameList(BuiltinSignatures.VALUES); List unknown = Arrays.asList(getClass().getPackage().getName(), getClass().getSimpleName(), getCurrentTestName()); @@ -93,52 +97,54 @@ public void testParseSignaturesList() { } @Test - public void testResolveFactoryOnBuiltinValues() { + void resolveFactoryOnBuiltinValues() { for (SignatureFactory expected : BuiltinSignatures.VALUES) { String name = expected.getName(); SignatureFactory actual = BuiltinSignatures.resolveFactory(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testNotAllowedToRegisterBuiltinFactories() { - BuiltinSignatures.VALUES.forEach(expected -> assertThrows("Unexpected success for " + expected.getName(), - IllegalArgumentException.class, () -> BuiltinSignatures.registerExtension(expected))); + void notAllowedToRegisterBuiltinFactories() { + BuiltinSignatures.VALUES.forEach(expected -> assertThrows(IllegalArgumentException.class, + () -> BuiltinSignatures.registerExtension(expected), "Unexpected success for " + expected.getName())); } - @Test(expected = IllegalArgumentException.class) - public void testNotAllowedToOverrideRegisteredFactories() { - SignatureFactory expected = Mockito.mock(SignatureFactory.class); - Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); + @Test + void notAllowedToOverrideRegisteredFactories() { + assertThrows(IllegalArgumentException.class, () -> { + SignatureFactory expected = Mockito.mock(SignatureFactory.class); + Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); - String name = expected.getName(); - try { - for (int index = 1; index <= Byte.SIZE; index++) { - BuiltinSignatures.registerExtension(expected); - assertEquals("Unexpected success at attempt #" + index, 1, index); + String name = expected.getName(); + try { + for (int index = 1; index <= Byte.SIZE; index++) { + BuiltinSignatures.registerExtension(expected); + assertEquals(1, index, "Unexpected success at attempt #" + index); + } + } finally { + BuiltinSignatures.unregisterExtension(name); } - } finally { - BuiltinSignatures.unregisterExtension(name); - } + }); } @Test - public void testResolveFactoryOnRegisteredExtension() { + void resolveFactoryOnRegisteredExtension() { SignatureFactory expected = Mockito.mock(SignatureFactory.class); Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); String name = expected.getName(); try { - assertNull("Extension already registered", BuiltinSignatures.resolveFactory(name)); + assertNull(BuiltinSignatures.resolveFactory(name), "Extension already registered"); BuiltinSignatures.registerExtension(expected); SignatureFactory actual = BuiltinSignatures.resolveFactory(name); - assertSame("Mismatched resolved instance", expected, actual); + assertSame(expected, actual, "Mismatched resolved instance"); } finally { SignatureFactory actual = BuiltinSignatures.unregisterExtension(name); - assertSame("Mismatched unregistered instance", expected, actual); - assertNull("Extension not un-registered", BuiltinSignatures.resolveFactory(name)); + assertSame(expected, actual, "Mismatched unregistered instance"); + assertNull(BuiltinSignatures.resolveFactory(name), "Extension not un-registered"); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/signature/RSASignatureVariantsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/signature/RSASignatureVariantsTest.java index 50d0066d6..15893fe3b 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/signature/RSASignatureVariantsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/signature/RSASignatureVariantsTest.java @@ -20,48 +20,34 @@ package org.apache.sshd.common.signature; import java.security.KeyPair; -import java.util.Arrays; -import java.util.List; import org.apache.sshd.common.config.keys.KeyUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; /** * NOTE: some tests are inherited from parent * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class RSASignatureVariantsTest extends SignatureVariantTestSupport { private static KeyPair kp; - public RSASignatureVariantsTest(SignatureFactory factory) { - super(factory, kp); + @ParameterizedTest + @EnumSource(value = BuiltinSignatures.class, names = { "rsa", "rsaSHA256", "rsaSHA512" }) + public void initRSASignatureVariantsTest(SignatureFactory factory) throws Exception { + signature(factory, kp); } - @BeforeClass - public static void initializeSigningKeyPair() throws Exception { + @BeforeAll + static void initializeSigningKeyPair() throws Exception { kp = initializeSigningKeyPair(KeyUtils.RSA_ALGORITHM); } - @Parameters(name = "{0}") - public static List parameters() { - return parameterize( - Arrays.asList( - BuiltinSignatures.rsa, - BuiltinSignatures.rsaSHA256, - BuiltinSignatures.rsaSHA512)); - } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureDSATest.java b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureDSATest.java index f5b1f4881..2eff33306 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureDSATest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureDSATest.java @@ -28,24 +28,25 @@ import org.apache.sshd.common.session.SessionContext; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SignatureDSATest extends JUnitTestSupport { public SignatureDSATest() { super(); } @Test - public void testTooShortSignature() throws Exception { + void tooShortSignature() throws Exception { KeyFactory kf = SecurityUtils.getKeyFactory(KeyUtils.DSS_ALGORITHM); SignatureDSA signatureDSA = new SignatureDSA(KeyUtils.DSS_ALGORITHM) { @Override diff --git a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureRSASHA1Test.java b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureRSASHA1Test.java index 7bb3a1586..f64a21dc2 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureRSASHA1Test.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureRSASHA1Test.java @@ -33,18 +33,23 @@ import org.apache.sshd.common.session.SessionContext; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SignatureRSASHA1Test extends JUnitTestSupport { private static final Base64.Decoder B64_DECODER = Base64.getDecoder(); @SuppressWarnings("checkstyle:linelength") @@ -59,8 +64,8 @@ public SignatureRSASHA1Test() { super(); } - @BeforeClass - public static void initializeTestKey() throws GeneralSecurityException { + @BeforeAll + static void initializeTestKey() throws GeneralSecurityException { byte[] exp = B64_DECODER.decode("Iw=="); @SuppressWarnings("checkstyle:linelength") byte[] mod = B64_DECODER.decode( @@ -69,8 +74,9 @@ public static void initializeTestKey() throws GeneralSecurityException { testKey = kf.generatePublic(new RSAPublicKeySpec(new BigInteger(mod), new BigInteger(exp))); } - @Test // see SSHD-642 - public void testLeadingZeroesBC() throws Throwable { + // see SSHD-642 + @Test + void leadingZeroesBC() throws Throwable { testLeadingZeroes(new Factory() { @Override public SignatureRSA create() { @@ -79,12 +85,12 @@ public SignatureRSA create() { protected java.security.Signature doInitSignature( SessionContext session, String algo, Key key, boolean forSigning) throws GeneralSecurityException { - assertFalse("Signature not initialized for verification", forSigning); + assertFalse(forSigning, "Signature not initialized for verification"); java.security.Signature signature = super.doInitSignature(session, algo, key, forSigning); if (SecurityUtils.isBouncyCastleRegistered()) { Provider provider = signature.getProvider(); String name = provider.getName(); - assertEquals("Mismatched BC provider name", SecurityUtils.BOUNCY_CASTLE, name); + assertEquals(SecurityUtils.BOUNCY_CASTLE, name, "Mismatched BC provider name"); } return signature; } @@ -93,18 +99,19 @@ protected java.security.Signature doInitSignature( }); } - @Test // see SSHD-642 - public void testLeadingZeroesJCE() throws Throwable { + // see SSHD-642 + @Test + void leadingZeroesJCE() throws Throwable { testLeadingZeroes(() -> new SignatureRSASHA1() { @Override protected java.security.Signature doInitSignature( SessionContext session, String algo, Key key, boolean forSigning) throws GeneralSecurityException { - assertFalse("Signature not initialized for verification", forSigning); + assertFalse(forSigning, "Signature not initialized for verification"); java.security.Signature signature = java.security.Signature.getInstance(algo); Provider provider = signature.getProvider(); String name = provider.getName(); - assertNotEquals("BC provider used although not required", SecurityUtils.BOUNCY_CASTLE, name); + assertNotEquals(SecurityUtils.BOUNCY_CASTLE, name, "BC provider used although not required"); return signature; } }); @@ -115,16 +122,16 @@ private void testLeadingZeroes(Factory factory) throws E rsa.initVerifier(null, testKey); int vSize = rsa.getVerifierSignatureSize(); - assertTrue("Verifier signature size not initialized", vSize > 0); + assertTrue(vSize > 0, "Verifier signature size not initialized"); // make sure padding is required Map.Entry encoding = rsa.extractEncodedSignature( TEST_SIGNATURE, SignatureRSA.SUPPORTED_KEY_TYPES); - assertNotNull("Signature is not encoded", encoding); + assertNotNull(encoding, "Signature is not encoded"); byte[] data = encoding.getValue(); - assertTrue("Signature data size (" + data.length + ") not below verifier size (" + vSize + ")", data.length < vSize); + assertTrue(data.length < vSize, "Signature data size (" + data.length + ") not below verifier size (" + vSize + ")"); rsa.update(null, TEST_MSG); - assertTrue("Failed to verify", rsa.verify(null, TEST_SIGNATURE)); + assertTrue(rsa.verify(null, TEST_SIGNATURE), "Failed to verify"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureSkECDSATest.java b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureSkECDSATest.java index f465b4069..85832dece 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureSkECDSATest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureSkECDSATest.java @@ -23,17 +23,18 @@ import org.apache.sshd.common.config.keys.AuthorizedKeyEntry; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SignatureSkECDSATest extends JUnitTestSupport { @SuppressWarnings("checkstyle:linelength") @@ -59,22 +60,22 @@ public SignatureSkECDSATest() { } @Test - public void testValidSignatureWithTouch() throws Exception { + void validSignatureWithTouch() throws Exception { testSignature(AUTHORIZED_KEY_ENTRY, MSG1, SIG_FOR_MSG1_WITH_TOUCH, true); } @Test - public void testValidSignatureWithNoTouch() throws Exception { + void validSignatureWithNoTouch() throws Exception { testSignature("no-touch-required " + AUTHORIZED_KEY_ENTRY, MSG2, SIG_FOR_MSG2_WITH_NO_TOUCH, true); } @Test - public void testValidSignatureWithMissingTouch() throws Exception { + void validSignatureWithMissingTouch() throws Exception { testSignature(AUTHORIZED_KEY_ENTRY, MSG2, SIG_FOR_MSG2_WITH_NO_TOUCH, false); } @Test - public void testInvalidSignatureWithTouch() throws Exception { + void invalidSignatureWithTouch() throws Exception { testSignature(AUTHORIZED_KEY_ENTRY, MSG2, SIG_FOR_MSG1_WITH_TOUCH, false); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureSkED25519Test.java b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureSkED25519Test.java index 1b1d5c8e1..2e71fd470 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureSkED25519Test.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureSkED25519Test.java @@ -23,17 +23,18 @@ import org.apache.sshd.common.config.keys.AuthorizedKeyEntry; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SignatureSkED25519Test extends JUnitTestSupport { @SuppressWarnings("checkstyle:linelength") @@ -59,22 +60,22 @@ public SignatureSkED25519Test() { } @Test - public void testValidSignatureWithTouch() throws Exception { + void validSignatureWithTouch() throws Exception { testSignature(AUTHORIZED_KEY_ENTRY, MSG1, SIG_FOR_MSG1_WITH_TOUCH, true); } @Test - public void testValidSignatureWithNoTouch() throws Exception { + void validSignatureWithNoTouch() throws Exception { testSignature("no-touch-required " + AUTHORIZED_KEY_ENTRY, MSG2, SIG_FOR_MSG2_WITH_NO_TOUCH, true); } @Test - public void testValidSignatureWithMissingTouch() throws Exception { + void validSignatureWithMissingTouch() throws Exception { testSignature(AUTHORIZED_KEY_ENTRY, MSG2, SIG_FOR_MSG2_WITH_NO_TOUCH, false); } @Test - public void testInvalidSignatureWithTouch() throws Exception { + void invalidSignatureWithTouch() throws Exception { testSignature(AUTHORIZED_KEY_ENTRY, MSG2, SIG_FOR_MSG1_WITH_TOUCH, false); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureVariantTestSupport.java b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureVariantTestSupport.java index 6707bfa82..aff16e405 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureVariantTestSupport.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignatureVariantTestSupport.java @@ -25,34 +25,26 @@ import java.nio.charset.StandardCharsets; import java.security.GeneralSecurityException; import java.security.KeyPair; -import java.util.Objects; import org.apache.sshd.client.config.keys.ClientIdentity; import org.apache.sshd.common.NamedResource; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.Assume; -import org.junit.Test; +import org.junit.jupiter.api.Assumptions; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Apache MINA SSHD Project */ public abstract class SignatureVariantTestSupport extends JUnitTestSupport { - protected final SignatureFactory factory; - protected final KeyPair kp; - - protected SignatureVariantTestSupport(SignatureFactory factory, KeyPair kp) { - this.factory = Objects.requireNonNull(factory, "No factory provided"); - this.kp = Objects.requireNonNull(kp, "No key pair provided"); - Assume.assumeTrue("Unsupported factory: " + factory, factory.isSupported()); - } protected static KeyPair initializeSigningKeyPair(String algorithm) throws IOException, GeneralSecurityException { String resourceKey = ClientIdentity.getIdentityFileName(algorithm); URL urlKeyPair = SignatureVariantTestSupport.class.getResource(resourceKey); - assertNotNull("Missing key-pair resource: " + resourceKey, urlKeyPair); + assertNotNull(urlKeyPair, "Missing key-pair resource: " + resourceKey); try (InputStream stream = urlKeyPair.openStream()) { Iterable ids = SecurityUtils.loadKeyPairIdentities( null, NamedResource.ofName(resourceKey), stream, null); @@ -60,8 +52,9 @@ protected static KeyPair initializeSigningKeyPair(String algorithm) } } - @Test - public void testSignature() throws Exception { + public void signature(SignatureFactory factory, KeyPair kp) throws Exception { + Assumptions.assumeTrue(factory.isSupported(), "Unsupported factory: " + factory); + byte[] data = (getClass().getName() + "#" + getCurrentTestName()) .getBytes(StandardCharsets.UTF_8); Signature signer = factory.create(); @@ -75,8 +68,4 @@ public void testSignature() throws Exception { verifier.verify(null, signature); } - @Override - public String toString() { - return getClass().getSimpleName() + "[" + factory + "]"; - } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignaturesDevelopment.java b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignaturesDevelopment.java index 20a7122e6..a741144ca 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/signature/SignaturesDevelopment.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/signature/SignaturesDevelopment.java @@ -27,14 +27,14 @@ import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.common.util.security.eddsa.EdDSASecurityProviderUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.Ignore; +import org.junit.jupiter.api.Disabled; /** * A "scratch-pad" class for testing signatures related code during development * * @author Apache MINA SSHD Project */ -@Ignore("Used only for development") +@Disabled("Used only for development") public class SignaturesDevelopment extends JUnitTestSupport { public SignaturesDevelopment() { super(); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/EventListenerUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/EventListenerUtilsTest.java index 2da97dd82..6b7e285a6 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/EventListenerUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/EventListenerUtilsTest.java @@ -27,24 +27,28 @@ import java.util.Set; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class EventListenerUtilsTest extends JUnitTestSupport { public EventListenerUtilsTest() { super(); } @Test - public void testProxyWrapper() { + void proxyWrapper() { List impls = new ArrayList<>(); for (int index = 0; index < Byte.SIZE; index++) { impls.add(new ProxyListenerImpl()); @@ -58,53 +62,53 @@ public void testProxyWrapper() { for (int index = 0; index < impls.size(); index++) { ProxyListenerImpl l = impls.get(index); - assertSame("Mismatched string at listener #" + index, expStr, l.getStringValue()); - assertSame("Mismatched number at listener #" + index, expNum, l.getNumberValue()); + assertSame(expStr, l.getStringValue(), "Mismatched string at listener #" + index); + assertSame(expNum, l.getNumberValue(), "Mismatched number at listener #" + index); } } @Test - public void testListenerInstanceComparatorOnProxy() { + void listenerInstanceComparatorOnProxy() { Comparator comparator = EventListenerUtils.LISTENER_INSTANCE_COMPARATOR; ProxyListener p1 = EventListenerUtils.proxyWrapper(ProxyListener.class, Collections.singletonList(new ProxyListenerImpl())); - assertEquals("Mismatched self reference comparison", 0, comparator.compare(p1, p1)); + assertEquals(0, comparator.compare(p1, p1), "Mismatched self reference comparison"); EventListener l = new EventListener() { /* nothing extra */ }; - assertEquals("Mismatched proxy vs. non-proxy result", 1, Integer.signum(comparator.compare(p1, l))); - assertEquals("Mismatched non-proxy vs. proxy result", -1, Integer.signum(comparator.compare(l, p1))); + assertEquals(1, Integer.signum(comparator.compare(p1, l)), "Mismatched proxy vs. non-proxy result"); + assertEquals(-1, Integer.signum(comparator.compare(l, p1)), "Mismatched non-proxy vs. proxy result"); ProxyListener p2 = EventListenerUtils.proxyWrapper(ProxyListener.class, Collections.singletonList(new ProxyListenerImpl())); int p1vsp2 = Integer.signum(comparator.compare(p1, p2)); - assertNotEquals("Mismatched p1 vs. p2 comparison", 0, p1vsp2); - assertEquals("Mismatched p2 vs. p1 comparison result", 0 - p1vsp2, Integer.signum(comparator.compare(p2, p1))); + assertNotEquals(0, p1vsp2, "Mismatched p1 vs. p2 comparison"); + assertEquals(0 - p1vsp2, Integer.signum(comparator.compare(p2, p1)), "Mismatched p2 vs. p1 comparison result"); } @Test - public void testListenerInstanceComparatorOnNonProxy() { + void listenerInstanceComparatorOnNonProxy() { Comparator comparator = EventListenerUtils.LISTENER_INSTANCE_COMPARATOR; EventListener l1 = new EventListener() { /* nothing extra */ }; - assertEquals("Mismatched self reference comparison", 0, comparator.compare(l1, l1)); + assertEquals(0, comparator.compare(l1, l1), "Mismatched self reference comparison"); EventListener l2 = new EventListener() { /* nothing extra */ }; int l1vsl2 = Integer.signum(comparator.compare(l1, l2)); - assertNotEquals("Mismatched l1 vs. l2 comparison result", 0, l1vsl2); - assertEquals("Mismatched l2 vs. l1 comparison result", 0 - l1vsl2, Integer.signum(comparator.compare(l2, l1))); + assertNotEquals(0, l1vsl2, "Mismatched l1 vs. l2 comparison result"); + assertEquals(0 - l1vsl2, Integer.signum(comparator.compare(l2, l1)), "Mismatched l2 vs. l1 comparison result"); } @Test - public void testSynchronizedListenersSetOnProxies() { + void synchronizedListenersSetOnProxies() { ProxyListener p1 = EventListenerUtils.proxyWrapper(ProxyListener.class, Collections.singletonList(new ProxyListenerImpl())); Set s = EventListenerUtils.synchronizedListenersSet(); for (int index = 1; index <= Byte.SIZE; index++) { boolean modified = s.add(p1); assertEquals("Mismatched p1 modification indicator at attempt #" + index, index == 1, modified); - assertEquals("Mismatched p1 set size at attempt #" + index, 1, s.size()); + assertEquals(1, s.size(), "Mismatched p1 set size at attempt #" + index); } ProxyListener p2 @@ -112,13 +116,13 @@ public void testSynchronizedListenersSetOnProxies() { for (int index = 1; index <= Byte.SIZE; index++) { boolean modified = s.add(p2); assertEquals("Mismatched p2 modification indicator at attempt #" + index, index == 1, modified); - assertEquals("Mismatched p2 set size at attempt #" + index, 2, s.size()); + assertEquals(2, s.size(), "Mismatched p2 set size at attempt #" + index); } - assertTrue("Failed to remove p1", s.remove(p1)); - assertEquals("Mismatched post p1-remove size", 1, s.size()); - assertTrue("Failed to remove p2", s.remove(p2)); - assertEquals("Mismatched post p2-remove size", 0, s.size()); + assertTrue(s.remove(p1), "Failed to remove p1"); + assertEquals(1, s.size(), "Mismatched post p1-remove size"); + assertTrue(s.remove(p2), "Failed to remove p2"); + assertEquals(0, s.size(), "Mismatched post p2-remove size"); } interface ProxyListener extends SshdEventListener { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/ExceptionUtilsAndroidPeelTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/ExceptionUtilsAndroidPeelTest.java index 28c3efb6a..d76ef5f13 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/ExceptionUtilsAndroidPeelTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/ExceptionUtilsAndroidPeelTest.java @@ -25,39 +25,35 @@ import javax.management.ReflectionException; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class ExceptionUtilsAndroidPeelTest extends JUnitTestSupport { - private final boolean androidMode; + private boolean androidMode; - public ExceptionUtilsAndroidPeelTest(boolean androidMode) { + public void initExceptionUtilsAndroidPeelTest(boolean androidMode) { this.androidMode = androidMode; } - @Parameters(name = "android={0}") public static List parameters() { return Stream.of(Boolean.TRUE, Boolean.FALSE).map(v -> new Object[] { v }).collect(Collectors.toList()); } - @Test - public void testPeelJavaxManagementException() { + @MethodSource("parameters") + @ParameterizedTest(name = "android={0}") + public void peelJavaxManagementException(boolean androidMode) { + initExceptionUtilsAndroidPeelTest(androidMode); try { OsUtils.setAndroid(androidMode); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/GenericUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/GenericUtilsTest.java index acceb344c..b4db71236 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/GenericUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/GenericUtilsTest.java @@ -25,24 +25,29 @@ import java.util.NoSuchElementException; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category(NoIoTestCase.class) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") +@SuppressWarnings("checksyle:MethodCount") public class GenericUtilsTest extends JUnitTestSupport { - public GenericUtilsTest() { - super(); - } @Test - public void testIsBlank() { + void isBlank() { assertTrue(GenericUtils.isBlank(null)); assertTrue(GenericUtils.isBlank("")); assertTrue(GenericUtils.isBlank(" ")); @@ -51,7 +56,7 @@ public void testIsBlank() { } @Test - public void testFilterToNotBlank() { + void filterToNotBlank() { assertEquals(Collections.emptyList(), GenericUtils.filterToNotBlank(Arrays.asList((String) null))); assertEquals(Collections.emptyList(), GenericUtils.filterToNotBlank(Arrays.asList(""))); assertEquals(Collections.emptyList(), GenericUtils.filterToNotBlank(Arrays.asList(" "))); @@ -68,7 +73,7 @@ public void testFilterToNotBlank() { } @Test - public void testSplitAndJoin() { + void splitAndJoin() { List expected = Collections.unmodifiableList( Arrays.asList( getClass().getPackage().getName().replace('.', '/'), @@ -80,8 +85,9 @@ public void testSplitAndJoin() { String sep = String.valueOf(ch); String s = GenericUtils.join(expected, sep); String[] actual = GenericUtils.split(s, ch); - assertEquals("Mismatched split length for separator=" + sep, expected.size(), - GenericUtils.length((Object[]) actual)); + assertEquals(expected.size(), + GenericUtils.length((Object[]) actual), + "Mismatched split length for separator=" + sep); for (int index = 0; index < actual.length; index++) { String e = expected.get(index); @@ -94,9 +100,9 @@ public void testSplitAndJoin() { } @Test - public void testStripQuotes() { + void stripQuotes() { String expected = getCurrentTestName(); - assertSame("Unexpected un-quoted stripping", expected, GenericUtils.stripQuotes(expected)); + assertSame(expected, GenericUtils.stripQuotes(expected), "Unexpected un-quoted stripping"); StringBuilder sb = new StringBuilder(2 + expected.length()).append('|').append(expected).append('|'); for (int index = 0; index < GenericUtils.QUOTES.length(); index++) { @@ -105,12 +111,12 @@ public void testStripQuotes() { sb.setCharAt(sb.length() - 1, delim); CharSequence actual = GenericUtils.stripQuotes(sb); - assertEquals("Mismatched result for delim (" + delim + ")", expected, actual.toString()); + assertEquals(expected, actual.toString(), "Mismatched result for delim (" + delim + ")"); } } @Test - public void testStripOnlyFirstLayerQuotes() { + void stripOnlyFirstLayerQuotes() { StringBuilder sb = new StringBuilder().append("||").append(getCurrentTestName()).append("||"); char[] delims = { '\'', '"', '"', '\'' }; for (int index = 0; index < delims.length; index += 2) { @@ -123,24 +129,25 @@ public void testStripOnlyFirstLayerQuotes() { CharSequence expected = sb.subSequence(1, sb.length() - 1); CharSequence actual = GenericUtils.stripQuotes(sb); - assertEquals("Mismatched result for delim (" + topDelim + "/" + innerDelim + ")", expected.toString(), - actual.toString()); + assertEquals(expected.toString(), + actual.toString(), + "Mismatched result for delim (" + topDelim + "/" + innerDelim + ")"); } } @Test - public void testStripDelimiters() { + void stripDelimiters() { String expected = getCurrentTestName(); final char delim = '|'; - assertSame("Unexpected un-delimited stripping", expected, GenericUtils.stripDelimiters(expected, delim)); + assertSame(expected, GenericUtils.stripDelimiters(expected, delim), "Unexpected un-delimited stripping"); CharSequence actual = GenericUtils.stripDelimiters( new StringBuilder(2 + expected.length()).append(delim).append(expected).append(delim), delim); - assertEquals("Mismatched stripped values", expected, actual.toString()); + assertEquals(expected, actual.toString(), "Mismatched stripped values"); } @Test - public void testStripDelimitersOnlyIfOnBothEnds() { + void stripDelimitersOnlyIfOnBothEnds() { final char delim = '$'; StringBuilder expected = new StringBuilder().append(delim).append(getCurrentTestName()).append(delim); for (int index : new int[] { 0, expected.length() - 1 }) { @@ -150,22 +157,23 @@ public void testStripDelimitersOnlyIfOnBothEnds() { // trash one end expected.setCharAt(index, (char) (delim + 1)); - assertSame("Mismatched result for delim at index=" + index, expected, - GenericUtils.stripDelimiters(expected, delim)); + assertSame(expected, + GenericUtils.stripDelimiters(expected, delim), + "Mismatched result for delim at index=" + index); } } @Test - public void testAccumulateExceptionOnNullValues() { - assertNull("Unexpected null/null result", ExceptionUtils.accumulateException(null, null)); + void accumulateExceptionOnNullValues() { + assertNull(ExceptionUtils.accumulateException(null, null), "Unexpected null/null result"); Throwable expected = new NoSuchMethodException(getClass().getName() + "#" + getCurrentTestName()); - assertSame("Mismatched null/extra result", expected, ExceptionUtils.accumulateException(null, expected)); - assertSame("Mismatched current/null result", expected, ExceptionUtils.accumulateException(expected, null)); + assertSame(expected, ExceptionUtils.accumulateException(null, expected), "Mismatched null/extra result"); + assertSame(expected, ExceptionUtils.accumulateException(expected, null), "Mismatched current/null result"); } @Test - public void testAccumulateExceptionOnExistingCurrent() { + void accumulateExceptionOnExistingCurrent() { RuntimeException[] expected = new RuntimeException[] { new IllegalArgumentException(getCurrentTestName()), new ClassCastException(getClass().getName()), @@ -174,33 +182,34 @@ public void testAccumulateExceptionOnExistingCurrent() { RuntimeException current = new UnsupportedOperationException("top"); for (RuntimeException extra : expected) { RuntimeException actual = ExceptionUtils.accumulateException(current, extra); - assertSame("Mismatched returned actual exception", current, actual); + assertSame(current, actual, "Mismatched returned actual exception"); } Throwable[] actual = current.getSuppressed(); - assertArrayEquals("Suppressed", expected, actual); + assertArrayEquals(expected, actual, "Suppressed"); } @Test - public void testNullOrEmptyCharArrayComparison() { + void nullOrEmptyCharArrayComparison() { char[][] values = new char[][] { null, GenericUtils.EMPTY_CHAR_ARRAY }; for (char[] c1 : values) { for (char[] c2 : values) { - assertEquals(((c1 == null) ? "null" : "empty") + " vs. " + ((c2 == null) ? "null" : "empty"), 0, - GenericUtils.compare(c1, c2)); + assertEquals(0, + GenericUtils.compare(c1, c2), + ((c1 == null) ? "null" : "empty") + " vs. " + ((c2 == null) ? "null" : "empty")); } } } @Test - public void testCharArrayComparison() { + void charArrayComparison() { String s1 = getClass().getSimpleName(); char[] c1 = s1.toCharArray(); - assertEquals("Same value equality", 0, GenericUtils.compare(c1, s1.toCharArray())); + assertEquals(0, GenericUtils.compare(c1, s1.toCharArray()), "Same value equality"); String s2 = getCurrentTestName(); char[] c2 = s2.toCharArray(); - assertEquals("s1 vs. s2", Integer.signum(s1.compareTo(s2)), Integer.signum(GenericUtils.compare(c1, c2))); - assertEquals("s2 vs. s1", Integer.signum(s2.compareTo(s1)), Integer.signum(GenericUtils.compare(c2, c1))); + assertEquals(Integer.signum(s1.compareTo(s2)), Integer.signum(GenericUtils.compare(c1, c2)), "s1 vs. s2"); + assertEquals(Integer.signum(s2.compareTo(s1)), Integer.signum(GenericUtils.compare(c2, c1)), "s2 vs. s1"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/Int2IntFunctionTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/Int2IntFunctionTest.java index b6238e0b9..86dac6bb3 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/Int2IntFunctionTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/Int2IntFunctionTest.java @@ -24,24 +24,27 @@ import org.apache.sshd.common.util.functors.Int2IntFunction; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class Int2IntFunctionTest extends JUnitTestSupport { public Int2IntFunctionTest() { super(); } @Test - public void testAdd() { + void add() { int factor = Byte.SIZE; IntUnaryOperator func = Int2IntFunction.add(factor); for (int index = 1, sum = 0; index <= Byte.SIZE; index++) { @@ -51,7 +54,7 @@ public void testAdd() { } @Test - public void testAddIdentity() { + void addIdentity() { IntUnaryOperator func = Int2IntFunction.add(0); Random rnd = new Random(System.nanoTime()); for (int index = 1; index <= Byte.SIZE; index++) { @@ -62,7 +65,7 @@ public void testAddIdentity() { } @Test - public void testSub() { + void sub() { int factor = Byte.SIZE; IntUnaryOperator func = Int2IntFunction.sub(factor); for (int index = 1, sum = 0; index <= Byte.SIZE; index++) { @@ -72,7 +75,7 @@ public void testSub() { } @Test - public void testSubIdentity() { + void subIdentity() { IntUnaryOperator func = Int2IntFunction.sub(0); Random rnd = new Random(System.nanoTime()); for (int index = 1; index <= Byte.SIZE; index++) { @@ -83,7 +86,7 @@ public void testSubIdentity() { } @Test - public void testMul() { + void mul() { int factor = 2; IntUnaryOperator func = Int2IntFunction.mul(factor); for (int index = 1, mul = 1, expected = factor; index <= Byte.SIZE; index++, expected *= factor) { @@ -93,7 +96,7 @@ public void testMul() { } @Test - public void testMulIdentity() { + void mulIdentity() { IntUnaryOperator func = Int2IntFunction.mul(1); Random rnd = new Random(System.nanoTime()); for (int index = 1; index <= Byte.SIZE; index++) { @@ -104,30 +107,30 @@ public void testMulIdentity() { } @Test - public void testMulZero() { + void mulZero() { IntUnaryOperator func = Int2IntFunction.mul(0); Random rnd = new Random(System.nanoTime()); for (int index = 1; index <= Byte.SIZE; index++) { int value = rnd.nextInt(); int actual = func.applyAsInt(value); - assertEquals(Integer.toString(value), 0, actual); + assertEquals(0, actual, Integer.toString(value)); } } @Test - public void testConstant() { + void constant() { int expected = 377347; IntUnaryOperator func = Int2IntFunction.constant(expected); Random rnd = new Random(System.nanoTime()); for (int index = 1; index <= Byte.SIZE; index++) { int value = rnd.nextInt(); int actual = func.applyAsInt(value); - assertEquals(Integer.toString(value), expected, actual); + assertEquals(expected, actual, Integer.toString(value)); } } @Test - public void testDiv() { + void div() { int factor = 2; IntUnaryOperator func = Int2IntFunction.div(factor); for (int index = 1, quot = 65536, expected = quot / factor; index <= Byte.SIZE; index++, expected /= factor) { @@ -137,7 +140,7 @@ public void testDiv() { } @Test - public void testDivIdentity() { + void divIdentity() { IntUnaryOperator func = Int2IntFunction.div(1); Random rnd = new Random(System.nanoTime()); for (int index = 1; index <= Byte.SIZE; index++) { @@ -147,9 +150,11 @@ public void testDivIdentity() { } } - @Test(expected = IllegalArgumentException.class) - public void testDivZeroFactor() { - IntUnaryOperator func = Int2IntFunction.div(0); - fail("Unexpected success: " + func); + @Test + void divZeroFactor() { + assertThrows(IllegalArgumentException.class, () -> { + IntUnaryOperator func = Int2IntFunction.div(0); + fail("Unexpected success: " + func); + }); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/NumberUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/NumberUtilsTest.java index 1ac93d425..0d3731af7 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/NumberUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/NumberUtilsTest.java @@ -20,75 +20,80 @@ package org.apache.sshd.common.util; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class NumberUtilsTest extends JUnitTestSupport { public NumberUtilsTest() { super(); } @Test - public void testIntNextPowerOf2() { + void intNextPowerOf2() { int expected = 1; for (int index = 0; index < Integer.SIZE; expected <<= 1, index++) { if (expected > 2) { - assertEquals("Mismatched lower bound value", expected, NumberUtils.getNextPowerOf2(expected - 1)); + assertEquals(expected, NumberUtils.getNextPowerOf2(expected - 1), "Mismatched lower bound value"); } if (expected > 0) { // avoid the negative value - assertEquals("Mismatched exact value", expected, NumberUtils.getNextPowerOf2(expected)); + assertEquals(expected, NumberUtils.getNextPowerOf2(expected), "Mismatched exact value"); } } } @Test - public void testIntNextPowerOf2Overflow() { + void intNextPowerOf2Overflow() { int expected = Integer.MAX_VALUE - Byte.SIZE; int actual = NumberUtils.getNextPowerOf2(expected); assertEquals(expected, actual); } @Test - public void testToInteger() { - assertNull("Unexpected null value", NumberUtils.toInteger(null)); + void toInteger() { + assertNull(NumberUtils.toInteger(null), "Unexpected null value"); for (Number n : new Number[] { Byte.valueOf(Byte.MAX_VALUE), Short.valueOf(Short.MIN_VALUE), Integer.valueOf(Short.MAX_VALUE), Long.valueOf(82007160L) }) { Integer i = NumberUtils.toInteger(n); if (n instanceof Integer) { - assertSame("Unexpected conversion", n, i); + assertSame(n, i, "Unexpected conversion"); } else { - assertEquals("Mismatched values", n.intValue(), i.intValue()); + assertEquals(n.intValue(), i.intValue(), "Mismatched values"); } } } @Test - public void testIsValidIntegerNumber() { + void isValidIntegerNumber() { for (String s : new String[] { "7", "73", "736", "7365", "19650307" }) { - assertTrue(s, NumberUtils.isIntegerNumber(s)); + assertTrue(NumberUtils.isIntegerNumber(s), s); String pos = "+" + s; - assertTrue(pos, NumberUtils.isIntegerNumber(pos)); + assertTrue(NumberUtils.isIntegerNumber(pos), pos); String neg = "-" + s; - assertTrue(neg, NumberUtils.isIntegerNumber(neg)); + assertTrue(NumberUtils.isIntegerNumber(neg), neg); } } @Test - public void testIsInvalidIntegerNumber() { + void isInvalidIntegerNumber() { for (String s : new String[] { null, "", " ", getCurrentTestName(), "3rd", "3.14", "-.3" }) { - assertFalse(s, NumberUtils.isIntegerNumber(s)); + assertFalse(NumberUtils.isIntegerNumber(s), s); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/OsUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/OsUtilsTest.java index 76073b42f..2b7ff03c9 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/OsUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/OsUtilsTest.java @@ -22,24 +22,26 @@ import java.util.Objects; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class OsUtilsTest extends JUnitTestSupport { public OsUtilsTest() { super(); } @Test - public void testSetOsTypeByProperty() { + void setOsTypeByProperty() { try { for (String osType : new String[] { "Some-Windows", "Some-Linux" }) { OsUtils.setOS(null); // force re-detection @@ -59,7 +61,7 @@ public void testSetOsTypeByProperty() { } @Test - public void testSetOsTypeProgrammatically() { + void setOsTypeProgrammatically() { try { OsUtils.setOS("windows 10"); assertEquals("Mismatched detection value", false, OsUtils.isOSX()); @@ -84,7 +86,7 @@ public void testSetOsTypeProgrammatically() { } @Test - public void testSetCurrentUserByProperty() { + void setCurrentUserByProperty() { try { for (String expected : new String[] { getClass().getSimpleName(), getCurrentTestName() }) { OsUtils.setCurrentUser(null); // force re-detection @@ -92,7 +94,7 @@ public void testSetCurrentUserByProperty() { try { System.setProperty(OsUtils.CURRENT_USER_OVERRIDE_PROP, expected); String actual = OsUtils.getCurrentUser(); - assertEquals("Mismatched reported current user", expected, actual); + assertEquals(expected, actual, "Mismatched reported current user"); } finally { System.clearProperty(OsUtils.CURRENT_USER_OVERRIDE_PROP); } @@ -103,11 +105,11 @@ public void testSetCurrentUserByProperty() { } @Test - public void testSetCurrentUserProgrammatically() { + void setCurrentUserProgrammatically() { try { for (String expected : new String[] { getClass().getSimpleName(), getCurrentTestName() }) { OsUtils.setCurrentUser(expected); // force value - assertEquals("Mismatched detection value", expected, OsUtils.getCurrentUser()); + assertEquals(expected, OsUtils.getCurrentUser(), "Mismatched detection value"); } } finally { OsUtils.setCurrentUser(null); // force re-detection @@ -115,7 +117,7 @@ public void testSetCurrentUserProgrammatically() { } @Test - public void testSetJavaVersionByProperty() { + void setJavaVersionByProperty() { try { for (String value : new String[] { "7.3.6_5", "37.77.34_7-" + getCurrentTestName() }) { OsUtils.setJavaVersion(null); // force re-detection @@ -124,7 +126,7 @@ public void testSetJavaVersionByProperty() { System.setProperty(OsUtils.JAVA_VERSION_OVERRIDE_PROP, value); String expected = value.replace('_', '.'); String actual = Objects.toString(OsUtils.getJavaVersion(), null); - assertTrue("Mismatched reported version value: " + actual, expected.startsWith(actual)); + assertTrue(expected.startsWith(actual), "Mismatched reported version value: " + actual); } finally { System.clearProperty(OsUtils.JAVA_VERSION_OVERRIDE_PROP); } @@ -135,11 +137,11 @@ public void testSetJavaVersionByProperty() { } @Test - public void testSetJavaVersionProgrammatically() { + void setJavaVersionProgrammatically() { try { for (VersionInfo expected : new VersionInfo[] { VersionInfo.parse("7.3.6.5"), VersionInfo.parse("37.77.34.7") }) { OsUtils.setJavaVersion(expected); // force value - assertEquals("Mismatched detection value", expected, OsUtils.getJavaVersion()); + assertEquals(expected, OsUtils.getJavaVersion(), "Mismatched detection value"); } } finally { OsUtils.setJavaVersion(null); // force re-detection diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/PathsConcatentionTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/PathsConcatentionTest.java index bf8fd585d..76ffc3906 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/PathsConcatentionTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/PathsConcatentionTest.java @@ -22,37 +22,31 @@ import java.util.ArrayList; import java.util.List; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class PathsConcatentionTest extends JUnitTestSupport { - private final String p1; - private final String p2; - private final String expected; + private String p1; + private String p2; + private String expected; - public PathsConcatentionTest(String p1, String p2, String expected) { + public void initPathsConcatentionTest(String p1, String p2, String expected) { this.p1 = p1; this.p2 = p2; this.expected = expected; } - @Parameters(name = "p1={0}, p2={1}, expected={2}") public static List parameters() { return new ArrayList() { // not serializing it @@ -80,8 +74,10 @@ private void addTestCase(String p1, String p2, String expected) { }; } - @Test - public void testConcatPaths() { + @MethodSource("parameters") + @ParameterizedTest(name = "p1={0}, p2={1}, expected={2}") + public void concatPaths(String p1, String p2, String expected) { + initPathsConcatentionTest(p1, p2, expected); assertEquals(expected, SelectorUtils.concatPaths(p1, p2, '/')); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/SelectorUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/SelectorUtilsTest.java index 128924e61..cccd25d3b 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/SelectorUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/SelectorUtilsTest.java @@ -22,30 +22,32 @@ import java.util.Random; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SelectorUtilsTest extends JUnitTestSupport { public SelectorUtilsTest() { super(); } @Test - public void testApplyLinuxSeparatorSlashifyRules() { + void applyLinuxSeparatorSlashifyRules() { testApplySlashifyRules('/'); } @Test - public void testApplyWindowsSeparatorSlashifyRules() { + void applyWindowsSeparatorSlashifyRules() { testApplySlashifyRules('\\'); } @@ -57,7 +59,7 @@ private void testApplySlashifyRules(char slash) { Character.toString(slash) + getClass().getSimpleName() + Character.toString(slash) + getCurrentTestName() }) { String actual = SelectorUtils.applySlashifyRules(expected, slash); - assertSame("Mismatched results for '" + expected + "'", expected, actual); + assertSame(expected, actual, "Mismatched results for '" + expected + "'"); } String[] comps = { getClass().getSimpleName(), getCurrentTestName() }; @@ -101,7 +103,7 @@ private void testApplySlashifyRules(char slash) { String expected = sb.toString(); String actual = SelectorUtils.applySlashifyRules(path, slash); - assertEquals("Mismatched results for path=" + path, expected, actual); + assertEquals(expected, actual, "Mismatched results for path=" + path); } } @@ -115,41 +117,41 @@ private static int slashify(StringBuilder sb, Random rnd, char slash) { } @Test - public void testTranslateToFileSystemPath() { + void translateToFileSystemPath() { String path = getClass().getPackage().getName().replace('.', File.separatorChar) + File.separator + getClass().getSimpleName() + File.separator + getCurrentTestName(); for (String expected : new String[] { null, "", path }) { String actual = SelectorUtils.translateToFileSystemPath(expected, File.separator, File.separator); - assertSame("Mismatched instance for translated result", expected, actual); + assertSame(expected, actual, "Mismatched instance for translated result"); } for (String fsSeparator : new String[] { String.valueOf('.'), "##" }) { String expected = path.replace(File.separator, fsSeparator); String actual = SelectorUtils.translateToFileSystemPath(path, File.separator, fsSeparator); - assertEquals("Mismatched translation result for separator='" + fsSeparator + "'", expected, actual); + assertEquals(expected, actual, "Mismatched translation result for separator='" + fsSeparator + "'"); actual = SelectorUtils.translateToFileSystemPath(actual, fsSeparator, File.separator); - assertEquals("Mismatched translation revert for separator='" + fsSeparator + "'", path, actual); + assertEquals(path, actual, "Mismatched translation revert for separator='" + fsSeparator + "'"); } } @Test - public void testAbsoluteWindowsPathTranslation() { - Assume.assumeTrue("Windows-specific test skipped", OsUtils.isWin32()); + void absoluteWindowsPathTranslation() { + Assumptions.assumeTrue(OsUtils.isWin32(), "Windows-specific test skipped"); String expected = detectTargetFolder().toString(); for (String prefix : new String[] { "", "/" }) { String actual = SelectorUtils.translateToLocalPath(prefix + expected.replace('/', File.separatorChar)); - assertEquals("Mismatched result for prefix='" + prefix + "'", expected, actual); + assertEquals(expected, actual, "Mismatched result for prefix='" + prefix + "'"); } } @Test - public void testConcatPathsOneEmptyOrNull() { + void concatPathsOneEmptyOrNull() { String path = getCurrentTestName(); - assertSame("Null 1st", path, SelectorUtils.concatPaths(null, path, File.separatorChar)); - assertSame("Empty 1st", path, SelectorUtils.concatPaths("", path, File.separatorChar)); - assertSame("Null 2nd", path, SelectorUtils.concatPaths(path, null, File.separatorChar)); - assertSame("Empty 2nd", path, SelectorUtils.concatPaths(path, "", File.separatorChar)); + assertSame(path, SelectorUtils.concatPaths(null, path, File.separatorChar), "Null 1st"); + assertSame(path, SelectorUtils.concatPaths("", path, File.separatorChar), "Empty 1st"); + assertSame(path, SelectorUtils.concatPaths(path, null, File.separatorChar), "Null 2nd"); + assertSame(path, SelectorUtils.concatPaths(path, "", File.separatorChar), "Empty 2nd"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/ThreadUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/ThreadUtilsTest.java index 4fc810c6a..c6ad50483 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/ThreadUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/ThreadUtilsTest.java @@ -24,45 +24,50 @@ import org.apache.sshd.common.util.threads.CloseableExecutorService; import org.apache.sshd.common.util.threads.ThreadUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ThreadUtilsTest extends JUnitTestSupport { public ThreadUtilsTest() { super(); } @Test - public void testProtectExecutorServiceShutdown() { + void protectExecutorServiceShutdown() { for (boolean shutdownOnExit : new boolean[] { true, false }) { - assertNull("Unexpected instance for shutdown=" + shutdownOnExit, - ThreadUtils.protectExecutorServiceShutdown(null, shutdownOnExit)); + assertNull(ThreadUtils.protectExecutorServiceShutdown(null, shutdownOnExit), + "Unexpected instance for shutdown=" + shutdownOnExit); } CloseableExecutorService service = ThreadUtils.newSingleThreadExecutor("pool"); try { - assertSame("Unexpected wrapped instance", service, ThreadUtils.protectExecutorServiceShutdown(service, true)); + assertSame(service, ThreadUtils.protectExecutorServiceShutdown(service, true), "Unexpected wrapped instance"); CloseableExecutorService wrapped = ThreadUtils.protectExecutorServiceShutdown(service, false); try { - assertNotSame("No wrapping occurred", service, wrapped); + assertNotSame(service, wrapped, "No wrapping occurred"); wrapped.shutdown(); - assertTrue("Wrapped service not shutdown", wrapped.isShutdown()); - assertFalse("Protected service is shutdown", service.isShutdown()); + assertTrue(wrapped.isShutdown(), "Wrapped service not shutdown"); + assertFalse(service.isShutdown(), "Protected service is shutdown"); Collection running = wrapped.shutdownNow(); - assertTrue("Non-empty runners list", running.isEmpty()); - assertTrue("Wrapped service not shutdownNow", wrapped.isShutdown()); - assertFalse("Protected service is shutdownNow", service.isShutdown()); + assertTrue(running.isEmpty(), "Non-empty runners list"); + assertTrue(wrapped.isShutdown(), "Wrapped service not shutdownNow"); + assertFalse(service.isShutdown(), "Protected service is shutdownNow"); } finally { wrapped.shutdownNow(); // just in case } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/ValidateUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/ValidateUtilsTest.java index 9efd5f919..d38cc52c8 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/ValidateUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/ValidateUtilsTest.java @@ -20,25 +20,28 @@ package org.apache.sshd.common.util; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category(NoIoTestCase.class) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ValidateUtilsTest extends JUnitTestSupport { public ValidateUtilsTest() { super(); } - @Test(expected = IllegalArgumentException.class) - public void checkNotNull() { - ValidateUtils.checkNotNull(getClass(), getCurrentTestName()); - ValidateUtils.checkNotNull(null, getCurrentTestName()); + @Test + void checkNotNull() { + assertThrows(IllegalArgumentException.class, () -> { + ValidateUtils.checkNotNull(getClass(), getCurrentTestName()); + ValidateUtils.checkNotNull(null, getCurrentTestName()); + }); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/VersionInfoTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/VersionInfoTest.java index 834be242e..7626ebc1d 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/VersionInfoTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/VersionInfoTest.java @@ -20,33 +20,34 @@ package org.apache.sshd.common.util; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class VersionInfoTest extends JUnitTestSupport { public VersionInfoTest() { super(); } @Test - public void testLessThan4Components() { + void lessThan4Components() { VersionInfo expected = new VersionInfo(73, 65); VersionInfo actual = VersionInfo.parse(NumberUtils.join('.', expected.getMajorVersion(), expected.getMinorVersion())); - assertEquals("Mismatched result", expected, actual); + assertEquals(expected, actual, "Mismatched result"); } @Test - public void testMoreThan4Components() { + void moreThan4Components() { VersionInfo expected = new VersionInfo(7, 3, 6, 5); VersionInfo actual = VersionInfo.parse(expected.toString() + ".3.7.7.7.3.4.7"); - assertEquals("Mismatched result", expected, actual); + assertEquals(expected, actual, "Mismatched result"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/buffer/BufferTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/buffer/BufferTest.java index 8e2be33a3..475c0da41 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/buffer/BufferTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/buffer/BufferTest.java @@ -24,21 +24,24 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class BufferTest extends JUnitTestSupport { public BufferTest() { super(); } @Test - public void testGetLong() throws Exception { + void getLong() throws Exception { long expected = 1234567890123456789L; try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { @@ -47,62 +50,62 @@ public void testGetLong() throws Exception { } Buffer buffer = new ByteArrayBuffer(stream.toByteArray()); - assertEquals("Mismatched recovered value", expected, buffer.getLong()); + assertEquals(expected, buffer.getLong(), "Mismatched recovered value"); } } @Test - public void testPutCharsWithNullOrEmptyValue() { + void putCharsWithNullOrEmptyValue() { Buffer buffer = new ByteArrayBuffer(Integer.SIZE); for (char[] chars : new char[][] { null, GenericUtils.EMPTY_CHAR_ARRAY }) { buffer.putChars(chars); String value = buffer.getString(); - assertEquals("Mismatched value for " + ((chars == null) ? "null" : "empty") + " characters", "", value); + assertEquals("", value, "Mismatched value for " + ((chars == null) ? "null" : "empty") + " characters"); } } @Test - public void testPutCharsOnNonEmptyValue() { + void putCharsOnNonEmptyValue() { String expected = getCurrentTestName(); Buffer buffer = new ByteArrayBuffer(expected.length() + Byte.SIZE); buffer.putChars(expected.toCharArray()); String actual = buffer.getString(); - assertEquals("Mismatched recovered values", expected, actual); + assertEquals(expected, actual, "Mismatched recovered values"); } @Test - public void testPutAndWipeChars() { + void putAndWipeChars() { String expected = getCurrentTestName(); char[] chars = expected.toCharArray(); Buffer buffer = new ByteArrayBuffer(chars.length + Byte.SIZE); buffer.putAndWipeChars(chars); String actual = buffer.getString(); - assertEquals("Mismatched recovered values", expected, actual); + assertEquals(expected, actual, "Mismatched recovered values"); for (int index = 0; index < chars.length; index++) { - assertEquals("Character not wiped at index=" + index, 0, chars[index]); + assertEquals(0, chars[index], "Character not wiped at index=" + index); } } @Test - public void testPutAndWipeBytes() { + void putAndWipeBytes() { String expected = getCurrentTestName(); byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); Buffer buffer = new ByteArrayBuffer(bytes.length + Byte.SIZE); buffer.putAndWipeBytes(bytes); String actual = buffer.getString(); - assertEquals("Mismatched recovered values", expected, actual); + assertEquals(expected, actual, "Mismatched recovered values"); for (int index = 0; index < bytes.length; index++) { - assertEquals("Value not wiped at index=" + index, 0, bytes[index]); + assertEquals(0, bytes[index], "Value not wiped at index=" + index); } } @Test - public void testGetPublicKeyCorrupted() { + void getPublicKeyCorrupted() { ByteArrayBuffer buffer = new ByteArrayBuffer(8); buffer.putInt(Integer.MAX_VALUE - 10000); buffer.putInt(0); @@ -112,14 +115,14 @@ public void testGetPublicKeyCorrupted() { } @Test - public void testShortPositive() { + void shortPositive() { ByteArrayBuffer buffer = new ByteArrayBuffer(2); buffer.putShort(261); assertEquals(261, buffer.getShort()); } @Test - public void testShortNegative() { + void shortNegative() { ByteArrayBuffer buffer = new ByteArrayBuffer(2); buffer.putShort(-2); assertEquals(-2, buffer.getShort()); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/buffer/BufferUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/buffer/BufferUtilsTest.java index 7ab8a3daa..632acc48b 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/buffer/BufferUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/buffer/BufferUtilsTest.java @@ -23,24 +23,27 @@ import java.util.Random; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class BufferUtilsTest extends JUnitTestSupport { public BufferUtilsTest() { super(); } @Test - public void testHexEncodeDecode() { + void hexEncodeDecode() { String expValue = getClass().getName() + "#" + getCurrentTestName(); byte[] expData = expValue.getBytes(StandardCharsets.UTF_8); for (char sep : new char[] { BufferUtils.EMPTY_HEX_SEPARATOR, ':' }) { @@ -49,12 +52,12 @@ public void testHexEncodeDecode() { String actValue = new String(actData, StandardCharsets.UTF_8); String sepName = (BufferUtils.EMPTY_HEX_SEPARATOR == sep) ? "EMPTY" : Character.toString(sep); outputDebugMessage("Decode(sep=%s) expected=%s, actual=%s", sepName, expValue, actValue); - assertArrayEquals("Mismatched result for sep='" + sepName + "'", expData, actData); + assertArrayEquals(expData, actData, "Mismatched result for sep='" + sepName + "'"); } } @Test - public void testGetCompactClone() { + void getCompactClone() { byte[] expected = getCurrentTestName().getBytes(StandardCharsets.UTF_8); final int testOffset = Byte.SIZE / 2; byte[] data = new byte[expected.length + 2 * testOffset]; @@ -63,11 +66,11 @@ public void testGetCompactClone() { System.arraycopy(expected, 0, data, testOffset, expected.length); Buffer buf = ByteArrayBuffer.getCompactClone(data, testOffset, expected.length); - assertEquals("Mismatched cloned buffer read position", 0, buf.rpos()); - assertEquals("Mismatched cloned buffer available size", expected.length, buf.available()); + assertEquals(0, buf.rpos(), "Mismatched cloned buffer read position"); + assertEquals(expected.length, buf.available(), "Mismatched cloned buffer available size"); byte[] actual = buf.array(); - assertNotSame("Original data not cloned", data, actual); - assertArrayEquals("Mismatched cloned contents", expected, actual); + assertNotSame(data, actual, "Original data not cloned"); + assertArrayEquals(expected, actual, "Mismatched cloned contents"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/closeable/CloseableUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/closeable/CloseableUtilsTest.java index 14977f9eb..37b99864a 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/closeable/CloseableUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/closeable/CloseableUtilsTest.java @@ -31,24 +31,27 @@ import org.apache.sshd.common.future.SshFutureListener; import org.apache.sshd.common.util.threads.ThreadUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class CloseableUtilsTest extends JUnitTestSupport { public CloseableUtilsTest() { super(); } @Test - public void testCloseImmediateNotCalledIfAlreadyClosed() throws IOException { + void closeImmediateNotCalledIfAlreadyClosed() throws IOException { Closeable closeable = new IoBaseCloseable() { @Override public CloseFuture close(boolean immediately) { @@ -80,7 +83,7 @@ public boolean isClosing() { } @Test - public void testCloseImmediateNotCalledIfIsClosing() throws IOException { + void closeImmediateNotCalledIfIsClosing() throws IOException { Closeable closeable = new IoBaseCloseable() { @Override public CloseFuture close(boolean immediately) { @@ -112,14 +115,14 @@ public boolean isClosing() { } @Test - public void testCloseImmediateCalledAndWait() throws Exception { + void closeImmediateCalledAndWait() throws Exception { DefaultCloseFuture future = new DefaultCloseFuture(this, this); AtomicInteger callsCount = new AtomicInteger(0); Closeable closeable = new IoBaseCloseable() { @Override public CloseFuture close(boolean immediately) { - assertTrue("Closure is not immediate", immediately); - assertEquals("Multiple close immediate calls", 1, callsCount.incrementAndGet()); + assertTrue(immediately, "Closure is not immediate"); + assertEquals(1, callsCount.incrementAndGet(), "Multiple close immediate calls"); return future; } @@ -155,7 +158,7 @@ public boolean isClosing() { }); future.setClosed(); // signal close complete task.get(5L, TimeUnit.SECONDS); // make sure #await call terminated - assertEquals("Close immediate not called", 1, callsCount.get()); + assertEquals(1, callsCount.get(), "Close immediate not called"); } finally { service.shutdownNow(); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/helper/LazyIterablesConcatenatorTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/helper/LazyIterablesConcatenatorTest.java index 5f145b636..f3956c685 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/helper/LazyIterablesConcatenatorTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/helper/LazyIterablesConcatenatorTest.java @@ -30,23 +30,23 @@ import java.util.stream.Stream; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class LazyIterablesConcatenatorTest extends JUnitTestSupport { public LazyIterablesConcatenatorTest() { super(); } @Test - public void testLazyConcatenateIterables() { + void lazyConcatenateIterables() { Collection l1 = Arrays.asList( getCurrentTestName(), getClass().getSimpleName(), diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/helper/LazyMatchingTypeIteratorTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/helper/LazyMatchingTypeIteratorTest.java index 08c748bea..adead714e 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/helper/LazyMatchingTypeIteratorTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/helper/LazyMatchingTypeIteratorTest.java @@ -35,23 +35,26 @@ import java.util.stream.Stream; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class LazyMatchingTypeIteratorTest extends JUnitTestSupport { public LazyMatchingTypeIteratorTest() { super(); } @Test - public void testLazySelectMatchingTypes() { + void lazySelectMatchingTypes() { Collection strings = Arrays.asList( getCurrentTestName(), getClass().getSimpleName(), @@ -90,8 +93,8 @@ public Object next() { Set expected = (type == String.class) ? new HashSet<>(strings) : new HashSet<>(times); for (int c = 1; lazy.hasNext(); c++) { Object o = lazy.next(); - assertEquals("Mismatched match count for " + o, c, matchCount.get()); - assertTrue("Unexpected value: " + o, expected.remove(o)); + assertEquals(c, matchCount.get(), "Mismatched match count for " + o); + assertTrue(expected.remove(o), "Unexpected value: " + o); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/DirectoryScannerTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/DirectoryScannerTest.java index 14116095a..5aa5f36c6 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/DirectoryScannerTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/DirectoryScannerTest.java @@ -30,26 +30,25 @@ import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class DirectoryScannerTest extends JUnitTestSupport { public DirectoryScannerTest() { super(); } @Test - public void testDeepScanning() throws IOException { + void deepScanning() throws IOException { Path rootDir = getTempTargetRelativeFile(getClass().getSimpleName(), getCurrentTestName()); CommonTestSupportUtils.deleteRecursive(rootDir); // start fresh @@ -73,7 +72,7 @@ public void testDeepScanning() throws IOException { } @Test - public void testFileSuffixMatching() throws IOException { + void fileSuffixMatching() throws IOException { Path rootDir = getTempTargetRelativeFile(getClass().getSimpleName(), getCurrentTestName()); CommonTestSupportUtils.deleteRecursive(rootDir); // start fresh Files.createDirectories(rootDir); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/IoUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/IoUtilsTest.java index b15cc34df..5077c6050 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/IoUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/IoUtilsTest.java @@ -29,40 +29,43 @@ import org.apache.sshd.common.util.OsUtils; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assert; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class IoUtilsTest extends JUnitTestSupport { public IoUtilsTest() { super(); } @Test - public void testFollowLinks() { - assertTrue("Null ?", IoUtils.followLinks((LinkOption[]) null)); - assertTrue("Empty ?", IoUtils.followLinks(IoUtils.EMPTY_LINK_OPTIONS)); - assertFalse("No-follow ?", IoUtils.followLinks(IoUtils.getLinkOptions(false))); + void followLinks() { + assertTrue(IoUtils.followLinks((LinkOption[]) null), "Null ?"); + assertTrue(IoUtils.followLinks(IoUtils.EMPTY_LINK_OPTIONS), "Empty ?"); + assertFalse(IoUtils.followLinks(IoUtils.getLinkOptions(false)), "No-follow ?"); } @Test - public void testGetEOLBytes() { + void getEOLBytes() { byte[] expected = IoUtils.getEOLBytes(); - assertTrue("Empty bytes", NumberUtils.length(expected) > 0); + assertTrue(NumberUtils.length(expected) > 0, "Empty bytes"); for (int index = 1; index < Byte.SIZE; index++) { byte[] actual = IoUtils.getEOLBytes(); - assertNotSame("Same bytes received at iteration " + index, expected, actual); - assertArrayEquals("Mismatched bytes at iteration " + index, expected, actual); + assertNotSame(expected, actual, "Same bytes received at iteration " + index); + assertArrayEquals(expected, actual, "Mismatched bytes at iteration " + index); } } @@ -72,8 +75,8 @@ public void testGetEOLBytes() { * @throws IOException on failure */ @Test - public void testCheckExists() throws IOException { - Assume.assumeFalse("Not relevant for Windows", OsUtils.isWin32()); + void checkExists() throws IOException { + Assumptions.assumeFalse(OsUtils.isWin32(), "Not relevant for Windows"); testCheckExists(Paths.get("target/IoUtilsTest").toAbsolutePath()); } @@ -98,15 +101,15 @@ public void testCheckExists(Path baseDir) throws IOException { Path targetWithLink = baseDir.resolve("folder1/folder2/link/dirintarget"); - Assert.assertTrue("symlink follow should work", IoUtils.checkFileExists(targetWithLink)); - Assert.assertTrue("symlink follow should work", IoUtils.checkFileExistsAnySymlinks(targetWithLink, false)); + assertTrue(IoUtils.checkFileExists(targetWithLink), "symlink follow should work"); + assertTrue(IoUtils.checkFileExistsAnySymlinks(targetWithLink, false), "symlink follow should work"); - Assert.assertFalse("Link at end shouldn't be followed", IoUtils.checkFileExistsAnySymlinks(link, true)); - Assert.assertFalse("Nofollow shouldn't follow directory", - IoUtils.checkFileExistsAnySymlinks(targetWithLink, true)); - Assert.assertFalse("Link at beginning shouldn't be followed", - IoUtils.checkFileExistsAnySymlinks(link2, true)); - Assert.assertTrue("Root directory must exist", - IoUtils.checkFileExistsAnySymlinks(baseDir, true)); + assertFalse(IoUtils.checkFileExistsAnySymlinks(link, true), "Link at end shouldn't be followed"); + assertFalse(IoUtils.checkFileExistsAnySymlinks(targetWithLink, true), + "Nofollow shouldn't follow directory"); + assertFalse(IoUtils.checkFileExistsAnySymlinks(link2, true), + "Link at beginning shouldn't be followed"); + assertTrue(IoUtils.checkFileExistsAnySymlinks(baseDir, true), + "Root directory must exist"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/ModifiableFileWatcherTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/ModifiableFileWatcherTest.java index ae72603ec..1ce84820f 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/ModifiableFileWatcherTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/ModifiableFileWatcherTest.java @@ -19,6 +19,7 @@ package org.apache.sshd.common.util.io; +import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.StandardCharsets; @@ -35,37 +36,42 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.OsUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.TemporaryFolder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.io.TempDir; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ModifiableFileWatcherTest extends JUnitTestSupport { - @Rule - public TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + protected File tmp; public ModifiableFileWatcherTest() { super(); } - @Test // see SSHD-606 - public void testValidateStrictConfigFilePermissions() throws IOException { - Assume.assumeTrue("Test does not always work on Windows", !OsUtils.isWin32()); + // see SSHD-606 + @Test + void validateStrictConfigFilePermissions() throws IOException { + Assumptions.assumeTrue(!OsUtils.isWin32(), "Test does not always work on Windows"); Path file = getTempTargetRelativeFile(getClass().getSimpleName(), getCurrentTestName()); outputDebugMessage("%s deletion result=%s", file, Files.deleteIfExists(file)); - assertNull("Unexpected violation for non-existent file: " + file, - ModifiableFileWatcher.validateStrictConfigFilePermissions(file)); + assertNull(ModifiableFileWatcher.validateStrictConfigFilePermissions(file), + "Unexpected violation for non-existent file: " + file); assertHierarchyTargetFolderExists(file.getParent()); try (OutputStream output = Files.newOutputStream(file)) { @@ -75,33 +81,33 @@ public void testValidateStrictConfigFilePermissions() throws IOException { Collection perms = IoUtils.getPermissions(file); if (GenericUtils.isEmpty(perms)) { - assertNull("Unexpected violation for no permissions file: " + file, - ModifiableFileWatcher.validateStrictConfigFilePermissions(file)); + assertNull(ModifiableFileWatcher.validateStrictConfigFilePermissions(file), + "Unexpected violation for no permissions file: " + file); } else if (OsUtils.isUNIX()) { Map.Entry violation = null; for (PosixFilePermission p : ModifiableFileWatcher.STRICTLY_PROHIBITED_FILE_PERMISSION) { if (perms.contains(p)) { violation = ModifiableFileWatcher.validateStrictConfigFilePermissions(file); - assertNotNull("Unexpected success for permission=" + p + " of file " + file + " permissions=" + perms, - violation); + assertNotNull(violation, + "Unexpected success for permission=" + p + " of file " + file + " permissions=" + perms); break; } } if (violation == null) { // we do not expected a failure if no permissions have been violated - assertNull("Unexpected UNIX violation for file " + file + " permissions=" + perms, - ModifiableFileWatcher.validateStrictConfigFilePermissions(file)); + assertNull(ModifiableFileWatcher.validateStrictConfigFilePermissions(file), + "Unexpected UNIX violation for file " + file + " permissions=" + perms); } } else { - assertNull("Unexpected Windows violation for file " + file + " permissions=" + perms, - ModifiableFileWatcher.validateStrictConfigFilePermissions(file)); + assertNull(ModifiableFileWatcher.validateStrictConfigFilePermissions(file), + "Unexpected Windows violation for file " + file + " permissions=" + perms); } } @Test - public void testSymlinkChain() throws Exception { - Assume.assumeFalse("Symlink test disabled on Windows", OsUtils.isWin32()); - Path adam = tmp.getRoot().toPath().resolve("adam"); + void symlinkChain() throws Exception { + Assumptions.assumeFalse(OsUtils.isWin32(), "Symlink test disabled on Windows"); + Path adam = tmp.toPath().resolve("adam"); Path jeff = adam.getParent().resolve("jeff"); Path link = adam.getParent().resolve(adam.getFileName() + ".link"); Path link2 = adam.getParent().resolve("topLink"); @@ -113,74 +119,74 @@ public void testSymlinkChain() throws Exception { Files.createSymbolicLink(link, adam); Files.createSymbolicLink(link2, link); ModifiableFileWatcher watcher = new ModifiableFileWatcher(link2); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); String data = new String(Files.readAllBytes(link2), StandardCharsets.US_ASCII); assertEquals("adam", data); watcher.updateReloadAttributes(); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); Files.delete(link); Files.createSymbolicLink(link, jeff); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); data = new String(Files.readAllBytes(link2), StandardCharsets.US_ASCII); assertEquals("jeff", data); } @Test - public void testFileModified() throws Exception { - Path adam = tmp.getRoot().toPath().resolve("adam"); + void fileModified() throws Exception { + Path adam = tmp.toPath().resolve("adam"); Files.write(adam, "adam".getBytes(StandardCharsets.US_ASCII)); Files.setLastModifiedTime(adam, FileTime.from(Instant.now().minusSeconds(6))); ModifiableFileWatcher watcher = new ModifiableFileWatcher(adam); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); String data = new String(Files.readAllBytes(adam), StandardCharsets.US_ASCII); assertEquals("adam", data); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); watcher.updateReloadAttributes(); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); Files.write(adam, "adam".getBytes(StandardCharsets.US_ASCII)); Files.setLastModifiedTime(adam, FileTime.from(Instant.now().minusSeconds(4))); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); watcher.updateReloadAttributes(); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); } @Test - public void testFileDeleted() throws Exception { - Path adam = tmp.getRoot().toPath().resolve("adam"); + void fileDeleted() throws Exception { + Path adam = tmp.toPath().resolve("adam"); Files.write(adam, "adam".getBytes(StandardCharsets.US_ASCII)); Files.setLastModifiedTime(adam, FileTime.from(Instant.now().minusSeconds(4))); ModifiableFileWatcher watcher = new ModifiableFileWatcher(adam); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); String data = new String(Files.readAllBytes(adam), StandardCharsets.US_ASCII); assertEquals("adam", data); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); watcher.updateReloadAttributes(); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); Files.delete(adam); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); watcher.updateReloadAttributes(); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); } @Test - public void testFileCreated() throws Exception { - Path adam = tmp.getRoot().toPath().resolve("adam"); + void fileCreated() throws Exception { + Path adam = tmp.toPath().resolve("adam"); ModifiableFileWatcher watcher = new ModifiableFileWatcher(adam); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); watcher.updateReloadAttributes(); Files.write(adam, "adam".getBytes(StandardCharsets.US_ASCII)); Files.setLastModifiedTime(adam, FileTime.from(Instant.now().minusSeconds(4))); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); String data = new String(Files.readAllBytes(adam), StandardCharsets.US_ASCII); assertEquals("adam", data); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); watcher.updateReloadAttributes(); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); } @Test - public void testLoadDirectly() throws Exception { - Path adam = tmp.getRoot().toPath().resolve("adam"); + void loadDirectly() throws Exception { + Path adam = tmp.toPath().resolve("adam"); Files.write(adam, "adam".getBytes(StandardCharsets.US_ASCII)); Files.setLastModifiedTime(adam, FileTime.from(Instant.now().minusSeconds(6))); ModifiableFileWatcher watcher = new ModifiableFileWatcher(adam); @@ -188,20 +194,20 @@ public void testLoadDirectly() throws Exception { assertEquals("adam", data); // No call to checkReloadRequired() before. watcher.updateReloadAttributes(); - assertFalse("Should not need to reload", watcher.checkReloadRequired()); + assertFalse(watcher.checkReloadRequired(), "Should not need to reload"); Files.write(adam, "adam".getBytes(StandardCharsets.US_ASCII)); Files.setLastModifiedTime(adam, FileTime.from(Instant.now().minusSeconds(4))); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); } @Test - public void testRacyFile() throws Exception { - Path adam = tmp.getRoot().toPath().resolve("adam"); + void racyFile() throws Exception { + Path adam = tmp.toPath().resolve("adam"); Files.write(adam, "adam".getBytes(StandardCharsets.US_ASCII)); Files.setLastModifiedTime(adam, FileTime.from(Instant.now())); FileTime timestamp = Files.getLastModifiedTime(adam); ModifiableFileWatcher watcher = new ModifiableFileWatcher(adam); - assertTrue("Should need to reload", watcher.checkReloadRequired()); + assertTrue(watcher.checkReloadRequired(), "Should need to reload"); String data = new String(Files.readAllBytes(adam), StandardCharsets.US_ASCII); assertEquals("adam", data); watcher.updateReloadAttributes(); @@ -217,8 +223,8 @@ public void testRacyFile() throws Exception { break; } } - assertNotNull("Expected non-racy clean", stop); - assertTrue("Should have been racy initially", n > 1); - assertTrue("Non-racy too early", Duration.between(timestamp.toInstant(), stop).compareTo(Duration.ofSeconds(2)) >= 0); + assertNotNull(stop, "Expected non-racy clean"); + assertTrue(n > 1, "Should have been racy initially"); + assertTrue(Duration.between(timestamp.toInstant(), stop).compareTo(Duration.ofSeconds(2)) >= 0, "Non-racy too early"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/PathUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/PathUtilsTest.java index 873190f5a..8af4ccfe4 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/PathUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/PathUtilsTest.java @@ -23,31 +23,33 @@ import java.nio.file.Path; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PathUtilsTest extends JUnitTestSupport { public PathUtilsTest() { super(); } @Test - public void testNormalizeUserHomeOnlyPath() { + void normalizeUserHomeOnlyPath() { Path expected = PathUtils.getUserHomeFolder(); String actual = PathUtils.normalizePath(Character.toString(PathUtils.HOME_TILDE_CHAR)); assertEquals(expected.toString(), actual); } @Test - public void testNormalizeLeadingUserHomePath() { + void normalizeLeadingUserHomePath() { Path expected = PathUtils.getUserHomeFolder() .resolve(getClass().getSimpleName()) .resolve(getCurrentTestName()); @@ -58,14 +60,14 @@ public void testNormalizeLeadingUserHomePath() { } @Test - public void testNormalizeStandardPath() { + void normalizeStandardPath() { String expected = detectTargetFolder().toString(); String actual = PathUtils.normalizePath(expected); assertSame(expected, actual); } @Test - public void testNormalizeForwardSlash() { + void normalizeForwardSlash() { String expected = detectTargetFolder().toString(); String actual = PathUtils.normalizePath(expected.replace(File.separatorChar, '/')); if (File.separatorChar == '/') { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/ASN1ClassTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/ASN1ClassTest.java index acf243059..6c6a04440 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/ASN1ClassTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/ASN1ClassTest.java @@ -20,48 +20,46 @@ import java.util.List; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class ASN1ClassTest extends JUnitTestSupport { - private final ASN1Class expected; + private ASN1Class expected; - public ASN1ClassTest(ASN1Class expected) { + public void initASN1ClassTest(ASN1Class expected) { this.expected = expected; } - @Parameters(name = "{0}") public static List parameters() { return parameterize(ASN1Class.VALUES); } - @Test - public void testFromName() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fromName(ASN1Class expected) { + initASN1ClassTest(expected); String name = expected.name(); for (int index = 1, count = name.length(); index <= count; index++) { - assertSame(name, expected, ASN1Class.fromName(name)); + assertSame(expected, ASN1Class.fromName(name), name); name = shuffleCase(name); } } - @Test // NOTE: this also tests "fromTypeValue" since "fromDERValue" invokes it - public void testFromDERValue() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") // NOTE: this also tests "fromTypeValue" since "fromDERValue" invokes it + public void fromDERValue(ASN1Class expected) { + initASN1ClassTest(expected); assertSame(expected, ASN1Class.fromDERValue((expected.getClassValue() << 6) & 0xFF)); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/ASN1TypeTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/ASN1TypeTest.java index 7830ebde5..3bb60d6ad 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/ASN1TypeTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/ASN1TypeTest.java @@ -20,48 +20,46 @@ import java.util.List; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class ASN1TypeTest extends JUnitTestSupport { - private final ASN1Type expected; + private ASN1Type expected; - public ASN1TypeTest(ASN1Type expected) { + public void initASN1TypeTest(ASN1Type expected) { this.expected = expected; } - @Parameters(name = "{0}") public static List parameters() { return parameterize(ASN1Type.VALUES); } - @Test - public void testFromName() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fromName(ASN1Type expected) { + initASN1TypeTest(expected); String name = expected.name(); for (int index = 1, count = name.length(); index <= count; index++) { - assertSame(name, expected, ASN1Type.fromName(name)); + assertSame(expected, ASN1Type.fromName(name), name); name = shuffleCase(name); } } - @Test - public void testFromTypeValue() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void fromTypeValue(ASN1Type expected) { + initASN1TypeTest(expected); assertSame(expected, ASN1Type.fromTypeValue(expected.getTypeValue())); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/DERParserTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/DERParserTest.java index ecc5b31bb..23c96f154 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/DERParserTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/DERParserTest.java @@ -23,24 +23,25 @@ import java.io.StreamCorruptedException; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class DERParserTest extends JUnitTestSupport { public DERParserTest() { super(); } @Test - public void testReadLengthConstraint() throws IOException { + void readLengthConstraint() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { try (DERWriter w = new DERWriter(baos)) { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/DERWriterTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/DERWriterTest.java index 6129bea89..a735ed827 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/DERWriterTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/der/DERWriterTest.java @@ -23,24 +23,25 @@ import java.math.BigInteger; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class DERWriterTest extends JUnitTestSupport { public DERWriterTest() { super(); } @Test - public void testWriteStripLeadingZeroes() throws IOException { + void writeStripLeadingZeroes() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { try (DERWriter w = new DERWriter(baos)) { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/EmptyInputStreamTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/EmptyInputStreamTest.java index df9d781f7..c47132d69 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/EmptyInputStreamTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/EmptyInputStreamTest.java @@ -24,31 +24,35 @@ import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class EmptyInputStreamTest extends JUnitTestSupport { public EmptyInputStreamTest() { super(); } @Test - public void testEmptyInputStream() throws IOException { + void emptyInputStream() throws IOException { try (EmptyInputStream in = new EmptyInputStream()) { testEmptyInputStream(in, false); } } @Test - public void testCloseableEmptyInputStream() throws IOException { + void closeableEmptyInputStream() throws IOException { try (EmptyInputStream in = new CloseableEmptyInputStream()) { testEmptyInputStream(in, true); } @@ -61,55 +65,55 @@ private void testEmptyInputStream(InputStream in, boolean failAfterClose) throws } private void testEmptyInputStream(String message, InputStream in, boolean errorExpected) { - assertFalse(message + ": unexpected markSupported()", in.markSupported()); - assertThrows(message + ": unexpected mark success", UnsupportedOperationException.class, () -> in.mark(Long.SIZE)); + assertFalse(in.markSupported(), message + ": unexpected markSupported()"); + assertThrows(UnsupportedOperationException.class, () -> in.mark(Long.SIZE), message + ": unexpected mark success"); try { int len = in.available(); - assertFalse(message + ": Unexpected success in available(): " + len, errorExpected); - assertEquals(message + ": Mismatched available() result", 0, len); + assertFalse(errorExpected, message + ": Unexpected success in available(): " + len); + assertEquals(0, len, message + ": Mismatched available() result"); } catch (IOException e) { - assertTrue(message + ": Unexpected error on available(): " + e.getMessage(), errorExpected); + assertTrue(errorExpected, message + ": Unexpected error on available(): " + e.getMessage()); } try { int data = in.read(); - assertFalse(message + ": Unexpected success in read(): " + data, errorExpected); - assertEquals(message + ": Mismatched read() result", -1, data); + assertFalse(errorExpected, message + ": Unexpected success in read(): " + data); + assertEquals(-1, data, message + ": Mismatched read() result"); } catch (IOException e) { - assertTrue(message + ": Unexpected error on read(): " + e.getMessage(), errorExpected); + assertTrue(errorExpected, message + ": Unexpected error on read(): " + e.getMessage()); } byte[] bytes = new byte[Byte.SIZE]; try { int len = in.read(bytes); - assertFalse(message + ": Unexpected success in read([]): " + BufferUtils.toHex(':', bytes), errorExpected); - assertEquals(message + ": Mismatched read([]) result", -1, len); + assertFalse(errorExpected, message + ": Unexpected success in read([]): " + BufferUtils.toHex(':', bytes)); + assertEquals(-1, len, message + ": Mismatched read([]) result"); } catch (IOException e) { - assertTrue(message + ": Unexpected error on read([]): " + e.getMessage(), errorExpected); + assertTrue(errorExpected, message + ": Unexpected error on read([]): " + e.getMessage()); } try { int len = in.read(bytes, 0, bytes.length); - assertFalse(message + ": Unexpected success in read([],int,int): " + BufferUtils.toHex(':', bytes), errorExpected); - assertEquals(message + ": Mismatched read([],int,int) result", -1, len); + assertFalse(errorExpected, message + ": Unexpected success in read([],int,int): " + BufferUtils.toHex(':', bytes)); + assertEquals(-1, len, message + ": Mismatched read([],int,int) result"); } catch (IOException e) { - assertTrue(message + ": Unexpected error on read([],int,int): " + e.getMessage(), errorExpected); + assertTrue(errorExpected, message + ": Unexpected error on read([],int,int): " + e.getMessage()); } try { long len = in.skip(Byte.MAX_VALUE); - assertFalse(message + ": Unexpected success in skip(): " + len, errorExpected); - assertEquals(message + ": Mismatched skip() result", 0L, len); + assertFalse(errorExpected, message + ": Unexpected success in skip(): " + len); + assertEquals(0L, len, message + ": Mismatched skip() result"); } catch (IOException e) { - assertTrue(message + ": Unexpected error on skip(): " + e.getMessage(), errorExpected); + assertTrue(errorExpected, message + ": Unexpected error on skip(): " + e.getMessage()); } try { in.reset(); - assertFalse(message + ": Unexpected success in reset()", errorExpected); + assertFalse(errorExpected, message + ": Unexpected success in reset()"); } catch (IOException e) { - assertTrue(message + ": Unexpected error on reset(): " + e.getMessage(), errorExpected); + assertTrue(errorExpected, message + ": Unexpected error on reset(): " + e.getMessage()); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/LimitInputStreamTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/LimitInputStreamTest.java index 51e801b9a..0074016b8 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/LimitInputStreamTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/LimitInputStreamTest.java @@ -26,24 +26,30 @@ import java.nio.file.Path; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class LimitInputStreamTest extends JUnitTestSupport { public LimitInputStreamTest() { super(); } @Test - public void testReadLimit() throws IOException { + void readLimit() throws IOException { Path targetPath = detectTargetFolder(); Path rootFolder = assertHierarchyTargetFolderExists(targetPath.resolve(getClass().getSimpleName())); Path inputFile = rootFolder.resolve(getCurrentTestName() + ".bin"); @@ -57,24 +63,24 @@ public void testReadLimit() throws IOException { byte[] actual = new byte[expected.length]; try (LimitInputStream limited = new LimitInputStream(in, expected.length)) { - assertTrue("Limited stream not marked as open", limited.isOpen()); - assertEquals("Mismatched initial available data size", expected.length, limited.available()); + assertTrue(limited.isOpen(), "Limited stream not marked as open"); + assertEquals(expected.length, limited.available(), "Mismatched initial available data size"); int readLen = limited.read(actual); - assertEquals("Incomplete actual data read", actual.length, readLen); - assertArrayEquals("Mismatched read data", expected, actual); - assertEquals("Mismatched remaining available data size", 0, limited.available()); + assertEquals(actual.length, readLen, "Incomplete actual data read"); + assertArrayEquals(expected, actual, "Mismatched read data"); + assertEquals(0, limited.available(), "Mismatched remaining available data size"); readLen = limited.read(); - assertTrue("Unexpected success to read one more byte: " + readLen, readLen < 0); + assertTrue(readLen < 0, "Unexpected success to read one more byte: " + readLen); readLen = limited.read(actual); - assertTrue("Unexpected success to read extra buffer: " + readLen, readLen < 0); + assertTrue(readLen < 0, "Unexpected success to read extra buffer: " + readLen); limited.close(); - assertFalse("Limited stream still marked as open", limited.isOpen()); + assertFalse(limited.isOpen(), "Limited stream still marked as open"); - assertThrows("Unexpected one byte read success after close", IOException.class, limited::read); + assertThrows(IOException.class, limited::read, "Unexpected one byte read success after close"); try { readLen = limited.read(actual); @@ -107,7 +113,7 @@ public void testReadLimit() throws IOException { // make sure underlying stream not closed int readLen = in.read(actual); - assertEquals("Incomplete extra data read", Math.min(actual.length, data.length - expected.length), readLen); + assertEquals(Math.min(actual.length, data.length - expected.length), readLen, "Incomplete extra data read"); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NoCloseInputStreamTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NoCloseInputStreamTest.java index e22a2ba5c..5bbbc4135 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NoCloseInputStreamTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NoCloseInputStreamTest.java @@ -27,24 +27,26 @@ import java.util.Date; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class NoCloseInputStreamTest extends JUnitTestSupport { public NoCloseInputStreamTest() { super(); } @Test - public void testCanKeepReadingAfterClose() throws IOException { + void canKeepReadingAfterClose() throws IOException { byte[] expected = (getClass().getName() + "#" + getCurrentTestName() + "@" + new Date()).getBytes(StandardCharsets.UTF_8); Path dir = createTempClassFolder(); @@ -81,10 +83,10 @@ public void testCanKeepReadingAfterClose() throws IOException { } int readValue = shielded.read(); - assertEquals("Shielded EOF not signalled", -1, readValue); + assertEquals(-1, readValue, "Shielded EOF not signalled"); readValue = fileStream.read(); - assertEquals("Original EOF not signalled", -1, readValue); + assertEquals(-1, readValue, "Original EOF not signalled"); } } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NoCloseReaderTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NoCloseReaderTest.java index 471a012fb..5bacf68a8 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NoCloseReaderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NoCloseReaderTest.java @@ -29,24 +29,26 @@ import java.util.Date; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class NoCloseReaderTest extends JUnitTestSupport { public NoCloseReaderTest() { super(); } @Test - public void testCanKeepReadingAfterClose() throws IOException { + void canKeepReadingAfterClose() throws IOException { String expected = getClass().getName() + "#" + getCurrentTestName() + "@" + new Date(); Path dir = createTempClassFolder(); Path file = Files.write(dir.resolve(getCurrentTestName() + ".txt"), expected.getBytes(StandardCharsets.UTF_8)); @@ -85,10 +87,10 @@ public void testCanKeepReadingAfterClose() throws IOException { } int readValue = shielded.read(); - assertEquals("Shielded EOF not signalled", -1, readValue); + assertEquals(-1, readValue, "Shielded EOF not signalled"); readValue = rdr.read(); - assertEquals("Original EOF not signalled", -1, readValue); + assertEquals(-1, readValue, "Original EOF not signalled"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NullInputStreamTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NullInputStreamTest.java index b61841fad..dcd749ef1 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NullInputStreamTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/input/NullInputStreamTest.java @@ -23,17 +23,21 @@ import java.io.IOException; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class NullInputStreamTest extends JUnitTestSupport { private static final NullInputStream INSTANCE = new NullInputStream(); @@ -42,36 +46,36 @@ public NullInputStreamTest() { } @Test - public void testReadOneChar() throws IOException { + void readOneChar() throws IOException { assertEquals(-1, INSTANCE.read()); } @Test - public void testReadFullBuffer() throws IOException { + void readFullBuffer() throws IOException { assertEquals(-1, INSTANCE.read(new byte[Byte.SIZE])); } @Test - public void testReadPartialBuffer() throws IOException { + void readPartialBuffer() throws IOException { byte[] buf = new byte[Byte.SIZE]; assertEquals(-1, INSTANCE.read(buf, buf.length / 2, (buf.length / 2) - 1)); } @Test - public void testSkip() throws IOException { + void skip() throws IOException { assertEquals(0L, INSTANCE.skip(Long.SIZE)); } @Test - public void testAvailable() throws IOException { + void available() throws IOException { assertEquals(0, INSTANCE.available()); } @Test - public void testNotAllowedToAccessAfterClose() throws IOException { + void notAllowedToAccessAfterClose() throws IOException { NullInputStream stream = new NullInputStream(); stream.close(); - assertFalse("Stream not marked as closed", stream.isOpen()); + assertFalse(stream.isOpen(), "Stream not marked as closed"); try { int nRead = stream.read(); @@ -108,6 +112,6 @@ public void testNotAllowedToAccessAfterClose() throws IOException { } catch (IOException e) { // expected } - assertThrows("Unexpected reset success", EOFException.class, stream::reset); + assertThrows(EOFException.class, stream::reset, "Unexpected reset success"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/LineOutputStreamTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/LineOutputStreamTest.java index 54b22595a..5beb42399 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/LineOutputStreamTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/LineOutputStreamTest.java @@ -31,39 +31,33 @@ import java.util.List; import org.apache.sshd.common.util.io.IoUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class LineOutputStreamTest extends JUnitTestSupport { - private final boolean withCR; + private boolean withCR; - public LineOutputStreamTest(boolean withCR) { + public void initLineOutputStreamTest(boolean withCR) { this.withCR = withCR; } - @Parameters(name = "CR={0}") public static List parameters() { return Arrays.asList(new Object[] { Boolean.TRUE }, new Object[] { Boolean.FALSE }); } - @Test - public void testLineParsing() throws IOException { + @MethodSource("parameters") + @ParameterizedTest(name = "CR={0}") + public void lineParsing(boolean withCR) throws IOException { + initLineOutputStreamTest(withCR); List expected = new ArrayList<>(); String prefix = getClass().getName() + "#" + getCurrentTestName() + "-"; for (int index = 1; index < Byte.MAX_VALUE; index++) { diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NoCloseOutputStreamTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NoCloseOutputStreamTest.java index 60db28bcb..2d36257c1 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NoCloseOutputStreamTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NoCloseOutputStreamTest.java @@ -27,24 +27,25 @@ import java.util.Date; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class NoCloseOutputStreamTest extends JUnitTestSupport { public NoCloseOutputStreamTest() { super(); } @Test - public void testCanKeepWritingAfterClose() throws IOException { + void canKeepWritingAfterClose() throws IOException { Path dir = createTempClassFolder(); Path file = dir.resolve(getCurrentTestName() + ".txt"); Files.deleteIfExists(file); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NoCloseWriterTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NoCloseWriterTest.java index 41cb5dfe9..da3362764 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NoCloseWriterTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NoCloseWriterTest.java @@ -29,24 +29,25 @@ import java.util.Date; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class NoCloseWriterTest extends JUnitTestSupport { public NoCloseWriterTest() { super(); } @Test - public void testCanKeepWritingAfterClose() throws IOException { + void canKeepWritingAfterClose() throws IOException { Path dir = createTempClassFolder(); Path file = dir.resolve(getCurrentTestName() + ".txt"); Files.deleteIfExists(file); diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NullOutputStreamTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NullOutputStreamTest.java index 3958bebc2..0d0b6a789 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NullOutputStreamTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/io/output/NullOutputStreamTest.java @@ -24,37 +24,40 @@ import java.util.Arrays; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class NullOutputStreamTest extends JUnitTestSupport { public NullOutputStreamTest() { super(); } @Test - public void testNoAccessAllowedAfterClose() throws IOException { + void noAccessAllowedAfterClose() throws IOException { NullOutputStream stream = new NullOutputStream(); stream.close(); - assertFalse("Stream not marked as closed", stream.isOpen()); - assertThrows("Unexpected single value write success", EOFException.class, () -> stream.write('a')); + assertFalse(stream.isOpen(), "Stream not marked as closed"); + assertThrows(EOFException.class, () -> stream.write('a'), "Unexpected single value write success"); byte[] buf = new byte[Byte.SIZE]; Arrays.fill(buf, (byte) 0x41); - assertThrows("Unexpected full buffer write success", EOFException.class, () -> stream.write(buf)); + assertThrows(EOFException.class, () -> stream.write(buf), "Unexpected full buffer write success"); Arrays.fill(buf, (byte) 0x42); - assertThrows("Unexpected full buffer write success", EOFException.class, - () -> stream.write(buf, buf.length / 2, (buf.length / 2) - 1)); + assertThrows(EOFException.class, + () -> stream.write(buf, buf.length / 2, (buf.length / 2) - 1), + "Unexpected full buffer write success"); - assertThrows("Unexpected flush success", EOFException.class, stream::flush); + assertThrows(EOFException.class, stream::flush, "Unexpected flush success"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/net/SshdSocketIpv6AddressTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/net/SshdSocketIpv6AddressTest.java index 7547430f3..0231c2ee8 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/net/SshdSocketIpv6AddressTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/net/SshdSocketIpv6AddressTest.java @@ -24,25 +24,18 @@ import java.util.stream.Collectors; import java.util.stream.Stream; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @author Apache MINA SSHD Project */ -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SshdSocketIpv6AddressTest extends JUnitTestSupport { public static final List VALID_ADDRESSES = Collections.unmodifiableList( Arrays.asList( @@ -56,15 +49,14 @@ public class SshdSocketIpv6AddressTest extends JUnitTestSupport { "fe80::1ff:fe23:4567:890a%3", "fe80:3::1ff:fe23:4567:890a", "::ffff:c000:0280", "::ffff:192.0.2.128")); - private final String address; - private final boolean matches; + private String address; + private boolean matches; - public SshdSocketIpv6AddressTest(String address, boolean matches) { + public void initSshdSocketIpv6AddressTest(String address, boolean matches) { this.address = address; this.matches = matches; } - @Parameters(name = "{0}") public static List parameters() { return Stream .concat(SshdSocketAddress.WELL_KNOWN_IPV6_ADDRESSES.stream(), VALID_ADDRESSES.stream()) @@ -72,8 +64,10 @@ public static List parameters() { .collect(Collectors.toList()); } - @Test - public void testIPv6AddressValidity() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void iPv6AddressValidity(String address, boolean matches) { + initSshdSocketIpv6AddressTest(address, matches); assertEquals(address, matches, SshdSocketAddress.isIPv6Address(address)); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityProviderRegistrarCipherNameTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityProviderRegistrarCipherNameTest.java index 9c7c665f2..a7af814a6 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityProviderRegistrarCipherNameTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityProviderRegistrarCipherNameTest.java @@ -25,33 +25,27 @@ import org.apache.sshd.common.cipher.BuiltinCiphers; import org.apache.sshd.common.cipher.CipherInformation; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class SecurityProviderRegistrarCipherNameTest extends JUnitTestSupport { - private final CipherInformation cipherInfo; + private CipherInformation cipherInfo; - public SecurityProviderRegistrarCipherNameTest(CipherInformation cipherInfo) { + public void initSecurityProviderRegistrarCipherNameTest(CipherInformation cipherInfo) { this.cipherInfo = cipherInfo; } - @Parameters(name = "{0}") public static List parameters() { List params = new ArrayList<>(); for (CipherInformation cipherInfo : BuiltinCiphers.VALUES) { @@ -66,10 +60,12 @@ public static List parameters() { return params; } - @Test - public void testGetEffectiveSecurityEntityName() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void getEffectiveSecurityEntityName(CipherInformation cipherInfo) { + initSecurityProviderRegistrarCipherNameTest(cipherInfo); String expected = cipherInfo.getAlgorithm(); String actual = SecurityProviderRegistrar.getEffectiveSecurityEntityName(Cipher.class, cipherInfo.getTransformation()); - assertEquals("Mismatched pure cipher name", expected, actual); + assertEquals(expected, actual, "Mismatched pure cipher name"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityProviderRegistrarTestSupport.java b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityProviderRegistrarTestSupport.java index 6f201830c..675d0d530 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityProviderRegistrarTestSupport.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityProviderRegistrarTestSupport.java @@ -24,6 +24,8 @@ import org.apache.sshd.util.test.JUnitTestSupport; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Apache MINA SSHD Project */ @@ -40,7 +42,7 @@ public static

P testGetSecurityProviderCaching( String prefix, SecurityProviderRegistrar registrar, P expected) { for (int index = 1; index <= Byte.SIZE; index++) { Provider actual = registrar.getSecurityProvider(); - assertSame(prefix + ": Mismatched provider instance at invocation #" + index, expected, actual); + assertSame(expected, actual, prefix + ": Mismatched provider instance at invocation #" + index); } return expected; diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsDHGEXGroupKeySizeTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsDHGEXGroupKeySizeTest.java index c2ff5489a..e4b426cb0 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsDHGEXGroupKeySizeTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsDHGEXGroupKeySizeTest.java @@ -22,43 +22,38 @@ import java.util.ArrayList; import java.util.List; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class SecurityUtilsDHGEXGroupKeySizeTest extends SecurityUtilsTestSupport { - private final int expected; + private int expected; - public SecurityUtilsDHGEXGroupKeySizeTest(int expected) { + public void initSecurityUtilsDHGEXGroupKeySizeTest(int expected) { this.expected = expected; } - @Before - @After - public void resetDHGEXGroupKeySizes() { + @BeforeEach + @AfterEach + void resetDHGEXGroupKeySizes() { System.clearProperty(SecurityUtils.MIN_DHGEX_KEY_SIZE_PROP); SecurityUtils.setMinDHGroupExchangeKeySize(0); // force detection System.clearProperty(SecurityUtils.MAX_DHGEX_KEY_SIZE_PROP); SecurityUtils.setMaxDHGroupExchangeKeySize(0); // force detection } - @Parameters(name = "keySize={0}") public static List parameters() { System.clearProperty(SecurityUtils.MAX_DHGEX_KEY_SIZE_PROP); SecurityUtils.setMaxDHGroupExchangeKeySize(0); // force detection @@ -76,32 +71,40 @@ public static List parameters() { } } - @Test - public void testSetMaxDHGroupExchangeKeySizeByProperty() { + @MethodSource("parameters") + @ParameterizedTest(name = "keySize={0}") + public void setMaxDHGroupExchangeKeySizeByProperty(int expected) { + initSecurityUtilsDHGEXGroupKeySizeTest(expected); System.setProperty(SecurityUtils.MAX_DHGEX_KEY_SIZE_PROP, Integer.toString(expected)); - assertTrue("DH group not supported for key size=" + expected, SecurityUtils.isDHGroupExchangeSupported()); - assertEquals("Mismatched values", expected, SecurityUtils.getMaxDHGroupExchangeKeySize()); + assertTrue(SecurityUtils.isDHGroupExchangeSupported(), "DH group not supported for key size=" + expected); + assertEquals(expected, SecurityUtils.getMaxDHGroupExchangeKeySize(), "Mismatched values"); } - @Test - public void testSetMaxDHGroupExchangeKeySizeProgrammatically() { + @MethodSource("parameters") + @ParameterizedTest(name = "keySize={0}") + public void setMaxDHGroupExchangeKeySizeProgrammatically(int expected) { + initSecurityUtilsDHGEXGroupKeySizeTest(expected); SecurityUtils.setMaxDHGroupExchangeKeySize(expected); - assertTrue("DH group not supported for key size=" + expected, SecurityUtils.isDHGroupExchangeSupported()); - assertEquals("Mismatched values", expected, SecurityUtils.getMaxDHGroupExchangeKeySize()); + assertTrue(SecurityUtils.isDHGroupExchangeSupported(), "DH group not supported for key size=" + expected); + assertEquals(expected, SecurityUtils.getMaxDHGroupExchangeKeySize(), "Mismatched values"); } - @Test - public void testSetMinDHGroupExchangeKeySizeByProperty() { + @MethodSource("parameters") + @ParameterizedTest(name = "keySize={0}") + public void setMinDHGroupExchangeKeySizeByProperty(int expected) { + initSecurityUtilsDHGEXGroupKeySizeTest(expected); System.setProperty(SecurityUtils.MIN_DHGEX_KEY_SIZE_PROP, Integer.toString(expected)); - assertTrue("DH group not supported for key size=" + expected, SecurityUtils.isDHGroupExchangeSupported()); - assertEquals("Mismatched values", expected, SecurityUtils.getMinDHGroupExchangeKeySize()); + assertTrue(SecurityUtils.isDHGroupExchangeSupported(), "DH group not supported for key size=" + expected); + assertEquals(expected, SecurityUtils.getMinDHGroupExchangeKeySize(), "Mismatched values"); } - @Test - public void testSetMinDHGroupExchangeKeySizeProgrammatically() { + @MethodSource("parameters") + @ParameterizedTest(name = "keySize={0}") + public void setMinDHGroupExchangeKeySizeProgrammatically(int expected) { + initSecurityUtilsDHGEXGroupKeySizeTest(expected); SecurityUtils.setMinDHGroupExchangeKeySize(expected); - assertTrue("DH group not supported for key size=" + expected, SecurityUtils.isDHGroupExchangeSupported()); - assertEquals("Mismatched values", expected, SecurityUtils.getMinDHGroupExchangeKeySize()); + assertTrue(SecurityUtils.isDHGroupExchangeSupported(), "DH group not supported for key size=" + expected); + assertEquals(expected, SecurityUtils.getMinDHGroupExchangeKeySize(), "Mismatched values"); } @Override diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsTest.java index 0dba74f13..a67168a61 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsTest.java @@ -46,18 +46,22 @@ import org.apache.sshd.common.keyprovider.FileKeyPairProvider; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.io.resource.PathResource; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") @SuppressWarnings("checkstyle:MethodCount") public class SecurityUtilsTest extends SecurityUtilsTestSupport { private static final String DEFAULT_PASSWORD = "super secret passphrase"; @@ -68,12 +72,12 @@ public SecurityUtilsTest() { } @Test - public void testLoadEncryptedDESPrivateKey() throws Exception { + void loadEncryptedDESPrivateKey() throws Exception { testLoadEncryptedRSAPrivateKey("DES-EDE3"); } @Test - public void testLoadEncryptedAESPrivateKey() { + void loadEncryptedAESPrivateKey() { for (BuiltinCiphers c : new BuiltinCiphers[] { BuiltinCiphers.aes128cbc, BuiltinCiphers.aes192cbc, BuiltinCiphers.aes256cbc }) { @@ -95,12 +99,12 @@ private KeyPair testLoadEncryptedRSAPrivateKey(String algorithm) throws Exceptio } @Test - public void testLoadUnencryptedRSAPrivateKey() throws Exception { + void loadUnencryptedRSAPrivateKey() throws Exception { testLoadRSAPrivateKey(getClass().getSimpleName() + "-RSA-KeyPair"); } @Test - public void testLoadUnencryptedDSSPrivateKey() throws Exception { + void loadUnencryptedDSSPrivateKey() throws Exception { testLoadDSSPrivateKey(getClass().getSimpleName() + "-DSA-KeyPair"); } @@ -109,8 +113,8 @@ private KeyPair testLoadDSSPrivateKey(String name) throws Exception { } @Test - public void testLoadUnencryptedECPrivateKey() throws Exception { - Assume.assumeTrue("EC not supported", SecurityUtils.isECCSupported()); + void loadUnencryptedECPrivateKey() throws Exception { + Assumptions.assumeTrue(SecurityUtils.isECCSupported(), "EC not supported"); for (ECCurves c : ECCurves.VALUES) { if (!c.isSupported()) { System.out.println("Skip unsupported curve: " + c.getName()); @@ -138,16 +142,16 @@ private KeyPair testLoadPrivateKey( if (SecurityUtils.isBouncyCastleRegistered()) { KeyPairResourceLoader bcLoader = SecurityUtils.getBouncycastleKeyPairResourceParser(); Collection kpList = bcLoader.loadKeyPairs(null, file, TEST_PASSWORD_PROVIDER); - assertEquals(name + ": Mismatched loaded BouncyCastle keys count", 1, GenericUtils.size(kpList)); + assertEquals(1, GenericUtils.size(kpList), name + ": Mismatched loaded BouncyCastle keys count"); KeyPair kpBC = GenericUtils.head(kpList); - assertTrue(name + ": Mismatched BouncyCastle vs. file values", KeyUtils.compareKeyPairs(kpFile, kpBC)); + assertTrue(KeyUtils.compareKeyPairs(kpFile, kpBC), name + ": Mismatched BouncyCastle vs. file values"); } Class clazz = getClass(); Package pkg = clazz.getPackage(); KeyPair kpResource = testLoadPrivateKeyResource(pkg.getName().replace('.', '/') + "/" + name, pubType, prvType); - assertTrue(name + ": Mismatched key file vs. resource values", KeyUtils.compareKeyPairs(kpFile, kpResource)); + assertTrue(KeyUtils.compareKeyPairs(kpFile, kpResource), name + ": Mismatched key file vs. resource values"); validateKeyPairSignable(name, kpResource); return kpResource; } @@ -177,24 +181,24 @@ private static KeyPair testLoadPrivateKey( pairs.add(kp); } - assertEquals("Mismatched loaded pairs count for " + resourceKey, 1, pairs.size()); + assertEquals(1, pairs.size(), "Mismatched loaded pairs count for " + resourceKey); KeyPair kp = pairs.get(0); PublicKey pub = kp.getPublic(); - assertNotNull("No public key extracted", pub); - assertTrue("Not an " + pubType.getSimpleName() + " public key for " + resourceKey, - pubType.isAssignableFrom(pub.getClass())); + assertNotNull(pub, "No public key extracted"); + assertTrue(pubType.isAssignableFrom(pub.getClass()), + "Not an " + pubType.getSimpleName() + " public key for " + resourceKey); PrivateKey prv = kp.getPrivate(); - assertNotNull("No private key extracted", prv); - assertTrue("Not an " + prvType.getSimpleName() + " private key for " + resourceKey, - prvType.isAssignableFrom(prv.getClass())); + assertNotNull(prv, "No private key extracted"); + assertTrue(prvType.isAssignableFrom(prv.getClass()), + "Not an " + prvType.getSimpleName() + " private key for " + resourceKey); return kp; } @Test - public void testSetMaxDHGroupExchangeKeySizeByProperty() { + void setMaxDHGroupExchangeKeySizeByProperty() { try { for (int expected = SecurityUtils.MIN_DHGEX_KEY_SIZE; expected <= SecurityUtils.MAX_DHGEX_KEY_SIZE; @@ -202,8 +206,8 @@ public void testSetMaxDHGroupExchangeKeySizeByProperty() { SecurityUtils.setMaxDHGroupExchangeKeySize(0); // force detection try { System.setProperty(SecurityUtils.MAX_DHGEX_KEY_SIZE_PROP, Integer.toString(expected)); - assertTrue("DH group not supported for key size=" + expected, SecurityUtils.isDHGroupExchangeSupported()); - assertEquals("Mismatched values", expected, SecurityUtils.getMaxDHGroupExchangeKeySize()); + assertTrue(SecurityUtils.isDHGroupExchangeSupported(), "DH group not supported for key size=" + expected); + assertEquals(expected, SecurityUtils.getMaxDHGroupExchangeKeySize(), "Mismatched values"); } finally { System.clearProperty(SecurityUtils.MAX_DHGEX_KEY_SIZE_PROP); } @@ -215,14 +219,14 @@ public void testSetMaxDHGroupExchangeKeySizeByProperty() { } @Test - public void testSetMaxDHGroupExchangeKeySizeProgrammatically() { + void setMaxDHGroupExchangeKeySizeProgrammatically() { try { for (int expected = SecurityUtils.MIN_DHGEX_KEY_SIZE; expected <= SecurityUtils.MAX_DHGEX_KEY_SIZE; expected += 1024) { SecurityUtils.setMaxDHGroupExchangeKeySize(expected); - assertTrue("DH group not supported for key size=" + expected, SecurityUtils.isDHGroupExchangeSupported()); - assertEquals("Mismatched values", expected, SecurityUtils.getMaxDHGroupExchangeKeySize()); + assertTrue(SecurityUtils.isDHGroupExchangeSupported(), "DH group not supported for key size=" + expected); + assertEquals(expected, SecurityUtils.getMaxDHGroupExchangeKeySize(), "Mismatched values"); } } finally { SecurityUtils.setMinDHGroupExchangeKeySize(0); // force detection diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsTestSupport.java b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsTestSupport.java index 84a6c0425..5fc8b8396 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsTestSupport.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/security/SecurityUtilsTestSupport.java @@ -20,8 +20,8 @@ package org.apache.sshd.common.util.security; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; /** * @author Apache MINA SSHD Project @@ -36,12 +36,12 @@ protected SecurityUtilsTestSupport() { } // NOTE: Using the BouncyCastle provider instead of the name does not work as expected so we take no chances - @BeforeClass + @BeforeAll public static void useNamedBouncyCastleProvider() { System.setProperty(BC_NAMED_USAGE_PROP, Boolean.TRUE.toString()); } - @AfterClass + @AfterAll public static void unsetBouncyCastleProviderUsagePreference() { System.clearProperty(BC_NAMED_USAGE_PROP); } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/security/bouncycastle/BouncyCastleGeneratorHostKeyProviderTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/security/bouncycastle/BouncyCastleGeneratorHostKeyProviderTest.java index bbc21fc41..4cc546f01 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/security/bouncycastle/BouncyCastleGeneratorHostKeyProviderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/security/bouncycastle/BouncyCastleGeneratorHostKeyProviderTest.java @@ -37,35 +37,30 @@ import org.apache.sshd.common.keyprovider.KeyPairProvider; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.server.keyprovider.AbstractGeneratorHostKeyProvider; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class BouncyCastleGeneratorHostKeyProviderTest extends JUnitTestSupport { - private final String keyType; - private final int keySize; + private String keyType; + private int keySize; - public BouncyCastleGeneratorHostKeyProviderTest(String keyType, int keySize) { + public void initBouncyCastleGeneratorHostKeyProviderTest(String keyType, int keySize) { this.keyType = keyType; this.keySize = keySize; } - @Parameters(name = "{0} / {1}") public static List parameters() { if (!SecurityUtils.isBouncyCastleRegistered()) { return Collections.emptyList(); @@ -87,8 +82,10 @@ public static List parameters() { return params; } - @Test - public void testKeyReadWrite() throws IOException, GeneralSecurityException { + @MethodSource("parameters") + @ParameterizedTest(name = "{0} / {1}") + public void keyReadWrite(String keyType, int keySize) throws IOException, GeneralSecurityException { + initBouncyCastleGeneratorHostKeyProviderTest(keyType, keySize); KeyPair expected; if (BuiltinIdentities.Constants.RSA.equalsIgnoreCase(keyType)) { expected = KeyUtils.generateKeyPair(KeyPairProvider.SSH_RSA, keySize); @@ -96,7 +93,7 @@ public void testKeyReadWrite() throws IOException, GeneralSecurityException { expected = KeyUtils.generateKeyPair(KeyPairProvider.SSH_DSS, keySize); } else if (BuiltinIdentities.Constants.ECDSA.equalsIgnoreCase(keyType)) { ECCurves curve = ECCurves.fromCurveSize(keySize); - assertNotNull("No curve for key size=" + keySize, curve); + assertNotNull(curve, "No curve for key size=" + keySize); expected = KeyUtils.generateKeyPair(curve.getKeyType(), curve.getKeySize()); } else if (BuiltinIdentities.Constants.ED25519.equalsIgnoreCase(keyType)) { KeyPairGenerator g = SecurityUtils.getKeyPairGenerator(SecurityUtils.EDDSA); @@ -124,7 +121,7 @@ public void testKeyReadWrite() throws IOException, GeneralSecurityException { Iterable keys = provider.loadKeys(null); KeyPair actual = null; for (KeyPair k : keys) { - assertNull("Unexpected multiple keys loaded", actual); + assertNull(actual, "Unexpected multiple keys loaded"); actual = k; } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/EDDSAProviderTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/EDDSAProviderTest.java index 1dfafc2fa..c566ade7e 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/EDDSAProviderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/EDDSAProviderTest.java @@ -34,19 +34,22 @@ import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class EDDSAProviderTest extends JUnitTestSupport { private static KeyPair keyPair; @@ -54,30 +57,30 @@ public EDDSAProviderTest() { super(); } - @BeforeClass - public static void checkProviderSupported() throws GeneralSecurityException { - Assume.assumeTrue(SecurityUtils.EDDSA + " not supported", SecurityUtils.isEDDSACurveSupported()); + @BeforeAll + static void checkProviderSupported() throws GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isEDDSACurveSupported(), SecurityUtils.EDDSA + " not supported"); KeyPairGenerator g = SecurityUtils.getKeyPairGenerator(SecurityUtils.EDDSA); - assertNotNull("No generator instance", g); + assertNotNull(g, "No generator instance"); keyPair = g.generateKeyPair(); - assertNotNull("No key pair generated", keyPair); + assertNotNull(keyPair, "No key pair generated"); PublicKey pubKey = keyPair.getPublic(); - assertNotNull("No public key", pubKey); - assertEquals("Mismatched public key algorithm", SecurityUtils.EDDSA, pubKey.getAlgorithm()); - assertEquals("Mismatched public key type", KeyPairProvider.SSH_ED25519, KeyUtils.getKeyType(pubKey)); + assertNotNull(pubKey, "No public key"); + assertEquals(SecurityUtils.EDDSA, pubKey.getAlgorithm(), "Mismatched public key algorithm"); + assertEquals(KeyPairProvider.SSH_ED25519, KeyUtils.getKeyType(pubKey), "Mismatched public key type"); PrivateKey prvKey = keyPair.getPrivate(); - assertNotNull("No private key", prvKey); - assertEquals("Mismatched key-pair algorithm", pubKey.getAlgorithm(), prvKey.getAlgorithm()); - assertEquals("Mismatched private key type", KeyPairProvider.SSH_ED25519, KeyUtils.getKeyType(prvKey)); + assertNotNull(prvKey, "No private key"); + assertEquals(pubKey.getAlgorithm(), prvKey.getAlgorithm(), "Mismatched key-pair algorithm"); + assertEquals(KeyPairProvider.SSH_ED25519, KeyUtils.getKeyType(prvKey), "Mismatched private key type"); } @Test - public void testSignature() throws GeneralSecurityException { + void signature() throws GeneralSecurityException { Signature s = SecurityUtils.getSignature(EdDSAEngine.SIGNATURE_ALGORITHM); - assertNotNull("No signature instance", s); + assertNotNull(s, "No signature instance"); s.initSign(keyPair.getPrivate()); byte[] data = (getClass().getName() + "#" + getCurrentTestName()).getBytes(StandardCharsets.UTF_8); @@ -87,39 +90,39 @@ public void testSignature() throws GeneralSecurityException { s = SecurityUtils.getSignature(EdDSAEngine.SIGNATURE_ALGORITHM); s.initVerify(keyPair.getPublic()); s.update(data); - assertTrue("Failed to verify", s.verify(signed)); + assertTrue(s.verify(signed), "Failed to verify"); } @Test - public void testPublicKeyEntryDecoder() throws IOException, GeneralSecurityException { + void publicKeyEntryDecoder() throws IOException, GeneralSecurityException { String comment = getCurrentTestName() + "@" + getClass().getSimpleName(); String expected = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIGPKSUTyz1HwHReFVvD5obVsALAgJRNarH4TRpNePnAS " + comment; AuthorizedKeyEntry keyEntry = AuthorizedKeyEntry.parseAuthorizedKeyEntry(expected); - assertNotNull("No extracted key entry", keyEntry); + assertNotNull(keyEntry, "No extracted key entry"); - assertEquals("Mismatched key type", KeyPairProvider.SSH_ED25519, keyEntry.getKeyType()); - assertEquals("Mismatched comment", comment, keyEntry.getComment()); + assertEquals(KeyPairProvider.SSH_ED25519, keyEntry.getKeyType(), "Mismatched key type"); + assertEquals(comment, keyEntry.getComment(), "Mismatched comment"); StringBuilder sb = new StringBuilder(expected.length()); PublicKey pubKey = keyEntry.appendPublicKey(null, sb, null); - assertEquals("Mismatched encoded result", expected, sb.toString()); + assertEquals(expected, sb.toString(), "Mismatched encoded result"); testPublicKeyRecovery(pubKey); } @Test - public void testGeneratedPublicKeyRecovery() throws IOException, GeneralSecurityException { + void generatedPublicKeyRecovery() throws IOException, GeneralSecurityException { testPublicKeyRecovery(keyPair.getPublic()); } private void testPublicKeyRecovery(PublicKey pubKey) throws IOException, GeneralSecurityException { - assertNotNull("No public key generated", pubKey); - assertEquals("Mismatched public key algorithm", SecurityUtils.EDDSA, pubKey.getAlgorithm()); + assertNotNull(pubKey, "No public key generated"); + assertEquals(SecurityUtils.EDDSA, pubKey.getAlgorithm(), "Mismatched public key algorithm"); ByteArrayBuffer buf = new ByteArrayBuffer(); buf.putRawPublicKey(pubKey); PublicKey actual = buf.getRawPublicKey(); - assertEquals("Mismatched key algorithm", pubKey.getAlgorithm(), actual.getAlgorithm()); - assertEquals("Mismatched recovered key", pubKey, actual); + assertEquals(pubKey.getAlgorithm(), actual.getAlgorithm(), "Mismatched key algorithm"); + assertEquals(pubKey, actual, "Mismatched recovered key"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/Ed25519VectorsTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/Ed25519VectorsTest.java index 1009e8f07..8b42895ce 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/Ed25519VectorsTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/Ed25519VectorsTest.java @@ -32,38 +32,34 @@ import org.apache.sshd.common.signature.Signature; import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project * @see EdDSA and Ed25519 * draft-josefsson-eddsa-ed25519-02 - section 6 - Test Vectors for Ed25519 */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class Ed25519VectorsTest extends JUnitTestSupport { - private final byte[] prvBytes; - private final PrivateKey privateKey; - private final byte[] pubBytes; - private final PublicKey publicKey; - private final byte[] msgBytes; - private final byte[] expSignature; - - public Ed25519VectorsTest(String name, String prvKey, String pubKey, String msg, String signature) + private byte[] prvBytes; + private PrivateKey privateKey; + private byte[] pubBytes; + private PublicKey publicKey; + private byte[] msgBytes; + private byte[] expSignature; + + public void initEd25519VectorsTest(String name, String prvKey, String pubKey, String msg, String signature) throws GeneralSecurityException { prvBytes = BufferUtils.decodeHex(BufferUtils.EMPTY_HEX_SEPARATOR, prvKey); privateKey = EdDSASecurityProviderUtils.generateEDDSAPrivateKey(prvBytes.clone()); @@ -73,7 +69,6 @@ public Ed25519VectorsTest(String name, String prvKey, String pubKey, String msg, expSignature = BufferUtils.decodeHex(BufferUtils.EMPTY_HEX_SEPARATOR, signature); } - @Parameters(name = "{0}") @SuppressWarnings("checkstyle:anoninnerlength") public static List parameters() { return new ArrayList<>( @@ -183,39 +178,48 @@ public static List parameters() { })); } - @BeforeClass - public static void checkEDDSASupported() { - Assume.assumeTrue("EDDSA N/A", SecurityUtils.isEDDSACurveSupported()); + @BeforeAll + static void checkEDDSASupported() { + Assumptions.assumeTrue(SecurityUtils.isEDDSACurveSupported(), "EDDSA N/A"); } - @Test - public void testPublicKeyBytes() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void publicKeyBytes(String name, String prvKey, String pubKey, String msg, String signature) throws Exception { + initEd25519VectorsTest(name, prvKey, pubKey, msg, signature); byte[] publicSeed = Ed25519PublicKeyDecoder.getSeedValue((EdDSAPublicKey) publicKey); - assertArrayEquals("Mismatched public seed value", pubBytes, publicSeed); + assertArrayEquals(pubBytes, publicSeed, "Mismatched public seed value"); } - @Test - public void testPrivateKeyBytes() { - assertArrayEquals("Mismatched private seed value", prvBytes, ((EdDSAPrivateKey) privateKey).getSeed()); + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void privateKeyBytes(String name, String prvKey, String pubKey, String msg, String signature) throws Exception { + initEd25519VectorsTest(name, prvKey, pubKey, msg, signature); + assertArrayEquals(prvBytes, ((EdDSAPrivateKey) privateKey).getSeed(), "Mismatched private seed value"); } - @Test - public void testSignature() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void signature(String name, String prvKey, String pubKey, String msg, String signature) throws Exception { + initEd25519VectorsTest(name, prvKey, pubKey, msg, signature); Signature signer = EdDSASecurityProviderUtils.getEDDSASignature(); signer.initSigner(null, privateKey); signer.update(null, msgBytes.clone()); byte[] actSignature = signer.sign(null); - assertArrayEquals("Mismatched signature", expSignature, actSignature); + assertArrayEquals(expSignature, actSignature, "Mismatched signature"); Signature verifier = EdDSASecurityProviderUtils.getEDDSASignature(); verifier.initVerifier(null, publicKey); verifier.update(null, msgBytes.clone()); - assertTrue("Verification failed", verifier.verify(null, expSignature)); + assertTrue(verifier.verify(null, expSignature), "Verification failed"); } - @Test - public void testPartialBufferSignature() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void partialBufferSignature(String name, String prvKey, String pubKey, String msg, String signature) + throws Exception { + initEd25519VectorsTest(name, prvKey, pubKey, msg, signature); byte[] extraData = getCurrentTestName().getBytes(StandardCharsets.UTF_8); byte[] dataBuf = new byte[msgBytes.length + extraData.length]; int offset = extraData.length / 2; @@ -228,11 +232,11 @@ public void testPartialBufferSignature() throws Exception { signer.update(null, dataBuf.clone(), offset, msgBytes.length); byte[] actSignature = signer.sign(null); - assertArrayEquals("Mismatched signature", expSignature, actSignature); + assertArrayEquals(expSignature, actSignature, "Mismatched signature"); Signature verifier = EdDSASecurityProviderUtils.getEDDSASignature(); verifier.initVerifier(null, publicKey); verifier.update(null, dataBuf.clone(), offset, msgBytes.length); - assertTrue("Verification failed", verifier.verify(null, expSignature)); + assertTrue(verifier.verify(null, expSignature), "Verification failed"); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/EdDSASecurityProviderRegistrarTest.java b/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/EdDSASecurityProviderRegistrarTest.java index 075127b8a..0d76789e0 100644 --- a/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/EdDSASecurityProviderRegistrarTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/common/util/security/eddsa/EdDSASecurityProviderRegistrarTest.java @@ -30,19 +30,22 @@ import org.apache.sshd.common.util.security.SecurityProviderRegistrar; import org.apache.sshd.common.util.security.SecurityProviderRegistrarTestSupport; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class EdDSASecurityProviderRegistrarTest extends SecurityProviderRegistrarTestSupport { private static SecurityProviderRegistrar registrarInstance; @@ -50,14 +53,14 @@ public EdDSASecurityProviderRegistrarTest() { super(); } - @BeforeClass - public static void checkEDDSASupported() { - Assume.assumeTrue(SecurityUtils.isEDDSACurveSupported()); + @BeforeAll + static void checkEDDSASupported() { + Assumptions.assumeTrue(SecurityUtils.isEDDSACurveSupported()); registrarInstance = new EdDSASecurityProviderRegistrar(); } @Test - public void testSupportedSecurityEntities() { + void supportedSecurityEntities() { assertSecurityEntitySupportState(getCurrentTestName(), registrarInstance, true, registrarInstance.getName(), KeyPairGenerator.class, KeyFactory.class); assertSecurityEntitySupportState(getCurrentTestName(), registrarInstance, true, @@ -69,21 +72,21 @@ public void testSupportedSecurityEntities() { if (supported.contains(entity)) { continue; } - assertFalse("Unexpected support for " + entity.getSimpleName(), - registrarInstance.isSecurityEntitySupported(entity, registrarInstance.getName())); + assertFalse(registrarInstance.isSecurityEntitySupported(entity, registrarInstance.getName()), + "Unexpected support for " + entity.getSimpleName()); } } @Test - public void testGetSecurityProvider() { + void getSecurityProvider() { Provider expected = registrarInstance.getSecurityProvider(); - assertNotNull("No provider created", expected); - assertEquals("Mismatched provider name", registrarInstance.getName(), expected.getName()); + assertNotNull(expected, "No provider created"); + assertEquals(registrarInstance.getName(), expected.getName(), "Mismatched provider name"); assertObjectInstanceOf("Mismatched provider type", EdDSASecurityProvider.class, expected); } @Test - public void testGetSecurityProviderCaching() { + void getSecurityProviderCaching() { testGetSecurityProviderCaching(getCurrentTestName(), registrarInstance); } } diff --git a/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/AbstractGeneratorHostKeyProviderTest.java b/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/AbstractGeneratorHostKeyProviderTest.java index fe5c38eed..67fc003f7 100644 --- a/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/AbstractGeneratorHostKeyProviderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/AbstractGeneratorHostKeyProviderTest.java @@ -30,14 +30,15 @@ import org.apache.sshd.common.NamedResource; import org.apache.sshd.common.session.SessionContext; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class AbstractGeneratorHostKeyProviderTest extends JUnitTestSupport { public AbstractGeneratorHostKeyProviderTest() { super(); @@ -45,19 +46,19 @@ public AbstractGeneratorHostKeyProviderTest() { @Test @SuppressWarnings("synthetic-access") - public void testOverwriteKey() throws Exception { + void overwriteKey() throws Exception { Path tempDir = assertHierarchyTargetFolderExists(getTempTargetFolder()); Path keyPairFile = tempDir.resolve(getCurrentTestName() + ".key"); Files.deleteIfExists(keyPairFile); TestProvider provider = new TestProvider(keyPairFile); provider.loadKeys(null); - assertEquals("Mismatched generate write count", 1, provider.getWriteCount()); + assertEquals(1, provider.getWriteCount(), "Mismatched generate write count"); provider = new TestProvider(keyPairFile); provider.setOverwriteAllowed(false); provider.loadKeys(null); - assertEquals("Mismatched load write count", 0, provider.getWriteCount()); + assertEquals(0, provider.getWriteCount(), "Mismatched load write count"); } private static final class TestProvider extends AbstractGeneratorHostKeyProvider { diff --git a/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java b/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java index 42a0f020c..345ab53e6 100644 --- a/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java @@ -34,58 +34,60 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PEMGeneratorHostKeyProviderTest extends JUnitTestSupport { public PEMGeneratorHostKeyProviderTest() { super(); } @Test - public void testDSA() throws IOException, GeneralSecurityException { - Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); + void dsa() throws IOException, GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BouncyCastle not registered"); testPEMGeneratorHostKeyProvider(KeyUtils.DSS_ALGORITHM, KeyPairProvider.SSH_DSS, 512, null); } @Test - public void testRSA() throws IOException, GeneralSecurityException { - Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); + void rsa() throws IOException, GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BouncyCastle not registered"); testPEMGeneratorHostKeyProvider(KeyUtils.RSA_ALGORITHM, KeyPairProvider.SSH_RSA, 512, null); } @Test - public void testECnistp256() throws IOException, GeneralSecurityException { - Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); - Assume.assumeTrue("ECC not supported", SecurityUtils.isECCSupported()); - Assume.assumeTrue(ECCurves.nistp256 + " N/A", ECCurves.nistp256.isSupported()); + void eCnistp256() throws IOException, GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BouncyCastle not registered"); + Assumptions.assumeTrue(SecurityUtils.isECCSupported(), "ECC not supported"); + Assumptions.assumeTrue(ECCurves.nistp256.isSupported(), ECCurves.nistp256 + " N/A"); testPEMGeneratorHostKeyProvider(KeyUtils.EC_ALGORITHM, KeyPairProvider.ECDSA_SHA2_NISTP256, -1, new ECGenParameterSpec("prime256v1")); } @Test - public void testECnistp384() throws IOException, GeneralSecurityException { - Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); - Assume.assumeTrue("ECC not supported", SecurityUtils.isECCSupported()); - Assume.assumeTrue(ECCurves.nistp384 + " N/A", ECCurves.nistp384.isSupported()); + void eCnistp384() throws IOException, GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BouncyCastle not registered"); + Assumptions.assumeTrue(SecurityUtils.isECCSupported(), "ECC not supported"); + Assumptions.assumeTrue(ECCurves.nistp384.isSupported(), ECCurves.nistp384 + " N/A"); testPEMGeneratorHostKeyProvider(KeyUtils.EC_ALGORITHM, KeyPairProvider.ECDSA_SHA2_NISTP384, -1, new ECGenParameterSpec("P-384")); } @Test - public void testECnistp521() throws IOException, GeneralSecurityException { - Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); - Assume.assumeTrue("ECC not supported", SecurityUtils.isECCSupported()); - Assume.assumeTrue(ECCurves.nistp521 + " N/A", ECCurves.nistp521.isSupported()); + void eCnistp521() throws IOException, GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BouncyCastle not registered"); + Assumptions.assumeTrue(SecurityUtils.isECCSupported(), "ECC not supported"); + Assumptions.assumeTrue(ECCurves.nistp521.isSupported(), ECCurves.nistp521 + " N/A"); testPEMGeneratorHostKeyProvider(KeyUtils.EC_ALGORITHM, KeyPairProvider.ECDSA_SHA2_NISTP521, -1, new ECGenParameterSpec("P-521")); } @@ -95,7 +97,7 @@ private Path testPEMGeneratorHostKeyProvider( throws IOException, GeneralSecurityException { Path path = initKeyFileLocation(algorithm); KeyPair kpWrite = invokePEMGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec); - assertTrue("Key file not generated: " + path, Files.exists(path, IoUtils.EMPTY_LINK_OPTIONS)); + assertTrue(Files.exists(path, IoUtils.EMPTY_LINK_OPTIONS), "Key file not generated: " + path); KeyPair kpRead = invokePEMGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec); PublicKey pubWrite = kpWrite.getPublic(); @@ -134,12 +136,12 @@ private static KeyPair validateKeyPairProvider(KeyPairProvider provider, String for (String type : types) { if (keyType.equals(type)) { kp = provider.loadKey(null, keyType); - assertNotNull("Failed to load key for " + keyType, kp); + assertNotNull(kp, "Failed to load key for " + keyType); break; } } - assertNotNull("Expected key type not found: " + keyType, kp); + assertNotNull(kp, "Expected key type not found: " + keyType); return kp; } diff --git a/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java b/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java index 55c3064b2..48533185c 100644 --- a/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java @@ -33,65 +33,65 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") +@SuppressWarnings("checksyle:MethodCount") public class SimpleGeneratorHostKeyProviderTest extends JUnitTestSupport { - public SimpleGeneratorHostKeyProviderTest() { - super(); - } @Test - public void testDSA() throws IOException, GeneralSecurityException { + void dsa() throws IOException, GeneralSecurityException { testSimpleGeneratorHostKeyProvider(KeyUtils.DSS_ALGORITHM, KeyPairProvider.SSH_DSS, 512, null); } @Test - public void testRSA() throws IOException, GeneralSecurityException { + void rsa() throws IOException, GeneralSecurityException { testSimpleGeneratorHostKeyProvider(KeyUtils.RSA_ALGORITHM, KeyPairProvider.SSH_RSA, 512, null); } @Test - public void testECnistp256() throws IOException, GeneralSecurityException { - Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); - Assume.assumeTrue("ECC not supported", SecurityUtils.isECCSupported()); - Assume.assumeTrue(ECCurves.nistp256 + " N/A", ECCurves.nistp256.isSupported()); + void eCnistp256() throws IOException, GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BouncyCastle not registered"); + Assumptions.assumeTrue(SecurityUtils.isECCSupported(), "ECC not supported"); + Assumptions.assumeTrue(ECCurves.nistp256.isSupported(), ECCurves.nistp256 + " N/A"); testSimpleGeneratorHostKeyProvider(KeyUtils.EC_ALGORITHM, KeyPairProvider.ECDSA_SHA2_NISTP256, -1, new ECGenParameterSpec("prime256v1")); } @Test - public void testECnistp384() throws IOException, GeneralSecurityException { - Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); - Assume.assumeTrue("ECC not supported", SecurityUtils.isECCSupported()); - Assume.assumeTrue(ECCurves.nistp384 + " N/A", ECCurves.nistp384.isSupported()); + void eCnistp384() throws IOException, GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BouncyCastle not registered"); + Assumptions.assumeTrue(SecurityUtils.isECCSupported(), "ECC not supported"); + Assumptions.assumeTrue(ECCurves.nistp384.isSupported(), ECCurves.nistp384 + " N/A"); testSimpleGeneratorHostKeyProvider(KeyUtils.EC_ALGORITHM, KeyPairProvider.ECDSA_SHA2_NISTP384, -1, new ECGenParameterSpec("P-384")); } @Test - public void testECnistp521() throws IOException, GeneralSecurityException { - Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); - Assume.assumeTrue("ECC not supported", SecurityUtils.isECCSupported()); - Assume.assumeTrue(ECCurves.nistp521 + " N/A", ECCurves.nistp521.isSupported()); + void eCnistp521() throws IOException, GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BouncyCastle not registered"); + Assumptions.assumeTrue(SecurityUtils.isECCSupported(), "ECC not supported"); + Assumptions.assumeTrue(ECCurves.nistp521.isSupported(), ECCurves.nistp521 + " N/A"); testSimpleGeneratorHostKeyProvider(KeyUtils.EC_ALGORITHM, KeyPairProvider.ECDSA_SHA2_NISTP521, -1, new ECGenParameterSpec("P-521")); } @Test - public void testEdDSA() throws IOException, GeneralSecurityException { - Assume.assumeTrue("EdDSA not supported", SecurityUtils.isEDDSACurveSupported()); + void edDSA() throws IOException, GeneralSecurityException { + Assumptions.assumeTrue(SecurityUtils.isEDDSACurveSupported(), "EdDSA not supported"); testSimpleGeneratorHostKeyProvider(SecurityUtils.EDDSA, KeyPairProvider.SSH_ED25519, -1, null); } @@ -100,7 +100,7 @@ private void testSimpleGeneratorHostKeyProvider( throws IOException, GeneralSecurityException { Path path = initKeyFileLocation(algorithm); KeyPair kpWrite = invokeSimpleGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec); - assertTrue("Key file not generated: " + path, Files.exists(path, IoUtils.EMPTY_LINK_OPTIONS)); + assertTrue(Files.exists(path, IoUtils.EMPTY_LINK_OPTIONS), "Key file not generated: " + path); KeyPair kpRead = invokeSimpleGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec); assertKeyPairEquals("Mismatched write/read key pairs", kpWrite, kpRead); @@ -141,12 +141,12 @@ private static KeyPair validateKeyPairProvider( for (String type : types) { if (keyType.equals(type)) { kp = provider.loadKey(null, keyType); - assertNotNull("Failed to load key for " + keyType, kp); + assertNotNull(kp, "Failed to load key for " + keyType); break; } } - assertNotNull("Expected key type not found: " + keyType, kp); + assertNotNull(kp, "Expected key type not found: " + keyType); return kp; } diff --git a/sshd-common/src/test/java/org/apache/sshd/server/shell/TtyFilterInputStreamTest.java b/sshd-common/src/test/java/org/apache/sshd/server/shell/TtyFilterInputStreamTest.java index 1cde70f46..f5c4815ce 100644 --- a/sshd-common/src/test/java/org/apache/sshd/server/shell/TtyFilterInputStreamTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/server/shell/TtyFilterInputStreamTest.java @@ -40,43 +40,44 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.common.util.io.IoUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class TtyFilterInputStreamTest extends JUnitTestSupport { private static final List MODES = Collections.unmodifiableList( Stream.concat(Stream.of(PtyMode.ECHO), TtyFilterInputStream.INPUT_OPTIONS.stream()) .collect(Collectors.toList())); - private final PtyMode mode; + private PtyMode mode; + + public TtyFilterInputStreamTest() { + } - public TtyFilterInputStreamTest(PtyMode mode) { + public void initTtyFilterInputStreamTest(PtyMode mode) { this.mode = Objects.requireNonNull(mode, "No test modes"); } - @Parameters(name = "mode={0}") public static Collection parameters() { return parameterize(MODES); } - @Test - public void testCRLFHandling() throws IOException { + @MethodSource("parameters") + @ParameterizedTest(name = "mode={0}") + public void crlfHandling(PtyMode mode) throws IOException { + initTtyFilterInputStreamTest(mode); List lines = Arrays.asList(getClass().getPackage().getName(), getClass().getSimpleName(), getCurrentTestName(), "(" + mode + ")", new Date(System.currentTimeMillis()).toString()); @@ -97,16 +98,18 @@ public void write(int b) throws IOException { } }) { long copySize = IoUtils.copy(tty, output); - assertTrue("Copy size (" + copySize + ") above total length (" + content.length() + ")", - copySize <= content.length()); + assertTrue(copySize <= content.length(), + "Copy size (" + copySize + ") above total length (" + content.length() + ")"); } assertCRLFCounts(mode, lines.size() - 1 /* last line has no NL */, crCount.get(), lfCount.get()); } } - @Test - public void testInternalBufferSizeDoesNotGrow() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "mode={0}") + public void internalBufferSizeDoesNotGrow(PtyMode mode) throws Exception { + initTtyFilterInputStreamTest(mode); try (TtyFilterInputStream is = new TtyFilterInputStream(new InputStream() { int next; @@ -140,20 +143,20 @@ private static void assertCRLFCounts(PtyMode mode, int numLines, int crCount, in case ONLCR: case ONOCR: // No modifications - assertEquals("Mismatched CR count", numLines, crCount); - assertEquals("Mismatched LF count", numLines, lfCount); + assertEquals(numLines, crCount, "Mismatched CR count"); + assertEquals(numLines, lfCount, "Mismatched LF count"); break; case OCRNL: // Translate carriage return to newline - assertEquals("Mismatched CR count", 0, crCount); - assertEquals("Mismatched LF count", 2 * numLines, lfCount); + assertEquals(0, crCount, "Mismatched CR count"); + assertEquals(2 * numLines, lfCount, "Mismatched LF count"); break; case ONLRET: // Newline performs a carriage return - assertEquals("Mismatched CR count", 2 * numLines, crCount); - assertEquals("Mismatched LF count", 0, lfCount); + assertEquals(2 * numLines, crCount, "Mismatched CR count"); + assertEquals(0, lfCount, "Mismatched LF count"); break; default: diff --git a/sshd-common/src/test/java/org/apache/sshd/server/shell/TtyFilterOutputStreamTest.java b/sshd-common/src/test/java/org/apache/sshd/server/shell/TtyFilterOutputStreamTest.java index 9762ffce9..f57f6bcb1 100644 --- a/sshd-common/src/test/java/org/apache/sshd/server/shell/TtyFilterOutputStreamTest.java +++ b/sshd-common/src/test/java/org/apache/sshd/server/shell/TtyFilterOutputStreamTest.java @@ -34,39 +34,39 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.sshd.common.channel.PtyMode; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class TtyFilterOutputStreamTest extends JUnitTestSupport { - private final PtyMode mode; + private PtyMode mode; + + public TtyFilterOutputStreamTest() { + } - public TtyFilterOutputStreamTest(PtyMode mode) { + public void initTtyFilterOutputStreamTest(PtyMode mode) { this.mode = Objects.requireNonNull(mode, "No test modes"); } - @Parameters(name = "mode={0}") public static Collection parameters() { return parameterize(TtyFilterOutputStream.OUTPUT_OPTIONS); } - @Test - public void testCRLFHandling() throws IOException { + @MethodSource("parameters") + @ParameterizedTest(name = "mode={0}") + public void crlfHandling(PtyMode mode) throws IOException { + initTtyFilterOutputStreamTest(mode); List lines = Arrays.asList(getClass().getPackage().getName(), getClass().getSimpleName(), getCurrentTestName(), "(" + mode + ")", new Date(System.currentTimeMillis()).toString()); @@ -98,23 +98,23 @@ public void write(int b) throws IOException { private static void assertCRLFCounts(PtyMode mode, int numLines, int crCount, int lfCount) { switch (mode) { case ECHO: // no modifications - assertEquals("Mismatched CR coumt", numLines, crCount); - assertEquals("Mismatched LF coumt", numLines, lfCount); + assertEquals(numLines, crCount, "Mismatched CR coumt"); + assertEquals(numLines, lfCount, "Mismatched LF coumt"); break; case INLCR: // Map NL into CR - assertEquals("Mismatched CR count", numLines * 2, crCount); - assertEquals("Mismatched LF coumt", 0, lfCount); + assertEquals(numLines * 2, crCount, "Mismatched CR count"); + assertEquals(0, lfCount, "Mismatched LF coumt"); break; case ICRNL: // Map CR to NL on input - assertEquals("Mismatched CR count", 0, crCount); - assertEquals("Mismatched LF coumt", numLines * 2, lfCount); + assertEquals(0, crCount, "Mismatched CR count"); + assertEquals(numLines * 2, lfCount, "Mismatched LF coumt"); break; case IGNCR: // Ignore CR - assertEquals("Mismatched CR count", 0, crCount); - assertEquals("Mismatched LF coumt", numLines, lfCount); + assertEquals(0, crCount, "Mismatched CR count"); + assertEquals(numLines, lfCount, "Mismatched LF coumt"); break; default: diff --git a/sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4ClassRunnerWithParameters.java b/sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4ClassRunnerWithParameters.java deleted file mode 100644 index acf44a575..000000000 --- a/sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4ClassRunnerWithParameters.java +++ /dev/null @@ -1,48 +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.util.test; - -import org.junit.runners.model.InitializationError; -import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters; -import org.junit.runners.parameterized.TestWithParameters; - -/** - * Uses a cached created instance instead of a new one on every call of {@code #createTest()} - * - * @author Apache MINA SSHD Project - */ -public class JUnit4ClassRunnerWithParameters extends BlockJUnit4ClassRunnerWithParameters { - private volatile Object testInstance; - - public JUnit4ClassRunnerWithParameters(TestWithParameters test) throws InitializationError { - super(test); - } - - @Override - public Object createTest() throws Exception { - synchronized (this) { - if (testInstance == null) { - testInstance = super.createTest(); - } - } - - return testInstance; - } -} diff --git a/sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4ClassRunnerWithParametersFactory.java b/sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4ClassRunnerWithParametersFactory.java deleted file mode 100644 index 202846b3b..000000000 --- a/sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4ClassRunnerWithParametersFactory.java +++ /dev/null @@ -1,60 +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.util.test; - -import org.junit.runner.Runner; -import org.junit.runners.model.InitializationError; -import org.junit.runners.parameterized.ParametersRunnerFactory; -import org.junit.runners.parameterized.TestWithParameters; - -/** - * Avoids re-creating a test class instance for each parameterized test method. Usage: - * - *

- * 
- * @FixMethodOrder(MethodSorters.NAME_ASCENDING)
- * @RunWith(Parameterized.class)
- * @UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class)
- * public class MyParameterizedTest {
- *      public MyParameterizedTest(...params...) {
- *          ....
- *      }
- *
- *      @Parameters(...)
- *      public static List parameters() {
- *          ...
- *      }
- * }
- * 
- * 
- * - * @see JUnit4ClassRunnerWithParameters - * @author Apache MINA SSHD Project - */ -public class JUnit4ClassRunnerWithParametersFactory implements ParametersRunnerFactory { - public JUnit4ClassRunnerWithParametersFactory() { - super(); - } - - @Override - public Runner createRunnerForTestWithParameters(TestWithParameters test) throws InitializationError { - return new JUnit4ClassRunnerWithParameters(test); - } -} diff --git a/sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4SingleInstanceClassRunner.java b/sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4SingleInstanceClassRunner.java deleted file mode 100644 index 72cf99aea..000000000 --- a/sshd-common/src/test/java/org/apache/sshd/util/test/JUnit4SingleInstanceClassRunner.java +++ /dev/null @@ -1,54 +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.util.test; - -import java.util.AbstractMap.SimpleImmutableEntry; -import java.util.Map; -import java.util.concurrent.atomic.AtomicReference; - -import org.junit.runners.BlockJUnit4ClassRunner; -import org.junit.runners.model.InitializationError; -import org.junit.runners.model.TestClass; - -/** - * @see SSHD-764 - * @author Apache MINA SSHD Project - */ -public class JUnit4SingleInstanceClassRunner extends BlockJUnit4ClassRunner { - private final AtomicReference, ?>> testHolder = new AtomicReference<>(); - - public JUnit4SingleInstanceClassRunner(Class klass) throws InitializationError { - super(klass); - } - - @Override - protected Object createTest() throws Exception { - Map.Entry, ?> lastTest = testHolder.get(); - Class lastTestClass = (lastTest == null) ? null : lastTest.getKey(); - TestClass curTest = getTestClass(); - Class curTestClass = curTest.getJavaClass(); - if (curTestClass == lastTestClass) { - return lastTest.getValue(); - } - - Object instance = super.createTest(); - testHolder.set(new SimpleImmutableEntry<>(curTestClass, instance)); - return instance; - } -} diff --git a/sshd-common/src/test/java/org/apache/sshd/util/test/JUnitTestSupport.java b/sshd-common/src/test/java/org/apache/sshd/util/test/JUnitTestSupport.java index e3eca3dbc..d736f8464 100644 --- a/sshd-common/src/test/java/org/apache/sshd/util/test/JUnitTestSupport.java +++ b/sshd-common/src/test/java/org/apache/sshd/util/test/JUnitTestSupport.java @@ -23,6 +23,7 @@ import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Field; +import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.file.Files; import java.nio.file.LinkOption; @@ -62,11 +63,10 @@ import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.common.util.logging.LoggingUtils; -import org.junit.Assert; -import org.junit.BeforeClass; -import org.junit.Rule; -import org.junit.rules.TestName; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.TestInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.slf4j.bridge.SLF4JBridgeHandler; @@ -76,8 +76,7 @@ * * @author Apache MINA SSHD Project */ -@RunWith(JUnit4SingleInstanceClassRunner.class) -public abstract class JUnitTestSupport extends Assert { +public abstract class JUnitTestSupport extends Assertions { public static final String TEMP_SUBFOLDER_NAME = "temp"; public static final boolean OUTPUT_DEBUG_MESSAGES = Boolean.parseBoolean(System.getProperty("org.apache.sshd.test.outputDebugMessages", "false")); @@ -92,8 +91,7 @@ public abstract class JUnitTestSupport extends Assert { public static final List RSA_SIZES = Collections.unmodifiableList(Arrays.asList(1024, 2048, 3072, 4096)); public static final List ED25519_SIZES = Collections.unmodifiableList(Arrays.asList(256)); - @Rule - public final TestName testNameHolder = new TestName(); + protected String testNameHolder; private Path targetFolder; private Path tempFolder; @@ -102,7 +100,7 @@ protected JUnitTestSupport() { replaceJULLoggers(); } - @BeforeClass + @BeforeAll public static void setupRootLoggerLevel() { String levelName = System.getProperty( "org.apache.sshd.test.root.log.level", DEFAULT_LOGGING_LEVEL.toString()); @@ -140,7 +138,7 @@ public static ch.qos.logback.classic.Level getRawLoggerLevel(org.slf4j.event.Lev } public final String getCurrentTestName() { - return testNameHolder.getMethodName(); + return testNameHolder; } /** @@ -324,7 +322,7 @@ public static List parameterize(Collection params) { /* ----------------------- Useful extra assertions --------------------- */ public static void assertEquals(String message, boolean expected, boolean actual) { - assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual)); + assertEquals(Boolean.valueOf(expected), Boolean.valueOf(actual), message); } public static void assertEquals(String message, Iterable expected, Iterable actual) { @@ -339,15 +337,15 @@ public static void assertEquals(String message, Iterator expect } for (int index = 0; expected.hasNext(); index++) { - assertTrue(message + "[next actual index=" + index + "]", actual.hasNext()); + assertTrue(actual.hasNext(), message + "[next actual index=" + index + "]"); T expValue = expected.next(); T actValue = actual.next(); - assertEquals(message + "[iterator index=" + index + "]", expValue, actValue); + assertEquals(expValue, actValue, message + "[iterator index=" + index + "]"); } // once expected is exhausted make sure no more actual items left - assertFalse(message + "[non-empty-actual]", actual.hasNext()); + assertFalse(actual.hasNext(), message + "[non-empty-actual]"); } public static void assertFieldsEqual(String extension, T expected, T actual) throws Exception { @@ -361,13 +359,13 @@ public static void assertFieldsEqual(String extension, T expected, T actual) Object expValue = f.get(expected); Object actValue = f.get(actual); - assertEquals(extension + "[" + name + "]", expValue, actValue); + assertEquals(expValue, actValue, extension + "[" + name + "]"); } } public static Path assertHierarchyTargetFolderExists(Path folder, LinkOption... options) throws IOException { if (Files.exists(folder, options)) { - assertTrue("Target is an existing file instead of a folder: " + folder, Files.isDirectory(folder, options)); + assertTrue(Files.isDirectory(folder, options), "Target is an existing file instead of a folder: " + folder); } else { Files.createDirectories(folder); } @@ -377,7 +375,7 @@ public static Path assertHierarchyTargetFolderExists(Path folder, LinkOption... public static void assertFileContentsEquals(String prefix, Path expected, Path actual) throws IOException { long cmpSize = Files.size(expected); - assertEquals(prefix + ": Mismatched file size", cmpSize, Files.size(expected)); + assertEquals(cmpSize, Files.size(expected), prefix + ": Mismatched file size"); try (InputStream expStream = Files.newInputStream(expected); InputStream actStream = Files.newInputStream(actual)) { @@ -389,8 +387,8 @@ public static void assertFileContentsEquals(String prefix, Path expected, Path a int expLen = expStream.read(expData); Arrays.fill(actData, (byte) 0); int actLen = actStream.read(actData); - assertEquals(prefix + ": Mismatched read size at offset=" + offset, expLen, actLen); - assertArrayEquals(prefix + ": Mismatched data at offset=" + offset, expData, actData); + assertEquals(expLen, actLen, prefix + ": Mismatched read size at offset=" + offset); + assertArrayEquals(expData, actData, prefix + ": Mismatched data at offset=" + offset); offset += expLen; } @@ -399,16 +397,16 @@ public static void assertFileContentsEquals(String prefix, Path expected, Path a public static File assertHierarchyTargetFolderExists(File folder) { if (folder.exists()) { - assertTrue("Target is an existing file instead of a folder: " + folder.getAbsolutePath(), folder.isDirectory()); + assertTrue(folder.isDirectory(), "Target is an existing file instead of a folder: " + folder.getAbsolutePath()); } else { - assertTrue("Failed to create hierarchy of " + folder.getAbsolutePath(), folder.mkdirs()); + assertTrue(folder.mkdirs(), "Failed to create hierarchy of " + folder.getAbsolutePath()); } return folder; } public static T assertObjectInstanceOf(String message, Class expected, Object obj) { - assertNotNull(message + " - no actual object", obj); + assertNotNull(obj, message + " - no actual object"); Class actual = obj.getClass(); if (!expected.isAssignableFrom(actual)) { @@ -427,7 +425,7 @@ public static void assertListEquals( String message, List expected, List actual, BiPredicate equator) { int expSize = GenericUtils.size(expected); int actSize = GenericUtils.size(actual); - assertEquals(message + "[size]", expSize, actSize); + assertEquals(expSize, actSize, message + "[size]"); for (int index = 0; index < expSize; index++) { E expValue = expected.get(index); @@ -447,7 +445,7 @@ public static void assertMapEquals( String message, Map expected, Map actual, BiPredicate equator) { int numItems = MapEntryUtils.size(expected); - assertEquals(message + "[size]", numItems, MapEntryUtils.size(actual)); + assertEquals(numItems, MapEntryUtils.size(actual), message + "[size]"); if (numItems > 0) { expected.forEach((key, expValue) -> { @@ -469,14 +467,14 @@ public static void assertKeyEncodingEquals(String message, Key expected, Key act return; } - assertEquals(message + "[format]", expected.getFormat(), actual.getFormat()); - assertArrayEquals(message + "[encoded-data]", expected.getEncoded(), actual.getEncoded()); + assertEquals(expected.getFormat(), actual.getFormat(), message + "[format]"); + assertArrayEquals(expected.getEncoded(), actual.getEncoded(), message + "[encoded-data]"); } public static void assertKeyListEquals( String message, List expected, List actual) { int numKeys = GenericUtils.size(expected); - assertEquals(message + "[size]", numKeys, GenericUtils.size(actual)); + assertEquals(numKeys, GenericUtils.size(actual), message + "[size]"); if (numKeys <= 0) { return; } @@ -491,9 +489,9 @@ public static void assertKeyEquals(String message, T expected, T return; } - assertEquals(message + "[algorithm]", - resolveEffectiveAlgorithm(expected.getAlgorithm()), - resolveEffectiveAlgorithm(actual.getAlgorithm())); + assertEquals(resolveEffectiveAlgorithm(expected.getAlgorithm()), + resolveEffectiveAlgorithm(actual.getAlgorithm()), + message + "[algorithm]"); if (expected instanceof RSAPublicKey) { assertRSAPublicKeyEquals(message, RSAPublicKey.class.cast(expected), RSAPublicKey.class.cast(actual)); @@ -511,10 +509,10 @@ public static void assertKeyEquals(String message, T expected, T } public static KeyPair validateKeyPairSignable(Object hint, KeyPair kp) throws Exception { - assertNotNull(hint + ": no key pair provided", kp); + assertNotNull(kp, hint + ": no key pair provided"); Optional signable = CommonTestSupportUtils.verifySignatureMatch(kp); // if no result then assume "OK" - assertTrue(hint + ": Failed to validate signature", signable.orElse(Boolean.TRUE)); + assertTrue(signable.orElse(Boolean.TRUE), hint + ": Failed to validate signature"); return kp; } @@ -533,8 +531,8 @@ public static void assertRSAPublicKeyEquals(String message, RSAPublicKey expecte return; } - assertEquals(message + "[e]", expected.getPublicExponent(), actual.getPublicExponent()); - assertEquals(message + "[n]", expected.getModulus(), actual.getModulus()); + assertEquals(expected.getPublicExponent(), actual.getPublicExponent(), message + "[e]"); + assertEquals(expected.getModulus(), actual.getModulus(), message + "[n]"); } public static void assertDSAPublicKeyEquals(String message, DSAPublicKey expected, DSAPublicKey actual) { @@ -542,7 +540,7 @@ public static void assertDSAPublicKeyEquals(String message, DSAPublicKey expecte return; } - assertEquals(message + "[y]", expected.getY(), actual.getY()); + assertEquals(expected.getY(), actual.getY(), message + "[y]"); assertDSAParamsEquals(message + "[params]", expected.getParams(), actual.getParams()); } @@ -560,8 +558,8 @@ public static void assertRSAPrivateKeyEquals(String message, RSAPrivateKey expec return; } - assertEquals(message + "[d]", expected.getPrivateExponent(), actual.getPrivateExponent()); - assertEquals(message + "[n]", expected.getModulus(), actual.getModulus()); + assertEquals(expected.getPrivateExponent(), actual.getPrivateExponent(), message + "[d]"); + assertEquals(expected.getModulus(), actual.getModulus(), message + "[n]"); } public static void assertDSAPrivateKeyEquals(String message, DSAPrivateKey expected, DSAPrivateKey actual) { @@ -569,7 +567,7 @@ public static void assertDSAPrivateKeyEquals(String message, DSAPrivateKey expec return; } - assertEquals(message + "[x]", expected.getX(), actual.getX()); + assertEquals(expected.getX(), actual.getX(), message + "[x]"); assertDSAParamsEquals(message + "[params]", expected.getParams(), actual.getParams()); } @@ -578,9 +576,9 @@ public static void assertDSAParamsEquals(String message, DSAParams expected, DSA return; } - assertEquals(message + "[g]", expected.getG(), actual.getG()); - assertEquals(message + "[p]", expected.getP(), actual.getP()); - assertEquals(message + "[q]", expected.getQ(), actual.getQ()); + assertEquals(expected.getG(), actual.getG(), message + "[g]"); + assertEquals(expected.getP(), actual.getP(), message + "[p]"); + assertEquals(expected.getQ(), actual.getQ(), message + "[q]"); } public static void assertECPrivateKeyEquals(String message, ECPrivateKey expected, ECPrivateKey actual) { @@ -588,7 +586,7 @@ public static void assertECPrivateKeyEquals(String message, ECPrivateKey expecte return; } - assertEquals(message + "[S]", expected.getS(), actual.getS()); + assertEquals(expected.getS(), actual.getS(), message + "[S]"); assertECParameterSpecEquals(message, expected, actual); } @@ -604,8 +602,8 @@ public static void assertECParameterSpecEquals(String message, ECParameterSpec e return; } - assertEquals(message + "[order]", expected.getOrder(), actual.getOrder()); - assertEquals(message + "[cofactor]", expected.getCofactor(), actual.getCofactor()); + assertEquals(expected.getOrder(), actual.getOrder(), message + "[order]"); + assertEquals(expected.getCofactor(), actual.getCofactor(), message + "[cofactor]"); assertECPointEquals(message + "[generator]", expected.getGenerator(), actual.getGenerator()); assertCurveEquals(message + "[curve]", expected.getCurve(), actual.getCurve()); } @@ -615,9 +613,9 @@ public static void assertCurveEquals(String message, EllipticCurve expected, Ell return; } - assertEquals(message + "[A]", expected.getA(), actual.getA()); - assertEquals(message + "[B]", expected.getB(), actual.getB()); - assertArrayEquals(message + "[seed]", expected.getSeed(), actual.getSeed()); + assertEquals(expected.getA(), actual.getA(), message + "[A]"); + assertEquals(expected.getB(), actual.getB(), message + "[B]"); + assertArrayEquals(expected.getSeed(), actual.getSeed(), message + "[seed]"); assertECFieldEquals(message + "[field]", expected.getField(), actual.getField()); } @@ -626,7 +624,7 @@ public static void assertECFieldEquals(String message, ECField expected, ECField return; } - assertEquals(message + "[size]", expected.getFieldSize(), actual.getFieldSize()); + assertEquals(expected.getFieldSize(), actual.getFieldSize(), message + "[size]"); } public static void assertECPointEquals(String message, ECPoint expected, ECPoint actual) { @@ -634,8 +632,8 @@ public static void assertECPointEquals(String message, ECPoint expected, ECPoint return; } - assertEquals(message + "[x]", expected.getAffineX(), actual.getAffineX()); - assertEquals(message + "[y]", expected.getAffineY(), actual.getAffineY()); + assertEquals(expected.getAffineX(), actual.getAffineX(), message + "[x]"); + assertEquals(expected.getAffineY(), actual.getAffineY(), message + "[y]"); } public static void assertFileLength(File file, long length, long timeout) throws Exception { @@ -662,8 +660,8 @@ public static void assertFileLength(Path file, long length, long timeout) throws if (waitForFile(file, length, timeout)) { return; } - assertTrue("File not found: " + file, Files.exists(file)); - assertEquals("Mismatched file size for " + file, length, Files.size(file)); + assertTrue(Files.exists(file), "File not found: " + file); + assertEquals(length, Files.size(file), "Mismatched file size for " + file); } public static boolean waitForFile(Path file, long length, Duration timeout) throws Exception { @@ -725,4 +723,12 @@ public static void replaceJULLoggers() { SLF4JBridgeHandler.install(); } } + + @BeforeEach + public void setup(TestInfo testInfo) { + Optional testMethod = testInfo.getTestMethod(); + if (testMethod.isPresent()) { + this.testNameHolder = testMethod.get().getName(); + } + } } diff --git a/sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/testReadGlobalHostsConfigEntries.config.txt b/sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/readGlobalHostsConfigEntries.config.txt similarity index 100% rename from sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/testReadGlobalHostsConfigEntries.config.txt rename to sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/readGlobalHostsConfigEntries.config.txt diff --git a/sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/testReadMultipleHostPatterns.config.txt b/sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/readMultipleHostPatterns.config.txt similarity index 100% rename from sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/testReadMultipleHostPatterns.config.txt rename to sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/readMultipleHostPatterns.config.txt diff --git a/sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/testReadSimpleHostsConfigEntries.config.txt b/sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/readSimpleHostsConfigEntries.config.txt similarity index 100% rename from sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/testReadSimpleHostsConfigEntries.config.txt rename to sshd-common/src/test/resources/org/apache/sshd/client/config/hosts/readSimpleHostsConfigEntries.config.txt diff --git a/sshd-contrib/pom.xml b/sshd-contrib/pom.xml index d2b4aaabe..c5d07f9b6 100644 --- a/sshd-contrib/pom.xml +++ b/sshd-contrib/pom.xml @@ -59,13 +59,13 @@ sshd-sftp ${project.version} - + net.i2p.crypto eddsa true - + org.apache.sshd sshd-core @@ -73,6 +73,11 @@ test-jar test + + org.junit.jupiter + junit-jupiter + test + org.apache.sshd sshd-common @@ -85,6 +90,11 @@ mockito-core test + + org.mockito + mockito-junit-jupiter + test + org.assertj assertj-core diff --git a/sshd-contrib/src/test/java/org/apache/sshd/contrib/client/auth/password/InteractivePasswordIdentityProviderTest.java b/sshd-contrib/src/test/java/org/apache/sshd/contrib/client/auth/password/InteractivePasswordIdentityProviderTest.java index 94990c4b0..8b0149129 100644 --- a/sshd-contrib/src/test/java/org/apache/sshd/contrib/client/auth/password/InteractivePasswordIdentityProviderTest.java +++ b/sshd-contrib/src/test/java/org/apache/sshd/contrib/client/auth/password/InteractivePasswordIdentityProviderTest.java @@ -28,30 +28,33 @@ import org.apache.sshd.client.auth.password.PasswordIdentityProvider; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; + /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class InteractivePasswordIdentityProviderTest extends BaseTestSupport { public InteractivePasswordIdentityProviderTest() { super(); } @Test - public void testPasswordEnumerations() throws IOException, GeneralSecurityException { + void passwordEnumerations() throws IOException, GeneralSecurityException { List expected = Arrays.asList(getClass().getSimpleName(), getClass().getPackage().getName(), getCurrentTestName()); ClientSession session = Mockito.mock(ClientSession.class); @@ -65,14 +68,14 @@ public void testPasswordEnumerations() throws IOException, GeneralSecurityExcept @Override public String answer(InvocationOnMock invocation) throws Throwable { Object[] args = invocation.getArguments(); - assertSame("Mismatched session instance at index=" + passwordIndex, session, args[0]); - assertSame("Mismatched prompt instance at index=" + passwordIndex, prompt, args[1]); + assertSame(session, args[0], "Mismatched session instance at index=" + passwordIndex); + assertSame(prompt, args[1], "Mismatched prompt instance at index=" + passwordIndex); int index = passwordIndex.getAndIncrement(); if (index < expected.size()) { return expected.get(index); } - assertEquals("Mismatched last call index", expected.size(), index); + assertEquals(expected.size(), index, "Mismatched last call index"); return null; } }); @@ -83,16 +86,16 @@ public String answer(InvocationOnMock invocation) throws Throwable { int expIndex = 0; for (String actValue : passwords) { String expValue = expected.get(expIndex); - assertSame("Mismatched password provided at index=" + expIndex, expValue, actValue); + assertSame(expValue, actValue, "Mismatched password provided at index=" + expIndex); expIndex++; } - assertEquals("Not all passwords exhausted", expected.size() + 1, passwordIndex.get()); - assertEquals("Mismatched retrieved passwords count", expIndex, expected.size()); + assertEquals(expected.size() + 1, passwordIndex.get(), "Not all passwords exhausted"); + assertEquals(expIndex, expected.size(), "Mismatched retrieved passwords count"); } @Test - public void testInteractionAllowedConsultation() throws IOException, GeneralSecurityException { + void interactionAllowedConsultation() throws IOException, GeneralSecurityException { ClientSession session = Mockito.mock(ClientSession.class); UserInteraction userInteraction = Mockito.mock(UserInteraction.class); Mockito.when(userInteraction.isInteractionAllowed(ArgumentMatchers.any(ClientSession.class))).thenReturn(Boolean.FALSE); diff --git a/sshd-contrib/src/test/java/org/apache/sshd/contrib/common/channel/throttle/ThrottlingChannelStreamWriterTest.java b/sshd-contrib/src/test/java/org/apache/sshd/contrib/common/channel/throttle/ThrottlingChannelStreamWriterTest.java index d9ed03b75..1a60338b8 100644 --- a/sshd-contrib/src/test/java/org/apache/sshd/contrib/common/channel/throttle/ThrottlingChannelStreamWriterTest.java +++ b/sshd-contrib/src/test/java/org/apache/sshd/contrib/common/channel/throttle/ThrottlingChannelStreamWriterTest.java @@ -32,26 +32,33 @@ import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.Timeout; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ThrottlingChannelStreamWriterTest extends BaseTestSupport { public ThrottlingChannelStreamWriterTest() { super(); } - @Test(timeout = 10_000) - public void testThrottlerWaitsUntilPacketSendSignalled() throws IOException { + @Test + @Timeout(value = 10_000, unit = TimeUnit.MILLISECONDS) + void throttlerWaitsUntilPacketSendSignalled() throws IOException { try (ThrottlingChannelStreamWriter throttler = new ThrottlingChannelStreamWriter(new MockChannelStreamWriter(), Byte.SIZE, TimeUnit.SECONDS.toMillis(3L))) { int maxSize = throttler.getMaxPendingPackets(); @@ -60,10 +67,10 @@ public void testThrottlerWaitsUntilPacketSendSignalled() throws IOException { for (int index = maxSize; index > 0; index--) { IoWriteFuture future = throttler.writeData(buf); pendingWrites.add(future); - assertEquals("Mismatched available packets count", index - 1, throttler.getAvailablePacketsCount()); + assertEquals(index - 1, throttler.getAvailablePacketsCount(), "Mismatched available packets count"); } - assertEquals("Not all available packet window size exhausted", 0, throttler.getAvailablePacketsCount()); + assertEquals(0, throttler.getAvailablePacketsCount(), "Not all available packet window size exhausted"); try { IoWriteFuture future = throttler.writeData(buf); fail("Unexpected extra packet success: " + future); @@ -75,7 +82,7 @@ public void testThrottlerWaitsUntilPacketSendSignalled() throws IOException { for (int index = 0; index < sendSize; index++) { IoWriteFutureImpl future = (IoWriteFutureImpl) pendingWrites.get(index); future.setValue(Boolean.TRUE); - assertEquals("Mismatched available packets count", index + 1, throttler.getAvailablePacketsCount()); + assertEquals(index + 1, throttler.getAvailablePacketsCount(), "Mismatched available packets count"); } for (int index = throttler.getAvailablePacketsCount(); index < maxSize; index++) { @@ -84,32 +91,40 @@ public void testThrottlerWaitsUntilPacketSendSignalled() throws IOException { } } - @Test(expected = ClosedSelectorException.class, timeout = 10_000) - public void testThrottlerDoesNotSendIfClosed() throws IOException { - try (ChannelStreamWriter throttler - = new ThrottlingChannelStreamWriter(new MockChannelStreamWriter(), Byte.SIZE, TimeUnit.SECONDS.toMillis(3L))) { - assertTrue("Throttler not marked as open", throttler.isOpen()); - throttler.close(); - assertFalse("Throttler not marked as closed", throttler.isOpen()); - - IoWriteFuture future = throttler.writeData(new ByteArrayBuffer(Byte.SIZE)); - fail("Unexpected success: " + future); - } + @Test + @Timeout(value = 10_000, unit = TimeUnit.MILLISECONDS) + void throttlerDoesNotSendIfClosed() throws IOException { + assertThrows(ClosedSelectorException.class, () -> { + try (ChannelStreamWriter throttler + = new ThrottlingChannelStreamWriter(new MockChannelStreamWriter(), Byte.SIZE, + TimeUnit.SECONDS.toMillis(3L))) { + assertTrue(throttler.isOpen(), "Throttler not marked as open"); + throttler.close(); + assertFalse(throttler.isOpen(), "Throttler not marked as closed"); + + IoWriteFuture future = throttler.writeData(new ByteArrayBuffer(Byte.SIZE)); + fail("Unexpected success: " + future); + } + }); } - @Test(expected = ClosedSelectorException.class, timeout = 10_000) - public void testThrottlerStopsSendingIfExceptionSignaledOnFutureOperationCompletion() throws IOException { - try (ChannelStreamWriter throttler - = new ThrottlingChannelStreamWriter(new MockChannelStreamWriter(), Byte.SIZE, TimeUnit.SECONDS.toMillis(3L))) { - assertTrue("Throttler not marked as open", throttler.isOpen()); - - IoWriteFutureImpl futureImpl = (IoWriteFutureImpl) throttler.writeData(new ByteArrayBuffer(Byte.SIZE)); - futureImpl.setValue(new StreamCorruptedException(getCurrentTestName())); - assertFalse("Throttler not marked as closed", throttler.isOpen()); - - IoWriteFuture future = throttler.writeData(new ByteArrayBuffer(Byte.SIZE)); - fail("Unexpected success: " + future); - } + @Test + @Timeout(value = 10_000, unit = TimeUnit.MILLISECONDS) + void throttlerStopsSendingIfExceptionSignaledOnFutureOperationCompletion() throws IOException { + assertThrows(ClosedSelectorException.class, () -> { + try (ChannelStreamWriter throttler + = new ThrottlingChannelStreamWriter(new MockChannelStreamWriter(), Byte.SIZE, + TimeUnit.SECONDS.toMillis(3L))) { + assertTrue(throttler.isOpen(), "Throttler not marked as open"); + + IoWriteFutureImpl futureImpl = (IoWriteFutureImpl) throttler.writeData(new ByteArrayBuffer(Byte.SIZE)); + futureImpl.setValue(new StreamCorruptedException(getCurrentTestName())); + assertFalse(throttler.isOpen(), "Throttler not marked as closed"); + + IoWriteFuture future = throttler.writeData(new ByteArrayBuffer(Byte.SIZE)); + fail("Unexpected success: " + future); + } + }); } private static class MockChannelStreamWriter implements ChannelStreamWriter { diff --git a/sshd-contrib/src/test/java/org/apache/sshd/contrib/common/signature/LegacyDSASignerTest.java b/sshd-contrib/src/test/java/org/apache/sshd/contrib/common/signature/LegacyDSASignerTest.java index 0a6350d35..6c050d1a9 100644 --- a/sshd-contrib/src/test/java/org/apache/sshd/contrib/common/signature/LegacyDSASignerTest.java +++ b/sshd-contrib/src/test/java/org/apache/sshd/contrib/common/signature/LegacyDSASignerTest.java @@ -36,56 +36,54 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.ValidateUtils; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class LegacyDSASignerTest extends JUnitTestSupport { - private final int keySize; - private final KeyPair kp; + private int keySize; + private KeyPair kp; - public LegacyDSASignerTest(int keySize) + public void initLegacyDSASignerTest(int keySize) throws IOException, GeneralSecurityException { this.keySize = keySize; String resourceName = KeyPairProvider.SSH_DSS + "-" + keySize; URL url = getClass().getResource(resourceName); - assertNotNull("Missing test key file " + resourceName, url); + assertNotNull(url, "Missing test key file " + resourceName); Collection keys = DSSPEMResourceKeyPairParser.INSTANCE.loadKeyPairs(null, url, null); ValidateUtils.checkNotNullAndNotEmpty(keys, "No keys loaded from %s", resourceName); kp = GenericUtils.head(keys); int l = KeyUtils.getKeySize(kp.getPublic()); - assertEquals("Mismatched read public key size", keySize, l); + assertEquals(keySize, l, "Mismatched read public key size"); l = KeyUtils.getKeySize(kp.getPrivate()); - assertEquals("mismatched read private key size", keySize, l); + assertEquals(keySize, l, "mismatched read private key size"); } - @Parameters(name = "key-size={0}") public static List parameters() { return parameterize(Arrays.asList(1024, 2048)); } - @Test - public void testReflexiveSigning() throws GeneralSecurityException { + @MethodSource("parameters") + @ParameterizedTest(name = "key-size={0}") + public void reflexiveSigning(int keySize) throws Exception { + initLegacyDSASignerTest(keySize); java.security.Signature signer = new LegacyDSASigner(JceRandomFactory.INSTANCE); signer.initSign(kp.getPrivate()); @@ -99,9 +97,11 @@ public void testReflexiveSigning() throws GeneralSecurityException { assertTrue(signer.verify(signature)); } - @Test - public void testBuiltinVerifier() throws GeneralSecurityException { - Assume.assumeTrue("Skip SHA-1 with too large a key", keySize <= 1024); + @MethodSource("parameters") + @ParameterizedTest(name = "key-size={0}") + public void builtinVerifier(int keySize) throws Exception { + initLegacyDSASignerTest(keySize); + Assumptions.assumeTrue(keySize <= 1024, "Skip SHA-1 with too large a key"); java.security.Signature signer = new LegacyDSASigner(JceRandomFactory.INSTANCE); signer.initSign(kp.getPrivate()); @@ -117,9 +117,11 @@ public void testBuiltinVerifier() throws GeneralSecurityException { assertTrue(verifier.verify(signature)); } - @Test - public void testBuiltinSigner() throws GeneralSecurityException { - Assume.assumeTrue("Skip SHA-1 with too large a key", keySize <= 1024); + @MethodSource("parameters") + @ParameterizedTest(name = "key-size={0}") + public void builtinSigner(int keySize) throws Exception { + initLegacyDSASignerTest(keySize); + Assumptions.assumeTrue(keySize <= 1024, "Skip SHA-1 with too large a key"); java.security.Signature signer = SecurityUtils.getSignature(SignatureDSA.DEFAULT_ALGORITHM); signer.initSign(kp.getPrivate()); diff --git a/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/scp/SimpleAccessControlScpEventListenerTest.java b/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/scp/SimpleAccessControlScpEventListenerTest.java index 9aeee012e..fffd4009d 100644 --- a/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/scp/SimpleAccessControlScpEventListenerTest.java +++ b/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/scp/SimpleAccessControlScpEventListenerTest.java @@ -37,16 +37,19 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SimpleAccessControlScpEventListenerTest extends BaseTestSupport { private SshServer sshd; private int port; @@ -58,8 +61,8 @@ public SimpleAccessControlScpEventListenerTest() { fileSystemFactory = new VirtualFileSystemFactory(parentPath); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); sshd.setCommandFactory(new ScpCommandFactory()); sshd.setFileSystemFactory(fileSystemFactory); @@ -67,8 +70,8 @@ public void setUp() throws Exception { port = sshd.getPort(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -79,7 +82,7 @@ public void tearDown() throws Exception { } @Test - public void testReadOnlyScpTransferEventListener() throws Exception { + void readOnlyScpTransferEventListener() throws Exception { sshd.setCommandFactory(new ScpCommandFactory.Builder() .addEventListener(SimpleAccessControlScpEventListener.READ_ONLY_ACCESSOR) .build()); @@ -105,7 +108,7 @@ public void testReadOnlyScpTransferEventListener() throws Exception { byte[] data = (getClass().getName() + "#" + getCurrentTestName()).getBytes(StandardCharsets.UTF_8); Files.write(remoteFile, data); byte[] downloaded = scp.downloadBytes(remotePath); - assertArrayEquals("Mismatched downloaded data", data, downloaded); + assertArrayEquals(data, downloaded, "Mismatched downloaded data"); try { scp.upload(data, remotePath, EnumSet.allOf(PosixFilePermission.class), null); diff --git a/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/session/proxyprotocolv2/ProxyProtocolV2AcceptorTest.java b/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/session/proxyprotocolv2/ProxyProtocolV2AcceptorTest.java index 8ed5a3162..e1bbfc909 100644 --- a/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/session/proxyprotocolv2/ProxyProtocolV2AcceptorTest.java +++ b/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/session/proxyprotocolv2/ProxyProtocolV2AcceptorTest.java @@ -26,18 +26,18 @@ import org.apache.sshd.contrib.server.session.proxyprotocol.ProxyProtocolAcceptor; import org.apache.sshd.contrib.server.session.proxyprotocolv2.exception.ProxyProtocolException; import org.apache.sshd.server.session.AbstractServerSession; -import org.junit.Test; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; import static org.assertj.core.api.AssertionsForClassTypes.assertThat; import static org.assertj.core.api.InstanceOfAssertFactories.type; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -47,7 +47,7 @@ * * @author Oodrive - François HERBRETEAU (f.herbreteau@oodrive.com) */ -@RunWith(MockitoJUnitRunner.class) +@ExtendWith(MockitoExtension.class) public class ProxyProtocolV2AcceptorTest { private final ProxyProtocolAcceptor acceptor = new ProxyProtocolV2Acceptor(); @@ -63,7 +63,7 @@ public ProxyProtocolV2AcceptorTest() { } @Test - public void testHandlingProxyProtocolV1Tcp4() throws Exception { + void handlingProxyProtocolV1Tcp4() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer("PROXY TCP4 172.19.0.1 172.19.0.3 42272 80\r\n".getBytes()); @@ -86,7 +86,7 @@ public void testHandlingProxyProtocolV1Tcp4() throws Exception { } @Test - public void testHandlingProxyProtocolV1Tpc6() throws Exception { + void handlingProxyProtocolV1Tpc6() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer("PROXY TCP6 fe80::a00:27ff:fe9f:4016 fe80::a089:a3ff:fe15:e992 42272 80\r\n".getBytes()); @@ -110,7 +110,7 @@ public void testHandlingProxyProtocolV1Tpc6() throws Exception { } @Test - public void testHandlingProxyProtocolV2Tcp4() throws Exception { + void handlingProxyProtocolV2Tcp4() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -135,7 +135,7 @@ public void testHandlingProxyProtocolV2Tcp4() throws Exception { } @Test - public void testHandlingProxyProtocolV2Tcp6() throws Exception { + void handlingProxyProtocolV2Tcp6() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -163,7 +163,7 @@ public void testHandlingProxyProtocolV2Tcp6() throws Exception { } @Test - public void testHandlingProxyProtocolV2UnixSocket() throws Exception { + void handlingProxyProtocolV2UnixSocket() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -179,7 +179,7 @@ public void testHandlingProxyProtocolV2UnixSocket() throws Exception { } @Test - public void testHandlingProxyProtocolV2Udp4() throws Exception { + void handlingProxyProtocolV2Udp4() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -196,7 +196,7 @@ public void testHandlingProxyProtocolV2Udp4() throws Exception { } @Test - public void testHandlingProxyProtocolV2Udp6() throws Exception { + void handlingProxyProtocolV2Udp6() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -215,7 +215,7 @@ public void testHandlingProxyProtocolV2Udp6() throws Exception { } @Test - public void testHandlingOtherProtocolHeader() throws Exception { + void handlingOtherProtocolHeader() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer("SSH-2.0-OpenSSH_9.3".getBytes()); @@ -229,7 +229,7 @@ public void testHandlingOtherProtocolHeader() throws Exception { } @Test - public void testHandlingProxyProtocolV2WithLocalCommand() throws Exception { + void handlingProxyProtocolV2WithLocalCommand() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -245,7 +245,7 @@ public void testHandlingProxyProtocolV2WithLocalCommand() throws Exception { } @Test - public void testHandlingProxyProtocolV2WithExtendedData() throws Exception { + void handlingProxyProtocolV2WithExtendedData() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -261,7 +261,7 @@ public void testHandlingProxyProtocolV2WithExtendedData() throws Exception { } @Test - public void testHandlingProxyProtocolV2WithInvalidVersion() { + void handlingProxyProtocolV2WithInvalidVersion() { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -279,7 +279,7 @@ public void testHandlingProxyProtocolV2WithInvalidVersion() { } @Test - public void testHandlingProxyProtocolV2WithUnassignedCommand() { + void handlingProxyProtocolV2WithUnassignedCommand() { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -297,7 +297,7 @@ public void testHandlingProxyProtocolV2WithUnassignedCommand() { } @Test - public void testHandlingProxyProtocolV2WithUnexpectedFamily() { + void handlingProxyProtocolV2WithUnexpectedFamily() { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -315,7 +315,7 @@ public void testHandlingProxyProtocolV2WithUnexpectedFamily() { } @Test - public void testHandlingProxyProtocolV2WithUnexpectedTransport() { + void handlingProxyProtocolV2WithUnexpectedTransport() { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x0d, 0x0a, 0x0d, 0x0a, 0x00, 0x0d, 0x0a, 0x51, 0x55, 0x49, 0x54, 0x0a, @@ -333,7 +333,7 @@ public void testHandlingProxyProtocolV2WithUnexpectedTransport() { } @Test - public void testHandlingProxyProtocolV2WithInvalidSize() throws Exception { + void handlingProxyProtocolV2WithInvalidSize() throws Exception { // Given ByteArrayBuffer buffer = new ByteArrayBuffer(new byte[] { 0x00, 0x00, 0x00, 0x00 }); diff --git a/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/subsystem/sftp/SimpleAccessControlSftpEventListenerTest.java b/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/subsystem/sftp/SimpleAccessControlSftpEventListenerTest.java index 78ba22230..4e4b7d548 100644 --- a/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/subsystem/sftp/SimpleAccessControlSftpEventListenerTest.java +++ b/sshd-contrib/src/test/java/org/apache/sshd/contrib/server/subsystem/sftp/SimpleAccessControlSftpEventListenerTest.java @@ -39,16 +39,21 @@ import org.apache.sshd.sftp.server.SftpSubsystemFactory; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SimpleAccessControlSftpEventListenerTest extends BaseTestSupport { private SshServer sshd; private int port; @@ -60,8 +65,8 @@ public SimpleAccessControlSftpEventListenerTest() { fileSystemFactory = new VirtualFileSystemFactory(parentPath); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); SftpSubsystemFactory.Builder builder = new SftpSubsystemFactory.Builder(); builder.addSftpEventListener(SimpleAccessControlSftpEventListener.READ_ONLY_ACCESSOR); @@ -73,8 +78,8 @@ public void setUp() throws Exception { port = sshd.getPort(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -85,7 +90,7 @@ public void tearDown() throws Exception { } @Test - public void testReadOnlyFileAccess() throws Exception { + void readOnlyFileAccess() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), @@ -108,8 +113,8 @@ public void testReadOnlyFileAccess() throws Exception { try (CloseableHandle handle = sftp.open(file, OpenMode.Read)) { byte[] actual = new byte[data.length]; int readLen = sftp.read(handle, 0L, actual); - assertEquals("Mismatched read data length", data.length, readLen); - assertArrayEquals("Mismatched read file contents", data, actual); + assertEquals(data.length, readLen, "Mismatched read data length"); + assertArrayEquals(data, actual, "Mismatched read file contents"); } try (CloseableHandle handle @@ -118,7 +123,7 @@ public void testReadOnlyFileAccess() throws Exception { fail("Unexpected file write success"); } catch (SftpException e) { int status = e.getStatus(); - assertEquals("Unexpected write SFTP status code", SftpConstants.SSH_FX_PERMISSION_DENIED, status); + assertEquals(SftpConstants.SSH_FX_PERMISSION_DENIED, status, "Unexpected write SFTP status code"); } SftpClient.Attributes attrs = sftp.stat(file); @@ -128,8 +133,9 @@ public void testReadOnlyFileAccess() throws Exception { fail("Unexpected attributes modification success"); } catch (SftpException e) { int status = e.getStatus(); - assertEquals("Unexpected setAttributes SFTP status code", SftpConstants.SSH_FX_PERMISSION_DENIED, - status); + assertEquals(SftpConstants.SSH_FX_PERMISSION_DENIED, + status, + "Unexpected setAttributes SFTP status code"); } } } finally { @@ -139,7 +145,7 @@ public void testReadOnlyFileAccess() throws Exception { } @Test - public void testReadOnlyDirectoryAccess() throws Exception { + void readOnlyDirectoryAccess() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve( @@ -160,7 +166,7 @@ public void testReadOnlyDirectoryAccess() throws Exception { try (SftpClient sftp = SftpClientFactory.instance().createSftpClient(session)) { String folder = CommonTestSupportUtils.resolveRelativeRemotePath(parentPath, targetPath); for (SftpClient.DirEntry entry : sftp.readDir(folder)) { - assertNotNull("No entry", entry); + assertNotNull(entry, "No entry"); } String file = CommonTestSupportUtils.resolveRelativeRemotePath(parentPath, testFile); @@ -169,7 +175,7 @@ public void testReadOnlyDirectoryAccess() throws Exception { fail("Unexpected file remove success"); } catch (SftpException e) { int status = e.getStatus(); - assertEquals("Unexpected remove SFTP status code", SftpConstants.SSH_FX_PERMISSION_DENIED, status); + assertEquals(SftpConstants.SSH_FX_PERMISSION_DENIED, status, "Unexpected remove SFTP status code"); } try { @@ -177,7 +183,7 @@ public void testReadOnlyDirectoryAccess() throws Exception { fail("Unexpected folder creation success"); } catch (SftpException e) { int status = e.getStatus(); - assertEquals("Unexpected mkdir SFTP status code", SftpConstants.SSH_FX_PERMISSION_DENIED, status); + assertEquals(SftpConstants.SSH_FX_PERMISSION_DENIED, status, "Unexpected mkdir SFTP status code"); } try { @@ -185,7 +191,7 @@ public void testReadOnlyDirectoryAccess() throws Exception { fail("Unexpected folder removal success"); } catch (SftpException e) { int status = e.getStatus(); - assertEquals("Unexpected rmdir SFTP status code", SftpConstants.SSH_FX_PERMISSION_DENIED, status); + assertEquals(SftpConstants.SSH_FX_PERMISSION_DENIED, status, "Unexpected rmdir SFTP status code"); } } } finally { diff --git a/sshd-core/pom.xml b/sshd-core/pom.xml index d957e7597..eef8acd01 100644 --- a/sshd-core/pom.xml +++ b/sshd-core/pom.xml @@ -74,6 +74,16 @@ test-jar test + + org.junit.jupiter + junit-jupiter + test + + + org.mockito + mockito-junit-jupiter + test + org.apache.mina @@ -105,6 +115,11 @@ testcontainers test + + org.testcontainers + junit-jupiter + test + io.grpc grpc-netty-shaded @@ -291,7 +306,7 @@ org.apache.maven.plugins maven-surefire-plugin - org.apache.sshd.util.test.ContainerTestCase + ContainerTestCase diff --git a/sshd-core/src/test/java/org/apache/sshd/DefaultSetupTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/DefaultSetupTestSupport.java index 45f810db8..d0722e5e6 100644 --- a/sshd-core/src/test/java/org/apache/sshd/DefaultSetupTestSupport.java +++ b/sshd-core/src/test/java/org/apache/sshd/DefaultSetupTestSupport.java @@ -41,9 +41,12 @@ import org.apache.sshd.server.ServerBuilder; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; /** * Makes sure default client/server setup satisfies various conditions @@ -51,7 +54,7 @@ * @param The {@link AbstractFactoryManager} type being tested - can be client or server * @author Apache MINA SSHD Project */ -@Category({ NoIoTestCase.class }) +@Tag("NoIoTestCase") public abstract class DefaultSetupTestSupport extends BaseTestSupport { protected final M factory; @@ -60,7 +63,7 @@ protected DefaultSetupTestSupport(M factory) { } @Test - public void testDefaultCiphersList() { + public void defaultCiphersList() { assertSameNamedFactoriesListInstances(Cipher.class.getSimpleName(), factory instanceof SshServer ? ServerBuilder.DEFAULT_SERVER_CIPHERS_PREFERENCE @@ -70,7 +73,7 @@ public void testDefaultCiphersList() { @Test // SSHD-1004 @SuppressWarnings("deprecation") - public void testNoDeprecatedCiphers() { + public void noDeprecatedCiphers() { assertNoDeprecatedFactoryInstanceNames(Cipher.class.getSimpleName(), EnumSet.of(BuiltinCiphers.arcfour128, BuiltinCiphers.arcfour256, BuiltinCiphers.tripledescbc, BuiltinCiphers.blowfishcbc), @@ -78,14 +81,14 @@ public void testNoDeprecatedCiphers() { } @Test - public void testDefaultKeyExchangeList() { + public void defaultKeyExchangeList() { assertSameNamedResourceListNames(KeyExchange.class.getSimpleName(), BaseBuilder.DEFAULT_KEX_PREFERENCE.stream().filter(dh -> dh.isSupported()).collect(Collectors.toList()), factory.getKeyExchangeFactories()); } @Test // SSHD-1004 - public void testNoDeprecatedKeyExchanges() { + public void noDeprecatedKeyExchanges() { Collection disallowed = BuiltinDHFactories.VALUES.stream() .filter(f -> f.getName().endsWith("sha-1")) .collect(Collectors.toCollection(() -> EnumSet.noneOf(BuiltinDHFactories.class))); @@ -94,14 +97,14 @@ public void testNoDeprecatedKeyExchanges() { } @Test - public void testDefaultSignaturesList() { + public void defaultSignaturesList() { assertSameNamedFactoriesListInstances( Signature.class.getSimpleName(), BaseBuilder.DEFAULT_SIGNATURE_PREFERENCE, factory.getSignatureFactories()); } @Test // SSHD-1004 @SuppressWarnings("deprecation") - public void testNoDeprecatedSignatures() { + public void noDeprecatedSignatures() { assertNoDeprecatedFactoryInstanceNames(Cipher.class.getSimpleName(), EnumSet.of(BuiltinSignatures.dsa, BuiltinSignatures.rsa_cert, BuiltinSignatures.dsa_cert), factory.getSignatureFactories()); @@ -109,14 +112,14 @@ public void testNoDeprecatedSignatures() { } @Test - public void testDefaultMacsList() { + public void defaultMacsList() { assertSameNamedFactoriesListInstances( Mac.class.getSimpleName(), BaseBuilder.DEFAULT_MAC_PREFERENCE, factory.getMacFactories()); } @Test @SuppressWarnings("deprecation") - public void testNoDeprecatedMacs() { + public void noDeprecatedMacs() { assertNoDeprecatedFactoryInstanceNames( Mac.class.getSimpleName(), EnumSet.of(BuiltinMacs.hmacmd5, BuiltinMacs.hmacmd596, BuiltinMacs.hmacsha196), factory.getMacFactories()); @@ -125,14 +128,14 @@ public void testNoDeprecatedMacs() { protected static void assertSameNamedResourceListNames( String hint, List expected, List actual) { int len = GenericUtils.size(expected); - assertEquals(hint + "[size]", len, GenericUtils.size(actual)); + assertEquals(len, GenericUtils.size(actual), hint + "[size]"); for (int index = 0; index < len; index++) { NamedResource expRes = expected.get(index); String expName = expRes.getName(); NamedResource actRes = actual.get(index); String actName = actRes.getName(); - assertSame(hint + "[" + index + "]", expName, actName); + assertSame(expName, actName, hint + "[" + index + "]"); } } @@ -143,19 +146,19 @@ protected static void assertNoDeprecatedFactoryInstanceNames( .collect(Collectors.toCollection(() -> new TreeSet<>(String.CASE_INSENSITIVE_ORDER))); for (NamedResource namedFactory : actual) { String name = namedFactory.getName(); - assertFalse(hint + " - disallowed: " + name, disallowedNames.contains(name)); + assertFalse(disallowedNames.contains(name), hint + " - disallowed: " + name); } } protected static > void assertSameNamedFactoriesListInstances( String hint, List expected, List actual) { int len = GenericUtils.size(expected); - assertEquals(hint + "[size]", len, GenericUtils.size(actual)); + assertEquals(len, GenericUtils.size(actual), hint + "[size]"); for (int index = 0; index < len; index++) { F expFactory = expected.get(index); F actFactory = actual.get(index); - assertSame(hint + "[" + index + "]", expFactory, actFactory); + assertSame(expFactory, actFactory, hint + "[" + index + "]"); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java b/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java index 7d9948799..174eeb77c 100644 --- a/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java @@ -44,18 +44,20 @@ import org.apache.sshd.util.test.CoreTestSupportUtils; import org.apache.sshd.util.test.EchoShell; import org.apache.sshd.util.test.EchoShellFactory; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class KeepAliveTest extends BaseTestSupport { private static final Duration HEARTBEAT = Duration.ofSeconds(2L); @@ -66,12 +68,8 @@ public class KeepAliveTest extends BaseTestSupport { private static int port; private static SshClient client; - public KeepAliveTest() { - super(); - } - - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(KeepAliveTest.class); sshd.setShellFactory(new TestEchoShellFactory()); sshd.start(); @@ -81,8 +79,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -100,13 +98,13 @@ public static void tearDownClientAndServer() throws Exception { } } - @Before - public void setUp() { + @BeforeEach + void setUp() { CoreModuleProperties.IDLE_TIMEOUT.set(sshd, TIMEOUT); } - @After - public void tearDown() { + @AfterEach + void tearDown() { // Restore default value CoreModuleProperties.IDLE_TIMEOUT.remove(sshd); CoreModuleProperties.HEARTBEAT_INTERVAL.remove(client); @@ -114,7 +112,7 @@ public void tearDown() { } @Test - public void testIdleClient() throws Exception { + void idleClient() throws Exception { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT) .getSession()) { @@ -125,14 +123,14 @@ public void testIdleClient() throws Exception { long waitStart = System.currentTimeMillis(); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT); long waitEnd = System.currentTimeMillis(); - assertTrue("Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result, - result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED))); + assertTrue(result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)), + "Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result); } } } @Test - public void testClientWithHeartBeat() throws Exception { + void clientWithHeartBeat() throws Exception { CoreModuleProperties.HEARTBEAT_INTERVAL.set(client, HEARTBEAT); try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT) @@ -144,14 +142,14 @@ public void testClientWithHeartBeat() throws Exception { long waitStart = System.currentTimeMillis(); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT); long waitEnd = System.currentTimeMillis(); - assertTrue("Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result, - result.contains(ClientChannelEvent.TIMEOUT)); + assertTrue(result.contains(ClientChannelEvent.TIMEOUT), + "Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result); } } } @Test - public void testShellClosedOnClientTimeout() throws Exception { + void shellClosedOnClientTimeout() throws Exception { TestEchoShell.latch = new CountDownLatch(1); try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) @@ -168,21 +166,22 @@ public void testShellClosedOnClientTimeout() throws Exception { channel.setErr(err); channel.open().verify(OPEN_TIMEOUT); - assertTrue("Latch time out", TestEchoShell.latch.await(DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); + assertTrue(TestEchoShell.latch.await(DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS), "Latch time out"); long waitStart = System.currentTimeMillis(); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT); long waitEnd = System.currentTimeMillis(); - assertTrue("Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result, - result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED, ClientChannelEvent.OPENED))); + assertTrue(result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED, ClientChannelEvent.OPENED)), + "Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result); } } finally { TestEchoShell.latch = null; } } - @Test // see SSHD-968 - public void testAllowUnimplementedMessageHeartbeatResponse() throws Exception { + // see SSHD-968 + @Test + void allowUnimplementedMessageHeartbeatResponse() throws Exception { List> globalHandlers = sshd.getGlobalRequestHandlers(); sshd.setGlobalRequestHandlers( Collections.singletonList( @@ -209,16 +208,17 @@ public Result process( long waitStart = System.currentTimeMillis(); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), WAIT); long waitEnd = System.currentTimeMillis(); - assertTrue("Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result, - result.contains(ClientChannelEvent.TIMEOUT)); + assertTrue(result.contains(ClientChannelEvent.TIMEOUT), + "Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result); } } finally { sshd.setGlobalRequestHandlers(globalHandlers); // restore original } } - @Test // see GH-268 - public void testTimeoutOnMissingHeartbeatResponse() throws Exception { + // see GH-268 + @Test + void timeoutOnMissingHeartbeatResponse() throws Exception { CoreModuleProperties.IDLE_TIMEOUT.set(sshd, Duration.ofSeconds(30)); List> globalHandlers = sshd.getGlobalRequestHandlers(); sshd.setGlobalRequestHandlers(Collections.singletonList(new AbstractConnectionServiceRequestHandler() { @@ -241,8 +241,8 @@ public Result process(ConnectionService connectionService, String request, boole long waitStart = System.currentTimeMillis(); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TIMEOUT); long waitEnd = System.currentTimeMillis(); - assertTrue("Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result, - result.contains(ClientChannelEvent.CLOSED)); + assertTrue(result.contains(ClientChannelEvent.CLOSED), + "Wrong channel state after wait of " + (waitEnd - waitStart) + " ms: " + result); } } finally { sshd.setGlobalRequestHandlers(globalHandlers); // restore original diff --git a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java index 874c5b1af..9a3f6a173 100644 --- a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java @@ -67,19 +67,27 @@ import org.apache.sshd.util.test.OutputCountTrackingOutputStream; import org.apache.sshd.util.test.SimpleUserInfo; import org.apache.sshd.util.test.TeeOutputStream; -import org.junit.After; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test key exchange algorithms. * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class KeyReExchangeTest extends BaseTestSupport { private SshServer sshd; @@ -89,13 +97,13 @@ public KeyReExchangeTest() { super(); } - @BeforeClass - public static void jschInit() { + @BeforeAll + static void jschInit() { JSchLogger.init(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -119,7 +127,7 @@ protected void setUp(long bytesLimit, Duration timeLimit, long packetsLimit) thr } @Test - public void testSwitchToNoneCipher() throws Exception { + void switchToNoneCipher() throws Exception { setUp(0L, Duration.ZERO, 0L); sshd.getCipherFactories().add(BuiltinCiphers.none); @@ -144,8 +152,9 @@ public void testSwitchToNoneCipher() throws Exception { } } - @Test // see SSHD-558 - public void testKexFutureExceptionPropagation() throws Exception { + // see SSHD-558 + @Test + void kexFutureExceptionPropagation() throws Exception { setUp(0L, Duration.ZERO, 0L); sshd.getCipherFactories().add(BuiltinCiphers.none); @@ -209,14 +218,14 @@ private void testKexFutureExceptionPropagation(String failureType, AtomicBoolean successFlag.set(false); KeyExchangeFuture kexFuture = session.switchToNoneCipher(); - assertTrue(failureType + ": failed to complete KEX on time", kexFuture.await(DEFAULT_TIMEOUT)); - assertNotNull(failureType + ": unexpected success", kexFuture.getException()); + assertTrue(kexFuture.await(DEFAULT_TIMEOUT), failureType + ": failed to complete KEX on time"); + assertNotNull(kexFuture.getException(), failureType + ": unexpected success"); } } @Test - public void testReExchangeFromJschClient() throws Exception { - Assume.assumeTrue("DH Group Exchange not supported", SecurityUtils.isDHGroupExchangeSupported()); + void reExchangeFromJschClient() throws Exception { + Assumptions.assumeTrue(SecurityUtils.isDHGroupExchangeSupported(), "DH Group Exchange not supported"); setUp(0L, Duration.ZERO, 0L); JSch.setConfig("kex", BuiltinDHFactories.Constants.DIFFIE_HELLMAN_GROUP_EXCHANGE_SHA1); @@ -240,7 +249,7 @@ public void testReExchangeFromJschClient() throws Exception { int len = is.read(data); String str = new String(data, 0, len, StandardCharsets.UTF_8); - assertEquals("Mismatched data at iteration " + i, expected, str); + assertEquals(expected, str, "Mismatched data at iteration " + i); outputDebugMessage("Request re-key #%d", i); s.rekey(); @@ -254,7 +263,7 @@ public void testReExchangeFromJschClient() throws Exception { } @Test - public void testReExchangeFromSshdClient() throws Exception { + void reExchangeFromSshdClient() throws Exception { setUp(0L, Duration.ZERO, 0L); try (SshClient client = setupTestClient()) { @@ -315,15 +324,15 @@ private void updateWriteCount(long delta) { teeOut.flush(); KeyExchangeFuture kexFuture = session.reExchangeKeys(); - assertTrue("Failed to complete KEX on time at iteration " + i, kexFuture.await(DEFAULT_TIMEOUT)); - assertNull("KEX exception signalled at iteration " + i, kexFuture.getException()); + assertTrue(kexFuture.await(DEFAULT_TIMEOUT), "Failed to complete KEX on time at iteration " + i); + assertNull(kexFuture.getException(), "KEX exception signalled at iteration " + i); } teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8)); teeOut.flush(); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), DEFAULT_TIMEOUT); - assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting for channel closure"); byte[] expected = sent.toByteArray(); if (!pipedCount.tryAcquire(expected.length, DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) { @@ -331,7 +340,7 @@ private void updateWriteCount(long delta) { + pipedCount.availablePermits() + ")"); } - assertArrayEquals("Mismatched sent data content", expected, out.toByteArray()); + assertArrayEquals(expected, out.toByteArray(), "Mismatched sent data content"); } } finally { client.stop(); @@ -340,7 +349,7 @@ private void updateWriteCount(long delta) { } @Test - public void testReExchangeFromServerBySize() throws Exception { + void reExchangeFromServerBySize() throws Exception { final long bytesLImit = 10 * 1024L; setUp(bytesLImit, Duration.ZERO, 0L); @@ -424,19 +433,19 @@ public void sessionEvent(Session session, Event event) { Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), DEFAULT_TIMEOUT); - assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting for channel closure"); sentData = sent.toByteArray(); if (!pipedCount.tryAcquire(sentData.length, DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) { fail("Failed to await sent data signal for len=" + sentData.length + " (available=" + pipedCount.availablePermits() + ")"); } - assertTrue("Expected rekeying", exchanges.get() > 0); + assertTrue(exchanges.get() > 0, "Expected rekeying"); } byte[] outData = out.toByteArray(); - assertEquals("Mismatched sent data length", sentData.length, outData.length); - assertArrayEquals("Mismatched sent data content", sentData, outData); + assertEquals(sentData.length, outData.length, "Mismatched sent data length"); + assertArrayEquals(sentData, outData, "Mismatched sent data content"); } finally { client.stop(); } @@ -444,7 +453,7 @@ public void sessionEvent(Session session, Event event) { } @Test - public void testReExchangeFromServerByTime() throws Exception { + void reExchangeFromServerByTime() throws Exception { final Duration timeLimit = Duration.ofSeconds(2L); setUp(0L, timeLimit, 0L); @@ -539,7 +548,7 @@ public void sessionEvent(Session session, Event event) { Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), DEFAULT_TIMEOUT); - assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting for channel closure"); sentData = sent.toByteArray(); if (!pipedCount.tryAcquire(sentData.length, DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)) { @@ -547,20 +556,21 @@ public void sessionEvent(Session session, Event event) { + pipedCount.availablePermits() + ")"); } - assertTrue("Expected rekeying", exchanges.get() > 0); + assertTrue(exchanges.get() > 0, "Expected rekeying"); } byte[] outData = out.toByteArray(); - assertEquals("Mismatched sent data length", sentData.length, outData.length); - assertArrayEquals("Mismatched sent data content", sentData, outData); + assertEquals(sentData.length, outData.length, "Mismatched sent data length"); + assertArrayEquals(sentData, outData, "Mismatched sent data content"); } finally { client.stop(); } } } - @Test // see SSHD-601 - public void testReExchangeFromServerByPackets() throws Exception { + // see SSHD-601 + @Test + void reExchangeFromServerByPackets() throws Exception { final int packetsLimit = 135; setUp(0L, Duration.ZERO, packetsLimit); @@ -657,7 +667,7 @@ public void sessionEvent(Session session, Event event) { Duration timeout = CoreTestSupportUtils.getTimeout("KeyReExchangeTest", Duration.ofSeconds(15)); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), timeout); - assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting for channel closure"); sentData = sent.toByteArray(); if (!pipedCount.tryAcquire(sentData.length, timeout.toMillis(), TimeUnit.MILLISECONDS)) { @@ -665,12 +675,12 @@ public void sessionEvent(Session session, Event event) { + pipedCount.availablePermits() + ")"); } - assertTrue("Expected rekeying", exchanges.get() > 0); + assertTrue(exchanges.get() > 0, "Expected rekeying"); } byte[] outData = out.toByteArray(); - assertEquals("Mismatched sent data length", sentData.length, outData.length); - assertArrayEquals("Mismatched sent data content", sentData, outData); + assertEquals(sentData.length, outData.length, "Mismatched sent data length"); + assertArrayEquals(sentData, outData, "Mismatched sent data content"); } finally { client.stop(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java index 8a037a70c..8a760ae74 100644 --- a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java @@ -36,13 +36,16 @@ import org.apache.sshd.core.CoreModuleProperties; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + +@TestMethodOrder(MethodName.class) public class LoadTest extends BaseTestSupport { private SshServer sshd; @@ -52,25 +55,25 @@ public LoadTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestFullSupportServer(); sshd.start(); port = sshd.getPort(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { sshd.stop(true); } @Test - public void testLoad() throws Exception { + void load() throws Exception { test("this is my command", 4, 4); } @Test - public void testHighLoad() throws Exception { + void highLoad() throws Exception { final StringBuilder response = new StringBuilder(1000000); for (int i = 0; i < 100000; i++) { response.append("0123456789"); @@ -79,7 +82,7 @@ public void testHighLoad() throws Exception { } @Test - public void testBigResponse() throws Exception { + void bigResponse() throws Exception { final StringBuilder response = new StringBuilder(1000000); for (int i = 0; i < 100000; i++) { response.append("0123456789"); @@ -137,12 +140,12 @@ protected void runClient(String msg) throws Exception { Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L)); - assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting for channel closure"); } finally { channel.close(false); } - assertArrayEquals("Mismatched message data", msg.getBytes(StandardCharsets.UTF_8), out.toByteArray()); + assertArrayEquals(msg.getBytes(StandardCharsets.UTF_8), out.toByteArray(), "Mismatched message data"); } } finally { client.stop(); diff --git a/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java b/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java index 5f8d023dc..a99f16196 100644 --- a/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java @@ -43,18 +43,26 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.server.forward.AcceptAllForwardingFilter; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * Port forwarding tests */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ProxyTest extends BaseTestSupport { private SshServer sshd; private int sshPort; @@ -136,8 +144,8 @@ public ProxyTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); CoreModuleProperties.WINDOW_SIZE.set(sshd, 2048L); CoreModuleProperties.MAX_PACKET_SIZE.set(sshd, 256L); @@ -163,8 +171,8 @@ public void messageReceived(IoSession session, Object message) throws Exception this.acceptor = acceptor; } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -177,7 +185,7 @@ public void tearDown() throws Exception { } @Test - public void testSocksProxy() throws Exception { + void socksProxy() throws Exception { final AtomicReference localAddressHolder = new AtomicReference<>(); final AtomicReference boundAddressHolder = new AtomicReference<>(); final AtomicInteger tearDownSignal = new AtomicInteger(0); @@ -196,9 +204,9 @@ public void tornDownExplicitTunnel( public void tornDownDynamicTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress address, Throwable reason) throws IOException { - assertNotNull("Establishment (local) indication not invoked for address=" + address, localAddressHolder.get()); - assertNotNull("Establishment (bound) indication not invoked for address=" + address, boundAddressHolder.get()); - assertEquals("No tear down indication", 1, tearDownSignal.get()); + assertNotNull(localAddressHolder.get(), "Establishment (local) indication not invoked for address=" + address); + assertNotNull(boundAddressHolder.get(), "Establishment (bound) indication not invoked for address=" + address); + assertEquals(1, tearDownSignal.get(), "No tear down indication"); } @Override @@ -213,9 +221,9 @@ public void tearingDownExplicitTunnel( @Override public void tearingDownDynamicTunnel(org.apache.sshd.common.session.Session session, SshdSocketAddress address) throws IOException { - assertNotNull("Establishment (local) indication not invoked for address=" + address, localAddressHolder.get()); - assertNotNull("Establishment (bound) indication not invoked for address=" + address, boundAddressHolder.get()); - assertEquals("Multiple tearing down indications", 1, tearDownSignal.incrementAndGet()); + assertNotNull(localAddressHolder.get(), "Establishment (local) indication not invoked for address=" + address); + assertNotNull(boundAddressHolder.get(), "Establishment (bound) indication not invoked for address=" + address); + assertEquals(1, tearDownSignal.incrementAndGet(), "Multiple tearing down indications"); } @Override @@ -230,7 +238,7 @@ public void establishingExplicitTunnel( @Override public void establishingDynamicTunnel(org.apache.sshd.common.session.Session session, SshdSocketAddress local) throws IOException { - assertNull("Multiple calls to establishment indicator", localAddressHolder.getAndSet(local)); + assertNull(localAddressHolder.getAndSet(local), "Multiple calls to establishment indicator"); } @Override @@ -247,8 +255,8 @@ public void establishedDynamicTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress local, SshdSocketAddress boundAddress, Throwable reason) throws IOException { - assertSame("Establishment indication not invoked", local, localAddressHolder.get()); - assertNull("Multiple calls to establishment indicator", boundAddressHolder.getAndSet(boundAddress)); + assertSame(local, localAddressHolder.get(), "Establishment indication not invoked"); + assertNull(boundAddressHolder.getAndSet(boundAddress), "Multiple calls to establishment indicator"); } @Override @@ -266,7 +274,7 @@ public String toString() { try (DynamicPortForwardingTracker tracker = session.createDynamicPortForwardingTracker(new SshdSocketAddress(TEST_LOCALHOST, 0))) { dynamic = tracker.getBoundAddress(); - assertTrue("Tracker not marked as open", tracker.isOpen()); + assertTrue(tracker.isOpen(), "Tracker not marked as open"); for (int i = 0; i < 10; i++) { try (Socket s = new Socket( @@ -281,20 +289,21 @@ public String toString() { sockOut.flush(); int l = sockIn.read(buf); - assertEquals("Mismatched data at iteration " + i, expected, - new String(buf, 0, l, StandardCharsets.UTF_8)); + assertEquals(expected, + new String(buf, 0, l, StandardCharsets.UTF_8), + "Mismatched data at iteration " + i); } } } tracker.close(); - assertFalse("Tracker not marked as closed", tracker.isOpen()); + assertFalse(tracker.isOpen(), "Tracker not marked as closed"); } finally { client.removePortForwardingEventListener(listener); } - assertNotNull("Local tunnel address not indicated", localAddressHolder.getAndSet(null)); - assertNotNull("Bound tunnel address not indicated", boundAddressHolder.getAndSet(null)); + assertNotNull(localAddressHolder.getAndSet(null), "Local tunnel address not indicated"); + assertNotNull(boundAddressHolder.getAndSet(null), "Bound tunnel address not indicated"); try { try (Socket s diff --git a/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java b/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java index f0a89adae..7c4a30269 100644 --- a/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java @@ -51,16 +51,17 @@ import org.apache.sshd.server.command.AsyncCommand; import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.Timeout; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertFalse; + /** *

* This test simulates heavy traffic coming from the server towards the client making sure the traffic does not get @@ -69,15 +70,12 @@ * {@link AsyncInPendingWrapper} in this test serves as a handler for {@link WritePendingException}, which can occur * when sending too many messages one after another. */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class WindowAdjustTest extends BaseTestSupport { public static final byte END_FILE = '#'; public static final int BIG_MSG_SEND_COUNT = 10000; - @Rule - public Timeout timeout = Timeout.seconds(TimeUnit.MINUTES.toSeconds(6)); - private SshServer sshServer; private int port; @@ -85,8 +83,8 @@ public WindowAdjustTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshServer = setupTestServer(); byte[] msg = IoUtils.toByteArray(getClass().getResourceAsStream("/big-msg.txt")); @@ -98,8 +96,8 @@ public void setUp() throws Exception { port = sshServer.getPort(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshServer != null) { sshServer.stop(); sshServer.close(true); @@ -107,7 +105,8 @@ public void tearDown() throws Exception { } @Test - public void testTrafficHeavyLoad() throws Exception { + @Timeout(value = 6, unit = TimeUnit.MINUTES) + void trafficHeavyLoad() throws Exception { try (SshClient client = setupTestClient()) { client.start(); @@ -123,7 +122,7 @@ public void testTrafficHeavyLoad() throws Exception { Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(2L)); - assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting for channel closure"); } } finally { client.stop(); diff --git a/sshd-core/src/test/java/org/apache/sshd/agent/AgentTest.java b/sshd-core/src/test/java/org/apache/sshd/agent/AgentTest.java index 48a53be4d..ba89510f6 100644 --- a/sshd-core/src/test/java/org/apache/sshd/agent/AgentTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/agent/AgentTest.java @@ -49,23 +49,26 @@ import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.EchoShell; import org.apache.sshd.util.test.EchoShellFactory; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + +@TestMethodOrder(MethodName.class) public class AgentTest extends BaseTestSupport { public AgentTest() { super(); } - @BeforeClass - public static void checkTestAssumptions() { + @BeforeAll + static void checkTestAssumptions() { // TODO: revisit this test to work without BC - Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BouncyCastle not registered"); AprLibrary library = null; try { library = AprLibrary.getInstance(); @@ -77,11 +80,11 @@ public static void checkTestAssumptions() { throw e; } } - Assume.assumeTrue("Native library N/A", library != null); + Assumptions.assumeTrue(library != null, "Native library N/A"); } @Test - public void testAgentServer() throws Exception { + void agentServer() throws Exception { try (AgentServer agent = new AgentServer()) { String authSocket = agent.start(); @@ -91,23 +94,23 @@ public void testAgentServer() throws Exception { try (SshAgent client = new AgentClient(manager, authSocket)) { Iterable> keys = client.getIdentities(); - assertNotNull("No initial identities", keys); + assertNotNull(keys, "No initial identities"); assertObjectInstanceOf("Non collection initial identities", Collection.class, keys); - assertEquals("Unexpected initial identities size", 0, ((Collection) keys).size()); + assertEquals(0, ((Collection) keys).size(), "Unexpected initial identities size"); KeyPairProvider provider = createTestHostKeyProvider(); KeyPair k = provider.loadKey(null, KeyPairProvider.SSH_RSA); client.addIdentity(k, ""); keys = client.getIdentities(); - assertNotNull("No registered identities after add", keys); + assertNotNull(keys, "No registered identities after add"); assertObjectInstanceOf("Non collection registered identities", Collection.class, keys); - assertEquals("Mismatched registered keys size", 1, ((Collection) keys).size()); + assertEquals(1, ((Collection) keys).size(), "Mismatched registered keys size"); client.removeIdentity(k.getPublic()); keys = client.getIdentities(); - assertNotNull("No registered identities after remove", keys); + assertNotNull(keys, "No registered identities after remove"); assertObjectInstanceOf("Non collection removed identities", Collection.class, keys); - assertEquals("Registered keys size not empty", 0, ((Collection) keys).size()); + assertEquals(0, ((Collection) keys).size(), "Registered keys size not empty"); client.removeAllIdentities(); } @@ -116,7 +119,7 @@ public void testAgentServer() throws Exception { @Test @SuppressWarnings("checkstyle:nestedtrydepth") - public void testAgentForwarding() throws Exception { + void agentForwarding() throws Exception { TestEchoShellFactory shellFactory = new TestEchoShellFactory(); ProxyAgentFactory agentFactory = new ProxyAgentFactory(); LocalAgentFactory localAgentFactory = new LocalAgentFactory(); diff --git a/sshd-core/src/test/java/org/apache/sshd/agent/AgentUnitTest.java b/sshd-core/src/test/java/org/apache/sshd/agent/AgentUnitTest.java index 29223f49c..d7b532510 100644 --- a/sshd-core/src/test/java/org/apache/sshd/agent/AgentUnitTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/agent/AgentUnitTest.java @@ -35,37 +35,38 @@ import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Simple short-circuited test for {@link AbstractAgentClient} and {@link AbstractAgentProxy}. */ -@Category(NoIoTestCase.class) -@RunWith(Parameterized.class) +@Tag("NoIoTestCase") public class AgentUnitTest extends BaseTestSupport { private String algorithm; private BuiltinSignatures factory; - public AgentUnitTest(String algorithm, BuiltinSignatures factory) { + public void initAgentUnitTest(String algorithm, BuiltinSignatures factory) { this.algorithm = algorithm; this.factory = factory; } - @Parameterized.Parameters(name = "{0}") public static List getParameters() { return Arrays.asList(new Object[] { KeyUtils.RSA_SHA512_KEY_TYPE_ALIAS, BuiltinSignatures.rsaSHA512 }, new Object[] { KeyUtils.RSA_SHA256_KEY_TYPE_ALIAS, BuiltinSignatures.rsaSHA256 }, new Object[] { KeyPairProvider.SSH_RSA, BuiltinSignatures.rsa }); } - @Test - public void testRsaSignature() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "{0}") + public void rsaSignature(String algorithm, BuiltinSignatures factory) throws Exception { + initAgentUnitTest(algorithm, factory); SshAgent agent = new AgentImpl(); KeyPair pair = SecurityUtils.getKeyPairGenerator(KeyUtils.RSA_ALGORITHM).generateKeyPair(); agent.addIdentity(pair, "test key"); @@ -74,12 +75,12 @@ public void testRsaSignature() throws Exception { server.setClient(client); byte[] data = { 'd', 'a', 't', 'a' }; Map.Entry result = client.sign(null, pair.getPublic(), algorithm, data); - assertEquals("Unexpected signature algorithm", algorithm, result.getKey()); + assertEquals(algorithm, result.getKey(), "Unexpected signature algorithm"); byte[] signature = result.getValue(); Signature verifier = factory.get(); verifier.initVerifier(null, pair.getPublic()); verifier.update(null, data); - assertTrue("Signature should validate", verifier.verify(null, signature)); + assertTrue(verifier.verify(null, signature), "Signature should validate"); } private static class Server extends AbstractAgentClient { diff --git a/sshd-core/src/test/java/org/apache/sshd/certificates/GenerateOpenSSHClientCertificateTest.java b/sshd-core/src/test/java/org/apache/sshd/certificates/GenerateOpenSSHClientCertificateTest.java index 8110675cf..788b11f2d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/certificates/GenerateOpenSSHClientCertificateTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/certificates/GenerateOpenSSHClientCertificateTest.java @@ -40,24 +40,24 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@Category(NoIoTestCase.class) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@Tag("NoIoTestCase") // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class GenerateOpenSSHClientCertificateTest extends BaseTestSupport { private TestParams params; - public GenerateOpenSSHClientCertificateTest(TestParams params) { - super(); + public void initGenerateOpenSSHClientCertificateTest(TestParams params) { this.params = params; } - @Parameterized.Parameters(name = "{0}") public static Iterable privateKeyParams() { return Arrays.asList( new TestParams("ca_rsa2_256", "user01_rsa_sha2_256_4096"), @@ -132,8 +132,11 @@ protected OpenSshCertificate readOpenSshCertificate(String data) throws Exceptio return (OpenSshCertificate) certPublicKey; } - @Test - public void signCertificate() throws Exception { + @MethodSource("privateKeyParams") + @ParameterizedTest(name = "{0}") + public void signCertificate(TestParams params) throws Exception { + + initGenerateOpenSSHClientCertificateTest(params); final PublicKey clientPublicKey = readPublicKeyFromResource(getClientPublicKeyResource()); @@ -185,15 +188,15 @@ private void verifySignature(OpenSshCertificate cert, String signatureAlgorithm) PublicKey signatureKey = cert.getCaPubKey(); String keyAlg = KeyUtils.getKeyType(signatureKey); String sigAlg = cert.getSignatureAlgorithm(); - assertTrue("Invalid signature algorithm " + sigAlg + " for key " + keyAlg, - KeyUtils.getAllEquivalentKeyTypes(keyAlg).contains(sigAlg)); + assertTrue(KeyUtils.getAllEquivalentKeyTypes(keyAlg).contains(sigAlg), + "Invalid signature algorithm " + sigAlg + " for key " + keyAlg); if (signatureAlgorithm != null) { - assertEquals("Unexpected signature algorithm", signatureAlgorithm, sigAlg); + assertEquals(signatureAlgorithm, sigAlg, "Unexpected signature algorithm"); } Signature verif = NamedFactory.create(BaseBuilder.DEFAULT_SIGNATURE_PREFERENCE, sigAlg); verif.initVerifier(null, signatureKey); verif.update(null, cert.getMessage()); - assertTrue("Signature should validate", verif.verify(null, cert.getSignature())); + assertTrue(verif.verify(null, cert.getSignature()), "Signature should validate"); } private static void assertCertsEqual(OpenSshCertificate o1, OpenSshCertificate o2) { diff --git a/sshd-core/src/test/java/org/apache/sshd/certificates/GenerateOpenSshClientCertificateOracleTest.java b/sshd-core/src/test/java/org/apache/sshd/certificates/GenerateOpenSshClientCertificateOracleTest.java index 00eca2caa..27f237895 100644 --- a/sshd-core/src/test/java/org/apache/sshd/certificates/GenerateOpenSshClientCertificateOracleTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/certificates/GenerateOpenSshClientCertificateOracleTest.java @@ -38,24 +38,24 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@Category(NoIoTestCase.class) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@Tag("NoIoTestCase") // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class GenerateOpenSshClientCertificateOracleTest extends BaseTestSupport { private TestParams params; - public GenerateOpenSshClientCertificateOracleTest(TestParams params) { - super(); + public void initGenerateOpenSshClientCertificateOracleTest(TestParams params) { this.params = params; } - @Parameterized.Parameters(name = "{0}") public static Iterable privateKeyParams() { return Arrays.asList( new TestParams("rsa-sha2-256", "user_rsa_sha2_256_4096"), @@ -113,8 +113,11 @@ protected OpenSshCertificate readCertificateOracle() throws Exception { return (OpenSshCertificate) cert; } - @Test - public void signCertificate() throws Exception { + @MethodSource("privateKeyParams") + @ParameterizedTest(name = "{0}") + public void signCertificate(TestParams params) throws Exception { + + initGenerateOpenSshClientCertificateOracleTest(params); final PublicKey clientPublicKey = readPublicKeyFromResource(getClientPublicKeyResource()); final OpenSshCertificate oracle = readCertificateOracle(); @@ -152,15 +155,15 @@ private void verifySignature(OpenSshCertificate cert, String signatureAlgorithm) PublicKey signatureKey = cert.getCaPubKey(); String keyAlg = KeyUtils.getKeyType(signatureKey); String sigAlg = cert.getSignatureAlgorithm(); - assertTrue("Invalid signature algorithm " + sigAlg + " for key " + keyAlg, - KeyUtils.getAllEquivalentKeyTypes(keyAlg).contains(sigAlg)); + assertTrue(KeyUtils.getAllEquivalentKeyTypes(keyAlg).contains(sigAlg), + "Invalid signature algorithm " + sigAlg + " for key " + keyAlg); if (signatureAlgorithm != null) { - assertEquals("Unexpected signature algorithm", signatureAlgorithm, sigAlg); + assertEquals(signatureAlgorithm, sigAlg, "Unexpected signature algorithm"); } Signature verif = NamedFactory.create(BaseBuilder.DEFAULT_SIGNATURE_PREFERENCE, sigAlg); verif.initVerifier(null, signatureKey); verif.update(null, cert.getMessage()); - assertTrue("Signature should validate", verif.verify(null, cert.getSignature())); + assertTrue(verif.verify(null, cert.getSignature()), "Signature should validate"); } private static void assertCertsEqual(OpenSshCertificate o1, OpenSshCertificate o2) { diff --git a/sshd-core/src/test/java/org/apache/sshd/certificates/OpenSSHCertificateParserTest.java b/sshd-core/src/test/java/org/apache/sshd/certificates/OpenSSHCertificateParserTest.java index e75f84b0b..bd60e38f0 100644 --- a/sshd-core/src/test/java/org/apache/sshd/certificates/OpenSSHCertificateParserTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/certificates/OpenSSHCertificateParserTest.java @@ -34,25 +34,25 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; - -@Category(NoIoTestCase.class) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@Tag("NoIoTestCase") // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class OpenSSHCertificateParserTest extends BaseTestSupport { private static final String USER_KEY_PATH = "org/apache/sshd/client/opensshcerts/user/"; private TestParams params; - public OpenSSHCertificateParserTest(TestParams params) { + public void initOpenSSHCertificateParserTest(TestParams params) { this.params = params; } - @Parameterized.Parameters(name = "{0}") public static Iterable privateKeyParams() { return Arrays.asList( new TestParams("rsa-sha2-256", "user01_rsa_sha2_256_2048"), @@ -70,9 +70,12 @@ private String getCertificateResource() { return USER_KEY_PATH + params.privateKey + "-cert" + PublicKeyEntry.PUBKEY_FILE_SUFFIX; } - @Test + @MethodSource("privateKeyParams") + @ParameterizedTest(name = "{0}") @SuppressWarnings("synthetic-access") - public void testParseCertificate() throws Exception { + public void parseCertificate(TestParams params) throws Exception { + + initOpenSSHCertificateParserTest(params); try (InputStream certInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(getCertificateResource())) { @@ -112,12 +115,12 @@ private void verifySignature(OpenSshCertificate cert) throws Exception { PublicKey signatureKey = cert.getCaPubKey(); String keyAlg = KeyUtils.getKeyType(signatureKey); String sigAlg = cert.getSignatureAlgorithm(); - assertTrue("Invalid signature algorithm " + sigAlg + " for key " + keyAlg, - KeyUtils.getAllEquivalentKeyTypes(keyAlg).contains(sigAlg)); + assertTrue(KeyUtils.getAllEquivalentKeyTypes(keyAlg).contains(sigAlg), + "Invalid signature algorithm " + sigAlg + " for key " + keyAlg); Signature verif = NamedFactory.create(BaseBuilder.DEFAULT_SIGNATURE_PREFERENCE, sigAlg); verif.initVerifier(null, signatureKey); verif.update(null, cert.getMessage()); - assertTrue("Signature should validate", verif.verify(null, cert.getSignature())); + assertTrue(verif.verify(null, cert.getSignature()), "Signature should validate"); } private static class TestParams { diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ClientAuthenticationManagerTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ClientAuthenticationManagerTest.java index 0130c5c09..aa0e97163 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/ClientAuthenticationManagerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/ClientAuthenticationManagerTest.java @@ -53,22 +53,27 @@ import org.apache.sshd.common.session.SessionListener; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ClientAuthenticationManagerTest extends BaseTestSupport { public ClientAuthenticationManagerTest() { super(); } @Test - public void testDefaultUserAuthFactoriesMethods() { + void defaultUserAuthFactoriesMethods() { AtomicReference> factoriesHolder = new AtomicReference<>(); @SuppressWarnings("checkstyle:anoninnerlength") ClientAuthenticationManager manager = new ClientAuthenticationManager() { @@ -79,7 +84,7 @@ public List getUserAuthFactories() { @Override public void setUserAuthFactories(List userAuthFactories) { - assertNull("Unexpected multiple invocation", factoriesHolder.getAndSet(userAuthFactories)); + assertNull(factoriesHolder.getAndSet(userAuthFactories), "Unexpected multiple invocation"); } @Override @@ -177,36 +182,35 @@ public String removePasswordIdentity(String password) { throw new UnsupportedOperationException("removePasswordIdentity(" + password + ")"); } }; - assertEquals("Mismatched initial factories list", "", manager.getUserAuthFactoriesNameList()); + assertEquals("", manager.getUserAuthFactoriesNameList(), "Mismatched initial factories list"); String expected = NamedResource.getNames(BuiltinUserAuthFactories.VALUES); manager.setUserAuthFactoriesNameList(expected); - assertEquals("Mismatched updated factories names", expected, manager.getUserAuthFactoriesNameList()); + assertEquals(expected, manager.getUserAuthFactoriesNameList(), "Mismatched updated factories names"); List factories = factoriesHolder.get(); - assertEquals("Mismatched factories count", - BuiltinUserAuthFactories.VALUES.size(), GenericUtils.size(factories)); + assertEquals(BuiltinUserAuthFactories.VALUES.size(), GenericUtils.size(factories), "Mismatched factories count"); for (BuiltinUserAuthFactories f : BuiltinUserAuthFactories.VALUES) { - assertTrue("Missing factory=" + f.name(), factories.contains(f.create())); + assertTrue(factories.contains(f.create()), "Missing factory=" + f.name()); } } @Test - public void testAddRemoveClientSessionIdentities() throws Exception { + void addRemoveClientSessionIdentities() throws Exception { try (ClientSession session = createMockClientSession()) { testClientAuthenticationManager(session); } } @Test - public void testAddRemoveSshClientIdentities() throws Exception { + void addRemoveSshClientIdentities() throws Exception { try (SshClient client = SshClient.setUpDefaultClient()) { testClientAuthenticationManager(client); } } @Test - public void testClientProvidersPropagation() throws Exception { + void clientProvidersPropagation() throws Exception { try (SshClient client = SshClient.setUpDefaultClient()) { client.setServiceFactories(SshClient.DEFAULT_SERVICE_FACTORIES); client.setUserAuthFactories(SshClient.DEFAULT_USER_AUTH_FACTORIES); @@ -230,41 +234,41 @@ private void testClientProvidersPropagation( throws Exception { String baseName = type.getSimpleName(); outputDebugMessage("testClientProvidersPropagation(%s)", baseName); - assertTrue(baseName + ": not an interface", type.isInterface()); + assertTrue(type.isInterface(), baseName + ": not an interface"); Method getter = ClientAuthenticationManager.class.getMethod("get" + baseName); Method setter = ClientAuthenticationManager.class.getMethod("set" + baseName, type); Object clientProvider = Mockito.mock(type); setter.invoke(client, clientProvider); - assertSame(baseName + ": mismatched client-only provider", clientProvider, getter.invoke(session)); + assertSame(clientProvider, getter.invoke(session), baseName + ": mismatched client-only provider"); Object sessionProvider = Mockito.mock(type); setter.invoke(session, sessionProvider); - assertSame(baseName + ": mismatched session override provider", sessionProvider, getter.invoke(session)); + assertSame(sessionProvider, getter.invoke(session), baseName + ": mismatched session override provider"); setter.invoke(session, new Object[] { null }); - assertSame(baseName + ": mismatched nullified session provider", clientProvider, getter.invoke(session)); + assertSame(clientProvider, getter.invoke(session), baseName + ": mismatched nullified session provider"); } private M testClientAuthenticationManager(M manager) { if (manager != null) { String expected = getCurrentTestName(); - assertNull("Unexpected initial password identity", manager.removePasswordIdentity(expected)); + assertNull(manager.removePasswordIdentity(expected), "Unexpected initial password identity"); manager.addPasswordIdentity(expected); String actual = manager.removePasswordIdentity(expected); - assertSame("Mismatched removed password identity", expected, actual); - assertNull("Password identity not removed", manager.removePasswordIdentity(expected)); + assertSame(expected, actual, "Mismatched removed password identity"); + assertNull(manager.removePasswordIdentity(expected), "Password identity not removed"); } if (manager != null) { KeyPair expected = new KeyPair(Mockito.mock(PublicKey.class), Mockito.mock(PrivateKey.class)); - assertNull("Unexpected initial pubket identity", manager.removePublicKeyIdentity(expected)); + assertNull(manager.removePublicKeyIdentity(expected), "Unexpected initial pubket identity"); manager.addPublicKeyIdentity(expected); KeyPair actual = manager.removePublicKeyIdentity(expected); - assertSame("Mismatched removed pubkey identity", expected, actual); - assertNull("Pubkey identity not removed", manager.removePublicKeyIdentity(expected)); + assertSame(expected, actual, "Mismatched removed pubkey identity"); + assertNull(manager.removePublicKeyIdentity(expected), "Pubkey identity not removed"); } return manager; diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ClientDeadlockTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ClientDeadlockTest.java index 047aeb2d1..60f942393 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/ClientDeadlockTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/ClientDeadlockTest.java @@ -33,18 +33,21 @@ import org.apache.sshd.server.session.ServerSessionImpl; import org.apache.sshd.server.session.SessionFactory; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ClientDeadlockTest extends BaseTestSupport { private SshServer sshd; private SshClient client; @@ -54,8 +57,8 @@ public ClientDeadlockTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); sshd.setSessionFactory(new SessionFactory(sshd) { @Override @@ -69,8 +72,8 @@ protected ServerSessionImpl doCreateSession(IoSession ioSession) throws Exceptio client = setupTestClient(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -80,15 +83,15 @@ public void tearDown() throws Exception { } @Test - public void testSimpleClient() throws Exception { + void simpleClient() throws Exception { client.start(); ConnectFuture future = client.connect(getCurrentTestName(), TEST_LOCALHOST, port); try (ClientSession session = future.verify(CONNECT_TIMEOUT).getSession()) { Collection events = session.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED), TimeUnit.SECONDS.toMillis(7L)); - assertTrue("Close event not signalled: " + events, events.contains(ClientSession.ClientSessionEvent.CLOSED)); - assertFalse("Session not marked as closed", session.isOpen()); + assertTrue(events.contains(ClientSession.ClientSessionEvent.CLOSED), "Close event not signalled: " + events); + assertFalse(session.isOpen(), "Session not marked as closed"); } catch (SshException e) { Throwable cause = e.getCause(); // Due to a race condition we might get this exception diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ClientDefaultSetupTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ClientDefaultSetupTest.java index b689506ab..ebd149cad 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/ClientDefaultSetupTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/ClientDefaultSetupTest.java @@ -20,13 +20,13 @@ package org.apache.sshd.client; import org.apache.sshd.DefaultSetupTestSupport; -import org.junit.FixMethodOrder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ClientDefaultSetupTest extends DefaultSetupTestSupport { public ClientDefaultSetupTest() { super(SshClient.setUpDefaultClient()); diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ClientSessionListenerTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ClientSessionListenerTest.java index e1b73e822..21f004de0 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/ClientSessionListenerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/ClientSessionListenerTest.java @@ -44,16 +44,21 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ClientSessionListenerTest extends BaseTestSupport { private static SshServer sshd; private static int port; @@ -63,8 +68,8 @@ public ClientSessionListenerTest() { super(); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(ClientSessionListenerTest.class); sshd.start(); port = sshd.getPort(); @@ -73,8 +78,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -93,7 +98,7 @@ public static void tearDownClientAndServer() throws Exception { } @Test - public void testSessionListenerCanModifyKEXNegotiation() throws Exception { + void sessionListenerCanModifyKEXNegotiation() throws Exception { Map kexParams = new EnumMap<>(KexProposalOption.class); kexParams.put(KexProposalOption.ALGORITHMS, getLeastFavorite(KeyExchange.class, client.getKeyExchangeFactories())); kexParams.put(KexProposalOption.C2SENC, getLeastFavorite(CipherFactory.class, sshd.getCipherFactories())); @@ -117,7 +122,7 @@ public void sessionCreated(Session session) { kexParams.forEach((option, factory) -> { String expected = factory.getName(); String actual = session.getNegotiatedKexParameter(option); - assertEquals("Mismatched values for KEX=" + option, expected, actual); + assertEquals(expected, actual, "Mismatched values for KEX=" + option); }); } finally { client.removeSessionListener(listener); @@ -125,7 +130,7 @@ public void sessionCreated(Session session) { } @Test - public void testSessionListenerCanInfluenceAuthentication() throws IOException { + void sessionListenerCanInfluenceAuthentication() throws IOException { AtomicInteger verificationCount = new AtomicInteger(); ServerKeyVerifier verifier = (sshClientSession, remoteAddress, serverKey) -> { verificationCount.incrementAndGet(); @@ -146,11 +151,11 @@ public void sessionEvent(Session session, Event event) { client.addSessionListener(listener); try (ClientSession session = createTestClientSession()) { - assertNotSame("Invalid default user interaction", UserInteraction.NONE, client.getUserInteraction()); - assertNotSame("Invalid default server key verifier", verifier, client.getServerKeyVerifier()); - assertSame("Mismatched session user interaction", UserInteraction.NONE, session.getUserInteraction()); - assertSame("Mismatched session server key verifier", verifier, session.getServerKeyVerifier()); - assertEquals("Mismatched verification count", 1, verificationCount.get()); + assertNotSame(UserInteraction.NONE, client.getUserInteraction(), "Invalid default user interaction"); + assertNotSame(verifier, client.getServerKeyVerifier(), "Invalid default server key verifier"); + assertSame(UserInteraction.NONE, session.getUserInteraction(), "Mismatched session user interaction"); + assertSame(verifier, session.getServerKeyVerifier(), "Mismatched session server key verifier"); + assertEquals(1, verificationCount.get(), "Mismatched verification count"); } finally { client.removeSessionListener(listener); } @@ -159,7 +164,7 @@ public void sessionEvent(Session session, Event event) { private static NamedResource getLeastFavorite( Class type, List factories) { int numFactories = GenericUtils.size(factories); - assertTrue("No factories for " + type.getSimpleName(), numFactories > 0); + assertTrue(numFactories > 0, "No factories for " + type.getSimpleName()); return factories.get(numFactories - 1); } diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java index a41c2e1fc..a27ef1777 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/ClientTest.java @@ -129,20 +129,31 @@ import org.apache.sshd.util.test.EchoShell; import org.apache.sshd.util.test.EchoShellFactory; import org.apache.sshd.util.test.TeeOutputStream; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ClientTest extends BaseTestSupport { private SshServer sshd; @@ -158,31 +169,31 @@ public class ClientTest extends BaseTestSupport { @Override public void sessionCreated(Session session) { assertObjectInstanceOf("Non client session creation notification", ClientSession.class, session); - assertNull("Multiple creation notifications", clientSessionHolder.getAndSet((ClientSession) session)); + assertNull(clientSessionHolder.getAndSet((ClientSession) session), "Multiple creation notifications"); } @Override public void sessionEvent(Session session, Event event) { assertObjectInstanceOf("Non client session event notification: " + event, ClientSession.class, session); - assertSame("Mismatched client session event instance: " + event, clientSessionHolder.get(), session); + assertSame(clientSessionHolder.get(), session, "Mismatched client session event instance: " + event); } @Override public void sessionException(Session session, Throwable t) { assertObjectInstanceOf("Non client session exception notification", ClientSession.class, session); - assertNotNull("No session exception data", t); + assertNotNull(t, "No session exception data"); } @Override public void sessionDisconnect(Session session, int reason, String msg, String language, boolean initiator) { assertObjectInstanceOf("Non client session exception notification", ClientSession.class, session); - assertTrue("Invalid reason code: " + reason, reason >= 0); + assertTrue(reason >= 0, "Invalid reason code: " + reason); } @Override public void sessionClosed(Session session) { assertObjectInstanceOf("Non client session closure notification", ClientSession.class, session); - assertSame("Mismatched client session closure instance", clientSessionHolder.getAndSet(null), session); + assertSame(clientSessionHolder.getAndSet(null), session, "Mismatched client session closure instance"); sessionCloseLatch.countDown(); } }; @@ -191,8 +202,8 @@ public ClientTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { authLatch = new CountDownLatch(0); channelLatch = new CountDownLatch(0); sessionCloseLatch = new CountDownLatch(1); @@ -246,8 +257,8 @@ public String toString() { client.addSessionListener(clientSessionListener); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -258,19 +269,19 @@ public void tearDown() throws Exception { } @Test - public void testClientStartedIndicator() throws Exception { + void clientStartedIndicator() throws Exception { client.start(); try { - assertTrue("Client not marked as started", client.isStarted()); + assertTrue(client.isStarted(), "Client not marked as started"); } finally { client.stop(); } - assertFalse("Client not marked as stopped", client.isStarted()); + assertFalse(client.isStarted(), "Client not marked as stopped"); } @Test - public void testPropertyResolutionHierarchy() throws Exception { + void propertyResolutionHierarchy() throws Exception { String sessionPropName = getCurrentTestName() + "-session"; AtomicReference sessionConfigValueHolder = new AtomicReference<>(null); client.addSessionListener(new SessionListener() { @@ -327,22 +338,22 @@ private void updateChannelConfigProperty(Channel channel, Object value) { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertSame("Session established", - sessionConfigValueHolder.get(), PropertyResolverUtils.getObject(session, sessionPropName)); + assertSame(sessionConfigValueHolder.get(), PropertyResolverUtils.getObject(session, sessionPropName), + "Session established"); session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); - assertSame("Session authenticated", - sessionConfigValueHolder.get(), PropertyResolverUtils.getObject(session, sessionPropName)); + assertSame(sessionConfigValueHolder.get(), PropertyResolverUtils.getObject(session, sessionPropName), + "Session authenticated"); try (ChannelExec channel = session.createExecChannel(getCurrentTestName()); OutputStream stdout = new NoCloseOutputStream(System.out); OutputStream stderr = new NoCloseOutputStream(System.err)) { - assertSame("Channel created", - channelConfigValueHolder.get(), PropertyResolverUtils.getObject(channel, channelPropName)); - assertNull("Direct channel created session prop", - PropertyResolverUtils.getObject(channel.getProperties(), sessionPropName)); - assertSame("Indirect channel created session prop", - sessionConfigValueHolder.get(), PropertyResolverUtils.getObject(channel, sessionPropName)); + assertSame(channelConfigValueHolder.get(), PropertyResolverUtils.getObject(channel, channelPropName), + "Channel created"); + assertNull(PropertyResolverUtils.getObject(channel.getProperties(), sessionPropName), + "Direct channel created session prop"); + assertSame(sessionConfigValueHolder.get(), PropertyResolverUtils.getObject(channel, sessionPropName), + "Indirect channel created session prop"); channel.setOut(stdout); channel.setErr(stderr); @@ -354,7 +365,7 @@ private void updateChannelConfigProperty(Channel channel, Object value) { } @Test - public void testClientStillActiveIfListenerExceptions() throws Exception { + void clientStillActiveIfListenerExceptions() throws Exception { Map eventsMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); Collection failuresSet = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); Logger log = LoggerFactory.getLogger(getClass()); @@ -375,7 +386,7 @@ public void channelOpenFailure(Channel channel, Throwable reason) { String name = ((NamedResource) reason).getName(); synchronized (failuresSet) { - assertTrue("Re-signalled failure location: " + name, failuresSet.add(name)); + assertTrue(failuresSet.add(name), "Re-signalled failure location: " + name); } } @@ -432,14 +443,14 @@ private void handleChannelEvent(String name, Channel channel) { outputDebugMessage("%s at retry #%d: %s", e.getClass().getSimpleName(), retryCount, e.getMessage()); synchronized (eventsMap) { eventsMap.remove("Closed"); // since it is called anyway but does not cause an IOException - assertTrue("Unexpected failure at retry #" + retryCount, eventsMap.size() < 3); + assertTrue(eventsMap.size() < 3, "Unexpected failure at retry #" + retryCount); } } catch (ChannelFailureException e) { - assertEquals("Mismatched failure reason", "Initialized", e.getMessage()); + assertEquals("Initialized", e.getMessage(), "Mismatched failure reason"); } catch (IllegalStateException e) { // sometimes due to timing issues we get this problem - assertTrue("Premature exception phase - count=" + retryCount, retryCount > 0); - assertTrue("Session not closing", session.isClosing() || session.isClosed()); + assertTrue(retryCount > 0, "Premature exception phase - count=" + retryCount); + assertTrue(session.isClosing() || session.isClosed(), "Session not closing"); log.warn("Session closing prematurely: " + session); return; } @@ -448,27 +459,27 @@ private void handleChannelEvent(String name, Channel channel) { client.stop(); } - assertEquals("Mismatched total failures count on test end", 2, eventsMap.size()); - assertEquals("Mismatched open failures count on test end: " + failuresSet, 1, failuresSet.size()); + assertEquals(2, eventsMap.size(), "Mismatched total failures count on test end"); + assertEquals(1, failuresSet.size(), "Mismatched open failures count on test end: " + failuresSet); } @Test - public void testSimpleClientListener() throws Exception { + void simpleClientListener() throws Exception { AtomicReference channelHolder = new AtomicReference<>(null); client.addChannelListener(new ChannelListener() { @Override public void channelOpenSuccess(Channel channel) { - assertSame("Mismatched opened channel instances", channel, channelHolder.get()); + assertSame(channel, channelHolder.get(), "Mismatched opened channel instances"); } @Override public void channelOpenFailure(Channel channel, Throwable reason) { - assertSame("Mismatched failed open channel instances", channel, channelHolder.get()); + assertSame(channel, channelHolder.get(), "Mismatched failed open channel instances"); } @Override public void channelInitialized(Channel channel) { - assertNull("Multiple channel initialization notifications", channelHolder.getAndSet(channel)); + assertNull(channelHolder.getAndSet(channel), "Multiple channel initialization notifications"); } @Override @@ -478,7 +489,7 @@ public void channelStateChanged(Channel channel, String hint) { @Override public void channelClosed(Channel channel, Throwable reason) { - assertSame("Mismatched closed channel instances", channel, channelHolder.getAndSet(null)); + assertSame(channel, channelHolder.getAndSet(null), "Mismatched closed channel instances"); } }); @@ -507,7 +518,7 @@ public void channelClosed(Channel channel, Throwable reason) { private void testClientListener( AtomicReference channelHolder, Class channelType, Factory factory) throws Exception { - assertNull(channelType.getSimpleName() + ": Unexpected currently active channel", channelHolder.get()); + assertNull(channelHolder.get(), channelType.getSimpleName() + ": Unexpected currently active channel"); try (C instance = factory.create()) { Channel expectedChannel; @@ -520,14 +531,14 @@ private void testClientListener( } Channel actualChannel = channelHolder.get(); - assertSame("Mismatched listener " + channelType.getSimpleName() + " instances", expectedChannel, actualChannel); + assertSame(expectedChannel, actualChannel, "Mismatched listener " + channelType.getSimpleName() + " instances"); } - assertNull(channelType.getSimpleName() + ": Active channel closure not signalled", channelHolder.get()); + assertNull(channelHolder.get(), channelType.getSimpleName() + ": Active channel closure not signalled"); } @Test - public void testAsyncClient() throws Exception { + void asyncClient() throws Exception { CoreModuleProperties.WINDOW_SIZE.set(sshd, 1024L); sshd.setShellFactory(new AsyncEchoShellFactory()); @@ -615,9 +626,9 @@ public void operationComplete(IoReadFuture future) { Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(15L)); long waitEnd = System.currentTimeMillis(); - assertFalse("Timeout after " + (waitEnd - waitStart) + " ms. while waiting for channel closure", - result.contains(ClientChannelEvent.TIMEOUT)); - assertEquals("Mismatched sent and received data size", nbMessages * message.length, baosOut.size()); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), + "Timeout after " + (waitEnd - waitStart) + " ms. while waiting for channel closure"); + assertEquals(nbMessages * message.length, baosOut.size(), "Mismatched sent and received data size"); } client.close(true); @@ -628,13 +639,13 @@ public void operationComplete(IoReadFuture future) { // sessions get closed "bottom-up": the IO channel closes and notifies the SshSession about it, which then // closes itself. This is an asynchronous process, so we can't just synchronously test // clientSessionHolder.get()! - assertTrue("Asynchronous session closure took too long", - sessionCloseLatch.await(CLOSE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertTrue(sessionCloseLatch.await(CLOSE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS), + "Asynchronous session closure took too long"); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testExecAsyncClient() throws Exception { + void execAsyncClient() throws Exception { Logger log = LoggerFactory.getLogger(getClass()); client.start(); try (ClientSession session = createTestClientSession()) { @@ -702,7 +713,7 @@ public void operationComplete(IoReadFuture future) { } @Test - public void testCommandDeadlock() throws Exception { + void commandDeadlock() throws Exception { client.start(); try (ClientSession session = createTestClientSession(); @@ -729,18 +740,18 @@ public void testCommandDeadlock() throws Exception { Collection mask = EnumSet.of(ClientChannelEvent.CLOSED); Collection result = channel.waitFor(mask, CLOSE_TIMEOUT); - assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT)); - assertTrue("Missing close event: " + result, result.containsAll(mask)); - assertTrue("Failed to close session on time", session.close(false).await(CLOSE_TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting for channel closure"); + assertTrue(result.containsAll(mask), "Missing close event: " + result); + assertTrue(session.close(false).await(CLOSE_TIMEOUT), "Failed to close session on time"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testClient() throws Exception { + void client() throws Exception { client.start(); try (ClientSession session = createTestClientSession(); @@ -773,22 +784,22 @@ public void testClient() throws Exception { teeOut.flush(); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), CLOSE_TIMEOUT); - assertFalse("Timeout while waiting on channel close", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting on channel close"); channel.close(false); client.stop(); - assertArrayEquals("Mismatched sent and received data", sent.toByteArray(), out.toByteArray()); + assertArrayEquals(sent.toByteArray(), out.toByteArray(), "Mismatched sent and received data"); } } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testClientInverted() throws Exception { + void clientInverted() throws Exception { client.start(); try (ClientSession session = createTestClientSession(); @@ -817,23 +828,23 @@ public void testClientInverted() throws Exception { } Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), CLOSE_TIMEOUT); - assertFalse("Timeout while waiting on channel close", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting on channel close"); channel.close(false); client.stop(); - assertArrayEquals("Mismatched sent and received data", sent.toByteArray(), out.toByteArray()); + assertArrayEquals(sent.toByteArray(), out.toByteArray(), "Mismatched sent and received data"); } finally { client.stop(); } - assertTrue("Asynchronous session closure took too long", - sessionCloseLatch.await(CLOSE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertTrue(sessionCloseLatch.await(CLOSE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS), + "Asynchronous session closure took too long"); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testClientWithCustomChannel() throws Exception { + void clientWithCustomChannel() throws Exception { client.start(); try (ClientSession session = createTestClientSession(); @@ -846,16 +857,16 @@ public void testClientWithCustomChannel() throws Exception { channel.setOut(out); channel.setErr(err); channel.open().verify(OPEN_TIMEOUT); - assertTrue("Failed to close channel on time", channel.close(false).await(CLOSE_TIMEOUT)); + assertTrue(channel.close(false).await(CLOSE_TIMEOUT), "Failed to close channel on time"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testClientClosingStream() throws Exception { + void clientClosingStream() throws Exception { client.start(); try (ClientSession session = createTestClientSession(); @@ -884,23 +895,23 @@ public void testClientClosingStream() throws Exception { } Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), CLOSE_TIMEOUT); - assertFalse("Timeout while waiting on channel close", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting on channel close"); channel.close(false); client.stop(); - assertArrayEquals("Mismatched sent and received data", sent.toByteArray(), out.toByteArray()); + assertArrayEquals(sent.toByteArray(), out.toByteArray(), "Mismatched sent and received data"); } finally { client.stop(); } - assertTrue("Asynchronous session closure took too long", - sessionCloseLatch.await(CLOSE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertTrue(sessionCloseLatch.await(CLOSE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS), + "Asynchronous session closure took too long"); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testClientWithLengthyDialog() throws Exception { + void clientWithLengthyDialog() throws Exception { // Reduce window size and packet size // FactoryManagerUtils.updateProperty(client, SshClient.WINDOW_SIZE, 0x20000); // FactoryManagerUtils.updateProperty(client, SshClient.MAX_PACKET_SIZE, 0x1000); @@ -943,72 +954,74 @@ public void testClientWithLengthyDialog() throws Exception { outputDebugMessage("Waiting for channel to be closed"); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), CLOSE_TIMEOUT.multipliedBy(2)); - assertFalse("Timeout while waiting on channel close", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting on channel close"); channel.close(false); client.stop(); - assertArrayEquals("Mismatched sent and received data", sent.toByteArray(), out.toByteArray()); + assertArrayEquals(sent.toByteArray(), out.toByteArray(), "Mismatched sent and received data"); } finally { client.stop(); } - assertTrue("Asynchronous session closure took too long", - sessionCloseLatch.await(CLOSE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertTrue(sessionCloseLatch.await(CLOSE_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS), + "Asynchronous session closure took too long"); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } - @Test(expected = SshException.class) - public void testOpenChannelOnClosedSession() throws Exception { - client.start(); + @Test + void openChannelOnClosedSession() throws Exception { + assertThrows(SshException.class, () -> { + client.start(); - try (ClientSession session = createTestClientSession(); - ClientChannel channel = session.createShellChannel()) { + try (ClientSession session = createTestClientSession(); + ClientChannel channel = session.createShellChannel()) { - session.close(false); - assertNull("Session closure not signalled", clientSessionHolder.get()); + session.close(false); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); - try (PipedOutputStream pipedIn = new PipedOutputStream(); - InputStream inPipe = new PipedInputStream(pipedIn); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream()) { + try (PipedOutputStream pipedIn = new PipedOutputStream(); + InputStream inPipe = new PipedInputStream(pipedIn); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream err = new ByteArrayOutputStream()) { - channel.setIn(inPipe); - channel.setOut(out); - channel.setErr(err); - channel.open(); + channel.setIn(inPipe); + channel.setOut(out); + channel.setErr(err); + channel.open(); + } + } finally { + client.stop(); } - } finally { - client.stop(); - } + }); } @Test - public void testCloseBeforeAuthSucceed() throws Exception { + void closeBeforeAuthSucceed() throws Exception { authLatch = new CountDownLatch(1); client.start(); try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); session.addPasswordIdentity(getCurrentTestName()); AuthFuture authFuture = session.auth(); CloseFuture closeFuture = session.close(false); authLatch.countDown(); - assertTrue("Authentication writing not completed in time", authFuture.await(AUTH_TIMEOUT)); - assertTrue("Session closing not complete in time", closeFuture.await(CLOSE_TIMEOUT)); - assertNotNull("No authentication exception", authFuture.getException()); - assertTrue("Future not closed", closeFuture.isClosed()); + assertTrue(authFuture.await(AUTH_TIMEOUT), "Authentication writing not completed in time"); + assertTrue(closeFuture.await(CLOSE_TIMEOUT), "Session closing not complete in time"); + assertNotNull(authFuture.getException(), "No authentication exception"); + assertTrue(closeFuture.isClosed(), "Future not closed"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testCloseCleanBeforeChannelOpened() throws Exception { + void closeCleanBeforeChannelOpened() throws Exception { client.start(); try (ClientSession session = createTestClientSession(); @@ -1023,19 +1036,19 @@ public void testCloseCleanBeforeChannelOpened() throws Exception { OpenFuture openFuture = channel.open(); CloseFuture closeFuture = session.close(false); - assertTrue("Channel not open in time", openFuture.await(DEFAULT_TIMEOUT)); - assertTrue("Session closing not complete in time", closeFuture.await(DEFAULT_TIMEOUT)); - assertTrue("Not open", openFuture.isOpened()); - assertTrue("Not closed", closeFuture.isClosed()); + assertTrue(openFuture.await(DEFAULT_TIMEOUT), "Channel not open in time"); + assertTrue(closeFuture.await(DEFAULT_TIMEOUT), "Session closing not complete in time"); + assertTrue(openFuture.isOpened(), "Not open"); + assertTrue(closeFuture.isClosed(), "Not closed"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testCloseImmediateBeforeChannelOpened() throws Exception { + void closeImmediateBeforeChannelOpened() throws Exception { channelLatch = new CountDownLatch(1); client.start(); @@ -1051,20 +1064,20 @@ public void testCloseImmediateBeforeChannelOpened() throws Exception { OpenFuture openFuture = channel.open(); CloseFuture closeFuture = session.close(true); - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); channelLatch.countDown(); - assertTrue("Channel not open in time", openFuture.await(DEFAULT_TIMEOUT)); - assertTrue("Session closing not complete in time", closeFuture.await(DEFAULT_TIMEOUT)); - assertNotNull("No open exception", openFuture.getException()); - assertTrue("Not closed", closeFuture.isClosed()); + assertTrue(openFuture.await(DEFAULT_TIMEOUT), "Channel not open in time"); + assertTrue(closeFuture.await(DEFAULT_TIMEOUT), "Session closing not complete in time"); + assertNotNull(openFuture.getException(), "No open exception"); + assertTrue(closeFuture.isClosed(), "Not closed"); } finally { client.stop(); } } @Test - public void testPublicKeyAuth() throws Exception { + void publicKeyAuth() throws Exception { sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE); sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE); client.setUserAuthFactories(Collections.singletonList(UserAuthPublicKeyFactory.INSTANCE)); @@ -1072,18 +1085,18 @@ public void testPublicKeyAuth() throws Exception { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); KeyPairProvider keys = createTestHostKeyProvider(); session.addPublicKeyIdentity(keys.loadKey(session, CommonTestSupportUtils.DEFAULT_TEST_HOST_KEY_TYPE)); session.auth().verify(AUTH_TIMEOUT); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testPublicKeyAuthWithEncryptedKey() throws Exception { + void publicKeyAuthWithEncryptedKey() throws Exception { // Create an encrypted private key file KeyPair pair = SecurityUtils.getKeyPairGenerator("RSA").generateKeyPair(); Path keyFile = getTestResourcesFolder().resolve("userKey"); @@ -1112,17 +1125,17 @@ public void testPublicKeyAuthWithEncryptedKey() throws Exception { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(CONNECT_TIMEOUT) .getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); session.auth().verify(AUTH_TIMEOUT); - assertTrue("Password provider should have been called", passwordProvided.get()); + assertTrue(passwordProvided.get(), "Password provider should have been called"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testPublicKeyAuthNewWithFailureOnFirstIdentity() throws Exception { + void publicKeyAuthNewWithFailureOnFirstIdentity() throws Exception { SimpleGeneratorHostKeyProvider provider = new SimpleGeneratorHostKeyProvider(); provider.setAlgorithm(CommonTestSupportUtils.DEFAULT_TEST_HOST_KEY_PROVIDER_ALGORITHM); provider.setKeySize(CommonTestSupportUtils.DEFAULT_TEST_HOST_KEY_SIZE); @@ -1135,18 +1148,18 @@ public void testPublicKeyAuthNewWithFailureOnFirstIdentity() throws Exception { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); session.addPublicKeyIdentity(provider.loadKey(session, CommonTestSupportUtils.DEFAULT_TEST_HOST_KEY_TYPE)); session.addPublicKeyIdentity(pair); session.auth().verify(AUTH_TIMEOUT); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testPasswordAuthNew() throws Exception { + void passwordAuthNew() throws Exception { client.setUserAuthFactories(Collections.singletonList(UserAuthPasswordFactory.INSTANCE)); client.start(); @@ -1156,28 +1169,28 @@ public void testPasswordAuthNew() throws Exception { } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testPasswordAuthNewWithFailureOnFirstIdentity() throws Exception { + void passwordAuthNewWithFailureOnFirstIdentity() throws Exception { client.setUserAuthFactories(Collections.singletonList(UserAuthPasswordFactory.INSTANCE)); client.start(); try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); session.addPasswordIdentity(getClass().getSimpleName()); session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testKeyboardInteractiveAuthNew() throws Exception { + void keyboardInteractiveAuthNew() throws Exception { client.setUserAuthFactories(Collections.singletonList(UserAuthKeyboardInteractiveFactory.INSTANCE)); client.start(); @@ -1187,28 +1200,29 @@ public void testKeyboardInteractiveAuthNew() throws Exception { } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testKeyboardInteractiveAuthNewWithFailureOnFirstIdentity() throws Exception { + void keyboardInteractiveAuthNewWithFailureOnFirstIdentity() throws Exception { client.setUserAuthFactories(Collections.singletonList(UserAuthKeyboardInteractiveFactory.INSTANCE)); client.start(); try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); session.addPasswordIdentity(getClass().getSimpleName()); session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } - @Test // see SSHD-504 - public void testDefaultKeyboardInteractivePasswordPromptLocationIndependence() throws Exception { + // see SSHD-504 + @Test + void defaultKeyboardInteractivePasswordPromptLocationIndependence() throws Exception { Collection mismatchedPrompts = new LinkedList<>(); client.setUserAuthFactories( Collections.singletonList( @@ -1271,31 +1285,31 @@ protected String getInteractionPrompt(ServerSession session) { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT) .getSession()) { - assertNotNull("Client session creation not signalled at iteration #" + index, clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled at iteration #" + index); String password = "bad-" + getCurrentTestName() + "-" + index; session.addPasswordIdentity(password); AuthFuture future = session.auth(); - assertTrue("Failed to verify password=" + password + " in time", future.await(AUTH_TIMEOUT)); - assertFalse("Unexpected success for password=" + password, future.isSuccess()); + assertTrue(future.await(AUTH_TIMEOUT), "Failed to verify password=" + password + " in time"); + assertFalse(future.isSuccess(), "Unexpected success for password=" + password); session.removePasswordIdentity(password); } - assertNull("Session closure not signalled at iteration #" + index, clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled at iteration #" + index); } try (ClientSession session = createTestClientSession()) { - assertTrue("Mismatched prompts evaluation results", mismatchedPrompts.isEmpty()); + assertTrue(mismatchedPrompts.isEmpty(), "Mismatched prompts evaluation results"); } - assertNull("Final session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Final session closure not signalled"); } finally { client.stop(); } } @Test - public void testDefaultKeyboardInteractiveWithFailures() throws Exception { + void defaultKeyboardInteractiveWithFailures() throws Exception { client.setUserAuthFactories(Collections.singletonList(UserAuthKeyboardInteractiveFactory.INSTANCE)); AtomicInteger count = new AtomicInteger(); @@ -1335,7 +1349,7 @@ public String getUpdatedPassword(ClientSession session, String prompt, String la private void validateSession(String phase, ClientSession session) { ClientSession prev = interactionSessionHolder.getAndSet(session); if (prev != null) { - assertSame("Mismatched " + phase + " client session", prev, session); + assertSame(prev, session, "Mismatched " + phase + " client session"); } } }); @@ -1347,21 +1361,21 @@ private void validateSession(String phase, ClientSession session) { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); AuthFuture future = session.auth(); - assertTrue("Failed to complete authentication on time", future.await(DEFAULT_TIMEOUT)); - assertTrue("Unexpected authentication success", future.isFailure()); - assertEquals("Mismatched authentication retry count", maxPrompts, count.get()); + assertTrue(future.await(DEFAULT_TIMEOUT), "Failed to complete authentication on time"); + assertTrue(future.isFailure(), "Unexpected authentication success"); + assertEquals(maxPrompts, count.get(), "Mismatched authentication retry count"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testDefaultKeyboardInteractiveInSessionUserInteractive() throws Exception { + void defaultKeyboardInteractiveInSessionUserInteractive() throws Exception { final int maxPrompts = 3; CoreModuleProperties.PASSWORD_PROMPTS.set(client, maxPrompts); @@ -1370,7 +1384,7 @@ public void testDefaultKeyboardInteractiveInSessionUserInteractive() throws Exce try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); AtomicInteger count = new AtomicInteger(); session.setUserInteraction(new UserInteraction() { @Override @@ -1380,19 +1394,19 @@ public boolean isInteractionAllowed(ClientSession session) { @Override public void serverVersionInfo(ClientSession clientSession, List lines) { - assertSame("Mismatched server version info session", session, clientSession); + assertSame(session, clientSession, "Mismatched server version info session"); } @Override public void welcome(ClientSession clientSession, String banner, String lang) { - assertSame("Mismatched welcome session", session, clientSession); + assertSame(session, clientSession, "Mismatched welcome session"); } @Override public String[] interactive( ClientSession clientSession, String name, String instruction, String lang, String[] prompt, boolean[] echo) { - assertSame("Mismatched interactive session", session, clientSession); + assertSame(session, clientSession, "Mismatched interactive session"); count.incrementAndGet(); return new String[] { getCurrentTestName() }; } @@ -1404,19 +1418,20 @@ public String getUpdatedPassword(ClientSession clientSession, String prompt, Str }); AuthFuture future = session.auth(); - assertTrue("Failed to complete authentication on time", future.await(CLOSE_TIMEOUT)); - assertTrue("Authentication not marked as success", future.isSuccess()); - assertFalse("Authentication marked as failure", future.isFailure()); - assertEquals("Mismatched authentication attempts count", 1, count.get()); + assertTrue(future.await(CLOSE_TIMEOUT), "Failed to complete authentication on time"); + assertTrue(future.isSuccess(), "Authentication not marked as success"); + assertFalse(future.isFailure(), "Authentication marked as failure"); + assertEquals(1, count.get(), "Mismatched authentication attempts count"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } - @Test // See GH-283 - public void testPasswordPrompts() throws Exception { + // See GH-283 + @Test + void passwordPrompts() throws Exception { CoreModuleProperties.PASSWORD_PROMPTS.set(client, 1); AtomicInteger numberOfRequests = new AtomicInteger(); @@ -1443,7 +1458,7 @@ protected boolean sendAuthDataRequest(ClientSession session, String service) thr try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(CONNECT_TIMEOUT) .getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); AtomicInteger count = new AtomicInteger(); session.setUserInteraction(new UserInteraction() { @Override @@ -1453,19 +1468,19 @@ public boolean isInteractionAllowed(ClientSession session) { @Override public void serverVersionInfo(ClientSession clientSession, List lines) { - assertSame("Mismatched server version info session", session, clientSession); + assertSame(session, clientSession, "Mismatched server version info session"); } @Override public void welcome(ClientSession clientSession, String banner, String lang) { - assertSame("Mismatched welcome session", session, clientSession); + assertSame(session, clientSession, "Mismatched welcome session"); } @Override public String[] interactive( ClientSession clientSession, String name, String instruction, String lang, String[] prompt, boolean[] echo) { - assertSame("Mismatched interactive session", session, clientSession); + assertSame(session, clientSession, "Mismatched interactive session"); int n = count.incrementAndGet(); if (n == 1) { return new String[] { "bogus" }; @@ -1480,10 +1495,10 @@ public String getUpdatedPassword(ClientSession clientSession, String prompt, Str }); AuthFuture future = session.auth(); - assertTrue("Failed to complete authentication on time", future.await(CLOSE_TIMEOUT)); - assertTrue("Authentication should have failed", future.isFailure()); - assertEquals("Mismatched authentication attempts count", 1, count.get()); - assertEquals("Mismatched authentication request count", 1, numberOfRequests.get()); + assertTrue(future.await(CLOSE_TIMEOUT), "Failed to complete authentication on time"); + assertTrue(future.isFailure(), "Authentication should have failed"); + assertEquals(1, count.get(), "Mismatched authentication attempts count"); + assertEquals(1, numberOfRequests.get(), "Mismatched authentication request count"); count.set(0); numberOfRequests.set(0); // Also set a password on the session: this should be a non-interactive request, so we should have four @@ -1492,20 +1507,20 @@ public String getUpdatedPassword(ClientSession clientSession, String prompt, Str session.addPasswordIdentity("anotherwrongpassword"); CoreModuleProperties.PASSWORD_PROMPTS.set(client, 2); future = session.auth(); - assertTrue("Failed to complete authentication on time", future.await(CLOSE_TIMEOUT)); - assertFalse("Authentication should not have failed", future.isFailure()); - assertTrue("Authentication should have succeeded", future.isSuccess()); - assertEquals("Mismatched authentication attempts count", 2, count.get()); - assertEquals("Mismatched authentication request count", 4, numberOfRequests.get()); + assertTrue(future.await(CLOSE_TIMEOUT), "Failed to complete authentication on time"); + assertFalse(future.isFailure(), "Authentication should not have failed"); + assertTrue(future.isSuccess(), "Authentication should have succeeded"); + assertEquals(2, count.get(), "Mismatched authentication attempts count"); + assertEquals(4, numberOfRequests.get(), "Mismatched authentication request count"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testKeyboardInteractiveInSessionUserInteractiveFailure() throws Exception { + void keyboardInteractiveInSessionUserInteractiveFailure() throws Exception { final int maxPrompts = 3; CoreModuleProperties.PASSWORD_PROMPTS.set(client, maxPrompts); AtomicInteger numberOfRequests = new AtomicInteger(); @@ -1532,7 +1547,7 @@ protected boolean sendAuthDataRequest(ClientSession session, String service) thr try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); AtomicInteger count = new AtomicInteger(); session.setUserInteraction(new UserInteraction() { @Override @@ -1542,19 +1557,19 @@ public boolean isInteractionAllowed(ClientSession session) { @Override public void serverVersionInfo(ClientSession clientSession, List lines) { - assertSame("Mismatched server version info session", session, clientSession); + assertSame(session, clientSession, "Mismatched server version info session"); } @Override public void welcome(ClientSession clientSession, String banner, String lang) { - assertSame("Mismatched welcome session", session, clientSession); + assertSame(session, clientSession, "Mismatched welcome session"); } @Override public String[] interactive( ClientSession clientSession, String name, String instruction, String lang, String[] prompt, boolean[] echo) { - assertSame("Mismatched interactive session", session, clientSession); + assertSame(session, clientSession, "Mismatched interactive session"); int attemptId = count.incrementAndGet(); return new String[] { "bad#" + attemptId }; } @@ -1566,19 +1581,19 @@ public String getUpdatedPassword(ClientSession clientSession, String prompt, Str }); AuthFuture future = session.auth(); - assertTrue("Authentication not completed in time", future.await(AUTH_TIMEOUT)); - assertTrue("Authentication not, marked as failure", future.isFailure()); - assertEquals("Mismatched authentication retry count", maxPrompts, count.get()); - assertEquals("Mismatched authentication request count", maxPrompts, numberOfRequests.get()); + assertTrue(future.await(AUTH_TIMEOUT), "Authentication not completed in time"); + assertTrue(future.isFailure(), "Authentication not, marked as failure"); + assertEquals(maxPrompts, count.get(), "Mismatched authentication retry count"); + assertEquals(maxPrompts, numberOfRequests.get(), "Mismatched authentication request count"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testClientDisconnect() throws Exception { + void clientDisconnect() throws Exception { TestEchoShell.latch = new CountDownLatch(1); try { client.start(); @@ -1602,21 +1617,21 @@ public void testClientDisconnect() throws Exception { IoWriteFuture f = session.writePacket(buffer); f.addListener(f1 -> suspend(session.getIoSession())); - assertTrue("Packet writing not completed in time", f.await(DEFAULT_TIMEOUT)); + assertTrue(f.await(DEFAULT_TIMEOUT), "Packet writing not completed in time"); TestEchoShell.latch.await(); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } finally { TestEchoShell.latch = null; } } @Test - public void testWaitAuth() throws Exception { + void waitAuth() throws Exception { AtomicBoolean ok = new AtomicBoolean(); client.setServerKeyVerifier( (sshClientSession, remoteAddress, serverKey) -> { @@ -1628,19 +1643,19 @@ public void testWaitAuth() throws Exception { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); Collection result = session.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH), TimeUnit.SECONDS.toMillis(10L)); - assertFalse("Timeout while waiting on channel close", result.contains(ClientSession.ClientSessionEvent.TIMEOUT)); - assertTrue("Server key verifier invoked ?", ok.get()); + assertFalse(result.contains(ClientSession.ClientSessionEvent.TIMEOUT), "Timeout while waiting on channel close"); + assertTrue(ok.get(), "Server key verifier invoked ?"); } finally { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } @Test - public void testCreateChannelByType() throws Exception { + void createChannelByType() throws Exception { client.start(); Collection channels = new LinkedList<>(); @@ -1653,7 +1668,7 @@ public void testCreateChannelByType() throws Exception { Set ids = new HashSet<>(channels.size()); for (ClientChannel c : channels) { long id = c.getChannelId(); - assertTrue("Channel ID repeated: " + id, ids.add(id)); + assertTrue(ids.add(id), "Channel ID repeated: " + id); } } finally { for (Closeable c : channels) { @@ -1666,11 +1681,12 @@ public void testCreateChannelByType() throws Exception { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } - @Test // see SSHD-1295 - public void testConnectTimeout() throws Exception { + // see SSHD-1295 + @Test + void connectTimeout() throws Exception { List sessions = new CopyOnWriteArrayList<>(); client.addSessionListener(new SessionListener() { @@ -1693,27 +1709,28 @@ public void sessionCreated(Session session) { future.verify(1); fail("Timeout expected"); } catch (InterruptedIOException | SshException e) { - assertTrue("Expected a timeout, got " + e, e.getCause() instanceof TimeoutException); + assertTrue(e.getCause() instanceof TimeoutException, "Expected a timeout, got " + e); ClientSession session = null; try { session = future.verify(CONNECT_TIMEOUT).getSession(); } catch (SshException e2) { - assertTrue("Expected a timeout, got " + e2, e2.getCause() instanceof TimeoutException); + assertTrue(e2.getCause() instanceof TimeoutException, "Expected a timeout, got " + e2); } for (Session created : sessions) { - assertTrue("Created session should be closed", created.isClosed() || created.isClosing()); + assertTrue(created.isClosed() || created.isClosing(), "Created session should be closed"); } - assertNull("Session should not set since client timed out", session); + assertNull(session, "Session should not set since client timed out"); } } finally { client.stop(); } } - @Test // see SSHD-1295 - public void testConnectCancellation() throws Exception { + // see SSHD-1295 + @Test + void connectCancellation() throws Exception { List sessions = new CopyOnWriteArrayList<>(); AtomicReference future = new AtomicReference<>(); AtomicReference cancellation = new AtomicReference<>(); @@ -1746,33 +1763,34 @@ public void sessionCreated(Session session) { future.get().verify(CONNECT_TIMEOUT); fail("Cancellation expected"); } catch (InterruptedIOException | SshException e) { - assertTrue("Expected a cancellation, got " + e, e.getCause() instanceof CancellationException); + assertTrue(e.getCause() instanceof CancellationException, "Expected a cancellation, got " + e); ClientSession session = null; try { session = future.get().verify(CONNECT_TIMEOUT).getSession(); fail("Cancellation expected"); } catch (SshException e2) { - assertTrue("Expected a cancellation, got " + e2, e2.getCause() instanceof CancellationException); + assertTrue(e2.getCause() instanceof CancellationException, "Expected a cancellation, got " + e2); } cancellationSet.await(3, TimeUnit.SECONDS); CancelFuture canceled = future.get().getCancellation(); assertSame(cancellation.get(), canceled); - assertTrue("Future should be done", canceled.verify(5 * 1000)); + assertTrue(canceled.verify(5 * 1000), "Future should be done"); for (Session createdSession : sessions) { - assertTrue("Created session should be closed", createdSession.isClosed() || createdSession.isClosing()); + assertTrue(createdSession.isClosed() || createdSession.isClosing(), "Created session should be closed"); } - assertNull("Session should not set since client cancelled", session); - assertTrue("Cancellation should have been successful", canceled.isCanceled()); + assertNull(session, "Session should not set since client cancelled"); + assertTrue(canceled.isCanceled(), "Cancellation should have been successful"); } } finally { client.stop(); } } - @Test // see SSHD-1295 - public void testConnectTimeoutIgnore() throws Exception { + // see SSHD-1295 + @Test + void connectTimeoutIgnore() throws Exception { List sessions = new CopyOnWriteArrayList<>(); client.addSessionListener(new SessionListener() { @@ -1795,9 +1813,9 @@ public void sessionCreated(Session session) { future.verify(1, CancelOption.NO_CANCELLATION); fail("Timeout expected"); } catch (InterruptedIOException | SshException e) { - assertTrue("Expected a timeout, got " + e, e.getCause() instanceof TimeoutException); + assertTrue(e.getCause() instanceof TimeoutException, "Expected a timeout, got " + e); ClientSession session = future.verify(CONNECT_TIMEOUT).getSession(); - assertNotNull("Session expected", session); + assertNotNull(session, "Session expected"); session.close(false); } } finally { @@ -1805,10 +1823,11 @@ public void sessionCreated(Session session) { } } - @Test // see SSHD-1295 - public void testConnectNoListenerIoTimeout() throws Exception { + // see SSHD-1295 + @Test + void connectNoListenerIoTimeout() throws Exception { // Connect to a port where nothing listens. - Assume.assumeFalse(InetAddress.getByName("1.2.3.4").isReachable(5 * 1000)); + Assumptions.assumeFalse(InetAddress.getByName("1.2.3.4").isReachable(5 * 1000)); List sessions = new CopyOnWriteArrayList<>(); client.addSessionListener(new SessionListener() { @@ -1828,24 +1847,25 @@ public void sessionCreated(Session session) { fail("Timeout expected"); } catch (InterruptedIOException | SshException e) { time = System.currentTimeMillis() - time; - assertTrue("Expected an I/O timeout, got " + e, e.getCause() instanceof ConnectException); + assertTrue(e.getCause() instanceof ConnectException, "Expected an I/O timeout, got " + e); try { future.verify(CONNECT_TIMEOUT).getSession(); } catch (SshException e2) { - assertTrue("Expected a timeout, got " + e2, e2.getCause() instanceof ConnectException); + assertTrue(e2.getCause() instanceof ConnectException, "Expected a timeout, got " + e2); } } - assertTrue("No session should have been created", sessions.isEmpty()); - assertTrue("Timeout should have occurred after 1 second", time < 10 * 1000); // Be generous + assertTrue(sessions.isEmpty(), "No session should have been created"); + assertTrue(time < 10 * 1000, "Timeout should have occurred after 1 second"); // Be generous } finally { client.stop(); } } - @Test // see SSHD-1295 - public void testConnectNoListenerApplicationTimeout() throws Exception { + // see SSHD-1295 + @Test + void connectNoListenerApplicationTimeout() throws Exception { // Connect to a port where nothing listens. - Assume.assumeFalse(InetAddress.getByName("1.2.3.4").isReachable(5 * 1000)); + Assumptions.assumeFalse(InetAddress.getByName("1.2.3.4").isReachable(5 * 1000)); List sessions = new CopyOnWriteArrayList<>(); client.addSessionListener(new SessionListener() { @@ -1865,23 +1885,23 @@ public void sessionCreated(Session session) { fail("Timeout expected"); } catch (InterruptedIOException | SshException e) { time = System.currentTimeMillis() - time; - assertTrue("Expected an I/O timeout, got " + e, e.getCause() instanceof TimeoutException); + assertTrue(e.getCause() instanceof TimeoutException, "Expected an I/O timeout, got " + e); try { future.verify(CONNECT_TIMEOUT).getSession(); } catch (SshException e2) { - assertTrue("Expected a timeout, got " + e2, e2.getCause() instanceof TimeoutException); + assertTrue(e2.getCause() instanceof TimeoutException, "Expected a timeout, got " + e2); } } - assertTrue("No session should have been created", sessions.isEmpty()); - assertTrue("Timeout should have occurred after 1 second", time < 10 * 1000); // Be generous + assertTrue(sessions.isEmpty(), "No session should have been created"); + assertTrue(time < 10 * 1000, "Timeout should have occurred after 1 second"); // Be generous } finally { client.stop(); } } @Test - @Ignore - public void testConnectUsingIPv6Address() throws IOException { + @Disabled + void connectUsingIPv6Address() throws IOException { client.start(); try { @@ -1924,7 +1944,7 @@ private ClientSession createTestClientSession() throws IOException { ClientSession session = createTestClientSession(TEST_LOCALHOST); try { InetSocketAddress addr = SshdSocketAddress.toInetSocketAddress(session.getConnectAddress()); - assertEquals("Mismatched connect host", TEST_LOCALHOST, addr.getHostString()); + assertEquals(TEST_LOCALHOST, addr.getHostString(), "Mismatched connect host"); ClientSession returnValue = session; session = null; // avoid 'finally' close @@ -1940,13 +1960,13 @@ private ClientSession createTestClientSession(String host) throws IOException { ClientSession session = client.connect(getCurrentTestName(), host, port) .verify(CONNECT_TIMEOUT).getSession(); try { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); InetSocketAddress addr = SshdSocketAddress.toInetSocketAddress(session.getConnectAddress()); - assertNotNull("No reported connect address", addr); - assertEquals("Mismatched connect port", port, addr.getPort()); + assertNotNull(addr, "No reported connect address"); + assertEquals(port, addr.getPort(), "Mismatched connect port"); ClientSession returnValue = session; session = null; // avoid 'finally' close diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ProxyTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ProxyTest.java index cb4af069f..1dd141007 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/ProxyTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/ProxyTest.java @@ -49,26 +49,30 @@ import org.apache.sshd.server.forward.StaticDecisionForwardingFilter; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommandExecutionHelper; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.TemporaryFolder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ProxyTest extends BaseTestSupport { - @Rule - public TemporaryFolder tmpClientDir = new TemporaryFolder(); - protected final Logger logger = LoggerFactory.getLogger(getClass()); + @TempDir + private File tmpClientDir; + private ClientSession proxySession; public ProxyTest() { @@ -76,7 +80,7 @@ public ProxyTest() { } @Test - public void testProxy() throws Exception { + void proxy() throws Exception { try (SshServer server = setupTestServer(); SshServer proxy = setupTestServer(); SshClient client = setupTestClient()) { @@ -114,7 +118,7 @@ protected boolean handleCommandLine(String command) throws Exception { } @Test - public void testDirectWithHostKeyVerification() throws Exception { + void directWithHostKeyVerification() throws Exception { // This test exists only to show that the knownhosts setup is correct try (SshServer server = setupTestServer(); SshServer proxy = setupTestServer(); @@ -148,7 +152,7 @@ public void testDirectWithHostKeyVerification() throws Exception { } @Test - public void testProxyWithHostKeyVerification() throws Exception { + void proxyWithHostKeyVerification() throws Exception { try (SshServer server = setupTestServer(); SshServer proxy = setupTestServer(); SshClient client = setupTestClient()) { @@ -176,7 +180,7 @@ public void testProxyWithHostKeyVerification() throws Exception { } @Test - public void testProxyWithHostKeyVerificationAndCustomConfig() throws Exception { + void proxyWithHostKeyVerificationAndCustomConfig() throws Exception { try (SshServer server = setupTestServer(); SshServer proxy = setupTestServer(); SshClient client = setupTestClient()) { @@ -208,7 +212,7 @@ public void testProxyWithHostKeyVerificationAndCustomConfig() throws Exception { } @Test - public void testProxyChain() throws Exception { + void proxyChain() throws Exception { try (SshServer target = setupTestServer(); SshServer proxy1 = setupTestServer(); SshServer proxy2 = setupTestServer(); @@ -268,7 +272,7 @@ protected boolean checkAcceptance(String request, Session session, SshdSocketAdd } @Test - public void testProxyCascade() throws Exception { + void proxyCascade() throws Exception { try (SshServer target = setupTestServer(); SshServer proxy1 = setupTestServer(); SshServer proxy2 = setupTestServer(); @@ -328,7 +332,7 @@ protected boolean checkAcceptance(String request, Session session, SshdSocketAdd } @Test - public void testProxyInfinite() throws Exception { + void proxyInfinite() throws Exception { try (SshServer target = setupTestServer(); SshServer proxy1 = setupTestServer(); SshServer proxy2 = setupTestServer(); @@ -394,7 +398,7 @@ protected boolean checkAcceptance(String request, Session session, SshdSocketAdd } @Test - public void testProxyOverride() throws Exception { + void proxyOverride() throws Exception { try (SshServer target = setupTestServer(); SshServer proxy1 = setupTestServer(); SshServer proxy2 = setupTestServer(); @@ -455,8 +459,8 @@ protected boolean checkAcceptance(String request, Session session, SshdSocketAdd } @Test - @Ignore - public void testExternal() throws Exception { + @Disabled + void external() throws Exception { try (SshServer server = setupTestServer(); SshServer proxy = setupTestServer()) { @@ -501,7 +505,7 @@ protected boolean handleCommandLine(String command) throws Exception { }); server.start(); - File knownHosts = tmpClientDir.newFile("knownhosts"); + File knownHosts = File.createTempFile("knownhosts", null, tmpClientDir); writeKnownHosts(server, knownHosts); // setup proxy with a forwarding filter to allow the local port forwarding proxy.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE); diff --git a/sshd-core/src/test/java/org/apache/sshd/client/auth/BuiltinUserAuthFactoriesTest.java b/sshd-core/src/test/java/org/apache/sshd/client/auth/BuiltinUserAuthFactoriesTest.java index 84ababb60..6d1d1c194 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/auth/BuiltinUserAuthFactoriesTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/auth/BuiltinUserAuthFactoriesTest.java @@ -29,39 +29,36 @@ import org.apache.sshd.common.auth.UserAuthMethodFactory; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class BuiltinUserAuthFactoriesTest extends BaseTestSupport { - private final BuiltinUserAuthFactories factory; + private BuiltinUserAuthFactories factory; - public BuiltinUserAuthFactoriesTest(BuiltinUserAuthFactories factory) { + public void initBuiltinUserAuthFactoriesTest(BuiltinUserAuthFactories factory) { this.factory = factory; } - @Parameters(name = "Factory={0}") public static Collection parameters() { return parameterize(BuiltinUserAuthFactories.VALUES); } - @BeforeClass - public static void testAllConstantsCovered() throws Exception { + @BeforeAll + static void testAllConstantsCovered() throws Exception { Field[] fields = UserAuthMethodFactory.class.getDeclaredFields(); Collection factories = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); @@ -81,42 +78,49 @@ public static void testAllConstantsCovered() throws Exception { continue; } - assertTrue("Duplicate factory name constant: " + name, factories.add(name)); + assertTrue(factories.add(name), "Duplicate factory name constant: " + name); } - assertEquals("Mismatched factories names count: " + factories, factories.size(), - BuiltinUserAuthFactories.VALUES.size()); + assertEquals(factories.size(), + BuiltinUserAuthFactories.VALUES.size(), + "Mismatched factories names count: " + factories); } - @Test - public void testSingletonFactoryInstance() { + @MethodSource("parameters") + @ParameterizedTest(name = "Factory={0}") + public void singletonFactoryInstance(BuiltinUserAuthFactories factory) { + initBuiltinUserAuthFactoriesTest(factory); UserAuthFactory expected = factory.create(); for (int index = 1; index <= Byte.SIZE; index++) { - assertSame("Mismatched factory instance at invocation #" + index, expected, factory.create()); + assertSame(expected, factory.create(), "Mismatched factory instance at invocation #" + index); } } - @Test - public void testFromFactoryName() { + @MethodSource("parameters") + @ParameterizedTest(name = "Factory={0}") + public void fromFactoryName(BuiltinUserAuthFactories factory) { + initBuiltinUserAuthFactoriesTest(factory); String name = factory.getName(); UserAuthFactory expected = factory.create(); for (int index = 1, count = name.length(); index <= count; index++) { UserAuthFactory actual = BuiltinUserAuthFactories.fromFactoryName(name); - assertSame("Mismatched factory instance for name=" + name, expected, actual); + assertSame(expected, actual, "Mismatched factory instance for name=" + name); name = shuffleCase(name); // prepare for next iteration } } - @Test - public void testParseResult() { + @MethodSource("parameters") + @ParameterizedTest(name = "Factory={0}") + public void parseResult(BuiltinUserAuthFactories factory) { + initBuiltinUserAuthFactoriesTest(factory); ParseResult result = BuiltinUserAuthFactories.parseFactoriesList(factory.getName()); - assertNotNull("No parse result", result); + assertNotNull(result, "No parse result"); List parsed = result.getParsedFactories(); - assertEquals("Mismatched parsed count", 1, GenericUtils.size(parsed)); - assertSame("Mismatched parsed factory instance", factory.create(), parsed.get(0)); + assertEquals(1, GenericUtils.size(parsed), "Mismatched parsed count"); + assertSame(factory.create(), parsed.get(0), "Mismatched parsed factory instance"); Collection unsupported = result.getUnsupportedFactories(); - assertTrue("Unexpected unsupported values: " + unsupported, GenericUtils.isEmpty(unsupported)); + assertTrue(GenericUtils.isEmpty(unsupported), "Unexpected unsupported values: " + unsupported); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/HostBoundPubKeyAuthTest.java b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/HostBoundPubKeyAuthTest.java index 325f2fe04..9f91609aa 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/HostBoundPubKeyAuthTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/HostBoundPubKeyAuthTest.java @@ -28,22 +28,21 @@ import org.apache.sshd.common.keyprovider.FileKeyPairProvider; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.ContainerTestCase; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.output.Slf4jLogConsumer; import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.images.builder.ImageFromDockerfile; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.MountableFile; -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@Category(ContainerTestCase.class) +@Tag("ContainerTestCase") +@Testcontainers public class HostBoundPubKeyAuthTest extends BaseTestSupport { private static final Logger LOG = LoggerFactory.getLogger(HostBoundPubKeyAuthTest.class); @@ -57,8 +56,8 @@ public class HostBoundPubKeyAuthTest extends BaseTestSupport { Pattern.compile("\n.*debug2: userauth_pubkey: valid user bob attempting public key.*" + "\r?\n.*debug3: userauth_pubkey: publickey-hostbound-v00@openssh.com have"); - @Rule - public GenericContainer sshdContainer = new GenericContainer<>( + @Container + GenericContainer sshdContainer = new GenericContainer<>( new ImageFromDockerfile().withDockerfileFromBuilder(builder -> builder.from("alpine:3.16") .run("apk --update add openssh-server") // Installs OpenSSH 9.0 .run("ssh-keygen -A") // Generate multiple host keys @@ -78,13 +77,12 @@ public class HostBoundPubKeyAuthTest extends BaseTestSupport { .withExposedPorts(22) // .withLogConsumer(new Slf4jLogConsumer(LOG)); - private final String privateKeyName; + private String privateKeyName; - public HostBoundPubKeyAuthTest(String privateKeyName) { + public void initHostBoundPubKeyAuthTest(String privateKeyName) { this.privateKeyName = privateKeyName; } - @Parameterized.Parameters(name = "{0}") public static Iterable privateKeyParams() { return Arrays.asList( // "user01_rsa_sha2_512_2048", // @@ -101,11 +99,13 @@ private String getPrivateKeyResource() { private void checkLog(String logs) { Matcher m = EXPECTED_LOG_ENTRY.matcher(logs); - assertTrue("Expected server log message not found", m.find()); + assertTrue(m.find(), "Expected server log message not found"); } - @Test - public void testPubkeyAuth() throws Exception { + @MethodSource("privateKeyParams") + @ParameterizedTest(name = "{0}") + public void pubkeyAuth(String privateKeyName) throws Exception { + initHostBoundPubKeyAuthTest(privateKeyName); FileKeyPairProvider keyPairProvider = CommonTestSupportUtils.createTestKeyPairProvider(getPrivateKeyResource()); SshClient client = setupTestClient(); client.setKeyIdentityProvider(keyPairProvider); diff --git a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/InvalidRsaKeyAuthTest.java b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/InvalidRsaKeyAuthTest.java index cbfe89324..1d49f08ba 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/InvalidRsaKeyAuthTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/InvalidRsaKeyAuthTest.java @@ -32,9 +32,9 @@ import org.apache.sshd.server.auth.password.RejectAllPasswordAuthenticator; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; public class InvalidRsaKeyAuthTest extends BaseTestSupport { @@ -48,8 +48,8 @@ public InvalidRsaKeyAuthTest() { super(); } - @Before - public void setupClientAndServer() throws Exception { + @BeforeEach + void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(InvalidRsaKeyAuthTest.class); sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE); sshd.setHostBasedAuthenticator(RejectAllHostBasedAuthenticator.INSTANCE); @@ -65,8 +65,8 @@ public void setupClientAndServer() throws Exception { client.start(); } - @After - public void teardownClientAndServer() throws Exception { + @AfterEach + void teardownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -85,7 +85,7 @@ public void teardownClientAndServer() throws Exception { // SSHD-1231 @Test - public void testConnectWithWrongRsaKeyFirst() throws Exception { + void connectWithWrongRsaKeyFirst() throws Exception { // Generate an RSA key the client will try first, and which the server will reject. KeyPairGenerator generator = KeyPairGenerator.getInstance(KeyUtils.RSA_ALGORITHM); generator.initialize(2048); diff --git a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/MultiAuthTest.java b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/MultiAuthTest.java index aa62348fb..dea0b3e84 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/MultiAuthTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/MultiAuthTest.java @@ -40,11 +40,11 @@ import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class MultiAuthTest extends BaseTestSupport { +class MultiAuthTest extends BaseTestSupport { private static final String USER_NAME = "foo"; private static final String PASSWORD = "pass"; @@ -56,7 +56,7 @@ public class MultiAuthTest extends BaseTestSupport { private KeyPair ecKeyUser; private KeyPair rsaKeyUser; - public MultiAuthTest() { + MultiAuthTest() { super(); } @@ -97,7 +97,7 @@ private static KeyPair getKeyPair(String algorithm, int size) throws Exception { return generator.generateKeyPair(); } - @Before + @BeforeEach public void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(MultiAuthTest.class); sshd.setHostBasedAuthenticator(RejectAllHostBasedAuthenticator.INSTANCE); @@ -115,7 +115,7 @@ public void setupClientAndServer() throws Exception { client.start(); } - @After + @AfterEach public void teardownClientAndServer() throws Exception { if (sshd != null) { try { @@ -134,7 +134,7 @@ public void teardownClientAndServer() throws Exception { } @Test - public void testConnect() throws Exception { + void testConnect() throws Exception { CoreModuleProperties.AUTH_METHODS.set(sshd, "publickey,password,publickey"); StringBuilder sb = new StringBuilder(); try (ClientSession session = createClientSession(USER_NAME, client, port)) { @@ -161,7 +161,7 @@ public void testConnect() throws Exception { } @Test - public void testConnect2() throws Exception { + void testConnect2() throws Exception { CoreModuleProperties.AUTH_METHODS.set(sshd, "publickey,publickey"); StringBuilder sb = new StringBuilder(); try (ClientSession session = createClientSession(USER_NAME, client, port)) { @@ -185,7 +185,7 @@ public void testConnect2() throws Exception { } @Test - public void testConnect3() throws Exception { + void testConnect3() throws Exception { CoreModuleProperties.AUTH_METHODS.set(sshd, "publickey password"); StringBuilder sb = new StringBuilder(); try (ClientSession session = createClientSession(USER_NAME, client, port)) { @@ -207,7 +207,7 @@ public void testConnect3() throws Exception { } @Test - public void testConnect4() throws Exception { + void testConnect4() throws Exception { CoreModuleProperties.AUTH_METHODS.set(sshd, "password,publickey"); StringBuilder sb = new StringBuilder(); try (ClientSession session = createClientSession(USER_NAME, client, port)) { @@ -232,7 +232,7 @@ public void testConnect4() throws Exception { } @Test - public void testConnect5() throws Exception { + void testConnect5() throws Exception { CoreModuleProperties.AUTH_METHODS.set(sshd, "password,publickey,publickey"); StringBuilder sb = new StringBuilder(); try (ClientSession session = createClientSession(USER_NAME, client, port)) { diff --git a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/RSAVariantsAuthPublicKeyTest.java b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/RSAVariantsAuthPublicKeyTest.java index 1380e249f..b957f8303 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/RSAVariantsAuthPublicKeyTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/RSAVariantsAuthPublicKeyTest.java @@ -41,24 +41,20 @@ import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.junit.AfterClass; -import org.junit.Assume; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class RSAVariantsAuthPublicKeyTest extends BaseTestSupport { private static final List> RSA_FACTORIES = Collections.unmodifiableList( BaseBuilder.DEFAULT_SIGNATURE_PREFERENCE.stream() @@ -76,15 +72,15 @@ public class RSAVariantsAuthPublicKeyTest extends BaseTestSupport { private static int port; private static SshClient client; - private final SignatureFactory factory; + private SignatureFactory factory; - public RSAVariantsAuthPublicKeyTest(SignatureFactory factory) { - Assume.assumeTrue("Skip unsupported factory", factory.isSupported()); + public void initRSAVariantsAuthPublicKeyTest(SignatureFactory factory) { + Assumptions.assumeTrue(factory.isSupported(), "Skip unsupported factory"); this.factory = factory; } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(RSAVariantsAuthPublicKeyTest.class); sshd.setSignatureFactories(RSA_FACTORIES); sshd.setKeyPairProvider(KEYS_PROVIDER); @@ -108,8 +104,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -127,23 +123,24 @@ public static void tearDownClientAndServer() throws Exception { } } - @Parameters(name = "{0}") public static List parameters() { return parameterize(RSA_FACTORIES); } - @Test - public void testRSAVariantAuth() throws IOException { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void rsaVariantAuth(SignatureFactory factory) throws IOException { + initRSAVariantsAuthPublicKeyTest(factory); client.setSignatureFactories(Collections.singletonList(factory)); try (ClientSession session = createClientSession(client, port)) { List keys = KEYS_PROVIDER.loadKeys(session); KeyPair kp = keys.get(0); - assertEquals("Mismatched key type", KeyPairProvider.SSH_RSA, KeyUtils.getKeyType(kp)); + assertEquals(KeyPairProvider.SSH_RSA, KeyUtils.getKeyType(kp), "Mismatched key type"); session.addPublicKeyIdentity(kp); session.auth().verify(AUTH_TIMEOUT); String serverKeyType = session.getNegotiatedKexParameter(KexProposalOption.SERVERKEYS); - assertEquals("Mismatched host key used", factory.getName(), serverKeyType); + assertEquals(factory.getName(), serverKeyType, "Mismatched host key used"); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/client/channel/ChannelExecTest.java b/sshd-core/src/test/java/org/apache/sshd/client/channel/ChannelExecTest.java index f5bdf5844..80c6a8a00 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/channel/ChannelExecTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/channel/ChannelExecTest.java @@ -39,16 +39,18 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommandExecutionHelper; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ChannelExecTest extends BaseTestSupport { private static SshServer sshd; private static int port; @@ -58,8 +60,8 @@ public ChannelExecTest() { super(); } - @Before - public void setupClientAndServer() throws Exception { + @BeforeEach + void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(ChannelExecTest.class); sshd.setCommandFactory((session, command) -> new CommandExecutionHelper(command) { @Override @@ -77,8 +79,8 @@ protected boolean handleCommandLine(String command) throws Exception { client.start(); } - @After - public void tearDownClientAndServer() throws Exception { + @AfterEach + void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -96,8 +98,9 @@ public void tearDownClientAndServer() throws Exception { } } - @Test // see SSHD-692 - public void testMultipleRemoteCommandExecutions() throws Exception { + // see SSHD-692 + @Test + void multipleRemoteCommandExecutions() throws Exception { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { session.addPasswordIdentity(getCurrentTestName()); @@ -106,13 +109,13 @@ public void testMultipleRemoteCommandExecutions() throws Exception { for (int index = 1; index <= Byte.SIZE; index++) { String expected = getCurrentTestName() + "[" + index + "]"; String actual = session.executeRemoteCommand(expected + "\n"); - assertEquals("Mismatched reply", expected, actual); + assertEquals(expected, actual, "Mismatched reply"); } } } @Test - public void testHighChannelId() throws Exception { + void highChannelId() throws Exception { List factories = sshd.getServiceFactories(); List newFactories = new ArrayList<>(); for (ServiceFactory f : factories) { @@ -154,7 +157,7 @@ protected long getNextChannelId() { String expected = getCurrentTestName(); String actual = session.executeRemoteCommand(expected + '\n'); - assertEquals("Mismatched reply", expected, actual); + assertEquals(expected, actual, "Mismatched reply"); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/client/config/hosts/HostConfigEntryResolverTest.java b/sshd-core/src/test/java/org/apache/sshd/client/config/hosts/HostConfigEntryResolverTest.java index f66f8d431..416e805f5 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/config/hosts/HostConfigEntryResolverTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/config/hosts/HostConfigEntryResolverTest.java @@ -51,16 +51,20 @@ import org.apache.sshd.server.auth.password.RejectAllPasswordAuthenticator; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class HostConfigEntryResolverTest extends BaseTestSupport { private SshServer sshd; private SshClient client; @@ -70,8 +74,8 @@ public HostConfigEntryResolverTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); sshd.start(); port = sshd.getPort(); @@ -79,8 +83,8 @@ public void setUp() throws Exception { client = setupTestClient(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -90,7 +94,7 @@ public void tearDown() throws Exception { } @Test - public void testEffectiveHostConfigResolution() throws Exception { + void effectiveHostConfigResolution() throws Exception { HostConfigEntry entry = new HostConfigEntry(getCurrentTestName(), TEST_LOCALHOST, port, getCurrentTestName()); client.setHostConfigEntryResolver((host, portValue, lclAddress, username, proxy, context) -> entry); client.start(); @@ -108,7 +112,7 @@ public void testEffectiveHostConfigResolution() throws Exception { } @Test - public void testNegatedHostEntriesResolution() throws Exception { + void negatedHostEntriesResolution() throws Exception { HostConfigEntry positiveEntry = new HostConfigEntry(TEST_LOCALHOST, TEST_LOCALHOST, port, getCurrentTestName()); HostConfigEntry negativeEntry = new HostConfigEntry( Character.toString(HostPatternsHolder.NEGATION_CHAR_PATTERN) + positiveEntry.getHost(), @@ -133,7 +137,7 @@ public void testNegatedHostEntriesResolution() throws Exception { } @Test - public void testPreloadedIdentities() throws Exception { + void preloadedIdentities() throws Exception { KeyPair identity = CommonTestSupportUtils.getFirstKeyPair(sshd); String user = getCurrentTestName(); // make sure authentication is achieved only via the identity public key @@ -182,7 +186,7 @@ user, host, getMovedPortNumber(port)).verify(CONNECT_TIMEOUT).getSession()) { } @Test - public void testUseIdentitiesOnly() throws Exception { + void useIdentitiesOnly() throws Exception { Path clientIdFile = assertHierarchyTargetFolderExists(getTempTargetRelativeFile(getClass().getSimpleName())); KeyIdentityProvider clientIdProvider = CommonTestSupportUtils.createTestHostKeyProvider(clientIdFile.resolve(getCurrentTestName() + ".pem")); @@ -247,9 +251,9 @@ public Iterable loadKeys(SessionContext session) { try (ClientSession session = client.connect(entry) .verify(CONNECT_TIMEOUT).getSession()) { session.auth().verify(AUTH_TIMEOUT); - assertFalse("Unexpected default client identity attempted", defaultClientIdentityAttempted.get()); - assertNull("Default client identity auto-added", session.removePublicKeyIdentity(defaultIdentity)); - assertEquals("Entry identity not used", 1, specificIdentityLoadCount.get()); + assertFalse(defaultClientIdentityAttempted.get(), "Unexpected default client identity attempted"); + assertNull(session.removePublicKeyIdentity(defaultIdentity), "Default client identity auto-added"); + assertEquals(1, specificIdentityLoadCount.get(), "Entry identity not used"); assertEffectiveRemoteAddress(session, entry); } finally { client.stop(); @@ -264,8 +268,8 @@ private static S assertEffectiveRemoteAddress(S session, Hos IoSession ioSession = session.getIoSession(); SocketAddress remoteAddress = ioSession.getRemoteAddress(); InetSocketAddress inetAddress = SshdSocketAddress.toInetSocketAddress(remoteAddress); - assertEquals("Mismatched effective port", entry.getPort(), inetAddress.getPort()); - assertEquals("Mismatched effective user", entry.getUsername(), session.getUsername()); + assertEquals(entry.getPort(), inetAddress.getPort(), "Mismatched effective port"); + assertEquals(entry.getUsername(), session.getUsername(), "Mismatched effective user"); return session; } } diff --git a/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java b/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java index 9cf4ad059..c336c1196 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java @@ -41,46 +41,42 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.TeeOutputStream; -import org.junit.AfterClass; -import org.junit.Assume; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * Test client key exchange algorithms. * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class KexTest extends BaseTestSupport { private static final Duration TIMEOUT = Duration.ofSeconds(15); private static SshServer sshd; private static int port; private static SshClient client; - private final BuiltinDHFactories factory; + private BuiltinDHFactories factory; - public KexTest(BuiltinDHFactories factory) { + public void initKexTest(BuiltinDHFactories factory) { this.factory = factory; } - @Parameters(name = "Factory={0}") public static Collection parameters() { return parameterize(BuiltinDHFactories.VALUES); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestFullSupportServer(KexTest.class); sshd.start(); port = sshd.getPort(); @@ -89,8 +85,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -108,14 +104,16 @@ public static void tearDownClientAndServer() throws Exception { } } - @Test - public void testClientKeyExchange() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "Factory={0}") + public void clientKeyExchange(BuiltinDHFactories factory) throws Exception { + initKexTest(factory); if (factory.isGroupExchange()) { assertEquals(factory.getName() + " not supported even though DH group exchange supported", SecurityUtils.isDHGroupExchangeSupported(), factory.isSupported()); } - Assume.assumeTrue(factory.getName() + " not supported", factory.isSupported()); + Assumptions.assumeTrue(factory.isSupported(), factory.getName() + " not supported"); testClient(ClientBuilder.DH2KEX.apply(factory)); } @@ -155,11 +153,11 @@ private void testClient(KeyExchangeFactory kex) throws Exception { teeOut.flush(); Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TIMEOUT); - assertFalse("Timeout while waiting for channel closure", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Timeout while waiting for channel closure"); } } - assertArrayEquals(kex.getName(), sent.toByteArray(), out.toByteArray()); + assertArrayEquals(sent.toByteArray(), out.toByteArray(), kex.getName()); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/client/keyverifier/KnownHostsServerKeyVerifierTest.java b/sshd-core/src/test/java/org/apache/sshd/client/keyverifier/KnownHostsServerKeyVerifierTest.java index 9c323b855..e3ae6a454 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/keyverifier/KnownHostsServerKeyVerifierTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/keyverifier/KnownHostsServerKeyVerifierTest.java @@ -56,19 +56,26 @@ import org.apache.sshd.common.util.net.SshdSocketAddress; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class KnownHostsServerKeyVerifierTest extends BaseTestSupport { private static final String HASHED_HOST = "192.168.1.61"; private static final Map> HOST_KEYS = new TreeMap<>(SshdSocketAddress.BY_HOST_AND_PORT); @@ -79,10 +86,10 @@ public KnownHostsServerKeyVerifierTest() { super(); } - @BeforeClass - public static void loadHostsEntries() throws Exception { + @BeforeAll + static void loadHostsEntries() throws Exception { URL url = KnownHostsServerKeyVerifierTest.class.getResource(KnownHostEntry.STD_HOSTS_FILENAME); - assertNotNull("Missing test file resource", url); + assertNotNull(url, "Missing test file resource"); entriesFile = Paths.get(url.toURI()); outputDebugMessage("loadHostsEntries(%s)", entriesFile); hostsEntries = loadEntries(entriesFile); @@ -100,7 +107,7 @@ public static void loadHostsEntries() throws Exception { @Test @SuppressWarnings({ "unchecked", "rawtypes" }) - public void testParallelLoading() { + void parallelLoading() { KnownHostsServerKeyVerifier verifier = new KnownHostsServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE, entriesFile) { @Override @@ -133,15 +140,15 @@ protected boolean acceptKnownHostEntries( Mockito.when(session.getConnectAddress()).thenReturn(host); if ("revoked".equals(entry.getMarker())) { - assertFalse("Failed to validate server=" + entry, verifier.verifyServerKey(session, host, publicKey)); + assertFalse(verifier.verifyServerKey(session, host, publicKey), "Failed to validate server=" + entry); } else { - assertTrue("Failed to validate server=" + entry, verifier.verifyServerKey(session, host, publicKey)); + assertTrue(verifier.verifyServerKey(session, host, publicKey), "Failed to validate server=" + entry); } })); } @Test - public void testNoUpdatesNoNewHostsAuthentication() throws Exception { + void noUpdatesNoNewHostsAuthentication() throws Exception { AtomicInteger delegateCount = new AtomicInteger(0); ServerKeyVerifier delegate = (clientSession, remoteAddress, serverKey) -> { delegateCount.incrementAndGet(); @@ -170,17 +177,17 @@ protected KnownHostEntry updateKnownHostsFile( .orElseThrow(() -> new IllegalStateException("Missing updated key for " + KeyUtils.getKeyType(hostKey))); outputDebugMessage("Verify host=%s", entry); if ("revoked".equals(entry.getMarker())) { - assertFalse("Failed to verify server=" + entry, invokeVerifier(verifier, host, hostKey)); + assertFalse(invokeVerifier(verifier, host, hostKey), "Failed to verify server=" + entry); } else { - assertTrue("Failed to verify server=" + entry, invokeVerifier(verifier, host, hostKey)); + assertTrue(invokeVerifier(verifier, host, hostKey), "Failed to verify server=" + entry); } - assertEquals("Unexpected delegate invocation for host=" + entry, 0, delegateCount.get()); - assertEquals("Unexpected update invocation for host=" + entry, 0, updateCount.get()); + assertEquals(0, delegateCount.get(), "Unexpected delegate invocation for host=" + entry); + assertEquals(0, updateCount.get(), "Unexpected update invocation for host=" + entry); })); } @Test - public void testFileUpdatedOnEveryNewHost() throws Exception { + void fileUpdatedOnEveryNewHost() throws Exception { AtomicInteger delegateCount = new AtomicInteger(0); ServerKeyVerifier delegate = (clientSession, remoteAddress, serverKey) -> { delegateCount.incrementAndGet(); @@ -211,10 +218,10 @@ protected KnownHostEntry updateKnownHostsFile( .findAny() .orElseThrow(() -> new IllegalStateException("Missing updated key for " + KeyUtils.getKeyType(serverKey))); outputDebugMessage("Verify host=%s", entry); - assertTrue("Failed to verify server=" + entry, invokeVerifier(verifier, hostIdentity, serverKey)); + assertTrue(invokeVerifier(verifier, hostIdentity, serverKey), "Failed to verify server=" + entry); verificationCount++; - assertEquals("Mismatched number of delegate counts for server=" + entry, verificationCount, delegateCount.get()); - assertEquals("Mismatched number of update counts for server=" + entry, verificationCount, updateCount.get()); + assertEquals(verificationCount, delegateCount.get(), "Mismatched number of delegate counts for server=" + entry); + assertEquals(verificationCount, updateCount.get(), "Mismatched number of update counts for server=" + entry); } // make sure we have all the original entries and ONLY them @@ -227,7 +234,7 @@ protected KnownHostEntry updateKnownHostsFile( .findAny() .orElseThrow(() -> new IllegalStateException("Missing updated key for " + expected)); - assertTrue("No updated entry for host=" + hostIdentity, updatedEntries.get(hostIdentity).remove(actual)); + assertTrue(updatedEntries.get(hostIdentity).remove(actual), "No updated entry for host=" + hostIdentity); if (updatedEntries.get(hostIdentity).isEmpty()) { updatedEntries.remove(hostIdentity); } @@ -244,15 +251,15 @@ protected KnownHostEntry updateKnownHostsFile( expLine = expLine.substring(0, pos).trim(); } - assertEquals("Mismatched entry data for host=" + hostIdentity, expLine, actual.getConfigLine()); + assertEquals(expLine, actual.getConfigLine(), "Mismatched entry data for host=" + hostIdentity); }); - assertTrue("Unexpected extra updated hosts: " + updatedEntries, updatedEntries.isEmpty()); + assertTrue(updatedEntries.isEmpty(), "Unexpected extra updated hosts: " + updatedEntries); } @Test @SuppressWarnings({ "rawtypes", "unchecked" }) - public void testWriteHashedHostValues() throws Exception { + void writeHashedHostValues() throws Exception { Path path = getKnownHostCopyPath(); Files.deleteIfExists(path); @@ -278,14 +285,14 @@ protected NamedFactory getHostValueDigester( outputDebugMessage("Write host=%s", entry); Mockito.when(session.getConnectAddress()).thenReturn(host); - assertTrue("Failed to validate server=" + entry, verifier.verifyServerKey(session, host, serverKey)); + assertTrue(verifier.verifyServerKey(session, host, serverKey), "Failed to validate server=" + entry); }); // force re-read to ensure all values are hashed Collection keys = verifier.reloadKnownHosts(session, path); for (HostEntryPair ke : keys) { KnownHostEntry entry = ke.getHostEntry(); - assertNotNull("No hashing for entry=" + entry, entry.getHashedEntry()); + assertNotNull(entry.getHashedEntry(), "No hashing for entry=" + entry); } verifier.setLoadedHostsEntries(keys); @@ -299,12 +306,12 @@ protected NamedFactory getHostValueDigester( outputDebugMessage("Re-validate host=%s", entry); Mockito.when(session.getConnectAddress()).thenReturn(host); - assertTrue("Failed to re-validate server=" + entry, verifier.verifyServerKey(session, host, serverKey)); + assertTrue(verifier.verifyServerKey(session, host, serverKey), "Failed to re-validate server=" + entry); }); } @Test - public void testRejectModifiedServerKey() throws Exception { + void rejectModifiedServerKey() throws Exception { KeyPair kp = CommonTestSupportUtils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024); PublicKey modifiedKey = kp.getPublic(); AtomicInteger acceptCount = new AtomicInteger(0); @@ -317,8 +324,8 @@ public boolean acceptModifiedServerKey( KnownHostEntry entry, PublicKey expected, PublicKey actual) throws Exception { acceptCount.incrementAndGet(); - assertNull("Unexpected marker for " + remoteAddress, entry.getMarker()); - assertSame("Mismatched actual key for " + remoteAddress, modifiedKey, actual); + assertNull(entry.getMarker(), "Unexpected marker for " + remoteAddress); + assertSame(modifiedKey, actual, "Mismatched actual key for " + remoteAddress); return super.acceptModifiedServerKey(clientSession, remoteAddress, entry, expected, actual); } @@ -337,8 +344,8 @@ protected boolean acceptUnknownHostKey( SshdSocketAddress hostIdentity = ke.getKey(); for (KnownHostEntry entry : ke.getValue()) { outputDebugMessage("Verify host=%s", entry); - assertFalse("Unexpected to verification success for " + entry, - invokeVerifier(verifier, hostIdentity, modifiedKey)); + assertFalse(invokeVerifier(verifier, hostIdentity, modifiedKey), + "Unexpected to verification success for " + entry); long acceptedCount = ke.getValue().stream() .filter(k -> !"revoked".equals(k.getMarker())) .count(); @@ -347,16 +354,18 @@ protected boolean acceptUnknownHostKey( } else { validationCount++; } - assertEquals("Mismatched invocation count (acceptModifiedServerKey) for host=" + entry, validationCount, - acceptCount.get()); - assertEquals("Mismatched invocation count (acceptUnknownHostKey) host=" + entry, validUnknownCount, - unknownCount.get()); + assertEquals(validationCount, + acceptCount.get(), + "Mismatched invocation count (acceptModifiedServerKey) for host=" + entry); + assertEquals(validUnknownCount, + unknownCount.get(), + "Mismatched invocation count (acceptUnknownHostKey) host=" + entry); } } } @Test - public void testAcceptModifiedServerKeyUpdatesFile() throws Exception { + void acceptModifiedServerKeyUpdatesFile() throws Exception { KeyPair kp = CommonTestSupportUtils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024); PublicKey modifiedKey = kp.getPublic(); Path path = createKnownHostsCopy(); @@ -367,14 +376,14 @@ public boolean acceptModifiedServerKey( ClientSession clientSession, SocketAddress remoteAddress, KnownHostEntry entry, PublicKey expected, PublicKey actual) throws Exception { - assertSame("Mismatched actual key for " + remoteAddress, modifiedKey, actual); + assertSame(modifiedKey, actual, "Mismatched actual key for " + remoteAddress); return true; } }; hostsEntries.forEach((host, list) -> { outputDebugMessage("Verify host=%s", host); - assertTrue("Failed to verify " + host, invokeVerifier(verifier, host, modifiedKey)); + assertTrue(invokeVerifier(verifier, host, modifiedKey), "Failed to verify " + host); }); String expected = PublicKeyEntry.toString(modifiedKey); @@ -391,7 +400,7 @@ public boolean acceptModifiedServerKey( } String actual = updated.getConfigLine(); - assertNotNull("No updated entry for " + hostsEntries.get(host), actual); + assertNotNull(actual, "No updated entry for " + hostsEntries.get(host)); int pos = actual.indexOf(' '); if (actual.charAt(0) == KnownHostEntry.MARKER_INDICATOR) { for (pos++; pos < actual.length(); pos++) { @@ -403,39 +412,45 @@ public boolean acceptModifiedServerKey( } actual = GenericUtils.trimToEmpty(actual.substring(pos + 1)); - assertEquals("Mismatched updated value for host=" + host, expected, actual); + assertEquals(expected, actual, "Mismatched updated value for host=" + host); }); - assertTrue("Unexpected extra updated entries: " + updatedKeys, updatedKeys.isEmpty()); + assertTrue(updatedKeys.isEmpty(), "Unexpected extra updated entries: " + updatedKeys); } - @Test // SSHD-1063 - public void testUpdateSameHost2PortsStdFirstSameKey() throws Exception { + // SSHD-1063 + @Test + void updateSameHost2PortsStdFirstSameKey() throws Exception { testUpdateSameHostWithDifferentPorts(SshConstants.DEFAULT_PORT, 2020, true); } - @Test // SSHD-1063 - public void testUpdateSameHost2PortsStdLastSameKey() throws Exception { + // SSHD-1063 + @Test + void updateSameHost2PortsStdLastSameKey() throws Exception { testUpdateSameHostWithDifferentPorts(2020, SshConstants.DEFAULT_PORT, true); } - @Test // SSHD-1063 - public void testUpdateSameHost2NonStdPortsSameKey() throws Exception { + // SSHD-1063 + @Test + void updateSameHost2NonStdPortsSameKey() throws Exception { testUpdateSameHostWithDifferentPorts(2020, 2222, true); } - @Test // SSHD-1063 - public void testUpdateSameHost2PortsStdFirstDiffKeys() throws Exception { + // SSHD-1063 + @Test + void updateSameHost2PortsStdFirstDiffKeys() throws Exception { testUpdateSameHostWithDifferentPorts(SshConstants.DEFAULT_PORT, 2020, false); } - @Test // SSHD-1063 - public void testUpdateSameHost2PortsStdLastDiffKeys() throws Exception { + // SSHD-1063 + @Test + void updateSameHost2PortsStdLastDiffKeys() throws Exception { testUpdateSameHostWithDifferentPorts(2020, SshConstants.DEFAULT_PORT, false); } - @Test // SSHD-1063 - public void testUpdateSameHost2NonStdPortsDiffKeys() throws Exception { + // SSHD-1063 + @Test + void updateSameHost2NonStdPortsDiffKeys() throws Exception { testUpdateSameHostWithDifferentPorts(2020, 2222, false); } @@ -452,17 +467,17 @@ private void testUpdateSameHostWithDifferentPorts(int port1, int port2, boolean SocketAddress address1 = new SshdSocketAddress(HASHED_HOST, port1); boolean accepted1 = invokeVerifier(verifier, address1, serverKey1); - assertTrue("Accepted on port=" + port1 + " ?", accepted1); + assertTrue(accepted1, "Accepted on port=" + port1 + " ?"); KeyPair kp2 = useSameKey ? kp1 : CommonTestSupportUtils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024); PublicKey serverKey2 = kp2.getPublic(); SocketAddress address2 = new SshdSocketAddress(HASHED_HOST, port2); boolean accepted2 = invokeVerifier(verifier, address2, serverKey2); - assertTrue("Accepted on port=" + port2 + " ?", accepted2); + assertTrue(accepted2, "Accepted on port=" + port2 + " ?"); Map> updatedKeys = loadEntries(path); - assertEquals("Mismatched total entries count", 2, updatedKeys.size()); + assertEquals(2, updatedKeys.size(), "Mismatched total entries count"); } private Path createKnownHostsCopy() throws IOException { @@ -509,7 +524,7 @@ private static Map> loadEntries(Path fil int port = 0; if (a.charAt(0) == HostPatternsHolder.NON_STANDARD_PORT_PATTERN_ENCLOSURE_START_DELIM) { pos = a.indexOf(HostPatternsHolder.NON_STANDARD_PORT_PATTERN_ENCLOSURE_END_DELIM, 1); - assertTrue("Missing non-standard port host pattern enclosure: " + a, pos > 0); + assertTrue(pos > 0, "Missing non-standard port host pattern enclosure: " + a); port = Integer.parseInt(a.substring(pos + 2)); a = a.substring(1, pos); diff --git a/sshd-core/src/test/java/org/apache/sshd/client/keyverifier/StaticServerKeyVerifierTest.java b/sshd-core/src/test/java/org/apache/sshd/client/keyverifier/StaticServerKeyVerifierTest.java index 3bb2669bc..b5fa48a19 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/keyverifier/StaticServerKeyVerifierTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/keyverifier/StaticServerKeyVerifierTest.java @@ -29,30 +29,31 @@ import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class StaticServerKeyVerifierTest extends BaseTestSupport { public StaticServerKeyVerifierTest() { super(); } @Test - public void testAcceptAllServerKeyVerifier() throws Exception { + void acceptAllServerKeyVerifier() throws Exception { testStaticServerKeyVerifier(AcceptAllServerKeyVerifier.INSTANCE); } @Test - public void testRejectAllServerKeyVerifier() throws Exception { + void rejectAllServerKeyVerifier() throws Exception { testStaticServerKeyVerifier(RejectAllServerKeyVerifier.INSTANCE); } @@ -78,7 +79,7 @@ private void testStaticServerKeyVerifier(StaticServerKeyVerifier authenticator) } Object result = method.invoke(authenticator, invArgs); - assertTrue("No boolean result", result instanceof Boolean); + assertTrue(result instanceof Boolean, "No boolean result"); assertEquals("Mismatched result for " + Arrays.toString(invArgs), expected, ((Boolean) result).booleanValue()); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/client/opensshcerts/ClientOpenSSHCertificatesTest.java b/sshd-core/src/test/java/org/apache/sshd/client/opensshcerts/ClientOpenSSHCertificatesTest.java index a5fe5b121..157e8e974 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/opensshcerts/ClientOpenSSHCertificatesTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/opensshcerts/ClientOpenSSHCertificatesTest.java @@ -41,20 +41,19 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.ContainerTestCase; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.BeforeClass; -import org.junit.ClassRule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.testcontainers.containers.GenericContainer; import org.testcontainers.images.builder.ImageFromDockerfile; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.MountableFile; -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@Category(ContainerTestCase.class) +@Tag("ContainerTestCase") +@Testcontainers public class ClientOpenSSHCertificatesTest extends BaseTestSupport { /** @@ -78,8 +77,8 @@ public class ClientOpenSSHCertificatesTest extends BaseTestSupport { *
  • Two available host keypairs host01 and host02 (selected by env var SSH_HOST_KEY)
  • * **/ - @ClassRule - public static GenericContainer sshdContainer = new GenericContainer<>( + @Container + static GenericContainer sshdContainer = new GenericContainer<>( new ImageFromDockerfile().withDockerfileFromBuilder(builder -> builder.from("alpine:3.13") // .run("apk --update add supervisor openssh openssh-server bash") // Install .run("rm -rf /var/cache/apk/*") // Clear cache @@ -140,17 +139,16 @@ public class ClientOpenSSHCertificatesTest extends BaseTestSupport { private String privateKeyName; - public ClientOpenSSHCertificatesTest(String keyName) { + public void initClientOpenSSHCertificatesTest(String keyName) { privateKeyName = keyName; } - @BeforeClass - public static void ensureBC() { + @BeforeAll + static void ensureBC() { Security.removeProvider(BouncyCastleProvider.PROVIDER_NAME); Security.addProvider(new BouncyCastleProvider()); } - @Parameterized.Parameters(name = "key: {0}, cert: {0}-cert" + PublicKeyEntry.PUBKEY_FILE_SUFFIX) public static Iterable privateKeyParams() { return Arrays.asList( "user01_rsa_sha2_256_2048", @@ -171,8 +169,11 @@ private String getCertificateResource() { return getPrivateKeyResource() + "-cert" + PublicKeyEntry.PUBKEY_FILE_SUFFIX; } - @Test - public void clientCertAuth() throws Exception { + @MethodSource("privateKeyParams") + @ParameterizedTest(name = "key: {0}, cert: {0}-cert" + PublicKeyEntry.PUBKEY_FILE_SUFFIX) + public void clientCertAuth(String keyName) throws Exception { + + initClientOpenSSHCertificatesTest(keyName); try (InputStream certInputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(getCertificateResource())) { diff --git a/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionTest.java b/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionTest.java index fd547d4fa..ff728425f 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionTest.java @@ -51,17 +51,23 @@ import org.apache.sshd.util.test.BogusPasswordAuthenticator; import org.apache.sshd.util.test.CommandExecutionHelper; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ClientSessionTest extends BaseTestSupport { private static SshServer sshd; @@ -72,8 +78,8 @@ public ClientSessionTest() { super(); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(ClientSessionTest.class); sshd.start(); port = sshd.getPort(); @@ -82,8 +88,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -101,15 +107,15 @@ public static void tearDownClientAndServer() throws Exception { } } - @Before - public void setUp() { + @BeforeEach + void setUp() { sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE); sshd.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE); sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE); } @Test - public void testDefaultExecuteCommandMethod() throws Exception { + void defaultExecuteCommandMethod() throws Exception { String expectedCommand = getCurrentTestName() + "-CMD"; String expectedResponse = getCurrentTestName() + "-RSP"; sshd.setCommandFactory((session, command) -> new CommandExecutionHelper(command) { @@ -117,8 +123,8 @@ public void testDefaultExecuteCommandMethod() throws Exception { @Override protected boolean handleCommandLine(String command) throws Exception { - assertEquals("Mismatched incoming command", expectedCommand, command); - assertFalse("Duplicated command call", cmdProcessed); + assertEquals(expectedCommand, command, "Mismatched incoming command"); + assertFalse(cmdProcessed, "Duplicated command call"); OutputStream stdout = getOutputStream(); stdout.write(expectedResponse.getBytes(StandardCharsets.US_ASCII)); stdout.flush(); @@ -135,12 +141,12 @@ protected boolean handleCommandLine(String command) throws Exception { // NOTE !!! The LF is only because we are using a buffered reader on the server end to read the command String actualResponse = session.executeRemoteCommand(expectedCommand + "\n"); - assertEquals("Mismatched command response", expectedResponse, actualResponse); + assertEquals(expectedResponse, actualResponse, "Mismatched command response"); } } @Test - public void testExceptionThrownIfRemoteStderrWrittenTo() throws Exception { + void exceptionThrownIfRemoteStderrWrittenTo() throws Exception { String expectedCommand = getCurrentTestName() + "-CMD"; String expectedErrorMessage = getCurrentTestName() + "-ERR"; sshd.setCommandFactory((session, command) -> new CommandExecutionHelper(command) { @@ -148,8 +154,8 @@ public void testExceptionThrownIfRemoteStderrWrittenTo() throws Exception { @Override protected boolean handleCommandLine(String command) throws Exception { - assertEquals("Mismatched incoming command", expectedCommand, command); - assertFalse("Duplicated command call", cmdProcessed); + assertEquals(expectedCommand, command, "Mismatched incoming command"); + assertFalse(cmdProcessed, "Duplicated command call"); OutputStream stderr = getErrorStream(); stderr.write(expectedErrorMessage.getBytes(StandardCharsets.US_ASCII)); stderr.flush(); @@ -181,11 +187,11 @@ protected boolean handleCommandLine(String command) throws Exception { actualErrorMessage = cause.getMessage(); } - assertEquals("Mismatched captured error message", expectedErrorMessage, actualErrorMessage); + assertEquals(expectedErrorMessage, actualErrorMessage, "Mismatched captured error message"); } @Test - public void testExceptionThrownIfNonZeroExitStatus() throws Exception { + void exceptionThrownIfNonZeroExitStatus() throws Exception { String expectedCommand = getCurrentTestName() + "-CMD"; int expectedErrorCode = 7365; sshd.setCommandFactory((session, command) -> new CommandExecutionHelper(command) { @@ -198,8 +204,8 @@ protected void onExit(int exitValue, String exitMessage) { @Override protected boolean handleCommandLine(String command) throws Exception { - assertEquals("Mismatched incoming command", expectedCommand, command); - assertFalse("Duplicated command call", cmdProcessed); + assertEquals(expectedCommand, command, "Mismatched incoming command"); + assertFalse(cmdProcessed, "Duplicated command call"); OutputStream stdout = getOutputStream(); stdout.write(command.getBytes(StandardCharsets.US_ASCII)); stdout.flush(); @@ -231,11 +237,12 @@ protected boolean handleCommandLine(String command) throws Exception { actualErrorMessage = cause.getMessage(); } - assertEquals("Mismatched captured error code", Integer.toString(expectedErrorCode), actualErrorMessage); + assertEquals(Integer.toString(expectedErrorCode), actualErrorMessage, "Mismatched captured error code"); } - @Test // see SSHD-859 - public void testConnectionContextPropagation() throws Exception { + // see SSHD-859 + @Test + void connectionContextPropagation() throws Exception { AttributeRepository expected = AttributeRepository.ofKeyValuePair( new AttributeKey(), getCurrentTestName()); AtomicInteger creationCount = new AtomicInteger(0); @@ -243,7 +250,7 @@ public void testConnectionContextPropagation() throws Exception { @Override public void sessionCreated(Session session) { AttributeRepository actual = ((ClientSession) session).getConnectionContext(); - assertSame("Mismatched connection context", expected, actual); + assertSame(expected, actual, "Mismatched connection context"); creationCount.incrementAndGet(); } }; @@ -256,20 +263,22 @@ public void sessionCreated(Session session) { .getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); - assertEquals("Session listener invocation count mismatch", 1, creationCount.getAndSet(0)); + assertEquals(1, creationCount.getAndSet(0), "Session listener invocation count mismatch"); } } finally { client.removeSessionListener(listener); } } - @Test // SSHD-1050 - public void testAuthGetsNotifiedIfErrorBeforeFirstAuth() throws Exception { + // SSHD-1050 + @Test + void authGetsNotifiedIfErrorBeforeFirstAuth() throws Exception { testEarlyErrorAuthAttempts(1); } - @Test // SSHD-1050 - public void testSecondAuthNotifiedAfterEarlyError() throws Exception { + // SSHD-1050 + @Test + void secondAuthNotifiedAfterEarlyError() throws Exception { testEarlyErrorAuthAttempts(3); } @@ -297,22 +306,23 @@ private void testEarlyErrorAuthAttempts(int maxAttempts) throws Exception { outputDebugMessage("%s(%s)", getCurrentTestName(), authId); AuthFuture future = session.auth(); - assertTrue(authId + " not completed on time", future.await(AUTH_TIMEOUT)); - assertTrue(authId + " has no result", future.isDone()); - assertFalse(authId + " unexpected success", future.isSuccess()); - assertTrue(authId + " not marked as failed", future.isFailure()); + assertTrue(future.await(AUTH_TIMEOUT), authId + " not completed on time"); + assertTrue(future.isDone(), authId + " has no result"); + assertFalse(future.isSuccess(), authId + " unexpected success"); + assertTrue(future.isFailure(), authId + " not marked as failed"); Throwable exception = future.getException(); String message = exception.getMessage(); - assertTrue(authId + " invalid exception message: " + message, message.contains("too many header lines")); + assertTrue(message.contains("too many header lines"), authId + " invalid exception message: " + message); } } finally { CoreModuleProperties.SERVER_EXTRA_IDENTIFICATION_LINES.set(sshd, null); } } - @Test // SSHD-1276 - public void testRedirectCommandErrorStream() throws Exception { + // SSHD-1276 + @Test + void redirectCommandErrorStream() throws Exception { String expectedCommand = getCurrentTestName() + "-CMD"; String expectedStdout = getCurrentTestName() + "-STDOUT"; String expectedStderr = getCurrentTestName() + "-STDERR"; @@ -321,8 +331,8 @@ public void testRedirectCommandErrorStream() throws Exception { @Override protected boolean handleCommandLine(String command) throws Exception { - assertEquals("Mismatched incoming command", expectedCommand, command); - assertFalse("Duplicated command call", cmdProcessed); + assertEquals(expectedCommand, command, "Mismatched incoming command"); + assertFalse(cmdProcessed, "Duplicated command call"); writeResponse(getOutputStream(), expectedStdout); writeResponse(getErrorStream(), expectedStderr); cmdProcessed = true; @@ -360,7 +370,7 @@ private void writeResponse(OutputStream out, String rsp) throws IOException { } String[] lines = GenericUtils.split(response, '\n'); - assertEquals("Mismatched response lines count", 2, lines.length); + assertEquals(2, lines.length, "Mismatched response lines count"); Collection values = new ArrayList<>(Arrays.asList(lines)); // We don't rely on the order the strings were written @@ -370,11 +380,12 @@ private void writeResponse(OutputStream out, String rsp) throws IOException { } } - assertTrue("Unexpected response remainders: " + values, values.isEmpty()); + assertTrue(values.isEmpty(), "Unexpected response remainders: " + values); } - @Test // SSHD-1303 - public void testRedirectCommandErrorStreamIsEmpty() throws Exception { + // SSHD-1303 + @Test + void redirectCommandErrorStreamIsEmpty() throws Exception { String expectedCommand = getCurrentTestName() + "-CMD"; String expectedStdout = getCurrentTestName() + "-STDOUT"; String expectedStderr = getCurrentTestName() + "-STDERR"; @@ -383,8 +394,8 @@ public void testRedirectCommandErrorStreamIsEmpty() throws Exception { @Override protected boolean handleCommandLine(String command) throws Exception { - assertEquals("Mismatched incoming command", expectedCommand, command); - assertFalse("Duplicated command call", cmdProcessed); + assertEquals(expectedCommand, command, "Mismatched incoming command"); + assertFalse(cmdProcessed, "Duplicated command call"); writeResponse(getOutputStream(), expectedStdout); writeResponse(getErrorStream(), expectedStderr); cmdProcessed = true; @@ -423,7 +434,7 @@ private void writeResponse(OutputStream out, String rsp) throws IOException { } String[] lines = GenericUtils.split(response, '\n'); - assertEquals("Mismatched response lines count", 2, lines.length); + assertEquals(2, lines.length, "Mismatched response lines count"); Collection values = new ArrayList<>(Arrays.asList(lines)); // We don't rely on the order the strings were written @@ -433,11 +444,12 @@ private void writeResponse(OutputStream out, String rsp) throws IOException { } } - assertTrue("Unexpected response remainders: " + values, values.isEmpty()); + assertTrue(values.isEmpty(), "Unexpected response remainders: " + values); } - @Test // SSHD-1302 - public void testReadInputStreamTwice() throws Exception { + // SSHD-1302 + @Test + void readInputStreamTwice() throws Exception { String expectedCommand = getCurrentTestName() + "-CMD"; String expectedStdout = getCurrentTestName() + "-STDOUT"; String expectedStderr = getCurrentTestName() + "-STDERR"; @@ -446,8 +458,8 @@ public void testReadInputStreamTwice() throws Exception { @Override protected boolean handleCommandLine(String command) throws Exception { - assertEquals("Mismatched incoming command", expectedCommand, command); - assertFalse("Duplicated command call", cmdProcessed); + assertEquals(expectedCommand, command, "Mismatched incoming command"); + assertFalse(cmdProcessed, "Duplicated command call"); writeResponse(getOutputStream(), expectedStdout); writeResponse(getErrorStream(), expectedStderr); cmdProcessed = true; @@ -499,7 +511,7 @@ private void writeResponse(OutputStream out, String rsp) throws IOException { } String[] lines = GenericUtils.split(response, '\n'); - assertEquals("Mismatched response lines count", 2, lines.length); + assertEquals(2, lines.length, "Mismatched response lines count"); Collection values = new ArrayList<>(Arrays.asList(lines)); // We don't rely on the order the strings were written @@ -509,6 +521,6 @@ private void writeResponse(OutputStream out, String rsp) throws IOException { } } - assertTrue("Unexpected response remainders: " + values, values.isEmpty()); + assertTrue(values.isEmpty(), "Unexpected response remainders: " + values); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSessionClientTest.java b/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSessionClientTest.java index c1e83a13f..35fc5ad1b 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSessionClientTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/simple/SimpleSessionClientTest.java @@ -33,33 +33,37 @@ import org.apache.sshd.server.auth.pubkey.RejectAllPublickeyAuthenticator; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.client.simple.BaseSimpleClientTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SimpleSessionClientTest extends BaseSimpleClientTestSupport { public SimpleSessionClientTest() { super(); } @Test - public void testLoginSessionWithPassword() throws Exception { + void loginSessionWithPassword() throws Exception { // make sure authentication occurs only for passwords sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE); client.start(); try (ClientSession session = simple.sessionLogin( TEST_LOCALHOST, port, getCurrentTestName(), getCurrentTestName())) { - assertEquals("Mismatched session username", getCurrentTestName(), session.getUsername()); + assertEquals(getCurrentTestName(), session.getUsername(), "Mismatched session username"); } } @Test - public void testLoginSessionWithIdentity() throws Exception { + void loginSessionWithIdentity() throws Exception { KeyPair identity = CommonTestSupportUtils.getFirstKeyPair(createTestHostKeyProvider()); AtomicBoolean identityQueried = new AtomicBoolean(false); sshd.setPublickeyAuthenticator((username, key, session) -> { @@ -76,14 +80,13 @@ public void testLoginSessionWithIdentity() throws Exception { try (ClientSession session = simple.sessionLogin( TEST_LOCALHOST, port, getCurrentTestName(), identity)) { - assertEquals("Mismatched session username", - getCurrentTestName(), session.getUsername()); - assertTrue("User identity not queried", identityQueried.get()); + assertEquals(getCurrentTestName(), session.getUsername(), "Mismatched session username"); + assertTrue(identityQueried.get(), "User identity not queried"); } } @Test - public void testConnectionTimeout() throws Exception { + void connectionTimeout() throws Exception { client.addSessionListener(new SessionListener() { @Override public void sessionCreated(Session session) { @@ -105,12 +108,12 @@ TEST_LOCALHOST, port, getCurrentTestName(), getCurrentTestName())) { long nanoDuration = nanoEnd - nanoStart; long nanoTimeout = CONNECT_TIMEOUT.toNanos(); // we allow the timeout to be shorter than the connect timeout, but no more than 3 times its value - assertTrue("Expired time (" + nanoDuration + ") too long", nanoDuration < (nanoTimeout * 3L)); + assertTrue(nanoDuration < (nanoTimeout * 3L), "Expired time (" + nanoDuration + ") too long"); } } @Test - public void testAuthenticationTimeout() throws Exception { + void authenticationTimeout() throws Exception { // make sure authentication occurs only for passwords sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE); PasswordAuthenticator delegate = Objects.requireNonNull( @@ -134,7 +137,7 @@ TEST_LOCALHOST, port, getCurrentTestName(), getCurrentTestName())) { long nanoDuration = nanoEnd - nanoStart; long nanoTimeout = AUTH_TIMEOUT.toNanos(); // we allow the timeout to be shorter than the connect timeout, but no more than 3 times its value - assertTrue("Expired time (" + nanoDuration + ") too long", nanoDuration < (nanoTimeout * 3L)); + assertTrue(nanoDuration < (nanoTimeout * 3L), "Expired time (" + nanoDuration + ") too long"); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/AttributeStoreTest.java b/sshd-core/src/test/java/org/apache/sshd/common/AttributeStoreTest.java index f30ba0bc2..7f3fe7781 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/AttributeStoreTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/AttributeStoreTest.java @@ -24,19 +24,22 @@ import org.apache.sshd.common.channel.Channel; import org.apache.sshd.common.session.Session; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class AttributeStoreTest extends BaseTestSupport { private static final AttributeRepository.AttributeKey KEY = new AttributeRepository.AttributeKey<>(); @@ -45,17 +48,17 @@ public AttributeStoreTest() { } @Test - public void testResolveFactoryManagerAttribute() { - assertNull("Unexpected null factory value", FactoryManager.resolveAttribute((FactoryManager) null, KEY)); + void resolveFactoryManagerAttribute() { + assertNull(FactoryManager.resolveAttribute((FactoryManager) null, KEY), "Unexpected null factory value"); FactoryManager manager = Mockito.mock(FactoryManager.class); String expected = setAttributeValue(manager, getCurrentTestName()); - assertSame("Mismatched resolved value", expected, FactoryManager.resolveAttribute(manager, KEY)); + assertSame(expected, FactoryManager.resolveAttribute(manager, KEY), "Mismatched resolved value"); } @Test - public void testResolveSessionAttribute() { - assertNull("Unexpected null session value", Session.resolveAttribute((Session) null, KEY)); + void resolveSessionAttribute() { + assertNull(Session.resolveAttribute((Session) null, KEY), "Unexpected null session value"); Session session = Mockito.mock(Session.class); AtomicInteger managerCount = new AtomicInteger(0); @@ -64,17 +67,17 @@ public void testResolveSessionAttribute() { return null; }); setAttributeValue(session, null); - assertNull("Unexpected success for empty attribute", Session.resolveAttribute(session, KEY)); - assertEquals("Factory manager not requested", 1, managerCount.getAndSet(0)); + assertNull(Session.resolveAttribute(session, KEY), "Unexpected success for empty attribute"); + assertEquals(1, managerCount.getAndSet(0), "Factory manager not requested"); String expected = setAttributeValue(session, getCurrentTestName()); - assertSame("Mismatched attribute value", expected, Session.resolveAttribute(session, KEY)); - assertEquals("Unexpected manager request", 0, managerCount.get()); + assertSame(expected, Session.resolveAttribute(session, KEY), "Mismatched attribute value"); + assertEquals(0, managerCount.get(), "Unexpected manager request"); } @Test - public void testResolveChannelAttribute() { - assertNull("Unexpected null channek value", Channel.resolveAttribute((Channel) null, KEY)); + void resolveChannelAttribute() { + assertNull(Channel.resolveAttribute((Channel) null, KEY), "Unexpected null channek value"); Session session = Mockito.mock(Session.class); AtomicInteger managerCount = new AtomicInteger(0); @@ -92,14 +95,14 @@ public void testResolveChannelAttribute() { }); setAttributeValue(channel, null); - assertNull("Unexpected success for empty attribute", Channel.resolveAttribute(channel, KEY)); - assertEquals("Session not requested", 1, sessionCount.getAndSet(0)); - assertEquals("Factory manager not requested", 1, managerCount.getAndSet(0)); + assertNull(Channel.resolveAttribute(channel, KEY), "Unexpected success for empty attribute"); + assertEquals(1, sessionCount.getAndSet(0), "Session not requested"); + assertEquals(1, managerCount.getAndSet(0), "Factory manager not requested"); String expected = setAttributeValue(channel, getCurrentTestName()); - assertSame("Mismatched attribute value", expected, Channel.resolveAttribute(channel, KEY)); - assertEquals("Unexpected session request", 0, sessionCount.get()); - assertEquals("Unexpected manager request", 0, managerCount.get()); + assertSame(expected, Channel.resolveAttribute(channel, KEY), "Mismatched attribute value"); + assertEquals(0, sessionCount.get(), "Unexpected session request"); + assertEquals(0, managerCount.get(), "Unexpected manager request"); } private static String setAttributeValue(AttributeStore store, String value) { diff --git a/sshd-core/src/test/java/org/apache/sshd/common/PropertyResolverUtilsTest.java b/sshd-core/src/test/java/org/apache/sshd/common/PropertyResolverUtilsTest.java index 92471c924..c92bc68dc 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/PropertyResolverUtilsTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/PropertyResolverUtilsTest.java @@ -31,48 +31,55 @@ import org.apache.sshd.common.session.Session; import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PropertyResolverUtilsTest extends JUnitTestSupport { public PropertyResolverUtilsTest() { super(); } @Test - public void testResolveAndUpdateClosestPropertyValue() { + void resolveAndUpdateClosestPropertyValue() { String propName = getCurrentTestName(); String rootValue = getClass().getPackage().getName(); Session resolver = createMockSession(); FactoryManager root = Objects.requireNonNull(resolver.getFactoryManager(), "No manager"); - assertNull("Unexpected root previous value", PropertyResolverUtils.updateProperty(root, propName, rootValue)); - assertSame("Mismatched root value", rootValue, PropertyResolverUtils.getString(resolver, propName)); + assertNull(PropertyResolverUtils.updateProperty(root, propName, rootValue), "Unexpected root previous value"); + assertSame(rootValue, PropertyResolverUtils.getString(resolver, propName), "Mismatched root value"); String nodeValue = getClass().getSimpleName(); - assertNull("Unexpected node previous value", PropertyResolverUtils.updateProperty(resolver, propName, nodeValue)); - assertSame("Mismatched node value", nodeValue, PropertyResolverUtils.getString(resolver, propName)); + assertNull(PropertyResolverUtils.updateProperty(resolver, propName, nodeValue), "Unexpected node previous value"); + assertSame(nodeValue, PropertyResolverUtils.getString(resolver, propName), "Mismatched node value"); } @Test - public void testSyspropsResolver() { + void syspropsResolver() { PropertyResolver resolver = SyspropsMapWrapper.SYSPROPS_RESOLVER; Map props = resolver.getProperties(); - assertTrue("Unexpected initial resolver values: " + props, MapEntryUtils.isEmpty(props)); + assertTrue(MapEntryUtils.isEmpty(props), "Unexpected initial resolver values: " + props); final String propName = getCurrentTestName(); - assertNull("Unexpected initial resolved value", PropertyResolverUtils.getObject(resolver, propName)); + assertNull(PropertyResolverUtils.getObject(resolver, propName), "Unexpected initial resolved value"); final String propKey = SyspropsMapWrapper.getMappedSyspropKey(propName); - assertNull("Unexpected property value for " + propKey, System.getProperty(propKey)); + assertNull(System.getProperty(propKey), "Unexpected property value for " + propKey); try { long expected = System.currentTimeMillis(); @@ -101,12 +108,12 @@ public void testSyspropsResolver() { } @Test - public void testLongProperty() { + void longProperty() { long expected = System.currentTimeMillis(); String name = getCurrentTestName(); Session session = createMockSession(); - assertEquals("Mismatched empty props value", expected, PropertyResolverUtils.getLongProperty(session, name, expected)); + assertEquals(expected, PropertyResolverUtils.getLongProperty(session, name, expected), "Mismatched empty props value"); PropertyResolverUtils.updateProperty(session, name, expected); testLongProperty(session, name, expected); @@ -124,24 +131,24 @@ private void testLongProperty(PropertyResolver resolver, String name, long expec { Long actual = PropertyResolverUtils.getLong(resolver, name); - assertNotNull("No actual Long value found for storage as " + storage, actual); - assertEquals("Mismatched values on Long retrieval for storage as " + storage, expected, actual.longValue()); + assertNotNull(actual, "No actual Long value found for storage as " + storage); + assertEquals(expected, actual.longValue(), "Mismatched values on Long retrieval for storage as " + storage); } { String actual = PropertyResolverUtils.getString(resolver, name); - assertNotNull("No actual String value found for storage as " + storage, actual); - assertEquals("Mismatched values on String retrieval for storage as " + storage, Long.toString(expected), actual); + assertNotNull(actual, "No actual String value found for storage as " + storage); + assertEquals(Long.toString(expected), actual, "Mismatched values on String retrieval for storage as " + storage); } } @Test - public void testIntegerProperty() { + void integerProperty() { int expected = 3777347; String name = getCurrentTestName(); Session session = createMockSession(); - assertEquals("Mismatched empty props value", expected, PropertyResolverUtils.getIntProperty(session, name, expected)); + assertEquals(expected, PropertyResolverUtils.getIntProperty(session, name, expected), "Mismatched empty props value"); PropertyResolverUtils.updateProperty(session, name, expected); testIntegerProperty(session, name, expected); @@ -163,19 +170,19 @@ private void testIntegerProperty(PropertyResolver resolver, String name, int exp { Integer actual = PropertyResolverUtils.getInteger(resolver, name); - assertNotNull("No actual Integer value found for storage as " + storage, actual); - assertEquals("Mismatched values on Integer retrieval for storage as " + storage, expected, actual.intValue()); + assertNotNull(actual, "No actual Integer value found for storage as " + storage); + assertEquals(expected, actual.intValue(), "Mismatched values on Integer retrieval for storage as " + storage); } { String actual = PropertyResolverUtils.getString(resolver, name); - assertNotNull("No actual String value found for storage as " + storage, actual); - assertEquals("Mismatched values on String retrieval for storage as " + storage, Integer.toString(expected), actual); + assertNotNull(actual, "No actual String value found for storage as " + storage); + assertEquals(Integer.toString(expected), actual, "Mismatched values on String retrieval for storage as " + storage); } } @Test - public void testBooleanProperty() { + void booleanProperty() { for (boolean expected : new boolean[] { false, true }) { String name = getCurrentTestName(); @@ -200,41 +207,41 @@ private void testBooleanProperty(PropertyResolver resolver, String name, boolean { Boolean actual = PropertyResolverUtils.getBoolean(resolver, name); - assertNotNull("No actual Boolean value found for storage as " + storage, actual); + assertNotNull(actual, "No actual Boolean value found for storage as " + storage); assertEquals("Mismatched values on Boolean retrieval for storage as " + storage, expected, actual.booleanValue()); } { String actual = PropertyResolverUtils.getString(resolver, name); - assertNotNull("No actual String value found for storage as " + storage, actual); - assertEquals("Mismatched values on String retrieval for storage as " + storage, Boolean.toString(expected), actual); + assertNotNull(actual, "No actual String value found for storage as " + storage); + assertEquals(Boolean.toString(expected), actual, "Mismatched values on String retrieval for storage as " + storage); } } @Test - public void testToEnumFromString() { + void toEnumFromString() { Collection units = EnumSet.allOf(TimeUnit.class); for (TimeUnit expected : units) { String name = expected.name(); for (int index = 1, count = name.length(); index <= count; index++) { TimeUnit actual = PropertyResolverUtils.toEnum(TimeUnit.class, name, true, units); - assertSame("Mismatched instance for name=" + name, expected, actual); + assertSame(expected, actual, "Mismatched instance for name=" + name); name = shuffleCase(name); } } } @Test - public void testToEnumFromEnum() { + void toEnumFromEnum() { Collection units = EnumSet.allOf(TimeUnit.class); for (TimeUnit expected : units) { TimeUnit actual = PropertyResolverUtils.toEnum(TimeUnit.class, expected, true, null); - assertSame("Mismatched resolved value", expected, actual); + assertSame(expected, actual, "Mismatched resolved value"); } } @Test - public void testToEnumFromNonString() { + void toEnumFromNonString() { Collection units = EnumSet.allOf(TimeUnit.class); for (Object value : new Object[] { this, getClass(), new Date() }) { try { @@ -246,11 +253,13 @@ public void testToEnumFromNonString() { } } - @Test(expected = NoSuchElementException.class) - public void testToEnumNoMatchFound() { - TimeUnit result - = PropertyResolverUtils.toEnum(TimeUnit.class, getCurrentTestName(), true, EnumSet.allOf(TimeUnit.class)); - fail("Unexpected success: " + result); + @Test + void toEnumNoMatchFound() { + assertThrows(NoSuchElementException.class, () -> { + TimeUnit result + = PropertyResolverUtils.toEnum(TimeUnit.class, getCurrentTestName(), true, EnumSet.allOf(TimeUnit.class)); + fail("Unexpected success: " + result); + }); } private Session createMockSession() { diff --git a/sshd-core/src/test/java/org/apache/sshd/common/SshBuilderTest.java b/sshd-core/src/test/java/org/apache/sshd/common/SshBuilderTest.java index e28746f67..0301bacbd 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/SshBuilderTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/SshBuilderTest.java @@ -25,17 +25,19 @@ import org.apache.sshd.common.cipher.Cipher; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SshBuilderTest extends BaseTestSupport { public SshBuilderTest() { super(); @@ -46,13 +48,13 @@ public SshBuilderTest() { * the {@code ingoreUnsupported} parameter and in the defined preference order */ @Test - public void testSetUpDefaultCiphers() { + void setUpDefaultCiphers() { for (boolean ignoreUnsupported : new boolean[] { true, false }) { List> ciphers = BaseBuilder.setUpDefaultCiphers(ignoreUnsupported); int numCiphers = GenericUtils.size(ciphers); // make sure returned list size matches expected count if (ignoreUnsupported) { - assertEquals("Incomplete full ciphers size", BaseBuilder.DEFAULT_CIPHERS_PREFERENCE.size(), numCiphers); + assertEquals(BaseBuilder.DEFAULT_CIPHERS_PREFERENCE.size(), numCiphers, "Incomplete full ciphers size"); } else { int expectedCount = 0; for (BuiltinCiphers c : BaseBuilder.DEFAULT_CIPHERS_PREFERENCE) { @@ -60,7 +62,7 @@ public void testSetUpDefaultCiphers() { expectedCount++; } } - assertEquals("Incomplete supported ciphers size", expectedCount, numCiphers); + assertEquals(expectedCount, numCiphers, "Incomplete supported ciphers size"); } // make sure order is according to the default preference list @@ -72,11 +74,11 @@ public void testSetUpDefaultCiphers() { } String expectedName = c.getName(); - assertTrue("Out of actual ciphers for expected=" + expectedName, nameIndex < numCiphers); + assertTrue(nameIndex < numCiphers, "Out of actual ciphers for expected=" + expectedName); String actualName = cipherNames.get(nameIndex); - assertEquals("Mismatched cipher at position " + nameIndex + " for ignoreUnsupported=" + ignoreUnsupported, - expectedName, actualName); + assertEquals(expectedName, actualName, + "Mismatched cipher at position " + nameIndex + " for ignoreUnsupported=" + ignoreUnsupported); nameIndex++; } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/auth/AuthenticationTest.java b/sshd-core/src/test/java/org/apache/sshd/common/auth/AuthenticationTest.java index d3aece6ad..1c6b76511 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/auth/AuthenticationTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/auth/AuthenticationTest.java @@ -36,18 +36,26 @@ import org.apache.sshd.server.auth.password.PasswordAuthenticator; import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + +@TestMethodOrder(MethodName.class) public class AuthenticationTest extends AuthenticationTestSupport { public AuthenticationTest() { super(); } - @Test // see SSHD-600 - public void testAuthExceptionPropagation() throws Exception { + // see SSHD-600 + @Test + void authExceptionPropagation() throws Exception { try (SshClient client = setupTestClient()) { RuntimeException expected = new RuntimeException("Synthetic exception"); AtomicInteger invocations = new AtomicInteger(0); @@ -55,7 +63,7 @@ public void testAuthExceptionPropagation() throws Exception { client.addSessionListener(new SessionListener() { @Override public void sessionEvent(Session session, Event event) { - assertEquals("Mismatched invocations count", 1, invocations.incrementAndGet()); + assertEquals(1, invocations.incrementAndGet(), "Mismatched invocations count"); throw expected; } @@ -74,8 +82,8 @@ public void sessionException(Session session, Throwable t) { s.addPasswordIdentity(getCurrentTestName()); AuthFuture future = s.auth(); - assertTrue("Failed to complete auth in allocated time", future.await(DEFAULT_TIMEOUT)); - assertFalse("Unexpected authentication success", future.isSuccess()); + assertTrue(future.await(DEFAULT_TIMEOUT), "Failed to complete auth in allocated time"); + assertFalse(future.isSuccess(), "Unexpected authentication success"); Throwable signalled = future.getException(); Throwable actual = signalled; @@ -96,8 +104,9 @@ public void sessionException(Session session, Throwable t) { } } - @Test // see SSHD-625 - public void testRuntimeErrorsInAuthenticators() throws Exception { + // see SSHD-625 + @Test + void runtimeErrorsInAuthenticators() throws Exception { Error thrown = new OutOfMemoryError(getCurrentTestName()); PasswordAuthenticator authPassword = sshd.getPasswordAuthenticator(); AtomicInteger passCounter = new AtomicInteger(0); @@ -135,14 +144,14 @@ public void testRuntimeErrorsInAuthenticators() throws Exception { s.addPublicKeyIdentity(kp); AuthFuture auth = s.auth(); - assertTrue("Failed to complete authentication on time", auth.await(AUTH_TIMEOUT)); + assertTrue(auth.await(AUTH_TIMEOUT), "Failed to complete authentication on time"); if (auth.isSuccess()) { - assertTrue("Premature authentication success", index > 1); + assertTrue(index > 1, "Premature authentication success"); break; } - assertEquals("Password authenticator not consulted", 1, passCounter.get()); - assertEquals("Pubkey authenticator not consulted", 1, pubkeyCounter.get()); + assertEquals(1, passCounter.get(), "Password authenticator not consulted"); + assertEquals(1, pubkeyCounter.get(), "Pubkey authenticator not consulted"); } } } finally { @@ -151,8 +160,9 @@ public void testRuntimeErrorsInAuthenticators() throws Exception { } } - @Test // see SSHD-1040 - public void testServerKeyAvailableAfterAuth() throws Exception { + // see SSHD-1040 + @Test + void serverKeyAvailableAfterAuth() throws Exception { KeyPairProvider keyPairProvider = sshd.getKeyPairProvider(); Iterable availableKeys = keyPairProvider.loadKeys(null); PublicKey actualKey = null; @@ -166,7 +176,7 @@ public void testServerKeyAvailableAfterAuth() throws Exception { session.auth().verify(AUTH_TIMEOUT); KeyExchange kex = session.getKex(); - assertNull("KEX not nullified after completion", kex); + assertNull(kex, "KEX not nullified after completion"); actualKey = session.getServerKey(); } finally { @@ -174,7 +184,7 @@ public void testServerKeyAvailableAfterAuth() throws Exception { } } - assertNotNull("No server key extracted", actualKey); + assertNotNull(actualKey, "No server key extracted"); for (KeyPair kp : availableKeys) { PublicKey expectedKey = kp.getPublic(); diff --git a/sshd-core/src/test/java/org/apache/sshd/common/auth/AuthenticationTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/common/auth/AuthenticationTestSupport.java index 3fab5de2f..f0fcd232e 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/auth/AuthenticationTestSupport.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/auth/AuthenticationTestSupport.java @@ -29,8 +29,12 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project @@ -45,14 +49,14 @@ protected AuthenticationTestSupport() { super(); } - @Before + @BeforeEach public void setUp() throws Exception { sshd = setupTestServer(); sshd.start(); port = sshd.getPort(); } - @After + @AfterEach public void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); @@ -60,7 +64,7 @@ public void tearDown() throws Exception { } protected static void assertAuthenticationResult(String message, AuthFuture future, boolean expected) throws IOException { - assertTrue(message + ": failed to get result on time", future.await(AUTH_TIMEOUT)); + assertTrue(future.await(AUTH_TIMEOUT), message + ": failed to get result on time"); assertEquals(message + ": mismatched authentication result", expected, future.isSuccess()); } @@ -83,9 +87,9 @@ public boolean isInteractionAllowed(ClientSession session) { public String[] interactive( ClientSession session, String name, String instruction, String lang, String[] prompt, boolean[] echo) { - assertSame("Mismatched session instance", s, session); - assertEquals("Mismatched prompt size", 1, GenericUtils.length(prompt)); - assertTrue("Mismatched prompt: " + prompt[0], prompt[0].toLowerCase().contains("password")); + assertSame(s, session, "Mismatched session instance"); + assertEquals(1, GenericUtils.length(prompt), "Mismatched prompt size"); + assertTrue(prompt[0].toLowerCase().contains("password"), "Mismatched prompt: " + prompt[0]); return response; } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/auth/HostBasedAuthenticationTest.java b/sshd-core/src/test/java/org/apache/sshd/common/auth/HostBasedAuthenticationTest.java index 7568bc88f..cbafd76e5 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/auth/HostBasedAuthenticationTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/auth/HostBasedAuthenticationTest.java @@ -39,21 +39,25 @@ import org.apache.sshd.server.auth.password.RejectAllPasswordAuthenticator; import org.apache.sshd.server.auth.pubkey.RejectAllPublickeyAuthenticator; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class HostBasedAuthenticationTest extends AuthenticationTestSupport { public HostBasedAuthenticationTest() { super(); } - @Test // see SSHD-620 - public void testHostBasedAuthentication() throws Exception { + // see SSHD-620 + @Test + void hostBasedAuthentication() throws Exception { AtomicInteger invocationCount = new AtomicInteger(0); testHostBasedAuthentication( ( @@ -61,11 +65,12 @@ public void testHostBasedAuthentication() throws Exception { certificates) -> invocationCount.incrementAndGet() > 0, session -> { /* ignored */ }); - assertEquals("Mismatched authenticator invocation count", 1, invocationCount.get()); + assertEquals(1, invocationCount.get(), "Mismatched authenticator invocation count"); } - @Test // see SSHD-1114 - public void testHostBasedAuthenticationReporter() throws Exception { + // see SSHD-1114 + @Test + void hostBasedAuthenticationReporter() throws Exception { AtomicReference hostnameClientHolder = new AtomicReference<>(); AtomicReference usernameClientHolder = new AtomicReference<>(); AtomicReference keyClientHolder = new AtomicReference<>(); @@ -90,8 +95,8 @@ public void signalAuthenticationAttempt( public void signalAuthenticationSuccess( ClientSession session, String service, KeyPair identity, String hostname, String username) throws Exception { - assertEquals("Host", hostname, hostnameClientHolder.get()); - assertEquals("User", username, usernameClientHolder.get()); + assertEquals(hostname, hostnameClientHolder.get(), "Host"); + assertEquals(username, usernameClientHolder.get(), "User"); assertKeyEquals("Identity", identity.getPublic(), keyClientHolder.get()); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/auth/KeyboardInteractiveAuthenticationTest.java b/sshd-core/src/test/java/org/apache/sshd/common/auth/KeyboardInteractiveAuthenticationTest.java index 5a3785724..49dc1b277 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/auth/KeyboardInteractiveAuthenticationTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/auth/KeyboardInteractiveAuthenticationTest.java @@ -44,21 +44,25 @@ import org.apache.sshd.server.auth.pubkey.RejectAllPublickeyAuthenticator; import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class KeyboardInteractiveAuthenticationTest extends AuthenticationTestSupport { public KeyboardInteractiveAuthenticationTest() { super(); } - @Test // see SSHD-612 - public void testAuthDefaultKeyInteractive() throws Exception { + // see SSHD-612 + @Test + void authDefaultKeyInteractive() throws Exception { try (SshClient client = setupTestClient()) { sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE); sshd.setKeyboardInteractiveAuthenticator(new DefaultKeyboardInteractiveAuthenticator() { @@ -66,24 +70,25 @@ public void testAuthDefaultKeyInteractive() throws Exception { public InteractiveChallenge generateChallenge( ServerSession session, String username, String lang, String subMethods) throws Exception { - assertEquals("Mismatched user language", - CoreModuleProperties.INTERACTIVE_LANGUAGE_TAG.getRequired(client), - lang); - assertEquals("Mismatched client sub-methods", - CoreModuleProperties.INTERACTIVE_SUBMETHODS.getRequired(client), - subMethods); + assertEquals(CoreModuleProperties.INTERACTIVE_LANGUAGE_TAG.getRequired(client), + lang, + "Mismatched user language"); + assertEquals(CoreModuleProperties.INTERACTIVE_SUBMETHODS.getRequired(client), + subMethods, + "Mismatched client sub-methods"); InteractiveChallenge challenge = super.generateChallenge(session, username, lang, subMethods); - assertEquals("Mismatched interaction name", getInteractionName(session), challenge.getInteractionName()); - assertEquals("Mismatched interaction instruction", getInteractionInstruction(session), - challenge.getInteractionInstruction()); - assertEquals("Mismatched language tag", getInteractionLanguage(session), challenge.getLanguageTag()); + assertEquals(getInteractionName(session), challenge.getInteractionName(), "Mismatched interaction name"); + assertEquals(getInteractionInstruction(session), + challenge.getInteractionInstruction(), + "Mismatched interaction instruction"); + assertEquals(getInteractionLanguage(session), challenge.getLanguageTag(), "Mismatched language tag"); List entries = challenge.getPrompts(); - assertEquals("Mismatched prompts count", 1, GenericUtils.size(entries)); + assertEquals(1, GenericUtils.size(entries), "Mismatched prompts count"); PromptEntry entry = entries.get(0); - assertEquals("Mismatched prompt", getInteractionPrompt(session), entry.getPrompt()); + assertEquals(getInteractionPrompt(session), entry.getPrompt(), "Mismatched prompt"); assertEquals("Mismatched echo", isInteractionPromptEchoEnabled(session), entry.isEcho()); return challenge; @@ -105,7 +110,7 @@ public boolean authenticate( Collection result = s.waitFor( EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH), DEFAULT_TIMEOUT); - assertFalse("Timeout while waiting for session", result.contains(ClientSession.ClientSessionEvent.TIMEOUT)); + assertFalse(result.contains(ClientSession.ClientSessionEvent.TIMEOUT), "Timeout while waiting for session"); KeyPairProvider provider = createTestHostKeyProvider(); KeyPair pair = provider.loadKey(s, CommonTestSupportUtils.DEFAULT_TEST_HOST_KEY_TYPE); @@ -128,8 +133,9 @@ public boolean authenticate( } } - @Test // see SSHD-563 - public void testAuthMultiChallengeKeyInteractive() throws Exception { + // see SSHD-563 + @Test + void authMultiChallengeKeyInteractive() throws Exception { Class anchor = getClass(); InteractiveChallenge challenge = new InteractiveChallenge(); challenge.setInteractionName(getCurrentTestName()); @@ -153,7 +159,7 @@ public void testAuthMultiChallengeKeyInteractive() throws Exception { public InteractiveChallenge generateChallenge( ServerSession session, String username, String lang, String subMethods) throws Exception { - assertEquals("Unexpected challenge call", 1, genCount.incrementAndGet()); + assertEquals(1, genCount.incrementAndGet(), "Unexpected challenge call"); return challenge; } @@ -161,8 +167,8 @@ public InteractiveChallenge generateChallenge( public boolean authenticate( ServerSession session, String username, List responses) throws Exception { - assertEquals("Unexpected authenticate call", 1, authCount.incrementAndGet()); - assertEquals("Mismatched number of responses", MapEntryUtils.size(rspMap), GenericUtils.size(responses)); + assertEquals(1, authCount.incrementAndGet(), "Unexpected authenticate call"); + assertEquals(MapEntryUtils.size(rspMap), GenericUtils.size(responses), "Mismatched number of responses"); int index = 0; // Cannot use forEach because the index is not effectively final @@ -170,7 +176,7 @@ public boolean authenticate( String prompt = re.getKey(); String expected = re.getValue(); String actual = responses.get(index); - assertEquals("Mismatched response for prompt=" + prompt, expected, actual); + assertEquals(expected, actual, "Mismatched response for prompt=" + prompt); index++; } return true; @@ -190,19 +196,19 @@ public boolean isInteractionAllowed(ClientSession session) { public String[] interactive( ClientSession session, String name, String instruction, String lang, String[] prompt, boolean[] echo) { - assertEquals("Unexpected multiple calls", 1, interactiveCount.incrementAndGet()); - assertEquals("Mismatched name", challenge.getInteractionName(), name); - assertEquals("Mismatched instruction", challenge.getInteractionInstruction(), instruction); - assertEquals("Mismatched language", challenge.getLanguageTag(), lang); + assertEquals(1, interactiveCount.incrementAndGet(), "Unexpected multiple calls"); + assertEquals(challenge.getInteractionName(), name, "Mismatched name"); + assertEquals(challenge.getInteractionInstruction(), instruction, "Mismatched instruction"); + assertEquals(challenge.getLanguageTag(), lang, "Mismatched language"); List entries = challenge.getPrompts(); - assertEquals("Mismatched prompts count", GenericUtils.size(entries), GenericUtils.length(prompt)); + assertEquals(GenericUtils.size(entries), GenericUtils.length(prompt), "Mismatched prompts count"); String[] responses = new String[prompt.length]; for (int index = 0; index < prompt.length; index++) { PromptEntry e = entries.get(index); String key = e.getPrompt(); - assertEquals("Mismatched prompt at index=" + index, key, prompt[index]); + assertEquals(key, prompt[index], "Mismatched prompt at index=" + index); assertEquals("Mismatched echo at index=" + index, e.isEcho(), echo[index]); responses[index] = ValidateUtils.checkNotNull(rspMap.get(key), "No value for prompt=%s", key); } @@ -223,9 +229,9 @@ public String getUpdatedPassword(ClientSession session, String prompt, String la .verify(CONNECT_TIMEOUT) .getSession()) { s.auth().verify(AUTH_TIMEOUT); - assertEquals("Bad generated challenge count", 1, genCount.get()); - assertEquals("Bad authentication count", 1, authCount.get()); - assertEquals("Bad interactive count", 1, interactiveCount.get()); + assertEquals(1, genCount.get(), "Bad generated challenge count"); + assertEquals(1, authCount.get(), "Bad authentication count"); + assertEquals(1, interactiveCount.get(), "Bad interactive count"); } finally { client.stop(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/auth/PasswordAuthenticationTest.java b/sshd-core/src/test/java/org/apache/sshd/common/auth/PasswordAuthenticationTest.java index a3fdeca29..e1984ce7d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/auth/PasswordAuthenticationTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/auth/PasswordAuthenticationTest.java @@ -48,21 +48,27 @@ import org.apache.sshd.server.auth.pubkey.RejectAllPublickeyAuthenticator; import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class PasswordAuthenticationTest extends AuthenticationTestSupport { public PasswordAuthenticationTest() { super(); } @Test - public void testWrongPassword() throws Exception { + void wrongPassword() throws Exception { try (SshClient client = setupTestClient()) { client.start(); try (ClientSession s = client.connect("user", TEST_LOCALHOST, port) @@ -75,7 +81,7 @@ public void testWrongPassword() throws Exception { } @Test - public void testChangeUser() throws Exception { + void changeUser() throws Exception { try (SshClient client = setupTestClient()) { client.start(); @@ -85,8 +91,8 @@ public void testChangeUser() throws Exception { Collection mask = EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH); Collection result = s.waitFor(mask, DEFAULT_TIMEOUT); - assertFalse("Timeout while waiting on session events", - result.contains(ClientSession.ClientSessionEvent.TIMEOUT)); + assertFalse(result.contains(ClientSession.ClientSessionEvent.TIMEOUT), + "Timeout while waiting on session events"); String password = "the-password"; for (String username : new String[] { "user1", "user2" }) { @@ -100,15 +106,16 @@ public void testChangeUser() throws Exception { // Note that WAIT_AUTH flag should be false, but since the internal // authentication future is not updated, it's still returned result = s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED), DEFAULT_TIMEOUT); - assertTrue("Mismatched client session close mask: " + result, result.containsAll(mask)); + assertTrue(result.containsAll(mask), "Mismatched client session close mask: " + result); } finally { client.stop(); } } } - @Test // see SSHD-196 - public void testChangePassword() throws Exception { + // see SSHD-196 + @Test + void changePassword() throws Exception { PasswordAuthenticator delegate = sshd.getPasswordAuthenticator(); AtomicInteger attemptsCount = new AtomicInteger(0); AtomicInteger changesCount = new AtomicInteger(0); @@ -127,7 +134,7 @@ public boolean authenticate(String username, String password, ServerSession sess public boolean handleClientPasswordChangeRequest( ServerSession session, String username, String oldPassword, String newPassword) { if (changesCount.incrementAndGet() == 1) { - assertNotEquals("Non-different passwords", oldPassword, newPassword); + assertNotEquals(oldPassword, newPassword, "Non-different passwords"); return authenticate(username, newPassword, session); } else { return PasswordAuthenticator.super.handleClientPasswordChangeRequest( @@ -154,10 +161,10 @@ public String[] interactive( @Override public String getUpdatedPassword(ClientSession session, String prompt, String lang) { - assertEquals("Mismatched prompt", getCurrentTestName(), prompt); - assertEquals("Mismatched language", - CoreModuleProperties.WELCOME_BANNER_LANGUAGE.getRequiredDefault(), lang); - assertEquals("Unexpected repeated call", 1, updatesCount.incrementAndGet()); + assertEquals(getCurrentTestName(), prompt, "Mismatched prompt"); + assertEquals(CoreModuleProperties.WELCOME_BANNER_LANGUAGE.getRequiredDefault(), lang, + "Mismatched language"); + assertEquals(1, updatesCount.incrementAndGet(), "Unexpected repeated call"); return getCurrentTestName(); } }); @@ -194,9 +201,9 @@ protected IoWriteFuture sendPassword( .getSession()) { s.addPasswordIdentity(getCurrentTestName()); s.auth().verify(AUTH_TIMEOUT); - assertEquals("No password change request generated", 2, attemptsCount.get()); - assertEquals("No password change handled", 1, changesCount.get()); - assertEquals("No user interaction invoked", 1, updatesCount.get()); + assertEquals(2, attemptsCount.get(), "No password change request generated"); + assertEquals(1, changesCount.get(), "No password change handled"); + assertEquals(1, updatesCount.get(), "No user interaction invoked"); } finally { client.stop(); } @@ -204,7 +211,7 @@ protected IoWriteFuture sendPassword( } @Test - public void testAuthPasswordOnly() throws Exception { + void authPasswordOnly() throws Exception { try (SshClient client = setupTestClient()) { sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE); @@ -215,7 +222,7 @@ public void testAuthPasswordOnly() throws Exception { Collection result = s.waitFor( EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH), DEFAULT_TIMEOUT); - assertFalse("Timeout while waiting for session", result.contains(ClientSession.ClientSessionEvent.TIMEOUT)); + assertFalse(result.contains(ClientSession.ClientSessionEvent.TIMEOUT), "Timeout while waiting for session"); String password = getCurrentTestName(); try { @@ -231,7 +238,7 @@ public void testAuthPasswordOnly() throws Exception { } @Test - public void testAuthKeyPassword() throws Exception { + void authKeyPassword() throws Exception { try (SshClient client = setupTestClient()) { sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE); sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE); @@ -244,7 +251,7 @@ public void testAuthKeyPassword() throws Exception { Collection result = s.waitFor( EnumSet.of(ClientSession.ClientSessionEvent.CLOSED, ClientSession.ClientSessionEvent.WAIT_AUTH), DEFAULT_TIMEOUT); - assertFalse("Timeout while waiting for session", result.contains(ClientSession.ClientSessionEvent.TIMEOUT)); + assertFalse(result.contains(ClientSession.ClientSessionEvent.TIMEOUT), "Timeout while waiting for session"); KeyPairProvider provider = createTestHostKeyProvider(); KeyPair pair = provider.loadKey(s, CommonTestSupportUtils.DEFAULT_TEST_HOST_KEY_TYPE); @@ -268,8 +275,9 @@ public void testAuthKeyPassword() throws Exception { } } - @Test // see SSHD-196 - public void testAuthPasswordChangeRequest() throws Exception { + // see SSHD-196 + @Test + void authPasswordChangeRequest() throws Exception { PasswordAuthenticator delegate = Objects.requireNonNull(sshd.getPasswordAuthenticator(), "No password authenticator"); AtomicInteger attemptsCount = new AtomicInteger(0); sshd.setPasswordAuthenticator((username, password, session) -> { @@ -299,10 +307,10 @@ public String[] interactive( @Override public String getUpdatedPassword(ClientSession session, String prompt, String lang) { - assertEquals("Mismatched prompt", getCurrentTestName(), prompt); - assertEquals("Mismatched language", - CoreModuleProperties.WELCOME_BANNER_LANGUAGE.getRequiredDefault(), lang); - assertEquals("Unexpected repeated call", 1, updatesCount.incrementAndGet()); + assertEquals(getCurrentTestName(), prompt, "Mismatched prompt"); + assertEquals(CoreModuleProperties.WELCOME_BANNER_LANGUAGE.getRequiredDefault(), lang, + "Mismatched language"); + assertEquals(1, updatesCount.incrementAndGet(), "Unexpected repeated call"); return getCurrentTestName(); } }); @@ -315,8 +323,8 @@ public String getUpdatedPassword(ClientSession session, String prompt, String la .getSession()) { s.addPasswordIdentity(getCurrentTestName()); s.auth().verify(AUTH_TIMEOUT); - assertEquals("No password change request generated", 2, attemptsCount.get()); - assertEquals("No user interaction invoked", 1, updatesCount.get()); + assertEquals(2, attemptsCount.get(), "No password change request generated"); + assertEquals(1, updatesCount.get(), "No user interaction invoked"); } finally { client.stop(); } @@ -324,7 +332,7 @@ public String getUpdatedPassword(ClientSession session, String prompt, String la } @Test - public void testPasswordIdentityProviderPropagation() throws Exception { + void passwordIdentityProviderPropagation() throws Exception { try (SshClient client = setupTestClient()) { List passwords = Collections.singletonList(getCurrentTestName()); AtomicInteger loadCount = new AtomicInteger(0); @@ -340,16 +348,17 @@ public void testPasswordIdentityProviderPropagation() throws Exception { .verify(CONNECT_TIMEOUT) .getSession()) { s.auth().verify(AUTH_TIMEOUT); - assertEquals("Mismatched load passwords count", 1, loadCount.get()); - assertSame("Mismatched passwords identity provider", provider, s.getPasswordIdentityProvider()); + assertEquals(1, loadCount.get(), "Mismatched load passwords count"); + assertSame(provider, s.getPasswordIdentityProvider(), "Mismatched passwords identity provider"); } finally { client.stop(); } } } - @Test // see SSHD-714 - public void testPasswordIdentityWithSpacesPrefixOrSuffix() throws Exception { + // see SSHD-714 + @Test + void passwordIdentityWithSpacesPrefixOrSuffix() throws Exception { sshd.setPasswordAuthenticator((username, password, session) -> { return (username != null) && (!username.trim().isEmpty()) && (password != null) && (!password.isEmpty()) @@ -369,9 +378,9 @@ public void testPasswordIdentityWithSpacesPrefixOrSuffix() throws Exception { s.addPasswordIdentity(password); AuthFuture auth = s.auth(); - assertTrue("No authentication result in time for password='" + password + "'", - auth.await(AUTH_TIMEOUT)); - assertTrue("Failed to authenticate with password='" + password + "'", auth.isSuccess()); + assertTrue(auth.await(AUTH_TIMEOUT), + "No authentication result in time for password='" + password + "'"); + assertTrue(auth.isSuccess(), "Failed to authenticate with password='" + password + "'"); } } } finally { @@ -380,8 +389,9 @@ public void testPasswordIdentityWithSpacesPrefixOrSuffix() throws Exception { } } - @Test // see SSHD-1114 - public void testPasswordAuthenticationReporter() throws Exception { + // see SSHD-1114 + @Test + void passwordAuthenticationReporter() throws Exception { String goodPassword = getCurrentTestName(); String badPassword = getClass().getSimpleName(); List attempted = new ArrayList<>(); @@ -404,14 +414,14 @@ public void signalAuthenticationAttempt( @Override public void signalAuthenticationSuccess(ClientSession session, String service, String password) throws Exception { - assertEquals("Mismatched succesful password", goodPassword, password); + assertEquals(goodPassword, password, "Mismatched succesful password"); } @Override public void signalAuthenticationFailure( ClientSession session, String service, String password, boolean partial, List serverMethods) throws Exception { - assertEquals("Mismatched failed password", badPassword, password); + assertEquals(badPassword, password, "Mismatched failed password"); } }; @@ -436,8 +446,9 @@ public void signalAuthenticationFailure( assertListEquals("Reported passwords", expected, reported); } - @Test // see SSHD-1114 - public void testAuthenticationAttemptsExhausted() throws Exception { + // see SSHD-1114 + @Test + void authenticationAttemptsExhausted() throws Exception { sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE); sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE); sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE); @@ -494,7 +505,7 @@ public String resolveAuthPasswordAttempt(ClientSession session) throws Exception } } - assertEquals("Mismatched invocation count", 1, exhaustedCount.getAndSet(0)); - assertEquals("Mismatched retries count", 3, attemptsCount.getAndSet(0)); + assertEquals(1, exhaustedCount.getAndSet(0), "Mismatched invocation count"); + assertEquals(3, attemptsCount.getAndSet(0), "Mismatched retries count"); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/auth/PublicKeyAuthenticationTest.java b/sshd-core/src/test/java/org/apache/sshd/common/auth/PublicKeyAuthenticationTest.java index 8bbf0c876..80ca9eadf 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/auth/PublicKeyAuthenticationTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/auth/PublicKeyAuthenticationTest.java @@ -61,21 +61,29 @@ import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class PublicKeyAuthenticationTest extends AuthenticationTestSupport { public PublicKeyAuthenticationTest() { super(); } - @Test // see SSHD-618 - public void testPublicKeyAuthDifferentThanKex() throws Exception { + // see SSHD-618 + @Test + void publicKeyAuthDifferentThanKex() throws Exception { KeyPairProvider serverKeys = KeyPairProvider.wrap( CommonTestSupportUtils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 1024), CommonTestSupportUtils.generateKeyPair(KeyUtils.DSS_ALGORITHM, 512), @@ -88,7 +96,7 @@ public void testPublicKeyAuthDifferentThanKex() throws Exception { sshd.setPublickeyAuthenticator((username, key, session) -> { String keyType = KeyUtils.getKeyType(key); String expType = KeyUtils.getKeyType(clientIdentity); - assertEquals("Mismatched client key types", expType, keyType); + assertEquals(expType, keyType, "Mismatched client key types"); assertKeyEquals("Mismatched authentication public keys", clientIdentity.getPublic(), key); return true; }); @@ -102,7 +110,7 @@ public void testPublicKeyAuthDifferentThanKex() throws Exception { client.setServerKeyVerifier((sshClientSession, remoteAddress, serverKey) -> { String keyType = KeyUtils.getKeyType(serverKey); String expType = kexSignature.getName(); - assertEquals("Mismatched server key type", expType, keyType); + assertEquals(expType, keyType, "Mismatched server key type"); KeyPair kp; try { @@ -136,8 +144,9 @@ public void testPublicKeyAuthDifferentThanKex() throws Exception { } } - @Test // see SSHD-624 - public void testUserAuthPkOkWrongKey() throws Exception { + // see SSHD-624 + @Test + void userAuthPkOkWrongKey() throws Exception { sshd.setUserAuthFactories(Collections.singletonList( new org.apache.sshd.server.auth.pubkey.UserAuthPublicKeyFactory() { @Override @@ -183,8 +192,9 @@ protected void sendPublicKeyResponse( } } - @Test // see SSHD-1141 - public void testUserAuthPkOkWrongAlgorithm() throws Exception { + // see SSHD-1141 + @Test + void userAuthPkOkWrongAlgorithm() throws Exception { sshd.setUserAuthFactories(Collections.singletonList( new org.apache.sshd.server.auth.pubkey.UserAuthPublicKeyFactory() { @Override @@ -213,15 +223,16 @@ protected void sendPublicKeyResponse( try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { s.addPublicKeyIdentity(clientIdentity); - assertTrue("Successful authentication expected", s.auth().verify(AUTH_TIMEOUT).isSuccess()); + assertTrue(s.auth().verify(AUTH_TIMEOUT).isSuccess(), "Successful authentication expected"); } finally { client.stop(); } } } - @Test // see SSHD-862 - public void testSessionContextPropagatedToKeyFilePasswordProvider() throws Exception { + // see SSHD-862 + @Test + void sessionContextPropagatedToKeyFilePasswordProvider() throws Exception { try (SshClient client = setupTestClient()) { client.start(); @@ -234,18 +245,18 @@ public void testSessionContextPropagatedToKeyFilePasswordProvider() throws Excep public String getPassword( SessionContext session, NamedResource resourceKey, int retryIndex) throws IOException { - assertSame("Mismatched session context", s, session); - assertEquals("Mismatched retry index", 0, retryIndex); + assertSame(s, session, "Mismatched session context"); + assertEquals(0, retryIndex, "Mismatched retry index"); String name = resourceKey.getName(); int pos = name.lastIndexOf('/'); if (pos >= 0) { name = name.substring(pos + 1); } - assertEquals("Mismatched location", keyLocation, name); + assertEquals(keyLocation, name, "Mismatched location"); Boolean passwordRequested = session.getAttribute(PASSWORD_ATTR); - assertNull("Password already requested", passwordRequested); + assertNull(passwordRequested, "Password already requested"); session.setAttribute(PASSWORD_ATTR, Boolean.TRUE); return "super secret passphrase"; } @@ -253,9 +264,9 @@ public String getPassword( s.setKeyIdentityProvider(new KeyIdentityProvider() { @Override public Iterable loadKeys(SessionContext session) throws IOException, GeneralSecurityException { - assertSame("Mismatched session context", s, session); + assertSame(s, session, "Mismatched session context"); URL location = getClass().getResource(keyLocation); - assertNotNull("Missing key file " + keyLocation, location); + assertNotNull(location, "Missing key file " + keyLocation); URLResource resourceKey = new URLResource(location); Iterable ids; @@ -263,23 +274,24 @@ public Iterable loadKeys(SessionContext session) throws IOException, Ge ids = SecurityUtils.loadKeyPairIdentities(session, resourceKey, keyData, passwordProvider); } KeyPair kp = GenericUtils.head(ids); - assertNotNull("No identity loaded from " + resourceKey, kp); + assertNotNull(kp, "No identity loaded from " + resourceKey); return Collections.singletonList(kp); } }); s.auth().verify(AUTH_TIMEOUT); Boolean passwordRequested = s.getAttribute(PASSWORD_ATTR); - assertNotNull("Password provider not invoked", passwordRequested); - assertTrue("Password not requested", passwordRequested.booleanValue()); + assertNotNull(passwordRequested, "Password provider not invoked"); + assertTrue(passwordRequested.booleanValue(), "Password not requested"); } finally { client.stop(); } } } - @Test // see SSHD-1114 - public void testPublicKeyAuthenticationReporter() throws Exception { + // see SSHD-1114 + @Test + void publicKeyAuthenticationReporter() throws Exception { KeyPair goodIdentity = CommonTestSupportUtils.generateKeyPair(KeyUtils.EC_ALGORITHM, 256); KeyPair badIdentity = CommonTestSupportUtils.generateKeyPair(KeyUtils.EC_ALGORITHM, 256); List attempted = new ArrayList<>(); @@ -310,14 +322,14 @@ public void signalSignatureAttempt( @Override public void signalAuthenticationSuccess(ClientSession session, String service, KeyPair identity) throws Exception { - assertTrue("Mismatched success identity", KeyUtils.compareKeys(goodIdentity.getPublic(), identity.getPublic())); + assertTrue(KeyUtils.compareKeys(goodIdentity.getPublic(), identity.getPublic()), "Mismatched success identity"); } @Override public void signalAuthenticationFailure( ClientSession session, String service, KeyPair identity, boolean partial, List serverMethods) throws Exception { - assertTrue("Mismatched failed identity", KeyUtils.compareKeys(badIdentity.getPublic(), identity.getPublic())); + assertTrue(KeyUtils.compareKeys(badIdentity.getPublic(), identity.getPublic()), "Mismatched failed identity"); } }; @@ -346,8 +358,9 @@ public void signalAuthenticationFailure( assertKeyListEquals("Signed", Collections.singletonList(goodIdentity.getPublic()), signed); } - @Test // see SSHD-1114 - public void testAuthenticationAttemptsExhausted() throws Exception { + // see SSHD-1114 + @Test + void authenticationAttemptsExhausted() throws Exception { sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE); sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE); sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE); @@ -404,12 +417,12 @@ public KeyPair resolveAuthPublicKeyIdentityAttempt(ClientSession session) throws } } - assertEquals("Mismatched invocation count", 1, exhaustedCount.getAndSet(0)); - assertEquals("Mismatched retries count", 4 /* 3 attempts + null */, attemptsCount.getAndSet(0)); + assertEquals(1, exhaustedCount.getAndSet(0), "Mismatched invocation count"); + assertEquals(4 /* 3 attempts + null */, attemptsCount.getAndSet(0), "Mismatched retries count"); } @Test - public void testRsaAuthenticationOldServer() throws Exception { + void rsaAuthenticationOldServer() throws Exception { KeyPair userkey = CommonTestSupportUtils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 2048); List factoryNames = sshd.getSignatureFactoriesNames(); // Remove anything that has "rsa" in the name, except "ssh-rsa". Make sure "ssh-rsa" is there. @@ -440,7 +453,7 @@ public void testRsaAuthenticationOldServer() throws Exception { try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { session.addPublicKeyIdentity(userkey); - assertTrue("Successful authentication expected", session.auth().verify(AUTH_TIMEOUT).isSuccess()); + assertTrue(session.auth().verify(AUTH_TIMEOUT).isSuccess(), "Successful authentication expected"); } finally { client.stop(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/auth/SinglePublicKeyAuthTest.java b/sshd-core/src/test/java/org/apache/sshd/common/auth/SinglePublicKeyAuthTest.java index 45678e1b6..2315c03f8 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/auth/SinglePublicKeyAuthTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/auth/SinglePublicKeyAuthTest.java @@ -42,18 +42,22 @@ import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SinglePublicKeyAuthTest extends BaseTestSupport { private SshServer sshd; private int port; @@ -72,13 +76,13 @@ public SinglePublicKeyAuthTest() throws IOException, GeneralSecurityException { kpGood = badKeys.loadKey(null, CommonTestSupportUtils.DEFAULT_TEST_HOST_KEY_TYPE); } - @BeforeClass // FIXME inexplicably these tests fail without BC since SSHD-1004 - public static void ensureBouncycastleRegistered() { - Assume.assumeTrue("Requires BC security provider", SecurityUtils.isBouncyCastleRegistered()); + @BeforeAll // FIXME inexplicably these tests fail without BC since SSHD-1004 + static void ensureBouncycastleRegistered() { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "Requires BC security provider"); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestFullSupportServer(); CoreModuleProperties.AUTH_METHODS.set(sshd, UserAuthPublicKeyFactory.NAME); sshd.setPublickeyAuthenticator((username, key, session) -> delegate.authenticate(username, key, session)); @@ -86,15 +90,15 @@ public void setUp() throws Exception { port = sshd.getPort(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } } @Test - public void testPublicKeyAuthWithCache() throws Exception { + void publicKeyAuthWithCache() throws Exception { ConcurrentHashMap count = new ConcurrentHashMap<>(); TestCachingPublicKeyAuthenticator auth = new TestCachingPublicKeyAuthenticator((username, key, session) -> { String fp = KeyUtils.getFingerPrint(key); @@ -113,20 +117,20 @@ public void testPublicKeyAuthWithCache() throws Exception { session.addPublicKeyIdentity(kpGood); session.auth().verify(AUTH_TIMEOUT); - assertEquals("Mismatched authentication invocations count", 2, count.size()); + assertEquals(2, count.size(), "Mismatched authentication invocations count"); Map> cache = auth.getCache(); - assertEquals("Mismatched cache size", 1, cache.size()); + assertEquals(1, cache.size(), "Mismatched cache size"); String fpBad = KeyUtils.getFingerPrint(kpBad.getPublic()); AtomicInteger badCounter = count.get(fpBad); - assertNotNull("Missing bad public key", badCounter); - assertEquals("Mismatched bad key authentication attempts", 1, badCounter.get()); + assertNotNull(badCounter, "Missing bad public key"); + assertEquals(1, badCounter.get(), "Mismatched bad key authentication attempts"); String fpGood = KeyUtils.getFingerPrint(kpGood.getPublic()); AtomicInteger goodCounter = count.get(fpGood); - assertNotNull("Missing good public key", goodCounter); - assertEquals("Mismatched good key authentication attempts", 1, goodCounter.get()); + assertNotNull(goodCounter, "Missing good public key"); + assertEquals(1, goodCounter.get(), "Mismatched good key authentication attempts"); } finally { client.stop(); } @@ -134,7 +138,7 @@ public void testPublicKeyAuthWithCache() throws Exception { } @Test - public void testPublicKeyAuthWithoutCache() throws Exception { + void publicKeyAuthWithoutCache() throws Exception { ConcurrentHashMap count = new ConcurrentHashMap<>(); delegate = (username, key, session) -> { String fp = KeyUtils.getFingerPrint(key); @@ -152,24 +156,24 @@ public void testPublicKeyAuthWithoutCache() throws Exception { session.addPublicKeyIdentity(kpGood); AuthFuture auth = session.auth(); - assertTrue("Failed to authenticate on time", auth.await(AUTH_TIMEOUT)); - assertTrue("Authentication failed", auth.isSuccess()); + assertTrue(auth.await(AUTH_TIMEOUT), "Failed to authenticate on time"); + assertTrue(auth.isSuccess(), "Authentication failed"); } finally { client.stop(); } } - assertEquals("Mismatched attempted keys count", 2, count.size()); + assertEquals(2, count.size(), "Mismatched attempted keys count"); String badFingerPrint = KeyUtils.getFingerPrint(kpBad.getPublic()); Number badIndex = count.get(badFingerPrint); - assertNotNull("Missing bad key", badIndex); - assertEquals("Mismatched attempt index for bad key", 1, badIndex.intValue()); + assertNotNull(badIndex, "Missing bad key"); + assertEquals(1, badIndex.intValue(), "Mismatched attempt index for bad key"); String goodFingerPrint = KeyUtils.getFingerPrint(kpGood.getPublic()); Number goodIndex = count.get(goodFingerPrint); - assertNotNull("Missing good key", goodIndex); - assertEquals("Mismatched attempt index for good key", 2, goodIndex.intValue()); + assertNotNull(goodIndex, "Missing good key"); + assertEquals(2, goodIndex.intValue(), "Mismatched attempt index for good key"); } public static class TestCachingPublicKeyAuthenticator extends CachingPublicKeyAuthenticator { diff --git a/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelAsyncOutputStreamTest.java b/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelAsyncOutputStreamTest.java index 5f90ebd08..d54ab9d3c 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelAsyncOutputStreamTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelAsyncOutputStreamTest.java @@ -28,20 +28,21 @@ import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * Tests the behaviour of {@link ChannelAsyncOutputStream} regarding the chunking of the data to sent. */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ChannelAsyncOutputStreamTest extends BaseTestSupport { private static final String CLIENT_WITH_COMPATIBILITY_ISSUE = "specialClient"; @@ -55,8 +56,8 @@ public ChannelAsyncOutputStreamTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { channel = Mockito.mock(AbstractChannel.class); channelStreamWriter = Mockito.mock(ChannelStreamWriter.class); remoteWindow = new RemoteWindow(channel, true); @@ -78,7 +79,7 @@ public void setUp() throws Exception { } @Test - public void testCompleteDataSentIfDataFitsIntoPacketAndPacketFitsInRemoteWindow() throws IOException { + void completeDataSentIfDataFitsIntoPacketAndPacketFitsInRemoteWindow() throws IOException { ChannelAsyncOutputStream channelAsyncOutputStream = new ChannelAsyncOutputStream(channel, (byte) 0); checkChangeOfRemoteWindowSizeOnBufferWrite(channelAsyncOutputStream, 40000, 32000, 30000, 40000 - 30000); } @@ -88,19 +89,19 @@ public void testCompleteDataSentIfDataFitsIntoPacketAndPacketFitsInRemoteWindow( * remote window */ @Test - public void testChunkOfPacketSizeSentIfDataLargerThanPacketSizeAndPacketFitsInRemoteWindow() throws IOException { + void chunkOfPacketSizeSentIfDataLargerThanPacketSizeAndPacketFitsInRemoteWindow() throws IOException { ChannelAsyncOutputStream channelAsyncOutputStream = new ChannelAsyncOutputStream(channel, (byte) 0); checkChangeOfRemoteWindowSizeOnBufferWrite(channelAsyncOutputStream, 40000, 32000, 35000, 40000 - 32000); } @Test - public void testChunkOfPacketSizeSentIfDataLargerThanRemoteWindowAndPacketFitsInRemoteWindow() throws IOException { + void chunkOfPacketSizeSentIfDataLargerThanRemoteWindowAndPacketFitsInRemoteWindow() throws IOException { ChannelAsyncOutputStream channelAsyncOutputStream = new ChannelAsyncOutputStream(channel, (byte) 0); checkChangeOfRemoteWindowSizeOnBufferWrite(channelAsyncOutputStream, 40000, 32000, 50000, 40000 - 32000); } @Test - public void testChunkingIfRemoteWindowSmallerThanPacketSize() throws IOException { + void chunkingIfRemoteWindowSmallerThanPacketSize() throws IOException { ChannelAsyncOutputStream channelAsyncOutputStream = new ChannelAsyncOutputStream(channel, (byte) 0); checkChangeOfRemoteWindowSizeOnBufferWrite(channelAsyncOutputStream, 30000, 32000, 50000, 0); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedInputStreamTest.java b/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedInputStreamTest.java index 1fdd47092..30f41eca4 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedInputStreamTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedInputStreamTest.java @@ -26,39 +26,42 @@ import org.apache.sshd.common.PropertyResolverUtils; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.BogusChannel; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ChannelPipedInputStreamTest extends BaseTestSupport { public ChannelPipedInputStreamTest() { super(); } @Test - public void testAvailable() throws IOException { + void available() throws IOException { try (ChannelPipedInputStream stream = createTestStream()) { byte[] b = getCurrentTestName().getBytes(StandardCharsets.UTF_8); stream.receive(b, 0, b.length); - assertEquals("Mismatched reported available size after receive", b.length, stream.available()); + assertEquals(b.length, stream.available(), "Mismatched reported available size after receive"); stream.eof(); - assertEquals("Mismatched reported available size after EOF", b.length, stream.available()); + assertEquals(b.length, stream.available(), "Mismatched reported available size after EOF"); byte[] readBytes = new byte[b.length + Long.SIZE]; - assertEquals("Mismatched reported read size", b.length, stream.read(readBytes)); + assertEquals(b.length, stream.read(readBytes), "Mismatched reported read size"); assertStreamEquals(b, readBytes); - assertEquals("Unexpected data still available", -1, stream.available()); - assertEquals("Unexpectedly not at EOF", -1, stream.read()); + assertEquals(-1, stream.available(), "Unexpected data still available"); + assertEquals(-1, stream.read(), "Unexpectedly not at EOF"); } } @Test - public void testIdempotentClose() throws IOException { + void idempotentClose() throws IOException { try (ChannelPipedInputStream stream = createTestStream()) { byte[] b = getCurrentTestName().getBytes(StandardCharsets.UTF_8); stream.receive(b, 0, b.length); @@ -81,9 +84,9 @@ private static void assertStreamEquals(byte[] expected, byte[] read) { if (expected.length > read.length) { fail("Less bytes than expected: " + Arrays.toString(expected) + " but got: " + Arrays.toString(read)); } else { - assertArrayEquals("Mismatched stream content", expected, Arrays.copyOf(read, expected.length)); + assertArrayEquals(expected, Arrays.copyOf(read, expected.length), "Mismatched stream content"); for (int i = expected.length; i < read.length; i++) { - assertEquals("Non-zero value at position " + i, 0, read[i]); + assertEquals(0, read[i], "Non-zero value at position " + i); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedOutputStreamTest.java b/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedOutputStreamTest.java index c55bf3376..a7f37d5f0 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedOutputStreamTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedOutputStreamTest.java @@ -25,30 +25,34 @@ import java.util.concurrent.atomic.AtomicInteger; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ChannelPipedOutputStreamTest extends BaseTestSupport { public ChannelPipedOutputStreamTest() { super(); } @Test - public void testNioChannelImplementation() throws IOException { + void nioChannelImplementation() throws IOException { ChannelPipedSink sink = Mockito.mock(ChannelPipedSink.class); AtomicBoolean eofCalled = new AtomicBoolean(false); Mockito.doAnswer(invocation -> { - assertFalse("Multiple EOF calls", eofCalled.getAndSet(true)); + assertFalse(eofCalled.getAndSet(true), "Multiple EOF calls"); return null; }).when(sink).eof(); @@ -60,19 +64,19 @@ public void testNioChannelImplementation() throws IOException { }).when(sink).receive(ArgumentMatchers.any(byte[].class), ArgumentMatchers.anyInt(), ArgumentMatchers.anyInt()); try (ChannelPipedOutputStream stream = new ChannelPipedOutputStream(sink)) { - assertTrue("Stream not marked as initially open", stream.isOpen()); - assertEquals("Unexpected initial receive count", 0, receiveCount.intValue()); + assertTrue(stream.isOpen(), "Stream not marked as initially open"); + assertEquals(0, receiveCount.intValue(), "Unexpected initial receive count"); byte[] b = getCurrentTestName().getBytes(StandardCharsets.UTF_8); stream.write(b); - assertTrue("Stream not marked as still open after write data", stream.isOpen()); - assertEquals("Mismatched write data count", b.length, receiveCount.intValue()); + assertTrue(stream.isOpen(), "Stream not marked as still open after write data"); + assertEquals(b.length, receiveCount.intValue(), "Mismatched write data count"); stream.close(); - assertFalse("Stream still marked as open after close", stream.isOpen()); - assertTrue("Sink EOF not called on close", eofCalled.get()); + assertFalse(stream.isOpen(), "Stream still marked as open after close"); + assertTrue(eofCalled.get(), "Sink EOF not called on close"); - assertThrows("Unexpected write success after close", IOException.class, () -> stream.write(b)); + assertThrows(IOException.class, () -> stream.write(b), "Unexpected write success after close"); // flush() should not fail stream.flush(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowInitTest.java b/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowInitTest.java index 042499d30..c0571496d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowInitTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowInitTest.java @@ -28,24 +28,19 @@ import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.core.CoreModuleProperties; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertThrows; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class WindowInitTest extends BaseTestSupport { private static final AbstractChannel MOCK_CHANNEL = new AbstractChannel(true) { @Override @@ -77,12 +72,11 @@ protected void doWriteExtendedData(byte[] data, int off, long len) throws IOExce private long initialSize; private long packetSize; - public WindowInitTest(long initialSize, long packetSize) { + public void initWindowInitTest(long initialSize, long packetSize) { this.initialSize = initialSize; this.packetSize = packetSize; } - @Parameters(name = "initial-size={0}, packet-size={1}") public static List parameters() { List params = new ArrayList<>(); params.add(new Object[] { -128L, CoreModuleProperties.MAX_PACKET_SIZE.getRequiredDefault() }); @@ -97,8 +91,10 @@ public static List parameters() { return params; } - @Test - public void testInitializationFailure() throws IOException { + @MethodSource("parameters") + @ParameterizedTest(name = "initial-size={0}, packet-size={1}") + public void initializationFailure(long initialSize, long packetSize) throws IOException { + initWindowInitTest(initialSize, packetSize); try (RemoteWindow w = new RemoteWindow(MOCK_CHANNEL, true)) { assertThrows(IllegalArgumentException.class, () -> w.init(initialSize, packetSize, PropertyResolver.EMPTY)); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowTest.java b/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowTest.java index 8c7178986..59774438f 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowTest.java @@ -57,18 +57,22 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.EchoShell; import org.apache.sshd.util.test.EchoShellFactory; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class WindowTest extends BaseTestSupport { private SshServer sshd; @@ -81,8 +85,8 @@ public WindowTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { authLatch = new CountDownLatch(0); channelLatch = new CountDownLatch(0); @@ -133,8 +137,8 @@ public String toString() { client = setupTestClient(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -144,7 +148,7 @@ public void tearDown() throws Exception { } @Test - public void testWindowConsumptionWithInvertedStreams() throws Exception { + void windowConsumptionWithInvertedStreams() throws Exception { sshd.setShellFactory(new AsyncEchoShellFactory()); CoreModuleProperties.WINDOW_SIZE.set(sshd, 1024L); CoreModuleProperties.WINDOW_SIZE.set(client, 1024L); @@ -179,13 +183,13 @@ public void testWindowConsumptionWithInvertedStreams() throws Exception { writer.write("\n"); writer.flush(); - assertTrue("Client remote window should have changed", - clientRemote.getSize() != clientRemoteSize); + assertTrue(clientRemote.getSize() != clientRemoteSize, + "Client remote window should have changed"); waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L)); String line = reader.readLine(); - assertEquals("Mismatched message at line #" + i, message, line); + assertEquals(message, line, "Mismatched message at line #" + i); waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L)); @@ -201,7 +205,7 @@ public void testWindowConsumptionWithInvertedStreams() throws Exception { } @Test - public void testWindowConsumptionWithDirectStreams() throws Exception { + void windowConsumptionWithDirectStreams() throws Exception { sshd.setShellFactory(new AsyncEchoShellFactory()); CoreModuleProperties.WINDOW_SIZE.set(sshd, 1024L); CoreModuleProperties.WINDOW_SIZE.set(client, 1024L); @@ -246,7 +250,7 @@ public void testWindowConsumptionWithDirectStreams() throws Exception { TimeUnit.SECONDS.toMillis(3L)); String line = reader.readLine(); - assertEquals("Mismatched message at line #" + i, message, line); + assertEquals(message, line, "Mismatched message at line #" + i); waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L)); @@ -262,7 +266,7 @@ public void testWindowConsumptionWithDirectStreams() throws Exception { } @Test - public void testWindowConsumptionWithAsyncStreams() throws Exception { + void windowConsumptionWithAsyncStreams() throws Exception { sshd.setShellFactory(new AsyncEchoShellFactory()); CoreModuleProperties.WINDOW_SIZE.set(sshd, 1024L); CoreModuleProperties.WINDOW_SIZE.set(client, 1024L); @@ -295,17 +299,18 @@ public void testWindowConsumptionWithAsyncStreams() throws Exception { Buffer buffer = new ByteArrayBuffer(bytes); output.writeBuffer(buffer).verify(DEFAULT_TIMEOUT); - assertTrue("Client remote window should have changed", - clientRemote.getSize() != clientRemoteSize); + assertTrue(clientRemote.getSize() != clientRemoteSize, + "Client remote window should have changed"); waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local", TimeUnit.SECONDS.toMillis(3L)); Buffer buf = new ByteArrayBuffer(16); IoReadFuture future = input.read(buf); future.verify(DEFAULT_TIMEOUT); - assertEquals("Mismatched available data at line #" + i, message.length(), buf.available()); - assertEquals("Mismatched data at line #" + i, message, - new String(buf.array(), buf.rpos(), buf.available(), StandardCharsets.UTF_8)); + assertEquals(message.length(), buf.available(), "Mismatched available data at line #" + i); + assertEquals(message, + new String(buf.array(), buf.rpos(), buf.available(), StandardCharsets.UTF_8), + "Mismatched data at line #" + i); waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote", TimeUnit.SECONDS.toMillis(3L)); @@ -334,7 +339,7 @@ private static void waitForWindowNotEquals(Window w1, Window w2, String n1, Stri } // one last chance ... - assertNotEquals(n1 + " and " + n2, w1.getSize(), w2.getSize()); + assertNotEquals(w1.getSize(), w2.getSize(), n1 + " and " + n2); } private static void waitForWindowEquals(Window w1, Window w2, String n1, String n2, long maxWait) @@ -352,7 +357,7 @@ private static void waitForWindowEquals(Window w1, Window w2, String n1, String } // one last chance ... - assertEquals(n1 + " and " + n2, w1.getSize(), w2.getSize()); + assertEquals(w1.getSize(), w2.getSize(), n1 + " and " + n2); } public static class TestEchoShellFactory extends EchoShellFactory { diff --git a/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowTimeoutTest.java b/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowTimeoutTest.java index 9f7ddc510..816b302c8 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowTimeoutTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/channel/WindowTimeoutTest.java @@ -29,20 +29,25 @@ import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.core.CoreModuleProperties; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project * @see SSHD-565 */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class WindowTimeoutTest extends BaseTestSupport { public static final Duration MAX_WAIT_TIME = Duration.ofSeconds(2L); @@ -52,8 +57,8 @@ public WindowTimeoutTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { channel = new AbstractChannel(getCurrentTestName(), true) { @Override public OpenFuture open(long recipient, long rwSize, long packetSize, Buffer buffer) { @@ -82,21 +87,21 @@ protected void doWriteData(byte[] data, int off, long len) throws IOException { }; } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (channel != null) { channel.close(); } } @Test - public void testWindowWaitForSpaceTimeout() throws Exception { + void windowWaitForSpaceTimeout() throws Exception { try (RemoteWindow window = channel.getRemoteWindow()) { window.init(CoreModuleProperties.WINDOW_SIZE.getRequiredDefault(), CoreModuleProperties.MAX_PACKET_SIZE.getRequiredDefault(), PropertyResolver.EMPTY); window.consume(window.getSize()); - assertEquals("Window not empty", 0, window.getSize()); + assertEquals(0, window.getSize(), "Window not empty"); long waitStart = System.nanoTime(); try { @@ -106,11 +111,11 @@ public void testWindowWaitForSpaceTimeout() throws Exception { long waitEnd = System.nanoTime(); long waitDuration = TimeUnit.NANOSECONDS.toMillis(waitEnd - waitStart); // we allow ~100 millis variance to compensate for O/S wait time granularity - assertTrue("Timeout too soon: " + waitDuration, waitDuration >= (MAX_WAIT_TIME.toMillis() - 100L)); + assertTrue(waitDuration >= (MAX_WAIT_TIME.toMillis() - 100L), "Timeout too soon: " + waitDuration); } window.close(); - assertFalse("Window not closed", window.isOpen()); + assertFalse(window.isOpen(), "Window not closed"); try { long len = window.waitForSpace(MAX_WAIT_TIME); fail("Unexpected closed wait success - len=" + len); @@ -121,7 +126,7 @@ public void testWindowWaitForSpaceTimeout() throws Exception { } @Test - public void testWindowWaitAndConsumeTimeout() throws Exception { + void windowWaitAndConsumeTimeout() throws Exception { try (RemoteWindow window = channel.getRemoteWindow()) { window.init(CoreModuleProperties.WINDOW_SIZE.getRequiredDefault(), CoreModuleProperties.MAX_PACKET_SIZE.getRequiredDefault(), @@ -135,13 +140,14 @@ public void testWindowWaitAndConsumeTimeout() throws Exception { long waitEnd = System.nanoTime(); long waitDuration = TimeUnit.NANOSECONDS.toMillis(waitEnd - waitStart); // we allow ~100 millis variance to compensate for O/S wait time granularity - assertTrue("Timeout too soon: " + waitDuration, waitDuration >= (MAX_WAIT_TIME.toMillis() - 100L)); + assertTrue(waitDuration >= (MAX_WAIT_TIME.toMillis() - 100L), "Timeout too soon: " + waitDuration); } window.close(); - assertFalse("Window not closed", window.isOpen()); - assertThrows("Unexpected closed wait success", WindowClosedException.class, - () -> window.waitAndConsume(2 * window.getSize(), MAX_WAIT_TIME)); + assertFalse(window.isOpen(), "Window not closed"); + assertThrows(WindowClosedException.class, + () -> window.waitAndConsume(2 * window.getSize(), MAX_WAIT_TIME), + "Unexpected closed wait success"); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/cipher/BuiltinCiphersTest.java b/sshd-core/src/test/java/org/apache/sshd/common/cipher/BuiltinCiphersTest.java index e4448c057..06384a36b 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/cipher/BuiltinCiphersTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/cipher/BuiltinCiphersTest.java @@ -36,55 +36,64 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class BuiltinCiphersTest extends BaseTestSupport { public BuiltinCiphersTest() { super(); } @Test - public void testBlockSize() { + void blockSize() { for (BuiltinCiphers cipher : BuiltinCiphers.VALUES) { - assertTrue("Cipher " + cipher + " block size too small", cipher.getCipherBlockSize() >= 8); + assertTrue(cipher.getCipherBlockSize() >= 8, "Cipher " + cipher + " block size too small"); } } @Test - public void testFromEnumName() { + void fromEnumName() { for (BuiltinCiphers expected : BuiltinCiphers.VALUES) { String name = expected.name(); for (int index = 0; index < name.length(); index++) { BuiltinCiphers actual = BuiltinCiphers.fromString(name); - assertSame(name + " - mismatched enum values", expected, actual); + assertSame(expected, actual, name + " - mismatched enum values"); name = shuffleCase(name); // prepare for next time } } } @Test - public void testFromFactoryName() { + void fromFactoryName() { for (BuiltinCiphers expected : BuiltinCiphers.VALUES) { String name = expected.getName(); for (int index = 0; index < name.length(); index++) { BuiltinCiphers actual = BuiltinCiphers.fromFactoryName(name); - assertSame(name + " - mismatched enum values", expected, actual); + assertSame(expected, actual, name + " - mismatched enum values"); name = shuffleCase(name); // prepare for next time } } } @Test - public void testFromFactory() { + void fromFactory() { for (BuiltinCiphers expected : BuiltinCiphers.VALUES) { if (!expected.isSupported()) { System.out.append("Skip unsupported cipher: ").println(expected); @@ -92,15 +101,15 @@ public void testFromFactory() { } NamedFactory factory = expected; - assertEquals(expected.name() + " - mismatched factory names", expected.getName(), factory.getName()); + assertEquals(expected.getName(), factory.getName(), expected.name() + " - mismatched factory names"); BuiltinCiphers actual = BuiltinCiphers.fromFactory(factory); - assertSame(expected.getName() + " - mismatched enum values", expected, actual); + assertSame(expected, actual, expected.getName() + " - mismatched enum values"); } } @Test - public void testAllConstantsCovered() throws Exception { + void allConstantsCovered() throws Exception { Set avail = EnumSet.noneOf(BuiltinCiphers.class); Field[] fields = BuiltinCiphers.Constants.class.getFields(); for (Field f : fields) { @@ -116,15 +125,16 @@ public void testAllConstantsCovered() throws Exception { String name = Objects.toString(f.get(null), null); BuiltinCiphers value = BuiltinCiphers.fromFactoryName(name); - assertNotNull("No match found for " + name, value); - assertTrue(name + " re-specified", avail.add(value)); + assertNotNull(value, "No match found for " + name); + assertTrue(avail.add(value), name + " re-specified"); } assertEquals("Incomplete coverage", BuiltinCiphers.VALUES, avail); } - @Test // make sure that if a cipher is reported as supported we can indeed use it - public void testSupportedCipher() throws Exception { + // make sure that if a cipher is reported as supported we can indeed use it + @Test + void supportedCipher() throws Exception { Exception err = null; Random rnd = new Random(System.nanoTime()); for (BuiltinCiphers c : BuiltinCiphers.VALUES) { @@ -146,15 +156,16 @@ public void testSupportedCipher() throws Exception { } } - @Test // make sure that the reported support matches reality by trying to encrypt something - public void testCipherSupportDetection() throws Exception { + // make sure that the reported support matches reality by trying to encrypt something + @Test + void cipherSupportDetection() throws Exception { Random rnd = new Random(System.nanoTime()); for (BuiltinCiphers c : BuiltinCiphers.VALUES) { try { testCipherEncryption(rnd, c.create()); - assertTrue("Mismatched support report for " + c, c.isSupported()); + assertTrue(c.isSupported(), "Mismatched support report for " + c); } catch (Exception e) { - assertFalse("Mismatched support report for " + c, c.isSupported()); + assertFalse(c.isSupported(), "Mismatched support report for " + c); } } } @@ -180,7 +191,7 @@ private static void testCipherEncryption(Random rnd, Cipher cipher) throws Excep } @Test - public void testParseCiphersList() { + void parseCiphersList() { List builtin = NamedResource.getNameList(BuiltinCiphers.VALUES); List unknown = Arrays.asList( getClass().getPackage().getName(), getClass().getSimpleName(), getCurrentTestName()); @@ -217,16 +228,16 @@ public void testParseCiphersList() { } @Test - public void testResolveFactoryOnBuiltinValues() { + void resolveFactoryOnBuiltinValues() { for (NamedFactory expected : BuiltinCiphers.VALUES) { String name = expected.getName(); NamedFactory actual = BuiltinCiphers.resolveFactory(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testNotAllowedToRegisterBuiltinFactories() { + void notAllowedToRegisterBuiltinFactories() { for (CipherFactory expected : BuiltinCiphers.VALUES) { try { BuiltinCiphers.registerExtension(expected); @@ -237,38 +248,40 @@ public void testNotAllowedToRegisterBuiltinFactories() { } } - @Test(expected = IllegalArgumentException.class) - public void testNotAllowedToOverrideRegisteredFactories() { - CipherFactory expected = Mockito.mock(CipherFactory.class); - Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); + @Test + void notAllowedToOverrideRegisteredFactories() { + assertThrows(IllegalArgumentException.class, () -> { + CipherFactory expected = Mockito.mock(CipherFactory.class); + Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); - String name = expected.getName(); - try { - for (int index = 1; index <= Byte.SIZE; index++) { - BuiltinCiphers.registerExtension(expected); - assertEquals("Unexpected success at attempt #" + index, 1, index); + String name = expected.getName(); + try { + for (int index = 1; index <= Byte.SIZE; index++) { + BuiltinCiphers.registerExtension(expected); + assertEquals(1, index, "Unexpected success at attempt #" + index); + } + } finally { + BuiltinCiphers.unregisterExtension(name); } - } finally { - BuiltinCiphers.unregisterExtension(name); - } + }); } @Test - public void testResolveFactoryOnRegisteredExtension() { + void resolveFactoryOnRegisteredExtension() { CipherFactory expected = Mockito.mock(CipherFactory.class); Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); String name = expected.getName(); try { - assertNull("Extension already registered", BuiltinCiphers.resolveFactory(name)); + assertNull(BuiltinCiphers.resolveFactory(name), "Extension already registered"); BuiltinCiphers.registerExtension(expected); NamedFactory actual = BuiltinCiphers.resolveFactory(name); - assertSame("Mismatched resolved instance", expected, actual); + assertSame(expected, actual, "Mismatched resolved instance"); } finally { NamedFactory actual = BuiltinCiphers.unregisterExtension(name); - assertSame("Mismatched unregistered instance", expected, actual); - assertNull("Extension not un-registered", BuiltinCiphers.resolveFactory(name)); + assertSame(expected, actual, "Mismatched unregistered instance"); + assertNull(BuiltinCiphers.resolveFactory(name), "Extension not un-registered"); } } 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 f9c9f753a..935a8f5f2 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 @@ -40,27 +40,23 @@ import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.CoreTestSupportUtils; import org.apache.sshd.util.test.JSchLogger; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.AfterClass; -import org.junit.Assume; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test Cipher algorithms. * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class CipherTest extends BaseTestSupport { private static final Integer NUM_LOADTEST_ROUNDS = 100000; @@ -91,33 +87,33 @@ public class CipherTest extends BaseTestSupport { private static int port; private final Random random = CommonTestSupportUtils.getRandomizerInstance(); - private final BuiltinCiphers builtInCipher; - private final Class jschCipher; - private final int loadTestRounds; - - public CipherTest(BuiltinCiphers builtInCipher, - Class jschCipher, - int loadTestRounds) { + private BuiltinCiphers builtInCipher; + private Class jschCipher; + private int loadTestRounds; + + public void initCipherTest( + BuiltinCiphers builtInCipher, + Class jschCipher, + int loadTestRounds) { this.builtInCipher = builtInCipher; this.jschCipher = jschCipher; this.loadTestRounds = loadTestRounds; } - @Parameters(name = "cipher={0}, load={2}") public static Collection parameters() { return PARAMETERS; } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { JSchLogger.init(); sshd = CoreTestSupportUtils.setupTestFullSupportServer(CipherTest.class); sshd.start(); port = sshd.getPort(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -127,10 +123,14 @@ public static void tearDownClientAndServer() throws Exception { } } - @Test - public void testBuiltinCipherSession() throws Exception { - Assume.assumeTrue("No internal support for " + builtInCipher.getName(), - builtInCipher.isSupported() && checkCipher(jschCipher.getName())); + @MethodSource("parameters") + @ParameterizedTest(name = "cipher={0}, load={2}") + public void builtinCipherSession( + BuiltinCiphers builtInCipher, Class jschCipher, int loadTestRounds) + throws Exception { + initCipherTest(builtInCipher, jschCipher, loadTestRounds); + Assumptions.assumeTrue(builtInCipher.isSupported() && checkCipher(jschCipher.getName()), + "No internal support for " + builtInCipher.getName()); sshd.setCipherFactories(Collections.singletonList(builtInCipher)); runJschTest(port); } @@ -158,7 +158,7 @@ private void runJschTest(int port) throws Exception { int len = is.read(actData); String actual = new String(actData, 0, len, StandardCharsets.UTF_8); - assertEquals("Mismatched command at iteration " + i, expected, actual); + assertEquals(expected, actual, "Mismatched command at iteration " + i); } } finally { c.disconnect(); @@ -168,9 +168,12 @@ private void runJschTest(int port) throws Exception { } } - @Test - public void testCipherLoad() throws Exception { - Assume.assumeTrue("No internal support for " + builtInCipher.getName(), builtInCipher.isSupported()); + @MethodSource("parameters") + @ParameterizedTest(name = "cipher={0}, load={2}") + public void cipherLoad(BuiltinCiphers builtInCipher, Class jschCipher, int loadTestRounds) + throws Exception { + initCipherTest(builtInCipher, jschCipher, loadTestRounds); + Assumptions.assumeTrue(builtInCipher.isSupported(), "No internal support for " + builtInCipher.getName()); loadTest(builtInCipher, random, loadTestRounds); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/cipher/OpenSshCipherTest.java b/sshd-core/src/test/java/org/apache/sshd/common/cipher/OpenSshCipherTest.java index e7389c504..3585f9f98 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/cipher/OpenSshCipherTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/cipher/OpenSshCipherTest.java @@ -30,31 +30,31 @@ import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.ContainerTestCase; import org.bouncycastle.jce.provider.BouncyCastleProvider; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.output.Slf4jLogConsumer; import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.images.builder.ImageFromDockerfile; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.MountableFile; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Test ciphers against OpenSSH. Force resetting ciphers every time to verify that they are res-initialized correctly. * * @author Apache MINA SSHD Project */ -@RunWith(Parameterized.class) -@Category(ContainerTestCase.class) +@Tag("ContainerTestCase") +@Testcontainers public class OpenSshCipherTest extends BaseTestSupport { private static final Logger LOG = LoggerFactory.getLogger(OpenSshCipherTest.class); @@ -62,8 +62,8 @@ public class OpenSshCipherTest extends BaseTestSupport { // Re-use an already defined key private static final String TEST_RESOURCES = "org/apache/sshd/common/kex/extensions/client"; - @Rule - public GenericContainer sshdContainer = new GenericContainer<>(new ImageFromDockerfile() + @Container + GenericContainer sshdContainer = new GenericContainer<>(new ImageFromDockerfile() .withDockerfileFromBuilder(builder -> builder.from("alpine:3.19") // .run("apk --update add openssh-server") // Installs OpenSSH // Enable deprecated ciphers @@ -83,11 +83,11 @@ public class OpenSshCipherTest extends BaseTestSupport { .waitingFor(Wait.forLogMessage(".*Server listening on :: port 22.*\\n", 1)).withExposedPorts(22) // .withLogConsumer(new Slf4jLogConsumer(LOG)); - private final String providerName; + private String providerName; - private final BuiltinCiphers builtIn; + private BuiltinCiphers builtIn; - public OpenSshCipherTest(String providerName, BuiltinCiphers factory, String name) { + public void initOpenSshCipherTest(String providerName, BuiltinCiphers factory, String name) { this.providerName = providerName; this.builtIn = factory; if ("BC".equals(providerName)) { @@ -95,14 +95,14 @@ public OpenSshCipherTest(String providerName, BuiltinCiphers factory, String nam } } - @Before - public void changeCipher() { + @BeforeEach + void changeCipher() { BaseCipher.factory = t -> javax.crypto.Cipher.getInstance(t, providerName); BaseCipher.alwaysReInit = true; } - @After - public void resetCipher() { + @AfterEach + void resetCipher() { BaseCipher.factory = SecurityUtils::getCipher; BaseCipher.alwaysReInit = false; } @@ -119,7 +119,6 @@ private static void addCipher(BuiltinCiphers cipherFactory, List items } @SuppressWarnings("deprecation") - @Parameters(name = "{2} - {0}") public static List getParameters() { List items = new ArrayList<>(); addCipher(BuiltinCiphers.tripledescbc, items); @@ -135,8 +134,10 @@ public static List getParameters() { return items; } - @Test - public void testConnection() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "{2} - {0}") + public void connection(String providerName, BuiltinCiphers factory, String name) throws Exception { + initOpenSshCipherTest(providerName, factory, name); FileKeyPairProvider keyPairProvider = CommonTestSupportUtils.createTestKeyPairProvider(TEST_RESOURCES + "/bob_key"); SshClient client = setupTestClient(); client.setKeyIdentityProvider(keyPairProvider); 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 31c66d645..4dacd09c2 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 @@ -37,29 +37,24 @@ import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.CoreTestSupportUtils; import org.apache.sshd.util.test.JSchLogger; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assume; -import org.junit.Before; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test compression algorithms. * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class CompressionTest extends BaseTestSupport { private static final Collection COMPRESSION_OPTIONS = Collections.unmodifiableSet(EnumSet.of(KexProposalOption.C2SCOMP, KexProposalOption.S2CCOMP)); @@ -67,33 +62,14 @@ public class CompressionTest extends BaseTestSupport { 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); - } - } - } - }; - } + private SessionListener listener; - @Parameters(name = "factory={0}") public static List parameters() { return parameterize(BuiltinCompressions.VALUES); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { JSchLogger.init(); sshd = CoreTestSupportUtils.setupTestFullSupportServer(MacCompatibilityTest.class); @@ -102,8 +78,8 @@ public static void setupClientAndServer() throws Exception { port = sshd.getPort(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -113,8 +89,31 @@ public static void tearDownClientAndServer() throws Exception { } } - @Before - public void setUp() throws Exception { + @AfterEach + void tearDown() throws Exception { + if (sshd != null) { + sshd.removeSessionListener(listener); + } + JSch.setConfig("compression.s2c", "none"); + JSch.setConfig("compression.c2s", "none"); + } + + @MethodSource("parameters") + @ParameterizedTest(name = "factory={0}") + public void compression(CompressionFactory factory) throws Exception { + 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(expected, actual, "Mismatched value for " + option); + } + } + } + }; sshd.setCompressionFactories(Collections.singletonList(factory)); sshd.addSessionListener(listener); @@ -123,20 +122,7 @@ public void setUp() throws Exception { JSch.setConfig("compression.c2s", name); JSch.setConfig("zlib", com.jcraft.jsch.jzlib.Compression.class.getName()); JSch.setConfig("zlib@openssh.com", com.jcraft.jsch.jzlib.Compression.class.getName()); - } - - @After - public void tearDown() throws Exception { - if (sshd != null) { - sshd.removeSessionListener(listener); - } - JSch.setConfig("compression.s2c", "none"); - JSch.setConfig("compression.c2s", "none"); - } - - @Test - public void testCompression() throws Exception { - Assume.assumeTrue("Skip unsupported compression " + factory, factory.isSupported()); + Assumptions.assumeTrue(factory.isSupported(), "Skip unsupported compression " + factory); JSch sch = new JSch(); com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), TEST_LOCALHOST, port); @@ -158,7 +144,7 @@ public void testCompression() throws Exception { int len = is.read(data); String str = new String(data, 0, len, StandardCharsets.UTF_8); - assertEquals("Mismatched read data at iteration #" + i, testCommand, str); + assertEquals(testCommand, str, "Mismatched read data at iteration #" + i); } } finally { c.disconnect(); @@ -167,4 +153,5 @@ public void testCompression() throws Exception { s.disconnect(); } } + } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/config/SshConfigFileReaderTest.java b/sshd-core/src/test/java/org/apache/sshd/common/config/SshConfigFileReaderTest.java index c137b8de2..7d99cfa10 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/config/SshConfigFileReaderTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/config/SshConfigFileReaderTest.java @@ -49,17 +49,24 @@ import org.apache.sshd.common.signature.Signature; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") @SuppressWarnings("checkstyle:MethodCount") public class SshConfigFileReaderTest extends BaseTestSupport { public SshConfigFileReaderTest() { @@ -67,24 +74,24 @@ public SshConfigFileReaderTest() { } @Test - public void testReadFromURL() throws IOException { + void readFromURL() throws IOException { URL url = getClass().getResource("sshd_config"); - assertNotNull("Cannot locate test file", url); + assertNotNull(url, "Cannot locate test file"); Properties props = ConfigFileReaderSupport.readConfigFile(url); - assertFalse("No properties read", props.isEmpty()); - assertTrue("Unexpected commented property data", GenericUtils.isEmpty(props.getProperty("ListenAddress"))); - assertTrue("Unexpected non-existing property data", GenericUtils.isEmpty(props.getProperty(getCurrentTestName()))); + assertFalse(props.isEmpty(), "No properties read"); + assertTrue(GenericUtils.isEmpty(props.getProperty("ListenAddress")), "Unexpected commented property data"); + assertTrue(GenericUtils.isEmpty(props.getProperty(getCurrentTestName())), "Unexpected non-existing property data"); String keysList = props.getProperty("HostKey"); - assertFalse("No host keys", GenericUtils.isEmpty(keysList)); + assertFalse(GenericUtils.isEmpty(keysList), "No host keys"); String[] keys = GenericUtils.split(keysList, ','); - assertTrue("No multiple keys", GenericUtils.length((Object[]) keys) > 1); + assertTrue(GenericUtils.length((Object[]) keys) > 1, "No multiple keys"); } @Test - public void testParseCiphersList() { + void parseCiphersList() { List expected = BaseBuilder.DEFAULT_CIPHERS_PREFERENCE; Properties props = initNamedResourceProperties(ConfigFileReaderSupport.CIPHERS_CONFIG_PROP, expected); BuiltinCiphers.ParseResult result = SshConfigFileReader.getCiphers(PropertyResolverUtils.toPropertyResolver(props)); @@ -92,7 +99,7 @@ public void testParseCiphersList() { } @Test - public void testParseMacsList() { + void parseMacsList() { List expected = BaseBuilder.DEFAULT_MAC_PREFERENCE; Properties props = initNamedResourceProperties(ConfigFileReaderSupport.MACS_CONFIG_PROP, expected); BuiltinMacs.ParseResult result = SshConfigFileReader.getMacs(PropertyResolverUtils.toPropertyResolver(props)); @@ -100,7 +107,7 @@ public void testParseMacsList() { } @Test - public void testParseSignaturesList() { + void parseSignaturesList() { List expected = BaseBuilder.DEFAULT_SIGNATURE_PREFERENCE; Properties props = initNamedResourceProperties(ConfigFileReaderSupport.HOST_KEY_ALGORITHMS_CONFIG_PROP, expected); BuiltinSignatures.ParseResult result @@ -109,7 +116,7 @@ public void testParseSignaturesList() { } @Test - public void testParseKexFactoriesList() { + void parseKexFactoriesList() { List expected = BaseBuilder.DEFAULT_KEX_PREFERENCE; Properties props = initNamedResourceProperties(ConfigFileReaderSupport.KEX_ALGORITHMS_CONFIG_PROP, expected); BuiltinDHFactories.ParseResult result @@ -118,19 +125,19 @@ public void testParseKexFactoriesList() { } @Test - public void testGetCompression() { + void getCompression() { Properties props = new Properties(); for (CompressionConfigValue expected : CompressionConfigValue.VALUES) { props.setProperty(ConfigFileReaderSupport.COMPRESSION_PROP, expected.name().toLowerCase()); NamedResource actual = SshConfigFileReader.getCompression(PropertyResolverUtils.toPropertyResolver(props)); - assertNotNull("No match for " + expected.name(), actual); - assertEquals(expected.name(), expected.getName(), actual.getName()); + assertNotNull(actual, "No match for " + expected.name()); + assertEquals(expected.getName(), actual.getName(), expected.name()); } } @Test - public void testConfigureAbstractFactoryManagerWithDefaults() { + void configureAbstractFactoryManagerWithDefaults() { Properties props = new Properties(); // empty means use defaults AbstractFactoryManager expected = new AbstractFactoryManager() { @Override @@ -141,73 +148,82 @@ protected Closeable getInnerCloseable() { // must be lenient since we do not cover the full default spectrum AbstractFactoryManager actual = SshConfigFileReader.configure( expected, PropertyResolverUtils.toPropertyResolver(props), true, true); - assertSame("Mismatched configured result", expected, actual); + assertSame(expected, actual, "Mismatched configured result"); validateAbstractFactoryManagerConfiguration(expected, props, true); } - @Test(expected = IllegalArgumentException.class) - public void testNonLenientCiphersConfiguration() { - FactoryManager manager = SshConfigFileReader.configureCiphers( - new AbstractFactoryManager() { - @Override - protected Closeable getInnerCloseable() { - return null; - } - }, - getCurrentTestName(), - false, - true); - fail("Unexpected success: " + NamedResource.getNames(manager.getCipherFactories())); + @Test + void nonLenientCiphersConfiguration() { + assertThrows(IllegalArgumentException.class, () -> { + FactoryManager manager = SshConfigFileReader.configureCiphers( + new AbstractFactoryManager() { + @Override + protected Closeable getInnerCloseable() { + return null; + } + }, + getCurrentTestName(), + false, + true); + fail("Unexpected success: " + NamedResource.getNames(manager.getCipherFactories())); + }); } - @Test(expected = IllegalArgumentException.class) - public void testNonLenientSignaturesConfiguration() { - FactoryManager manager = SshConfigFileReader.configureSignatures( - new AbstractFactoryManager() { - @Override - protected Closeable getInnerCloseable() { - return null; - } - }, - getCurrentTestName(), - false, - true); - fail("Unexpected success: " + NamedResource.getNames(manager.getSignatureFactories())); + @Test + void nonLenientSignaturesConfiguration() { + assertThrows(IllegalArgumentException.class, () -> { + FactoryManager manager = SshConfigFileReader.configureSignatures( + new AbstractFactoryManager() { + @Override + protected Closeable getInnerCloseable() { + return null; + } + }, + getCurrentTestName(), + false, + true); + fail("Unexpected success: " + NamedResource.getNames(manager.getSignatureFactories())); + }); } - @Test(expected = IllegalArgumentException.class) - public void testNonLenientMacsConfiguration() { - FactoryManager manager = SshConfigFileReader.configureMacs( - new AbstractFactoryManager() { - @Override - protected Closeable getInnerCloseable() { - return null; - } - }, - getCurrentTestName(), - false, - true); - fail("Unexpected success: " + NamedResource.getNames(manager.getMacFactories())); + @Test + void nonLenientMacsConfiguration() { + assertThrows(IllegalArgumentException.class, () -> { + FactoryManager manager = SshConfigFileReader.configureMacs( + new AbstractFactoryManager() { + @Override + protected Closeable getInnerCloseable() { + return null; + } + }, + getCurrentTestName(), + false, + true); + fail("Unexpected success: " + NamedResource.getNames(manager.getMacFactories())); + }); } @Test - public void testConfigureCompressionFromStringAcceptsCombinedValues() { + void configureCompressionFromStringAcceptsCombinedValues() { testConfigureCompressionFromStringAcceptsCombinedValues(CompressionConfigValue.class, e -> (e == null) ? null : e.name()); testConfigureCompressionFromStringAcceptsCombinedValues(BuiltinCompressions.class, NamedResource.NAME_EXTRACTOR); } - @Test(expected = StreamCorruptedException.class) - public void testInvalidDelimiter() throws IOException { - String line = getClass().getSimpleName() + "+" + getCurrentTestName(); - try (Reader rdr = new StringReader(line)) { - Properties props = ConfigFileReaderSupport.readConfigFile(rdr, true); - fail("Unexpected success: " + props); - } + @Test + void invalidDelimiter() throws IOException { + assertThrows(StreamCorruptedException.class, () -> { + String line = getClass().getSimpleName() + "+" + getCurrentTestName(); + try (Reader rdr = new StringReader(line)) { + Properties props = ConfigFileReaderSupport.readConfigFile(rdr, true); + fail("Unexpected success: " + props); + } + }); } - @Test // SSHD-774 - public void testTabDelimiter() throws IOException { + // SSHD-774 + @Test + void tabDelimiter() throws IOException { String name = getClass().getSimpleName(); String expected = getCurrentTestName(); Properties props; @@ -216,7 +232,7 @@ public void testTabDelimiter() throws IOException { } String actual = props.getProperty(name); - assertEquals("Mismatched read configuration value", expected, actual); + assertEquals(expected, actual, "Mismatched read configuration value"); } private static & CompressionFactory> void testConfigureCompressionFromStringAcceptsCombinedValues( @@ -235,8 +251,8 @@ protected Closeable getInnerCloseable() { false, true); List> compressions = manager.getCompressionFactories(); - assertEquals(prefix + "(size)", 1, GenericUtils.size(compressions)); - assertSame(prefix + "[instance]", expected, compressions.get(0)); + assertEquals(1, GenericUtils.size(compressions), prefix + "(size)"); + assertSame(expected, compressions.get(0), prefix + "[instance]"); } } @@ -291,7 +307,7 @@ M extends FactoryManager> M validateFactoryManagerCompressions(M manager, Proper private static M validateFactoryManagerCompressions(M manager, String value, boolean lenient) { NamedFactory factory = CompressionConfigValue.fromName(value); - assertTrue("Unknown compression: " + value, lenient || (factory != null)); + assertTrue(lenient || (factory != null), "Unknown compression: " + value); if (factory != null) { validateFactoryManagerFactories(Compression.class, Collections.singletonList(factory), manager.getCompressionFactories()); @@ -316,14 +332,14 @@ private static void validateFactoryManagerSettings( private static List testParsedFactoriesList( List expected, List actual, Collection unsupported) { - assertTrue("Unexpected unsupported factories: " + unsupported, GenericUtils.isEmpty(unsupported)); - assertEquals("Mismatched list size", expected.size(), GenericUtils.size(actual)); + assertTrue(GenericUtils.isEmpty(unsupported), "Unexpected unsupported factories: " + unsupported); + assertEquals(expected.size(), GenericUtils.size(actual), "Mismatched list size"); for (int index = 0; index < expected.size(); index++) { NamedResource e = expected.get(index); String n1 = e.getName(); NamedResource a = actual.get(index); String n2 = a.getName(); - assertEquals("Mismatched name at index=" + index, n1, n2); + assertEquals(n1, n2, "Mismatched name at index=" + index); } return actual; diff --git a/sshd-core/src/test/java/org/apache/sshd/common/config/keys/AuthorizedKeyEntryTest.java b/sshd-core/src/test/java/org/apache/sshd/common/config/keys/AuthorizedKeyEntryTest.java index 3e4b53c0c..c78ac6644 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/config/keys/AuthorizedKeyEntryTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/config/keys/AuthorizedKeyEntryTest.java @@ -36,29 +36,34 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.apache.sshd.server.config.keys.AuthorizedKeysAuthenticator; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class AuthorizedKeyEntryTest extends AuthorizedKeysTestSupport { public AuthorizedKeyEntryTest() { super(); } @Test - public void testReadAuthorizedKeysFile() throws Exception { + void readAuthorizedKeysFile() throws Exception { Path file = getTempTargetRelativeFile(getCurrentTestName()); writeDefaultSupportedKeys(file); runAuthorizedKeysTests(AuthorizedKeyEntry.readAuthorizedKeys(file)); } @Test - public void testEncodePublicKeyEntry() throws Exception { + void encodePublicKeyEntry() throws Exception { List keyLines = loadDefaultSupportedKeys(); StringBuilder sb = new StringBuilder(Byte.MAX_VALUE); for (String line : keyLines) { @@ -76,33 +81,33 @@ public void testEncodePublicKeyEntry() throws Exception { } PublicKey key = entry.appendPublicKey(null, sb, PublicKeyEntryResolver.FAILING); - assertNotNull("No key for line=" + line, key); + assertNotNull(key, "No key for line=" + line); String encoded = sb.toString(); - assertEquals("Mismatched encoded form for line=" + line, data, encoded); + assertEquals(data, encoded, "Mismatched encoded form for line=" + line); } } @Test - @Ignore("It might cause some exceptions if user's file contains unsupported keys") - public void testReadDefaultAuthorizedKeysFile() throws Exception { + @Disabled("It might cause some exceptions if user's file contains unsupported keys") + void readDefaultAuthorizedKeysFile() throws Exception { Path path = AuthorizedKeysAuthenticator.getDefaultAuthorizedKeysFile(); - assertNotNull("No default location", path); + assertNotNull(path, "No default location"); LinkOption[] options = IoUtils.getLinkOptions(true); if (!Files.exists(path, options)) { outputDebugMessage("Verify non-existing %s", path); Collection entries = AuthorizedKeysAuthenticator.readDefaultAuthorizedKeys(); - assertTrue("Non-empty keys even though file not found: " + entries, GenericUtils.isEmpty(entries)); + assertTrue(GenericUtils.isEmpty(entries), "Non-empty keys even though file not found: " + entries); } else { - assertFalse("Not a file: " + path, Files.isDirectory(path, options)); + assertFalse(Files.isDirectory(path, options), "Not a file: " + path); runAuthorizedKeysTests(AuthorizedKeysAuthenticator.readDefaultAuthorizedKeys()); } } @Test - @Ignore("Used to test specific files") - public void testSpecificFile() throws Exception { + @Disabled("Used to test specific files") + void specificFile() throws Exception { Path path = Paths.get("C:" + File.separator + "Temp", "id_ed25519" + PublicKeyEntry.PUBKEY_FILE_SUFFIX); testReadAuthorizedKeys(AuthorizedKeyEntry.readAuthorizedKeys(path)); } @@ -114,7 +119,7 @@ private > C runAuthorizedKeysTests(C en } private static > C testReadAuthorizedKeys(C entries) throws Exception { - assertFalse("No entries read", GenericUtils.isEmpty(entries)); + assertFalse(GenericUtils.isEmpty(entries), "No entries read"); Exception err = null; for (AuthorizedKeyEntry entry : entries) { @@ -144,8 +149,8 @@ private PublickeyAuthenticator testAuthorizedKeysAuth(CollectionApache MINA SSHD Project */ -@Category({ NoIoTestCase.class }) +@Tag("NoIoTestCase") public abstract class AuthorizedKeysTestSupport extends BaseTestSupport { protected AuthorizedKeysTestSupport() { super(); diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/AbstractServerCloseTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/AbstractServerCloseTestSupport.java index 4801a2e16..d8bfd7b6a 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/AbstractServerCloseTestSupport.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/AbstractServerCloseTestSupport.java @@ -31,13 +31,15 @@ import org.apache.sshd.common.util.net.SshdSocketAddress; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Port forwarding tests */ @@ -57,7 +59,7 @@ protected AbstractServerCloseTestSupport() { * * This server sends PAYLOAD and then closes. */ - @Before + @BeforeEach public void startTestServer() throws Exception { InetSocketAddress sockAddr = new InetSocketAddress(TEST_LOCALHOST, 0); testServerSock = AsynchronousServerSocketChannel.open().bind(sockAddr); @@ -107,7 +109,7 @@ public void failed(Throwable exc, AsynchronousServerSocketChannel serverSock) { }); } - @After + @AfterEach public void stopTestServer() throws Exception { testServerSock.close(); } @@ -136,8 +138,8 @@ private void readInLoop(int serverPort) throws Exception { } } catch (IOException e) { String readData = sb.toString(); - assertEquals("Mismatched data length", PAYLOAD.length(), readData.length()); - assertEquals("Mismatched read data", PAYLOAD, readData); + assertEquals(PAYLOAD.length(), readData.length(), "Mismatched data length"); + assertEquals(PAYLOAD, readData, "Mismatched read data"); } } @@ -156,7 +158,7 @@ private void readInOneBuffer(int serverPort) throws Exception { outputDebugMessage("readInOneBuffer(port=%d) - Got %d bytes from the server", serverPort, readCount); String actual = new String(buf, 0, readCount, StandardCharsets.UTF_8); - assertEquals("Mismatched read data", PAYLOAD, actual); + assertEquals(PAYLOAD, actual, "Mismatched read data"); } } } @@ -184,7 +186,7 @@ private void readInTwoBuffersWithPause(int serverPort) throws Exception { outputDebugMessage("readInTwoBuffersWithPause(port=%d) - 2nd half is %d bytes", serverPort, read2); String half2 = new String(b2, 0, read2, StandardCharsets.UTF_8); - assertEquals("Mismatched read data", PAYLOAD, half1 + half2); + assertEquals(PAYLOAD, half1 + half2, "Mismatched read data"); } catch (IOException e) { log.error("Disconnected ({}) before all data read: {}", e.getClass().getSimpleName(), e.getMessage()); throw e; @@ -215,7 +217,7 @@ protected boolean hasRemotePFStarted(int port) { * PROVIDED AS TEST THAT HAS ALWAYS PASSED */ @Test - public void testRemotePortForwardOneBuffer() throws Exception { + public void remotePortForwardOneBuffer() throws Exception { SshdSocketAddress pf = startRemotePF(); try { readInOneBuffer(pf.getPort()); @@ -230,7 +232,7 @@ public void testRemotePortForwardOneBuffer() throws Exception { * THIS IS THE TEST OF SSHD-85 */ @Test - public void testRemotePortForwardTwoBuffers() throws Exception { + public void remotePortForwardTwoBuffers() throws Exception { SshdSocketAddress pf = startRemotePF(); try { readInTwoBuffersWithPause(pf.getPort()); @@ -240,7 +242,7 @@ public void testRemotePortForwardTwoBuffers() throws Exception { } @Test - public void testRemotePortForwardLoop() throws Exception { + public void remotePortForwardLoop() throws Exception { SshdSocketAddress pf = startRemotePF(); try { readInLoop(pf.getPort()); @@ -250,7 +252,7 @@ public void testRemotePortForwardLoop() throws Exception { } @Test - public void testLocalPortForwardOneBuffer() throws Exception { + public void localPortForwardOneBuffer() throws Exception { SshdSocketAddress pf = startLocalPF(); try { readInOneBuffer(pf.getPort()); @@ -265,7 +267,7 @@ public void testLocalPortForwardOneBuffer() throws Exception { * THIS IS THE TEST OF SSHD-85 */ @Test - public void testLocalPortForwardTwoBuffers() throws Exception { + public void localPortForwardTwoBuffers() throws Exception { SshdSocketAddress pf = startLocalPF(); try { readInTwoBuffersWithPause(pf.getPort()); @@ -275,7 +277,7 @@ public void testLocalPortForwardTwoBuffers() throws Exception { } @Test - public void testLocalPortForwardLoop() throws Exception { + public void localPortForwardLoop() throws Exception { SshdSocketAddress pf = startLocalPF(); try { readInLoop(pf.getPort()); @@ -285,20 +287,20 @@ public void testLocalPortForwardLoop() throws Exception { } @Test - public void testHasLocalPortForwardingStarted() throws Exception { + public void hasLocalPortForwardingStarted() throws Exception { SshdSocketAddress pf = startLocalPF(); try { - Assert.assertTrue(hasLocalPFStarted(pf.getPort())); + assertTrue(hasLocalPFStarted(pf.getPort())); } finally { stopLocalPF(pf); } } @Test - public void testHasRemotePortForwardingStarted() throws Exception { + public void hasRemotePortForwardingStarted() throws Exception { SshdSocketAddress pf = startRemotePF(); try { - Assert.assertTrue(hasRemotePFStarted(pf.getPort())); + assertTrue(hasRemotePFStarted(pf.getPort())); } finally { stopRemotePF(pf); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/ApacheServerApacheClientTest.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/ApacheServerApacheClientTest.java index 8c40b4b15..17c4e6f5a 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/ApacheServerApacheClientTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/ApacheServerApacheClientTest.java @@ -28,19 +28,21 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.server.forward.AcceptAllForwardingFilter; import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Port forwarding tests, Apache server & client */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ApacheServerApacheClientTest extends AbstractServerCloseTestSupport { private static final Logger LOG = LoggerFactory.getLogger(ApacheServerApacheClientTest.class); private static final Duration TIMEOUT = Duration.ofSeconds(10L); @@ -55,8 +57,8 @@ public ApacheServerApacheClientTest() { super(); } - @BeforeClass - public static void startSshServer() throws IOException { + @BeforeAll + static void startSshServer() throws IOException { LOG.info("Starting SSHD..."); server = SshServer.setUpDefaultServer(); server.setPasswordAuthenticator((u, p, s) -> true); @@ -75,15 +77,15 @@ public static void startSshServer() throws IOException { LOG.info("SSHD Running on port {}", server.getPort()); } - @AfterClass - public static void stopServer() throws IOException { + @AfterAll + static void stopServer() throws IOException { if (!server.close(true).await(TIMEOUT)) { LOG.warn("Failed to close server within {} sec.", TIMEOUT.toMillis() / 1000); } } - @Before - public void createClient() throws IOException { + @BeforeEach + void createClient() throws IOException { client = SshClient.setUpDefaultClient(); client.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE); CoreModuleProperties.NIO2_READ_BUFFER_SIZE.set(client, 32 * 1024); @@ -97,11 +99,11 @@ public void createClient() throws IOException { LOG.info("Authenticated"); } - @After - public void stopClient() throws Exception { + @AfterEach + void stopClient() throws Exception { LOG.info("Disconnecting Client"); try { - assertTrue("Failed to close session", session.close(true).await(TIMEOUT)); + assertTrue(session.close(true).await(TIMEOUT), "Failed to close session"); } finally { session = null; client.stop(); diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/ApacheServerJSchClientTest.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/ApacheServerJSchClientTest.java index 6273f3698..be40973d0 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/ApacheServerJSchClientTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/ApacheServerJSchClientTest.java @@ -33,19 +33,19 @@ import org.apache.sshd.util.test.JSchLogger; import org.apache.sshd.util.test.JSchUtils; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Port forwarding tests - Apache server, JSch client */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ApacheServerJSchClientTest extends AbstractServerCloseTestSupport { private static final long TIMEOUT = TimeUnit.SECONDS.toMillis(10L); private static final Logger LOG = LoggerFactory.getLogger(ApacheServerJSchClientTest.class); @@ -68,8 +68,8 @@ private static int findFreePort() throws IOException { /* * Starts an SSH Server */ - @BeforeClass - public static void startSshServer() throws IOException { + @BeforeAll + static void startSshServer() throws IOException { LOG.info("Starting SSHD..."); server = CoreTestSupportUtils.setupTestFullSupportServer(SshServer.setUpDefaultServer()); server.setPasswordAuthenticator((u, p, s) -> true); @@ -82,20 +82,20 @@ public static void startSshServer() throws IOException { LOG.info("SSHD Running on port {}", server.getPort()); } - @BeforeClass - public static void jschInit() { + @BeforeAll + static void jschInit() { JSchLogger.init(); } - @AfterClass - public static void stopServer() throws IOException { + @AfterAll + static void stopServer() throws IOException { if (!server.close(true).await(TIMEOUT)) { LOG.warn("Failed to close server within {} sec.", TimeUnit.MILLISECONDS.toSeconds(TIMEOUT)); } } - @Before - public void createClient() throws Exception { + @BeforeEach + void createClient() throws Exception { JSch client = new JSch(); session = client.getSession("user", TEST_LOCALHOST, sshServerPort); session.setUserInfo(new SimpleUserInfo("password")); @@ -104,8 +104,8 @@ public void createClient() throws Exception { LOG.trace("Client is running now..."); } - @After - public void stopClient() throws Exception { + @AfterEach + void stopClient() throws Exception { LOG.info("Disconnecting Client"); session.disconnect(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/ConcurrentConnectionTest.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/ConcurrentConnectionTest.java index ec9c24968..b8ef3067d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/ConcurrentConnectionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/ConcurrentConnectionTest.java @@ -35,14 +35,17 @@ import org.apache.sshd.server.forward.AcceptAllForwardingFilter; import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Port forwarding test multiple clients connecting at once. */ @@ -81,8 +84,8 @@ public ConcurrentConnectionTest() { * Reads PAYLOAD_TO_SERVER from client and then sends PAYLOAD_TO_CLIENT to client. This server emulates a web * server, closely enough for thie test */ - @Before - public void startTestServer() throws Exception { + @BeforeEach + void startTestServer() throws Exception { testServerThread = new Thread(this::serverAcceptLoop); testServerThread.setDaemon(true); testServerThread.setName("Server Acceptor"); @@ -126,14 +129,14 @@ private void serverSocketLoop(AtomicInteger activeServers, Socket s) { LOG.debug("Active Servers: {}", activeServers.decrementAndGet()); } - @After - public void stopTestServer() throws Exception { + @AfterEach + void stopTestServer() throws Exception { testServerSock.close(); testServerThread.interrupt(); } - @BeforeClass - public static void startSshServer() throws IOException { + @BeforeAll + static void startSshServer() throws IOException { LOG.debug("Starting SSHD..."); server = SshServer.setUpDefaultServer(); server.setPasswordAuthenticator((u, p, s) -> true); @@ -145,15 +148,15 @@ public static void startSshServer() throws IOException { LOG.debug("SSHD Running on port {}", server.getPort()); } - @AfterClass - public static void stopServer() throws IOException { + @AfterAll + static void stopServer() throws IOException { if (!server.close(true).await(CLOSE_TIMEOUT)) { LOG.warn("Failed to close server within {} sec.", CLOSE_TIMEOUT.toMillis() / 1000); } } - @Before - public void createClient() throws IOException { + @BeforeEach + void createClient() throws IOException { final SshClient client = SshClient.setUpDefaultClient(); client.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE); client.start(); @@ -165,24 +168,24 @@ public void createClient() throws IOException { LOG.debug("Authenticated"); } - @After - public void stopClient() throws Exception { + @AfterEach + void stopClient() throws Exception { LOG.debug("Disconnecting Client"); try { - assertTrue("Failed to close session", session.close(true).await(CLOSE_TIMEOUT)); + assertTrue(session.close(true).await(CLOSE_TIMEOUT), "Failed to close session"); } finally { session = null; } } - @Test /* * Run PORT_FORWARD_CLIENT_COUNT simultaneous server threads. * * Emulates a web browser making a number of simultaneous requests on different connections to the same server HTTP * specifies no more than two, but most modern browsers do 6 or more. */ - public void testConcurrentConnectionsToPortForward() throws Exception { + @Test + void concurrentConnectionsToPortForward() throws Exception { final SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, 0); final SshdSocketAddress local = new SshdSocketAddress(TEST_LOCALHOST, testServerPort); final SshdSocketAddress bound = session.startRemotePortForwarding(remote, local); @@ -216,14 +219,15 @@ public void testConcurrentConnectionsToPortForward() throws Exception { t.start(); } - assertTrue("All threads should be done after two minutes", threadsDone.await(2, TimeUnit.MINUTES)); + assertTrue(threadsDone.await(2, TimeUnit.MINUTES), "All threads should be done after two minutes"); for (int i = 0; i < PORT_FORWARD_CLIENT_COUNT; i++) { - assertEquals("Mismatched data length read from server for client " + i, PAYLOAD_TO_CLIENT.length, - bytesRead[i]); + assertEquals(PAYLOAD_TO_CLIENT.length, + bytesRead[i], + "Mismatched data length read from server for client " + i); } - assertEquals("Not all clients succeeded", PORT_FORWARD_CLIENT_COUNT, success.get()); + assertEquals(PORT_FORWARD_CLIENT_COUNT, success.get(), "Not all clients succeeded"); } /* @@ -247,7 +251,7 @@ private long makeClientRequest(final int serverPort, final CyclicBarrier barrier final long r = s.getInputStream().read(buf); LOG.debug("Read {} payload from server", r); - assertEquals("Mismatched data length", PAYLOAD_TO_CLIENT.length, r); + assertEquals(PAYLOAD_TO_CLIENT.length, r, "Mismatched data length"); return r; } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/LocalForwardingEntryCombinedBoundAddressTest.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/LocalForwardingEntryCombinedBoundAddressTest.java index 6c378d848..fe7699925 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/LocalForwardingEntryCombinedBoundAddressTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/LocalForwardingEntryCombinedBoundAddressTest.java @@ -24,36 +24,33 @@ import java.util.Objects; import org.apache.sshd.common.util.net.SshdSocketAddress; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class LocalForwardingEntryCombinedBoundAddressTest extends JUnitTestSupport { - private final LocalForwardingEntry entry; - private final SshdSocketAddress expected; + private LocalForwardingEntry entry; + private SshdSocketAddress expected; - public LocalForwardingEntryCombinedBoundAddressTest(SshdSocketAddress local, SshdSocketAddress bound, - SshdSocketAddress expected) { + public void initLocalForwardingEntryCombinedBoundAddressTest( + SshdSocketAddress local, SshdSocketAddress bound, + SshdSocketAddress expected) { this.entry = new LocalForwardingEntry(local, bound); this.expected = expected; } - @Parameters(name = "local={0}, bound={1}, expected={2}") public static List parameters() { return new ArrayList() { // Not serializing it @@ -86,30 +83,34 @@ private void addTestCase( }; } - @Test - public void testResolvedValue() { + @MethodSource("parameters") + @ParameterizedTest(name = "local={0}, bound={1}, expected={2}") + public void resolvedValue(SshdSocketAddress local, SshdSocketAddress bound, SshdSocketAddress expected) { + initLocalForwardingEntryCombinedBoundAddressTest(local, bound, expected); assertEquals(expected, entry.getCombinedBoundAddress()); } - @Test - public void testHashCode() { + @MethodSource("parameters") + @ParameterizedTest(name = "local={0}, bound={1}, expected={2}") + public void testHashCode(SshdSocketAddress local, SshdSocketAddress bound, SshdSocketAddress expected) { + initLocalForwardingEntryCombinedBoundAddressTest(local, bound, expected); assertEquals(expected.hashCode(), entry.hashCode()); } - @Test - public void testSameInstanceReuse() { + @MethodSource("parameters") + @ParameterizedTest(name = "local={0}, bound={1}, expected={2}") + public void sameInstanceReuse(SshdSocketAddress local, SshdSocketAddress bound, SshdSocketAddress expected) { + initLocalForwardingEntryCombinedBoundAddressTest(local, bound, expected); SshdSocketAddress combined = entry.getCombinedBoundAddress(); - SshdSocketAddress local = entry.getLocalAddress(); - SshdSocketAddress bound = entry.getBoundAddress(); boolean eqLocal = Objects.equals(combined, local); boolean eqBound = Objects.equals(combined, bound); if (eqLocal) { - assertSame("Not same local reference", combined, local); + assertSame(combined, local, "Not same local reference"); } else if (eqBound) { - assertSame("Not same bound reference", combined, bound); + assertSame(combined, bound, "Not same bound reference"); } else { - assertNotSame("Unexpected same local reference", combined, local); - assertNotSame("Unexpected same bound reference", combined, bound); + assertNotSame(combined, local, "Unexpected same local reference"); + assertNotSame(combined, bound, "Unexpected same bound reference"); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/LocalForwardingEntryTest.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/LocalForwardingEntryTest.java index a61441c6a..688a42087 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/LocalForwardingEntryTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/LocalForwardingEntryTest.java @@ -27,26 +27,30 @@ import org.apache.sshd.common.util.net.SshdSocketAddress; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class LocalForwardingEntryTest extends BaseTestSupport { public LocalForwardingEntryTest() { super(); } - @Test // NOTE: this also checks indirectly SshSocketAddress host comparison case-insensitive - public void testCaseInsensitiveMatching() { + // NOTE: this also checks indirectly SshSocketAddress host comparison case-insensitive + @Test + void caseInsensitiveMatching() { SshdSocketAddress local = new SshdSocketAddress(getClass().getSimpleName(), 0); SshdSocketAddress bound = new SshdSocketAddress(getCurrentTestName(), 7365); LocalForwardingEntry expected = new LocalForwardingEntry(local, bound); @@ -65,7 +69,7 @@ public void testCaseInsensitiveMatching() { Collections.shuffle(entries); LocalForwardingEntry actual = LocalForwardingEntry.findMatchingEntry(host, port, entries); - assertSame("Mismatched result for host=" + host, expected, actual); + assertSame(expected, actual, "Mismatched result for host=" + host); host = shuffleCase(host); } @@ -73,7 +77,7 @@ public void testCaseInsensitiveMatching() { } @Test - public void testSingleWildcardMatching() { + void singleWildcardMatching() { SshdSocketAddress address = new SshdSocketAddress(getCurrentTestName(), 7365); LocalForwardingEntry expected = new LocalForwardingEntry(address, address); int port = address.getPort(); @@ -91,12 +95,12 @@ public void testSingleWildcardMatching() { SshdSocketAddress.IPV6_SHORT_ANY_ADDRESS }) { LocalForwardingEntry actual = LocalForwardingEntry.findMatchingEntry(host, port, entries); - assertSame("Host=" + host, expected, actual); + assertSame(expected, actual, "Host=" + host); } } @Test - public void testLoopbackMatching() { + void loopbackMatching() { int port = 7365; List entries = IntStream.rangeClosed(1, 4) .mapToObj(seed -> { @@ -117,12 +121,12 @@ public void testLoopbackMatching() { LocalForwardingEntry actual = LocalForwardingEntry.findMatchingEntry(SshdSocketAddress.LOCALHOST_NAME, port, entries); entries.remove(numEntries); - assertSame("Host=" + host, expected, actual); + assertSame(expected, actual, "Host=" + host); } } @Test - public void testMultipleWildcardCandidates() { + void multipleWildcardCandidates() { int port = 7365; List entries = IntStream.rangeClosed(1, 4) .mapToObj(seed -> { @@ -145,8 +149,8 @@ public void testMultipleWildcardCandidates() { fail("Unexpected success for host=" + host + ": " + actual); } catch (IllegalStateException e) { String msg = e.getMessage(); - assertTrue("Bad exception message: " + msg, - msg.startsWith("Multiple candidate matches for " + host + "@" + port + ":")); + assertTrue(msg.startsWith("Multiple candidate matches for " + host + "@" + port + ":"), + "Bad exception message: " + msg); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/NoServerNoClientTest.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/NoServerNoClientTest.java index 2309424fe..f0f0d572e 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/NoServerNoClientTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/NoServerNoClientTest.java @@ -19,13 +19,13 @@ package org.apache.sshd.common.forward; import org.apache.sshd.common.util.net.SshdSocketAddress; -import org.junit.FixMethodOrder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; /** * Port forwarding tests - Control, direct connect. No SSH */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class NoServerNoClientTest extends AbstractServerCloseTestSupport { public NoServerNoClientTest() { super(); 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 8c57870d2..7b4c70ed3 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 @@ -59,19 +59,24 @@ import org.apache.sshd.util.test.JSchLogger; import org.apache.sshd.util.test.JSchUtils; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * Port forwarding tests */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class PortForwardingLoadTest extends BaseTestSupport { private final Logger log; @@ -151,13 +156,13 @@ public PortForwardingLoadTest() { log = LoggerFactory.getLogger(getClass()); } - @BeforeClass - public static void jschInit() { + @BeforeAll + static void jschInit() { JSchLogger.init(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestFullSupportServer(); sshd.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE); sshd.addPortForwardingEventListener(serverSideListener); @@ -181,8 +186,8 @@ public void messageReceived(IoSession session, Object message) throws Exception this.acceptor = acceptor; } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -193,7 +198,7 @@ public void tearDown() throws Exception { @Test @SuppressWarnings("checkstyle:nestedtrydepth") - public void testLocalForwardingPayload() throws Exception { + void localForwardingPayload() throws Exception { final int numIterations = 100; final String payloadTmpData = "This is significantly longer Test Data. This is significantly " + "longer Test Data. This is significantly longer Test Data. This is significantly " @@ -334,8 +339,8 @@ public void run() { } try { - assertTrue("Failed to await pending iterations=" + numIterations, - iterationsSignal.tryAcquire(numIterations, numIterations, TimeUnit.SECONDS)); + assertTrue(iterationsSignal.tryAcquire(numIterations, numIterations, TimeUnit.SECONDS), + "Failed to await pending iterations=" + numIterations); } finally { log.info("{} remove port forwarding for {}", getCurrentTestName(), sinkPort); session.delPortForwardingL(sinkPort); @@ -348,11 +353,11 @@ public void run() { session.disconnect(); } - assertEquals("Some errors occured", 0, errors.get()); + assertEquals(0, errors.get(), "Some errors occured"); } private static void assertPayloadEquals(String message, byte[] expectedBytes, byte[] actualBytes) { - assertEquals(message + ": mismatched payload length", expectedBytes.length, actualBytes.length); + assertEquals(expectedBytes.length, actualBytes.length, message + ": mismatched payload length"); for (int index = 0; index < expectedBytes.length; index++) { if (expectedBytes[index] == actualBytes[index]) { @@ -373,7 +378,7 @@ private static void assertPayloadEquals(String message, byte[] expectedBytes, by } @Test - public void testRemoteForwardingPayload() throws Exception { + void remoteForwardingPayload() throws Exception { final int numIterations = 100; final String payload = "This is significantly longer Test Data. This is significantly " + "longer Test Data. This is significantly longer Test Data. This is significantly " @@ -413,7 +418,7 @@ public void run() { } }; tWriter.start(); - assertTrue("Server not started", started.await(1, TimeUnit.SECONDS)); + assertTrue(started.await(1, TimeUnit.SECONDS), "Server not started"); final RuntimeException lenOK[] = new RuntimeException[numIterations]; final RuntimeException dataOK[] = new RuntimeException[numIterations]; @@ -462,8 +467,8 @@ public void run() { log.info("Successful iterations: " + ok + " out of " + numIterations); Thread.sleep(TimeUnit.SECONDS.toMillis(1L)); for (int i = 0; i < numIterations; i++) { - assertNull("Bad length at iteration " + i, lenOK[i]); - assertNull("Bad data at iteration " + i, dataOK[i]); + assertNull(lenOK[i], "Bad length at iteration " + i); + assertNull(dataOK[i], "Bad data at iteration " + i); } Thread.sleep(TimeUnit.SECONDS.toMillis(1L)); session.delPortForwardingR(forwardedPort); @@ -475,7 +480,7 @@ public void run() { } @Test - public void testForwardingOnLoad() throws Exception { + void forwardingOnLoad() throws Exception { // final String path = "/history/recent/troubles/"; // final String host = "www.bbc.co.uk"; // final String path = ""; @@ -576,7 +581,7 @@ protected void checkHtmlPage(HttpClient client, URL url) throws IOException { if (str.indexOf("") <= 0) { System.err.println(str); } - assertTrue("Missing HTML close tag", str.indexOf("") > 0); + assertTrue(str.indexOf("") > 0, "Missing HTML close tag"); get.releaseConnection(); // url.openConnection().setDefaultUseCaches(false); // Reader reader = new BufferedReader(new InputStreamReader(url.openStream())); 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 4ab98cf0b..dee4abcb7 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 @@ -81,20 +81,28 @@ import org.apache.sshd.util.test.JSchLogger; import org.apache.sshd.util.test.JSchUtils; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.AfterClass; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Port forwarding tests */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) @SuppressWarnings("checkstyle:MethodCount") public class PortForwardingTest extends BaseTestSupport { @@ -182,8 +190,8 @@ public PortForwardingTest() { super(); } - @BeforeClass - public static void setUpTestEnvironment() throws Exception { + @BeforeAll + static void setUpTestEnvironment() throws Exception { JSchLogger.init(); sshd = CoreTestSupportUtils.setupTestFullSupportServer(PortForwardingTest.class); CoreModuleProperties.WINDOW_SIZE.set(sshd, 2048L); @@ -258,8 +266,8 @@ public void messageReceived(IoSession session, Object message) throws Exception client.start(); } - @AfterClass - public static void tearDownTestEnvironment() throws Exception { + @AfterAll + static void tearDownTestEnvironment() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -271,8 +279,8 @@ public static void tearDownTestEnvironment() throws Exception { } } - @Before - public void setUp() { + @BeforeEach + void setUp() { if (!REQUESTS_QUEUE.isEmpty()) { REQUESTS_QUEUE.clear(); } @@ -299,7 +307,7 @@ private static void waitForForwardingRequest(String expected, Duration timeout) } @Test - public void testRemoteForwarding() throws Exception { + void remoteForwarding() throws Exception { Session session = createSession(); try { int forwardedPort = CoreTestSupportUtils.getFreePort(); @@ -320,7 +328,7 @@ public void testRemoteForwarding() throws Exception { byte[] buf = new byte[bytes.length + Long.SIZE]; int n = input.read(buf); String res = new String(buf, 0, n, StandardCharsets.UTF_8); - assertEquals("Mismatched data", expected, res); + assertEquals(expected, res, "Mismatched data"); } finally { session.delPortForwardingR(forwardedPort); } @@ -334,9 +342,9 @@ private boolean isMina() { } @Test - public void testRemoteForwardingSecondTimeInSameSession() throws Exception { + void remoteForwardingSecondTimeInSameSession() throws Exception { // TODO: remove assumption once DIRMINA-1169 is fixed in the MINA version we are using - Assume.assumeFalse("Skipped for MINA transport; can work reliably only once DIRMINS-1169 is fixed", isMina()); + Assumptions.assumeFalse(isMina(), "Skipped for MINA transport; can work reliably only once DIRMINS-1169 is fixed"); Session session = createSession(); try { int forwardedPort = CoreTestSupportUtils.getFreePort(); @@ -363,7 +371,7 @@ public void testRemoteForwardingSecondTimeInSameSession() throws Exception { byte[] buf = new byte[bytes.length + Long.SIZE]; int n = input.read(buf); String res = new String(buf, 0, n, StandardCharsets.UTF_8); - assertEquals("Mismatched data", expected, res); + assertEquals(expected, res, "Mismatched data"); } finally { session.delPortForwardingR(TEST_LOCALHOST, forwardedPort); } @@ -373,7 +381,7 @@ public void testRemoteForwardingSecondTimeInSameSession() throws Exception { } @Test - public void testRemoteForwardingNative() throws Exception { + void remoteForwardingNative() throws Exception { try (ClientSession session = createNativeSession(null)) { SshdSocketAddress remote = new SshdSocketAddress("", 0); SshdSocketAddress local = new SshdSocketAddress(TEST_LOCALHOST, echoPort); @@ -393,7 +401,7 @@ public void testRemoteForwardingNative() throws Exception { byte[] buf = new byte[bytes.length + Long.SIZE]; int n = input.read(buf); String res = new String(buf, 0, n); - assertEquals("Mismatched data", expected, res); + assertEquals(expected, res, "Mismatched data"); } finally { session.stopRemotePortForwarding(remote); } @@ -401,7 +409,7 @@ public void testRemoteForwardingNative() throws Exception { } @Test - public void testRemoteForwardingNativeBigPayload() throws Exception { + void remoteForwardingNativeBigPayload() throws Exception { AtomicReference localAddressHolder = new AtomicReference<>(); AtomicReference remoteAddressHolder = new AtomicReference<>(); AtomicReference boundAddressHolder = new AtomicReference<>(); @@ -413,8 +421,8 @@ public void tornDownExplicitTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress address, boolean localForwarding, SshdSocketAddress remoteAddress, Throwable reason) throws IOException { - assertFalse("Unexpected local tunnel has been torn down: address=" + address, localForwarding); - assertEquals("Tear down indication not invoked", 1, tearDownSignal.get()); + assertFalse(localForwarding, "Unexpected local tunnel has been torn down: address=" + address); + assertEquals(1, tearDownSignal.get(), "Tear down indication not invoked"); } @Override @@ -430,8 +438,8 @@ public void tearingDownExplicitTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress address, boolean localForwarding, SshdSocketAddress remoteAddress) throws IOException { - assertFalse("Unexpected local tunnel being torn down: address=" + address, localForwarding); - assertEquals("Duplicate tear down signalling", 1, tearDownSignal.incrementAndGet()); + assertFalse(localForwarding, "Unexpected local tunnel being torn down: address=" + address); + assertEquals(1, tearDownSignal.incrementAndGet(), "Duplicate tear down signalling"); } @Override @@ -446,12 +454,12 @@ public void establishingExplicitTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress local, SshdSocketAddress remote, boolean localForwarding) throws IOException { - assertFalse("Unexpected local tunnel being established: local=" + local + ", remote=" + remote, - localForwarding); - assertNull("Duplicate establishment indication call for local address=" + local, - localAddressHolder.getAndSet(local)); - assertNull("Duplicate establishment indication call for remote address=" + remote, - remoteAddressHolder.getAndSet(remote)); + assertFalse(localForwarding, + "Unexpected local tunnel being established: local=" + local + ", remote=" + remote); + assertNull(localAddressHolder.getAndSet(local), + "Duplicate establishment indication call for local address=" + local); + assertNull(remoteAddressHolder.getAndSet(remote), + "Duplicate establishment indication call for remote address=" + remote); } @Override @@ -466,13 +474,13 @@ public void establishedExplicitTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress local, SshdSocketAddress remote, boolean localForwarding, SshdSocketAddress boundAddress, Throwable reason) throws IOException { - assertFalse("Unexpected local tunnel has been established: local=" + local + ", remote=" + remote + ", bound=" - + boundAddress, - localForwarding); - assertSame("Mismatched established tunnel local address", local, localAddressHolder.get()); - assertSame("Mismatched established tunnel remote address", remote, remoteAddressHolder.get()); - assertNull("Duplicate establishment indication call for bound address=" + boundAddress, - boundAddressHolder.getAndSet(boundAddress)); + assertFalse(localForwarding, + "Unexpected local tunnel has been established: local=" + local + ", remote=" + remote + ", bound=" + + boundAddress); + assertSame(local, localAddressHolder.get(), "Mismatched established tunnel local address"); + assertSame(remote, remoteAddressHolder.get(), "Mismatched established tunnel remote address"); + assertNull(boundAddressHolder.getAndSet(boundAddress), + "Duplicate establishment indication call for bound address=" + boundAddress); } @Override @@ -488,8 +496,8 @@ public void establishedDynamicTunnel( try (ClientSession session = createNativeSession(listener); ExplicitPortForwardingTracker tracker = session.createRemotePortForwardingTracker(new SshdSocketAddress("", 0), new SshdSocketAddress(TEST_LOCALHOST, echoPort))) { - assertTrue("Tracker not marked as open", tracker.isOpen()); - assertFalse("Tracker not marked as remote", tracker.isLocalForwarding()); + assertTrue(tracker.isOpen(), "Tracker not marked as open"); + assertFalse(tracker.isLocalForwarding(), "Tracker not marked as remote"); SshdSocketAddress bound = tracker.getBoundAddress(); try (Socket s = new Socket(bound.getHostName(), bound.getPort()); @@ -508,23 +516,23 @@ public void establishedDynamicTunnel( int n = input.read(buf); String res = new String(buf, 0, n, StandardCharsets.UTF_8); - assertEquals("Mismatched data at iteration #" + i, expected, res); + assertEquals(expected, res, "Mismatched data at iteration #" + i); } } finally { tracker.close(); } - assertFalse("Tracker not marked as closed", tracker.isOpen()); + assertFalse(tracker.isOpen(), "Tracker not marked as closed"); } finally { client.removePortForwardingEventListener(listener); } - assertNotNull("Local tunnel address not indicated", localAddressHolder.getAndSet(null)); - assertNotNull("Remote tunnel address not indicated", remoteAddressHolder.getAndSet(null)); - assertNotNull("Bound tunnel address not indicated", boundAddressHolder.getAndSet(null)); + assertNotNull(localAddressHolder.getAndSet(null), "Local tunnel address not indicated"); + assertNotNull(remoteAddressHolder.getAndSet(null), "Remote tunnel address not indicated"); + assertNotNull(boundAddressHolder.getAndSet(null), "Bound tunnel address not indicated"); } @Test - public void testLocalForwarding() throws Exception { + void localForwarding() throws Exception { Session session = createSession(); try { int forwardedPort = CoreTestSupportUtils.getFreePort(); @@ -545,7 +553,7 @@ public void testLocalForwarding() throws Exception { byte[] buf = new byte[bytes.length + Long.SIZE]; int n = input.read(buf); String res = new String(buf, 0, n, StandardCharsets.UTF_8); - assertEquals("Mismatched data", expected, res); + assertEquals(expected, res, "Mismatched data"); } finally { session.delPortForwardingL(forwardedPort); } @@ -555,7 +563,7 @@ public void testLocalForwarding() throws Exception { } @Test - public void testLocalForwardingNative() throws Exception { + void localForwardingNative() throws Exception { AtomicReference localAddressHolder = new AtomicReference<>(); AtomicReference remoteAddressHolder = new AtomicReference<>(); AtomicReference boundAddressHolder = new AtomicReference<>(); @@ -568,8 +576,8 @@ public void tornDownExplicitTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress address, boolean localForwarding, SshdSocketAddress remoteAddress, Throwable reason) throws IOException { - assertTrue("Unexpected remote tunnel has been torn down: address=" + address, localForwarding); - assertEquals("Tear down indication not invoked", 1, tearDownSignal.get()); + assertTrue(localForwarding, "Unexpected remote tunnel has been torn down: address=" + address); + assertEquals(1, tearDownSignal.get(), "Tear down indication not invoked"); tearDownSignalInvoked.set(true); } @@ -586,8 +594,8 @@ public void tearingDownExplicitTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress address, boolean localForwarding, SshdSocketAddress remoteAddress) throws IOException { - assertTrue("Unexpected remote tunnel being torn down: address=" + address, localForwarding); - assertEquals("Duplicate tear down signalling", 1, tearDownSignal.incrementAndGet()); + assertTrue(localForwarding, "Unexpected remote tunnel being torn down: address=" + address); + assertEquals(1, tearDownSignal.incrementAndGet(), "Duplicate tear down signalling"); } @Override @@ -602,12 +610,12 @@ public void establishingExplicitTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress local, SshdSocketAddress remote, boolean localForwarding) throws IOException { - assertTrue("Unexpected remote tunnel being established: local=" + local + ", remote=" + remote, - localForwarding); - assertNull("Duplicate establishment indication call for local address=" + local, - localAddressHolder.getAndSet(local)); - assertNull("Duplicate establishment indication call for remote address=" + remote, - remoteAddressHolder.getAndSet(remote)); + assertTrue(localForwarding, + "Unexpected remote tunnel being established: local=" + local + ", remote=" + remote); + assertNull(localAddressHolder.getAndSet(local), + "Duplicate establishment indication call for local address=" + local); + assertNull(remoteAddressHolder.getAndSet(remote), + "Duplicate establishment indication call for remote address=" + remote); } @Override @@ -622,13 +630,13 @@ public void establishedExplicitTunnel( org.apache.sshd.common.session.Session session, SshdSocketAddress local, SshdSocketAddress remote, boolean localForwarding, SshdSocketAddress boundAddress, Throwable reason) throws IOException { - assertTrue("Unexpected remote tunnel has been established: local=" + local + ", remote=" + remote + ", bound=" - + boundAddress, - localForwarding); - assertSame("Mismatched established tunnel local address", local, localAddressHolder.get()); - assertSame("Mismatched established tunnel remote address", remote, remoteAddressHolder.get()); - assertNull("Duplicate establishment indication call for bound address=" + boundAddress, - boundAddressHolder.getAndSet(boundAddress)); + assertTrue(localForwarding, + "Unexpected remote tunnel has been established: local=" + local + ", remote=" + remote + ", bound=" + + boundAddress); + assertSame(local, localAddressHolder.get(), "Mismatched established tunnel local address"); + assertSame(remote, remoteAddressHolder.get(), "Mismatched established tunnel remote address"); + assertNull(boundAddressHolder.getAndSet(boundAddress), + "Duplicate establishment indication call for bound address=" + boundAddress); } @Override @@ -644,8 +652,8 @@ public void establishedDynamicTunnel( try (ClientSession session = createNativeSession(listener); ExplicitPortForwardingTracker tracker = session.createLocalPortForwardingTracker(new SshdSocketAddress("", 0), new SshdSocketAddress(TEST_LOCALHOST, echoPort))) { - assertTrue("Tracker not marked as open", tracker.isOpen()); - assertTrue("Tracker not marked as local", tracker.isLocalForwarding()); + assertTrue(tracker.isOpen(), "Tracker not marked as open"); + assertTrue(tracker.isLocalForwarding(), "Tracker not marked as local"); SshdSocketAddress bound = tracker.getBoundAddress(); try (Socket s = new Socket(bound.getHostName(), bound.getPort()); @@ -662,26 +670,26 @@ public void establishedDynamicTunnel( byte[] buf = new byte[bytes.length + Long.SIZE]; int n = input.read(buf); - assertTrue("No data read from tunnel", n > 0); + assertTrue(n > 0, "No data read from tunnel"); String res = new String(buf, 0, n, StandardCharsets.UTF_8); - assertEquals("Mismatched data", expected, res); + assertEquals(expected, res, "Mismatched data"); } finally { tracker.close(); } - assertFalse("Tracker not marked as closed", tracker.isOpen()); - assertTrue("Tear down signal did not occur", tearDownSignalInvoked.get()); + assertFalse(tracker.isOpen(), "Tracker not marked as closed"); + assertTrue(tearDownSignalInvoked.get(), "Tear down signal did not occur"); } finally { client.removePortForwardingEventListener(listener); } - assertNotNull("Local tunnel address not indicated", localAddressHolder.getAndSet(null)); - assertNotNull("Remote tunnel address not indicated", remoteAddressHolder.getAndSet(null)); - assertNotNull("Bound tunnel address not indicated", boundAddressHolder.getAndSet(null)); + assertNotNull(localAddressHolder.getAndSet(null), "Local tunnel address not indicated"); + assertNotNull(remoteAddressHolder.getAndSet(null), "Remote tunnel address not indicated"); + assertNotNull(boundAddressHolder.getAndSet(null), "Bound tunnel address not indicated"); } @Test - public void testLocalForwardingNativeReuse() throws Exception { + void localForwardingNativeReuse() throws Exception { try (ClientSession session = createNativeSession(null)) { SshdSocketAddress local = new SshdSocketAddress("", 0); SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort); @@ -695,7 +703,7 @@ public void testLocalForwardingNativeReuse() throws Exception { } @Test - public void testLocalForwardingNativeBigPayload() throws Exception { + void localForwardingNativeBigPayload() throws Exception { try (ClientSession session = createNativeSession(null)) { String expected = getCurrentTestName(); byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); @@ -715,10 +723,10 @@ public void testLocalForwardingNativeBigPayload() throws Exception { output.flush(); int n = input.read(buf); - assertTrue("No data read from tunnel", n > 0); + assertTrue(n > 0, "No data read from tunnel"); String res = new String(buf, 0, n, StandardCharsets.UTF_8); - assertEquals("Mismatched data at iteration #" + i, expected, res); + assertEquals(expected, res, "Mismatched data at iteration #" + i); } } finally { session.stopLocalPortForwarding(bound); @@ -727,7 +735,7 @@ public void testLocalForwardingNativeBigPayload() throws Exception { } @Test - public void testForwardingChannel() throws Exception { + void forwardingChannel() throws Exception { try (ClientSession session = createNativeSession(null)) { SshdSocketAddress local = new SshdSocketAddress("", 0); SshdSocketAddress remote = new SshdSocketAddress(TEST_LOCALHOST, echoPort); @@ -746,15 +754,16 @@ public void testForwardingChannel() throws Exception { byte[] buf = new byte[bytes.length + Long.SIZE]; int n = input.read(buf); String res = new String(buf, 0, n, StandardCharsets.UTF_8); - assertEquals("Mismatched data", expected, res); + assertEquals(expected, res, "Mismatched data"); } channel.close(false); } } } - @Test(timeout = 45000) - public void testRemoteForwardingWithDisconnect() throws Exception { + @Test + @Timeout(value = 45000, unit = TimeUnit.MILLISECONDS) + void remoteForwardingWithDisconnect() throws Exception { Session session = createSession(); try { // 1. Create a Port Forward @@ -799,8 +808,9 @@ public void testRemoteForwardingWithDisconnect() throws Exception { } } - @Test // see SSHD-1066 - public void testLocalBindingOnDifferentInterfaces() throws Exception { + // see SSHD-1066 + @Test + void localBindingOnDifferentInterfaces() throws Exception { InetSocketAddress addr = (InetSocketAddress) GenericUtils.head(sshd.getBoundAddresses()); log.info("{} - using bound address={}", getCurrentTestName(), addr); @@ -851,7 +861,7 @@ private static void testRemoteURL(Proxy proxy, String url) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))) { result = in.lines().collect(Collectors.joining(System.lineSeparator())); } - assertEquals("Unexpected server response", "OK", result); + assertEquals("OK", result, "Unexpected server response"); } /** @@ -865,10 +875,10 @@ private void rudelyDisconnectJschSession(Session session) throws Exception { fSocket.setAccessible(true); try (Socket socket = (Socket) fSocket.get(session)) { - assertTrue("socket is not connected", socket.isConnected()); - assertFalse("socket should not be closed", socket.isClosed()); + assertTrue(socket.isConnected(), "socket is not connected"); + assertFalse(socket.isClosed(), "socket should not be closed"); socket.close(); - assertTrue("socket has not closed", socket.isClosed()); + assertTrue(socket.isClosed(), "socket has not closed"); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingWithOpenSshTest.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingWithOpenSshTest.java index 1d9910c81..86abf7f2b 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingWithOpenSshTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/PortForwardingWithOpenSshTest.java @@ -40,16 +40,13 @@ import org.apache.sshd.server.forward.DirectTcpipFactory; import org.apache.sshd.server.forward.ForwardedTcpipFactory; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.ContainerTestCase; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.TemporaryFolder; -import org.junit.runner.RunWith; -import org.junit.runners.Parameterized; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.Testcontainers; @@ -59,6 +56,9 @@ import org.testcontainers.images.builder.ImageFromDockerfile; import org.testcontainers.utility.MountableFile; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Test setup: run a gRPC server on localhost; run an Apache MINA sshd server on localhost. Run an OpenSSH client in a * container, set up to remote forward a port on the SSH server to the gRPC server. Then connect to the gRPC server via @@ -79,8 +79,7 @@ * @see SSHD-1055 * @see SSHD-1269 */ -@RunWith(Parameterized.class) -@Category(ContainerTestCase.class) +@Tag("ContainerTestCase") public class PortForwardingWithOpenSshTest extends BaseTestSupport { private static final Logger LOG = LoggerFactory.getLogger(PortForwardingWithOpenSshTest.class); @@ -88,8 +87,8 @@ public class PortForwardingWithOpenSshTest extends BaseTestSupport { // We re-use a key from the ClientOpenSSHCertificatesTest. private static final String TEST_KEYS = "org/apache/sshd/client/opensshcerts/user"; - @Rule - public TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + File tmp; private Server gRpc; private int gRpcPort; @@ -100,9 +99,9 @@ public class PortForwardingWithOpenSshTest extends BaseTestSupport { private CountDownLatch forwardingSetup; private int forwardedPort; - private final String portToForward; + private String portToForward; - public PortForwardingWithOpenSshTest(String portToForward) { + public void initPortForwardingWithOpenSshTest(String portToForward) { this.portToForward = portToForward; } @@ -112,13 +111,12 @@ public PortForwardingWithOpenSshTest(String portToForward) { * @return the remote port specifications to use * @see SSHD-1269 */ - @Parameterized.Parameters(name = "{0}") public static String[] portSpecifications() { return new String[] { "127.0.0.1:0", "0.0.0.0:0", "0", "localhost:0" }; } - @Before - public void startServers() throws Exception { + @BeforeEach + void startServers() throws Exception { // gRPC server gRpc = ServerBuilder.forPort(0).build(); CountDownLatch gRpcStarted = new CountDownLatch(1); @@ -161,8 +159,8 @@ public SshdSocketAddress localPortForwardingRequested(SshdSocketAddress local) t sshPort = sshd.getPort(); } - @After - public void teardownServers() throws Exception { + @AfterEach + void teardownServers() throws Exception { try { gRpc.shutdownNow(); } finally { @@ -170,11 +168,13 @@ public void teardownServers() throws Exception { } } - @Test - public void forwardingWithConnectionClose() throws Exception { + @MethodSource("portSpecifications") + @ParameterizedTest(name = "{0}") + public void forwardingWithConnectionClose(String portToForward) throws Exception { + initPortForwardingWithOpenSshTest(portToForward); // Write the entrypoint file. From within the test container, the host running the container and our two servers // is accessible as "host.testcontainers.internal". - File entryPoint = tmp.newFile(); + File entryPoint = File.createTempFile("junit", null, tmp); String lines = "#!/bin/sh\n" // + "\n" // + "chmod 0600 /root/.ssh/*\n" // @@ -204,7 +204,7 @@ public void forwardingWithConnectionClose() throws Exception { Testcontainers.exposeHostPorts(sshPort, gRpcPort); sshdContainer.start(); forwardingSetup.await(); - assertTrue("Server should listen on port", forwardedPort > 0); + assertTrue(forwardedPort > 0, "Server should listen on port"); LOG.info("sshd server listening for forwarding on port {}", forwardedPort); // Connect to the forwarded port. We should end up connecting to the gRPC server, which will balk // because it expects HTTP 2, and disconnect. @@ -226,10 +226,11 @@ public void forwardingWithConnectionClose() throws Exception { } } } - assertFalse("Expected data", content.isEmpty()); + assertFalse(content.isEmpty(), "Expected data"); String last = content.get(content.size() - 1); - assertTrue("Unexpected data: " + last, last.endsWith( - "HTTP/2 client preface string missing or corrupt. Hex dump for received bytes: 474554202f204854545020312e310d0a436f6e6e65637469")); + assertTrue(last.endsWith( + "HTTP/2 client preface string missing or corrupt. Hex dump for received bytes: 474554202f204854545020312e310d0a436f6e6e65637469"), + "Unexpected data: " + last); } finally { sshdContainer.stop(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/Sshd1033Test.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/Sshd1033Test.java index 6f166fdf1..d0a91dc3d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/forward/Sshd1033Test.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/Sshd1033Test.java @@ -41,18 +41,21 @@ import org.apache.sshd.server.forward.ForwardedTcpipFactory; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * Local + dynamic port forwarding test */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class Sshd1033Test extends BaseTestSupport { private static final Logger LOGGER = LoggerFactory.getLogger(Sshd1033Test.class); @@ -64,8 +67,8 @@ public Sshd1033Test() { // Default constructor } - @BeforeClass - public static void beforeClass() throws Exception { + @BeforeAll + static void beforeClass() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(Sshd1033Test.class); sshd.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE); sshd.setChannelFactories(Arrays.asList( @@ -76,28 +79,28 @@ public static void beforeClass() throws Exception { sshPort = sshd.getPort(); } - @AfterClass - public static void afterClass() throws Exception { + @AfterAll + static void afterClass() throws Exception { sshd.stop(); } @Test - public void testDirect() throws IOException { + void direct() throws IOException { testRemoteURL(null); } @Test - public void testLocalAndDynamic() throws IOException { + void localAndDynamic() throws IOException { doTest(true, true); } @Test - public void testLocal() throws IOException { + void local() throws IOException { doTest(true, false); } @Test - public void testDynamic() throws IOException { + void dynamic() throws IOException { doTest(false, true); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/global/OpenSshHostKeysHandlerTest.java b/sshd-core/src/test/java/org/apache/sshd/common/global/OpenSshHostKeysHandlerTest.java index 555d121ba..aa97d1f89 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/global/OpenSshHostKeysHandlerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/global/OpenSshHostKeysHandlerTest.java @@ -30,19 +30,18 @@ import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; +import org.mockito.junit.jupiter.MockitoExtension; /** * @author Apache MINA SSHD Project */ -@Category(NoIoTestCase.class) -@RunWith(MockitoJUnitRunner.class) +@Tag("NoIoTestCase") +@ExtendWith(MockitoExtension.class) public class OpenSshHostKeysHandlerTest extends BaseTestSupport { @Mock @@ -55,8 +54,8 @@ public OpenSshHostKeysHandlerTest() { super(); } - @Before - public void prepareBuffer() throws Exception { + @BeforeEach + void prepareBuffer() throws Exception { // Create an RSA key key = KeyPairGenerator.getInstance("RSA").generateKeyPair().getPublic(); // Serialize it twice to a buffer, but insert a fake item in between @@ -69,7 +68,7 @@ public void prepareBuffer() throws Exception { } @Test - public void clientIgnoresUnknownKeys() throws Exception { + void clientIgnoresUnknownKeys() throws Exception { boolean[] handlerCalled = { false }; org.apache.sshd.client.global.OpenSshHostKeysHandler handler = new org.apache.sshd.client.global.OpenSshHostKeysHandler() { @@ -78,19 +77,19 @@ protected Result handleHostKeys( Session session, Collection keys, boolean wantReply, Buffer buffer) throws Exception { handlerCalled[0] = true; - assertEquals("Unexpected number of keys", 2, keys.size()); + assertEquals(2, keys.size(), "Unexpected number of keys"); for (PublicKey k : keys) { - assertTrue("Unexpected public key", KeyUtils.compareKeys(key, k)); + assertTrue(KeyUtils.compareKeys(key, k), "Unexpected public key"); } return Result.Replied; } }; handler.process(connectionService, org.apache.sshd.client.global.OpenSshHostKeysHandler.REQUEST, false, buffer); - assertTrue("Handler should have been called", handlerCalled[0]); + assertTrue(handlerCalled[0], "Handler should have been called"); } @Test - public void serverThrowsOnUnknownKeys() throws Exception { + void serverThrowsOnUnknownKeys() throws Exception { boolean[] handlerCalled = { false }; org.apache.sshd.server.global.OpenSshHostKeysHandler handler = new org.apache.sshd.server.global.OpenSshHostKeysHandler() { @@ -104,7 +103,7 @@ protected Result handleHostKeys( }; SshException e = assertThrows(SshException.class, () -> handler.process(connectionService, org.apache.sshd.server.global.OpenSshHostKeysHandler.REQUEST, false, buffer)); - assertFalse("Handler should not have been called", handlerCalled[0]); - assertTrue("Expected exception cause", e.getCause() instanceof GeneralSecurityException); + assertFalse(handlerCalled[0], "Handler should not have been called"); + assertInstanceOf(GeneralSecurityException.class, e.getCause(), "Expected exception cause"); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/io/BuiltinIoServiceFactoryFactoriesTest.java b/sshd-core/src/test/java/org/apache/sshd/common/io/BuiltinIoServiceFactoryFactoriesTest.java index 43fc0b357..b922e7113 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/io/BuiltinIoServiceFactoryFactoriesTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/io/BuiltinIoServiceFactoryFactoriesTest.java @@ -22,33 +22,37 @@ import java.util.Objects; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class BuiltinIoServiceFactoryFactoriesTest extends BaseTestSupport { public BuiltinIoServiceFactoryFactoriesTest() { super(); } @Test - public void testFromFactoryName() { + void fromFactoryName() { for (String name : new String[] { null, "", getCurrentTestName() }) { - assertNull("Unexpected success for name='" + name + "'", BuiltinIoServiceFactoryFactories.fromFactoryName(name)); + assertNull(BuiltinIoServiceFactoryFactories.fromFactoryName(name), "Unexpected success for name='" + name + "'"); } for (BuiltinIoServiceFactoryFactories expected : BuiltinIoServiceFactoryFactories.VALUES) { String name = expected.getName(); - assertSame(name, expected, BuiltinIoServiceFactoryFactories.fromFactoryName(name)); + assertSame(expected, BuiltinIoServiceFactoryFactories.fromFactoryName(name), name); } } @Test - public void testFromFactoryClass() { + void fromFactoryClass() { IoServiceFactoryFactory ioServiceProvider = getIoServiceProvider(); Class providerClass = ioServiceProvider.getClass(); String providerClassName = providerClass.getName(); @@ -65,12 +69,12 @@ public void testFromFactoryClass() { outputDebugMessage("Testing: %s", expected); Class clazz = expected.getFactoryClass(); - assertSame(clazz.getSimpleName(), expected, BuiltinIoServiceFactoryFactories.fromFactoryClass(clazz)); + assertSame(expected, BuiltinIoServiceFactoryFactories.fromFactoryClass(clazz), clazz.getSimpleName()); } } @Test - public void testClassNames() { + void classNames() { IoServiceFactoryFactory ioServiceProvider = getIoServiceProvider(); Class providerClass = ioServiceProvider.getClass(); String providerClassName = providerClass.getName(); @@ -81,6 +85,6 @@ public void testClassNames() { break; } } - assertTrue("No BuiltinIoServiceFactoryFactories match for class name " + providerClassName, found); + assertTrue(found, "No BuiltinIoServiceFactoryFactories match for class name " + providerClassName); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/io/DefaultIoServiceFactoryFactoryTest.java b/sshd-core/src/test/java/org/apache/sshd/common/io/DefaultIoServiceFactoryFactoryTest.java index aabfbfd60..3a399c063 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/io/DefaultIoServiceFactoryFactoryTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/io/DefaultIoServiceFactoryFactoryTest.java @@ -24,22 +24,24 @@ import org.apache.sshd.common.FactoryManager; import org.apache.sshd.common.util.threads.CloseableExecutorService; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class DefaultIoServiceFactoryFactoryTest extends BaseTestSupport { public DefaultIoServiceFactoryFactoryTest() { super(); } @Test - public void testBuiltinIoServiceFactoryFactories() { + void builtinIoServiceFactoryFactories() { for (BuiltinIoServiceFactoryFactories f : BuiltinIoServiceFactoryFactories.VALUES) { if (!f.isSupported()) { continue; @@ -49,13 +51,13 @@ public void testBuiltinIoServiceFactoryFactories() { = DefaultIoServiceFactoryFactory.newInstance(IoServiceFactoryFactory.class, name); Class expected = f.getFactoryClass(); Class actual = factoryInstance.getClass(); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @SuppressWarnings("boxing") @Test - public void testExecutorServiceInitialization() throws Exception { + void executorServiceInitialization() throws Exception { CloseableExecutorService service = Mockito.mock(CloseableExecutorService.class); Mockito.when(service.shutdownNow()).thenReturn(Collections.emptyList()); Mockito.when(service.isShutdown()).thenReturn(Boolean.TRUE); @@ -78,7 +80,7 @@ public void testExecutorServiceInitialization() throws Exception { CloseableExecutorService svc = (CloseableExecutorService) factory.getClass().getMethod("getExecutorService").invoke(factory); - assertSame(name + " - mismatched executor service", service, svc); + assertSame(service, svc, name + " - mismatched executor service"); } catch (NoSuchMethodException e) { // ignore if there's no executor service } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/io/nio2/Nio2ServiceTest.java b/sshd-core/src/test/java/org/apache/sshd/common/io/nio2/Nio2ServiceTest.java index 2a25db0bf..b15bed06e 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/io/nio2/Nio2ServiceTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/io/nio2/Nio2ServiceTest.java @@ -41,21 +41,24 @@ import org.apache.sshd.server.session.ServerSessionImpl; import org.apache.sshd.server.session.SessionFactory; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class Nio2ServiceTest extends BaseTestSupport { public Nio2ServiceTest() { super(); } - @Test // see SSHD-554, SSHD-722 - public void testSetSocketOptions() throws Exception { + // see SSHD-554, SSHD-722 + @Test + void setSocketOptions() throws Exception { try (SshServer sshd = setupTestServer()) { Map, Object> expectedOptions = new LinkedHashMap<>(); expectedOptions.put(CoreModuleProperties.SOCKET_KEEPALIVE, true); @@ -109,8 +112,8 @@ private void validateSocketOptions(IoSession ioSession) throws Exception { try (Socket s = new Socket(TEST_LOCALHOST, port)) { long endTime = System.nanoTime(); long duration = endTime - startTime; - assertTrue("Connect duration is too high: " + duration, duration <= TimeUnit.SECONDS.toNanos(15L)); - assertTrue("Validation not completed on time", sigSem.tryAcquire(15L, TimeUnit.SECONDS)); + assertTrue(duration <= TimeUnit.SECONDS.toNanos(15L), "Connect duration is too high: " + duration); + assertTrue(sigSem.tryAcquire(15L, TimeUnit.SECONDS), "Validation not completed on time"); } finally { sshd.stop(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/kex/AbstractDHTest.java b/sshd-core/src/test/java/org/apache/sshd/common/kex/AbstractDHTest.java index 1d56589cd..8c24f3812 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/kex/AbstractDHTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/kex/AbstractDHTest.java @@ -22,25 +22,29 @@ import java.util.Arrays; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; + +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class AbstractDHTest extends BaseTestSupport { public AbstractDHTest() { super(); } @Test - public void testStripLeadingZeroes() { + void stripLeadingZeroes() { byte[] data = { 3, 7, 7, 3, 4, 7 }; for (int index = 1; index <= data.length; index++) { - assertSame("Unexpected sub-array generation for " + Arrays.toString(data), data, - AbstractDH.stripLeadingZeroes(data)); + assertSame(data, + AbstractDH.stripLeadingZeroes(data), + "Unexpected sub-array generation for " + Arrays.toString(data)); if (index < data.length) { data[index] = 0; } @@ -60,7 +64,7 @@ public void testStripLeadingZeroes() { byte[] stripped = AbstractDH.stripLeadingZeroes(data); String ds = Arrays.toString(data); String ss = Arrays.toString(stripped); - assertEquals("Mismatched stripped (" + ss + ") length for " + ds, data.length - index, stripped.length); + assertEquals(data.length - index, stripped.length, "Mismatched stripped (" + ss + ") length for " + ds); for (int i = index, j = 0; j < stripped.length; i++, j++) { if (data[i] != stripped[j]) { fail("Mismatched values at stripped index = " + j + ": data=" + ds + ", stripped=" + ss); diff --git a/sshd-core/src/test/java/org/apache/sshd/common/kex/BuiltinDHFactoriesTest.java b/sshd-core/src/test/java/org/apache/sshd/common/kex/BuiltinDHFactoriesTest.java index 4376c55d3..10d5ce7c3 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/kex/BuiltinDHFactoriesTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/kex/BuiltinDHFactoriesTest.java @@ -32,48 +32,56 @@ import org.apache.sshd.common.kex.BuiltinDHFactories.ParseResult; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class BuiltinDHFactoriesTest extends BaseTestSupport { public BuiltinDHFactoriesTest() { super(); } @Test - public void testFromName() { + void fromName() { for (BuiltinDHFactories expected : BuiltinDHFactories.VALUES) { String name = expected.getName(); BuiltinDHFactories actual = BuiltinDHFactories.fromFactoryName(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testAllConstantsCovered() throws Exception { + void allConstantsCovered() throws Exception { Set avail = EnumSet.noneOf(BuiltinDHFactories.class); Field[] fields = BuiltinDHFactories.Constants.class.getFields(); for (Field f : fields) { String name = (String) f.get(null); BuiltinDHFactories value = BuiltinDHFactories.fromFactoryName(name); - assertNotNull("No match found for " + name, value); - assertTrue(name + " re-specified", avail.add(value)); + assertNotNull(value, "No match found for " + name); + assertTrue(avail.add(value), name + " re-specified"); } assertEquals("Incomplete coverage", BuiltinDHFactories.VALUES, avail); } @Test - public void testParseDHFactorysList() { + void parseDHFactorysList() { List builtin = NamedResource.getNameList(BuiltinDHFactories.VALUES); List unknown = Arrays.asList(getClass().getPackage().getName(), getClass().getSimpleName(), getCurrentTestName()); @@ -110,16 +118,16 @@ public void testParseDHFactorysList() { } @Test - public void testResolveFactoryOnBuiltinValues() { + void resolveFactoryOnBuiltinValues() { for (DHFactory expected : BuiltinDHFactories.VALUES) { String name = expected.getName(); DHFactory actual = BuiltinDHFactories.resolveFactory(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); } } @Test - public void testNotAllowedToRegisterBuiltinFactories() { + void notAllowedToRegisterBuiltinFactories() { for (DHFactory expected : BuiltinDHFactories.VALUES) { try { BuiltinDHFactories.registerExtension(expected); @@ -130,55 +138,57 @@ public void testNotAllowedToRegisterBuiltinFactories() { } } - @Test(expected = IllegalArgumentException.class) - public void testNotAllowedToOverrideRegisteredFactories() { - DHFactory expected = Mockito.mock(DHFactory.class); - Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); + @Test + void notAllowedToOverrideRegisteredFactories() { + assertThrows(IllegalArgumentException.class, () -> { + DHFactory expected = Mockito.mock(DHFactory.class); + Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); - String name = expected.getName(); - try { - for (int index = 1; index <= Byte.SIZE; index++) { - BuiltinDHFactories.registerExtension(expected); - assertEquals("Unexpected success at attempt #" + index, 1, index); + String name = expected.getName(); + try { + for (int index = 1; index <= Byte.SIZE; index++) { + BuiltinDHFactories.registerExtension(expected); + assertEquals(1, index, "Unexpected success at attempt #" + index); + } + } finally { + BuiltinDHFactories.unregisterExtension(name); } - } finally { - BuiltinDHFactories.unregisterExtension(name); - } + }); } @Test - public void testResolveFactoryOnRegisteredExtension() { + void resolveFactoryOnRegisteredExtension() { DHFactory expected = Mockito.mock(DHFactory.class); Mockito.when(expected.getName()).thenReturn(getCurrentTestName()); String name = expected.getName(); try { - assertNull("Extension already registered", BuiltinDHFactories.resolveFactory(name)); + assertNull(BuiltinDHFactories.resolveFactory(name), "Extension already registered"); BuiltinDHFactories.registerExtension(expected); DHFactory actual = BuiltinDHFactories.resolveFactory(name); - assertSame("Mismatched resolved instance", expected, actual); + assertSame(expected, actual, "Mismatched resolved instance"); } finally { DHFactory actual = BuiltinDHFactories.unregisterExtension(name); - assertSame("Mismatched unregistered instance", expected, actual); - assertNull("Extension not un-registered", BuiltinDHFactories.resolveFactory(name)); + assertSame(expected, actual, "Mismatched unregistered instance"); + assertNull(BuiltinDHFactories.resolveFactory(name), "Extension not un-registered"); } } @Test - public void testDHG() throws Exception { + void dhg() throws Exception { for (DHFactory expected : BuiltinDHFactories.VALUES) { if (!expected.isGroupExchange()) { if (expected.isSupported()) { - assertNotNull(expected + ": Null DH created", expected.create()); + assertNotNull(expected.create(), expected + ": Null DH created"); } } } } @Test - public void testDHGRead() throws Exception { - assertArrayEquals("P1", DHGroupData.getP1(), DHGroupData.getOakleyGroupPrimeValue("group2.prime")); - assertArrayEquals("P14", DHGroupData.getP14(), DHGroupData.getOakleyGroupPrimeValue("group14.prime")); + void dhgRead() throws Exception { + assertArrayEquals(DHGroupData.getP1(), DHGroupData.getOakleyGroupPrimeValue("group2.prime"), "P1"); + assertArrayEquals(DHGroupData.getP14(), DHGroupData.getOakleyGroupPrimeValue("group14.prime"), "P14"); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/kex/DHGroupDataParseTest.java b/sshd-core/src/test/java/org/apache/sshd/common/kex/DHGroupDataParseTest.java index a6a9e9a56..4a5114054 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/kex/DHGroupDataParseTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/kex/DHGroupDataParseTest.java @@ -31,36 +31,34 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class DHGroupDataParseTest extends BaseTestSupport { - private final String name; - private final byte[] expected; + private String name; + private byte[] expected; - public DHGroupDataParseTest(String name, byte[] expected) { + public void initDHGroupDataParseTest(String name, byte[] expected) { this.name = name; this.expected = expected; } - @Parameters(name = "{0}") // Note: we rely on the naming convention + // Note: we rely on the naming convention public static List parameters() throws Exception { Collection processedResources = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); List testCases = new ArrayList<>(); @@ -87,28 +85,30 @@ public static List parameters() throws Exception { break; } - assertTrue("Cannot extract group ID from " + name, groupId > 0); + assertTrue(groupId > 0, "Cannot extract group ID from " + name); // For some reason, P1 is stored in 'group2.prime' - TODO standardize the naming convention if (groupId == 1) { groupId = 2; } String resName = "group" + groupId + ".prime"; - assertTrue("Duplicate resource name: " + resName, processedResources.add(resName)); + assertTrue(processedResources.add(resName), "Duplicate resource name: " + resName); byte[] expected = (byte[]) m.invoke(null, GenericUtils.EMPTY_OBJECT_ARRAY); testCases.add(new Object[] { resName, expected }); } - assertFalse("No resources processed", processedResources.isEmpty()); + assertFalse(processedResources.isEmpty(), "No resources processed"); return testCases; } - @Test - public void testParseOakleyGroupPrimeValues() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void parseOakleyGroupPrimeValues(String name, byte[] expected) throws Exception { + initDHGroupDataParseTest(name, expected); List lines; try (InputStream stream = DHGroupData.class.getResourceAsStream(name)) { - assertNotNull("Missing prime value file for group=" + name, stream); + assertNotNull(stream, "Missing prime value file for group=" + name); lines = IoUtils.readAllLines(stream); } @@ -127,7 +127,7 @@ public void testParseOakleyGroupPrimeValues() throws Exception { Random rnd = new Random(System.nanoTime()); for (int index = 1, numDataLines = dataLines.size(), numOtherLines = otherLines.size(); index <= 4; index++) { byte[] actual = DHGroupData.readOakleyGroupPrimeValue(lines.stream()); - assertArrayEquals(name + "[" + index + "]", expected, actual); + assertArrayEquals(expected, actual, name + "[" + index + "]"); lines.clear(); // create an interleaving of the data lines and the other ones 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 acfd70a96..56f410b49 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 @@ -34,87 +34,89 @@ import org.apache.sshd.common.signature.Signature; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class KexFactoryManagerTest extends BaseTestSupport { public KexFactoryManagerTest() { super(); } @Test - public void testDefaultCompressionFactoriesMethods() { + void defaultCompressionFactoriesMethods() { KexFactoryManager manager = new TestKexFactoryManager(); - assertEquals("Mismatched empty factories name list", "", manager.getCompressionFactoriesNameList()); + assertEquals("", manager.getCompressionFactoriesNameList(), "Mismatched empty factories name list"); String expected = NamedResource.getNames(BuiltinCompressions.VALUES); manager.setCompressionFactoriesNameList(expected); - assertEquals("Mismatched updated factories name list", expected, manager.getCompressionFactoriesNameList()); + assertEquals(expected, manager.getCompressionFactoriesNameList(), "Mismatched updated factories name list"); List> factories = manager.getCompressionFactories(); - assertEquals("Mismatched updated factories count", BuiltinCompressions.VALUES.size(), GenericUtils.size(factories)); + assertEquals(BuiltinCompressions.VALUES.size(), GenericUtils.size(factories), "Mismatched updated factories count"); for (NamedFactory f : BuiltinCompressions.VALUES) { - assertTrue("Factory not set: " + f, factories.contains(f)); + assertTrue(factories.contains(f), "Factory not set: " + f); } } @Test - public void testDefaultCipherFactoriesMethods() { + void defaultCipherFactoriesMethods() { KexFactoryManager manager = new TestKexFactoryManager(); - assertEquals("Mismatched empty factories name list", "", manager.getCipherFactoriesNameList()); + assertEquals("", manager.getCipherFactoriesNameList(), "Mismatched empty factories name list"); String expected = NamedResource.getNames(BuiltinCiphers.VALUES); manager.setCipherFactoriesNameList(expected); - assertEquals("Mismatched updated factories name list", expected, manager.getCipherFactoriesNameList()); + assertEquals(expected, manager.getCipherFactoriesNameList(), "Mismatched updated factories name list"); List> factories = manager.getCipherFactories(); - assertEquals("Mismatched updated factories count", BuiltinCiphers.VALUES.size(), GenericUtils.size(factories)); + assertEquals(BuiltinCiphers.VALUES.size(), GenericUtils.size(factories), "Mismatched updated factories count"); for (NamedFactory f : BuiltinCiphers.VALUES) { - assertTrue("Factory not set: " + f, factories.contains(f)); + assertTrue(factories.contains(f), "Factory not set: " + f); } } @Test - public void testDefaultMacFactoriesMethods() { + void defaultMacFactoriesMethods() { KexFactoryManager manager = new TestKexFactoryManager(); - assertEquals("Mismatched empty factories name list", "", manager.getMacFactoriesNameList()); + assertEquals("", manager.getMacFactoriesNameList(), "Mismatched empty factories name list"); String expected = NamedResource.getNames(BuiltinMacs.VALUES); manager.setMacFactoriesNameList(expected); - assertEquals("Mismatched updated factories name list", expected, manager.getMacFactoriesNameList()); + assertEquals(expected, manager.getMacFactoriesNameList(), "Mismatched updated factories name list"); List> factories = manager.getMacFactories(); - assertEquals("Mismatched updated factories count", BuiltinMacs.VALUES.size(), GenericUtils.size(factories)); + assertEquals(BuiltinMacs.VALUES.size(), GenericUtils.size(factories), "Mismatched updated factories count"); for (NamedFactory f : BuiltinMacs.VALUES) { - assertTrue("Factory not set: " + f, factories.contains(f)); + assertTrue(factories.contains(f), "Factory not set: " + f); } } @Test - public void testDefaultSignatureFactoriesMethods() { + void defaultSignatureFactoriesMethods() { KexFactoryManager manager = new TestKexFactoryManager(); - assertEquals("Mismatched empty factories name list", "", manager.getSignatureFactoriesNameList()); + assertEquals("", manager.getSignatureFactoriesNameList(), "Mismatched empty factories name list"); String expected = NamedResource.getNames(BuiltinSignatures.VALUES); manager.setSignatureFactoriesNameList(expected); - assertEquals("Mismatched updated factories name list", expected, manager.getSignatureFactoriesNameList()); + assertEquals(expected, manager.getSignatureFactoriesNameList(), "Mismatched updated factories name list"); List> factories = manager.getSignatureFactories(); - assertEquals("Mismatched updated factories count", BuiltinSignatures.VALUES.size(), GenericUtils.size(factories)); + assertEquals(BuiltinSignatures.VALUES.size(), GenericUtils.size(factories), "Mismatched updated factories count"); for (NamedFactory f : BuiltinSignatures.VALUES) { - assertTrue("Factory not set: " + f, factories.contains(f)); + assertTrue(factories.contains(f), "Factory not set: " + f); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/kex/KeyExchangeTest.java b/sshd-core/src/test/java/org/apache/sshd/common/kex/KeyExchangeTest.java index ae18cd91a..89f42cf21 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/kex/KeyExchangeTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/kex/KeyExchangeTest.java @@ -24,40 +24,43 @@ import org.apache.sshd.common.SshConstants; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class KeyExchangeTest extends BaseTestSupport { public KeyExchangeTest() { super(); } @Test - public void testSimpleKexOpcodeName() { + void simpleKexOpcodeName() { testKexOpcodeName(KeyExchange.SIMPLE_KEX_OPCODES_MAP, KeyExchange::getSimpleKexOpcodeName); } @Test - public void testGroupKexOpcodeName() { + void groupKexOpcodeName() { testKexOpcodeName(KeyExchange.GROUP_KEX_OPCODES_MAP, KeyExchange::getGroupKexOpcodeName); } private static void testKexOpcodeName(Map opsMap, Function xformer) { opsMap.forEach((cmd, expected) -> { String actual = xformer.apply(cmd); - assertSame("Mismatched results for cmd=" + cmd, expected, actual); + assertSame(expected, actual, "Mismatched results for cmd=" + cmd); if (SshConstants.isAmbiguousOpcode(cmd)) { - assertEquals("Unexpected ambiguous command resolution for " + cmd, cmd.toString(), - SshConstants.getCommandMessageName(cmd)); + assertEquals(cmd.toString(), + SshConstants.getCommandMessageName(cmd), + "Unexpected ambiguous command resolution for " + cmd); } }); } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/KexExtensionHandlerTest.java b/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/KexExtensionHandlerTest.java index 307cccccf..35ee667a3 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/KexExtensionHandlerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/KexExtensionHandlerTest.java @@ -35,25 +35,27 @@ import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class KexExtensionHandlerTest extends JUnitTestSupport { public KexExtensionHandlerTest() { super(); } @Test - public void testEncodeDecodeExtensionMessage() throws Exception { + void encodeDecodeExtensionMessage() throws Exception { List> expected = Arrays.asList( new SimpleImmutableEntry<>( DelayCompression.NAME, @@ -76,10 +78,10 @@ public void testEncodeDecodeExtensionMessage() throws Exception { public boolean handleKexExtensionRequest(Session session, int index, int count, String name, byte[] data) throws IOException { KexExtensionParser parser = KexExtensions.getRegisteredExtensionParser(name); - assertNotNull("No parser found for extension=" + name, parser); + assertNotNull(parser, "No parser found for extension=" + name); Object value = parser.parseExtension(data); - assertNotNull("No value extracted for extension=" + name, value); + assertNotNull(value, "No value extracted for extension=" + name); actual.add(new SimpleImmutableEntry<>(name, value)); return true; } @@ -87,19 +89,19 @@ public boolean handleKexExtensionRequest(Session session, int index, int count, Session session = Mockito.mock(Session.class); handler.handleKexExtensionsMessage(session, buffer); - assertEquals("Mismatched recovered extensions count", expected.size(), actual.size()); + assertEquals(expected.size(), actual.size(), "Mismatched recovered extensions count"); for (int index = 0; index < actual.size(); index++) { Map.Entry expEntry = expected.get(index); String name = expEntry.getKey(); Map.Entry actEntry = actual.get(index); - assertEquals("Mismatched extension name at index=" + index, name, actEntry.getKey()); + assertEquals(name, actEntry.getKey(), "Mismatched extension name at index=" + index); Object expValue = expEntry.getValue(); Object actValue = actEntry.getValue(); if (expValue instanceof List) { assertListEquals(name, (List) expValue, (List) actValue); } else { - assertEquals("Mismatched values for extension=" + name, expValue, actValue); + assertEquals(expValue, actValue, "Mismatched values for extension=" + name); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/StrictKexInteroperabilityTest.java b/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/StrictKexInteroperabilityTest.java index 7c578202e..f90cecd4f 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/StrictKexInteroperabilityTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/StrictKexInteroperabilityTest.java @@ -34,11 +34,10 @@ import org.apache.sshd.common.keyprovider.FileKeyPairProvider; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.ContainerTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.GenericContainer; @@ -48,6 +47,8 @@ import org.testcontainers.images.builder.dockerfile.DockerfileBuilder; import org.testcontainers.utility.MountableFile; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * Tests to ensure that an Apache MINA sshd client can talk to OpenSSH servers with or without "strict KEX". This * implicitly tests the message sequence number handling; if sequence numbers get out of sync or are reset wrongly, @@ -56,7 +57,7 @@ * @author Apache MINA SSHD Project * @see Terrapin Mitigation: "strict-kex" */ -@Category(ContainerTestCase.class) +@Tag("ContainerTestCase") public class StrictKexInteroperabilityTest extends BaseTestSupport { private static final Logger LOG = LoggerFactory.getLogger(StrictKexInteroperabilityTest.class); @@ -69,15 +70,15 @@ public StrictKexInteroperabilityTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { client = setupTestClient(); SessionFactory factory = new TestSessionFactory(client); client.setSessionFactory(factory); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (client != null) { client.stop(); } @@ -102,12 +103,12 @@ private DockerfileBuilder strictKexImage(DockerfileBuilder builder, boolean with } @Test - public void testStrictKexOff() throws Exception { + void strictKexOff() throws Exception { testStrictKex(false); } @Test - public void testStrictKexOn() throws Exception { + void strictKexOn() throws Exception { testStrictKex(true); } @@ -138,8 +139,8 @@ private void testStrictKex(boolean withStrictKex) throws Exception { try (ClientSession session = client.connect("bob", sshdContainer.getHost(), sshdContainer.getMappedPort(22)) .verify(CONNECT_TIMEOUT).getSession()) { session.auth().verify(AUTH_TIMEOUT); - assertTrue("Should authenticate", session.isAuthenticated()); - assertTrue("Unexpected session type " + session.getClass().getName(), session instanceof TestSession); + assertTrue(session.isAuthenticated(), "Should authenticate"); + assertTrue(session instanceof TestSession, "Unexpected session type " + session.getClass().getName()); assertEquals("Unexpected strict KEX usage", withStrictKex, ((TestSession) session).usesStrictKex()); try (ChannelShell channel = session.createShellChannel()) { channel.setOut(System.out); @@ -148,15 +149,15 @@ private void testStrictKex(boolean withStrictKex) throws Exception { PipedOutputStream pos = new PipedOutputStream(); PipedInputStream pis = new PipedInputStream(pos); channel.setIn(pis); - assertTrue("Could not open session", channel.open().await(DEFAULT_TIMEOUT)); + assertTrue(channel.open().await(DEFAULT_TIMEOUT), "Could not open session"); LOG.info("writing some data..."); pos.write("\n\n".getBytes(StandardCharsets.UTF_8)); - assertTrue("Channel should be open", channel.isOpen()); + assertTrue(channel.isOpen(), "Channel should be open"); assertTrue(session.reExchangeKeys().verify(CONNECT_TIMEOUT).isDone()); - assertTrue("Channel should be open", channel.isOpen()); + assertTrue(channel.isOpen(), "Channel should be open"); LOG.info("writing some data..."); pos.write("\n\n".getBytes(StandardCharsets.UTF_8)); - assertTrue("Channel should be open", channel.isOpen()); + assertTrue(channel.isOpen(), "Channel should be open"); channel.close(true); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/StrictKexTest.java b/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/StrictKexTest.java index 6d6c2ce8c..28d667625 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/StrictKexTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/kex/extension/StrictKexTest.java @@ -35,11 +35,16 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Tests for message handling during "strict KEX" is active: initial KEX must fail and disconnect if the KEX_INIT @@ -54,7 +59,7 @@ * @author Apache MINA SSHD Project * @see Terrapin Mitigation: "strict-kex" */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class StrictKexTest extends BaseTestSupport { private SshServer sshd; private SshClient client; @@ -63,14 +68,14 @@ public StrictKexTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); client = setupTestClient(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -80,12 +85,12 @@ public void tearDown() throws Exception { } @Test - public void connectionClosedIfFirstPacketFromClientNotKexInit() throws Exception { + void connectionClosedIfFirstPacketFromClientNotKexInit() throws Exception { testConnectionClosedIfFirstPacketFromPeerNotKexInit(true); } @Test - public void connectionClosedIfFirstPacketFromServerNotKexInit() throws Exception { + void connectionClosedIfFirstPacketFromServerNotKexInit() throws Exception { testConnectionClosedIfFirstPacketFromPeerNotKexInit(false); } @@ -112,25 +117,26 @@ public void sessionNegotiationOptionsCreated(Session session, Map provider.loadCertificates(null)); - assertTrue("Expected error in line 1", e.getMessage().contains("line 1")); - assertTrue("Unexpected exception message: " + e.getMessage(), - e.getMessage().contains("host") || e.getMessage().contains("user")); + assertTrue(e.getMessage().contains("line 1"), "Expected error in line 1"); + assertTrue(e.getMessage().contains("host") || e.getMessage().contains("user"), + "Unexpected exception message: " + e.getMessage()); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/mac/EncryptThenMacTest.java b/sshd-core/src/test/java/org/apache/sshd/common/mac/EncryptThenMacTest.java index dbdfeaa84..26b835e01 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/mac/EncryptThenMacTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/mac/EncryptThenMacTest.java @@ -31,37 +31,34 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.junit.AfterClass; -import org.junit.Before; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class EncryptThenMacTest extends BaseTestSupport { private static SshServer sshd; private static int port; private static SshClient client; - private final MacFactory factory; + private MacFactory factory; - public EncryptThenMacTest(MacFactory factory) { + public void initEncryptThenMacTest(MacFactory factory) throws Exception { this.factory = factory; + sshd.setMacFactories(Collections.singletonList(this.factory)); + client.setMacFactories(Collections.singletonList(this.factory)); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(EncryptThenMacTest.class); sshd.setKeyPairProvider(CommonTestSupportUtils.createTestHostKeyProvider(EncryptThenMacTest.class)); sshd.start(); @@ -71,8 +68,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -90,7 +87,6 @@ public static void tearDownClientAndServer() throws Exception { } } - @Parameters(name = "{0}") public static Collection parameters() { List ret = new ArrayList<>(); for (MacFactory f : BuiltinMacs.VALUES) { @@ -111,14 +107,10 @@ public static Collection parameters() { return ret; } - @Before - public void setUp() throws Exception { - sshd.setMacFactories(Collections.singletonList(factory)); - client.setMacFactories(Collections.singletonList(factory)); - } - - @Test - public void testClientConnection() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void clientConnection(MacFactory factory) throws Exception { + initEncryptThenMacTest(factory); try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT).getSession()) { session.addPasswordIdentity(getCurrentTestName()); @@ -127,7 +119,7 @@ public void testClientConnection() throws Exception { String expected = factory.getName(); for (KexProposalOption opt : KexProposalOption.MAC_PROPOSALS) { String actual = session.getNegotiatedKexParameter(opt); - assertEquals("Mismatched " + opt + " negotiation", expected, actual); + assertEquals(expected, actual, "Mismatched " + opt + " negotiation"); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/mac/MacCompatibilityTest.java b/sshd-core/src/test/java/org/apache/sshd/common/mac/MacCompatibilityTest.java index 319d27406..ff6cef5b9 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/mac/MacCompatibilityTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/mac/MacCompatibilityTest.java @@ -43,28 +43,24 @@ import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.CoreTestSupportUtils; import org.apache.sshd.util.test.JSchLogger; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.AfterClass; -import org.junit.Assume; -import org.junit.Before; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test MAC algorithms with other known implementations. * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class MacCompatibilityTest extends BaseTestSupport { private static final Collection GANYMEDE_MACS = Collections.unmodifiableSet( GenericUtils.asSortedSet(String.CASE_INSENSITIVE_ORDER, Connection.getAvailableMACs())); @@ -72,15 +68,8 @@ public class MacCompatibilityTest extends BaseTestSupport { private static SshServer sshd; private static int port; - private final MacFactory factory; - private final String jschMacClass; - - public MacCompatibilityTest(MacFactory factory, String jschMacClass) { - this.factory = factory; - this.jschMacClass = jschMacClass; - } + private MacFactory factory; - @Parameters(name = "factory={0}") public static Collection parameters() { List ret = new ArrayList<>(); for (MacFactory f : BuiltinMacs.VALUES) { @@ -120,8 +109,8 @@ public static Collection parameters() { return ret; } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { JSchLogger.init(); setupClientAndServer(MacCompatibilityTest.class); } @@ -142,8 +131,8 @@ private static void setupClientAndServer(Class anchor) throws Exception { port = sshd.getPort(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -153,15 +142,12 @@ public static void tearDownClientAndServer() throws Exception { } } - @Before - public void setUp() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "factory={0}") + public void withJSCH(MacFactory factory, String jschMacClass) throws Exception { sshd.setMacFactories(Collections.singletonList(factory)); - } - - @Test - public void testWithJSCH() throws Exception { String macName = factory.getName(); - Assume.assumeTrue("Known JSCH bug with " + macName, !BuiltinMacs.hmacsha512.equals(factory)); + Assumptions.assumeTrue(!BuiltinMacs.hmacsha512.equals(factory), "Known JSCH bug with " + macName); JSch sch = new JSch(); Map values = new HashMap<>(); @@ -202,10 +188,12 @@ public void testWithJSCH() throws Exception { } } - @Test - public void testWithGanymede() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "factory={0}") + public void withGanymede(MacFactory factory, String jschMacClass) throws Exception { + sshd.setMacFactories(Collections.singletonList(factory)); String macName = factory.getName(); - Assume.assumeTrue("Factory not supported: " + macName, GANYMEDE_MACS.contains(macName)); + Assumptions.assumeTrue(GANYMEDE_MACS.contains(macName), "Factory not supported: " + macName); ch.ethz.ssh2.log.Logger.enabled = true; Connection conn = new Connection(TEST_LOCALHOST, port); @@ -218,7 +206,7 @@ public void testWithGanymede() throws Exception { info.keyExchangeAlgorithm, info.serverHostKeyAlgorithm, info.clientToServerCryptoAlgorithm, info.serverToClientCryptoAlgorithm, info.clientToServerMACAlgorithm, info.serverToClientMACAlgorithm); - assertTrue("Failed to authenticate", conn.authenticateWithPassword(getCurrentTestName(), getCurrentTestName())); + assertTrue(conn.authenticateWithPassword(getCurrentTestName(), getCurrentTestName()), "Failed to authenticate"); ch.ethz.ssh2.Session session = conn.openSession(); try { @@ -246,7 +234,7 @@ private void runShellTest(OutputStream stdin, InputStream stdout) throws IOExcep int len = stdout.read(data); String str = new String(data, 0, len, StandardCharsets.UTF_8); - assertEquals("Mismatched data at iteration " + index, expected, str); + assertEquals(expected, str, "Mismatched data at iteration " + index); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/session/GlobalRequestTest.java b/sshd-core/src/test/java/org/apache/sshd/common/session/GlobalRequestTest.java index 3765031e9..e800b8247 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/session/GlobalRequestTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/session/GlobalRequestTest.java @@ -44,9 +44,14 @@ import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for sending global requests. @@ -60,8 +65,8 @@ public GlobalRequestTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); sshd.start(); port = sshd.getPort(); @@ -69,8 +74,8 @@ public void setUp() throws Exception { client = setupTestClient(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -80,7 +85,7 @@ public void tearDown() throws Exception { } @Test - public void testSingleRequestNoReply() throws Exception { + void singleRequestNoReply() throws Exception { AtomicBoolean wrongWantReply = new AtomicBoolean(false); CountDownLatch latch = new CountDownLatch(1); List> globalHandlers = new ArrayList<>(sshd.getGlobalRequestHandlers()); @@ -111,16 +116,16 @@ public Result process(ConnectionService connectionService, String request, boole buffer.putString(testRequest); buffer.putBoolean(false); // want-reply false Buffer reply = session.request(testRequest, buffer, DEFAULT_TIMEOUT); - assertNotNull("Expected a (fake) reply", reply); - assertEquals("Expected a (fake) success", 0, reply.available()); + assertNotNull(reply, "Expected a (fake) reply"); + assertEquals(0, reply.available(), "Expected a (fake) success"); // Check that the server got it. Should take much less than 5 seconds. - assertTrue("Server did not get request", latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS), "Server did not get request"); } - assertFalse("Had a wrong want-reply", wrongWantReply.get()); + assertFalse(wrongWantReply.get(), "Had a wrong want-reply"); } @Test - public void testOverlappedRequests() throws Exception { + void overlappedRequests() throws Exception { final int numberOfRequests = 6; CountDownLatch latch = new CountDownLatch(numberOfRequests); List> globalHandlers = new ArrayList<>(sshd.getGlobalRequestHandlers()); @@ -186,10 +191,10 @@ public Result process(ConnectionService connectionService, String request, boole for (int i = 0; i < numberOfRequests; i++) { GlobalRequestFuture request = requests[i]; request.await(DEFAULT_TIMEOUT); - assertTrue("Unexpected timeout after " + DEFAULT_TIMEOUT + "on request " + i, request.isDone()); + assertTrue(request.isDone(), "Unexpected timeout after " + DEFAULT_TIMEOUT + "on request " + i); } // Check that the server got it. Should take much less than 5 seconds. - assertTrue("Server did not get all requests", latch.await(5, TimeUnit.SECONDS)); + assertTrue(latch.await(5, TimeUnit.SECONDS), "Server did not get all requests"); int j = 0; for (int i = 0; i < numberOfRequests; i++) { GlobalRequestFuture request = requests[i]; @@ -198,28 +203,30 @@ public Result process(ConnectionService connectionService, String request, boole case 0: { j++; Buffer reply = request.getBuffer(); - assertNotNull("Expected success for request " + i, reply); - assertEquals("Expected a success", (byte) ('1' + j - 1), reply.getByte()); + assertNotNull(reply, "Expected success for request " + i); + assertEquals((byte) ('1' + j - 1), reply.getByte(), "Expected a success"); break; } case 1: j++; failure = request.getException(); - assertNotNull("Expected failure for request " + i, failure); - assertTrue("Unexpected failure type", failure instanceof GlobalRequestException); - assertEquals("Unexpected failure reason for request " + i, SshConstants.SSH_MSG_REQUEST_FAILURE, - ((GlobalRequestException) failure).getCode()); - assertTrue("Unexpected failure message for request " + i, - failure.getMessage().contains("SSH_MSG_REQUEST_FAILURE")); + assertNotNull(failure, "Expected failure for request " + i); + assertTrue(failure instanceof GlobalRequestException, "Unexpected failure type"); + assertEquals(SshConstants.SSH_MSG_REQUEST_FAILURE, + ((GlobalRequestException) failure).getCode(), + "Unexpected failure reason for request " + i); + assertTrue(failure.getMessage().contains("SSH_MSG_REQUEST_FAILURE"), + "Unexpected failure message for request " + i); break; default: failure = request.getException(); - assertNotNull("Expected failure for request " + i, failure); - assertTrue("Unexpected failure type", failure instanceof GlobalRequestException); - assertEquals("Unexpected failure reason for request " + i, SshConstants.SSH_MSG_UNIMPLEMENTED, - ((GlobalRequestException) failure).getCode()); - assertTrue("Unexpected failure message for request " + i, - failure.getMessage().contains("SSH_MSG_UNIMPLEMENTED")); + assertNotNull(failure, "Expected failure for request " + i); + assertTrue(failure instanceof GlobalRequestException, "Unexpected failure type"); + assertEquals(SshConstants.SSH_MSG_UNIMPLEMENTED, + ((GlobalRequestException) failure).getCode(), + "Unexpected failure reason for request " + i); + assertTrue(failure.getMessage().contains("SSH_MSG_UNIMPLEMENTED"), + "Unexpected failure message for request " + i); break; } } @@ -228,12 +235,12 @@ public Result process(ConnectionService connectionService, String request, boole buffer.putString(testRequest); buffer.putBoolean(true); // want-reply true Buffer reply = session.request(testRequest, buffer, DEFAULT_TIMEOUT); - assertNotNull("Expected a success", reply); + assertNotNull(reply, "Expected a success"); } } @Test - public void testGlobalRequestWithReplyInMessageHandling() throws Exception { + void globalRequestWithReplyInMessageHandling() throws Exception { // Use a crude implementation of the hostkey rotation OpenSSH extension. Note that the implementation in // Apache MINA sshd server is incomplete, and for RSA keys does not match the OpenSSH implementation. List> globalHandlers = new ArrayList<>(sshd.getGlobalRequestHandlers()); @@ -303,12 +310,12 @@ protected Result handleHostKeys( // For once use session.request() instead of session.writePacket() to make the request. session.request(testRequest, buffer, DEFAULT_TIMEOUT); // Wait until we've received the hostkeys-00 message, and have made our hostkeys-prove-00 request. - assertTrue("Did not get hostkeys-00 message in time", latch.await(5, TimeUnit.SECONDS)); - assertNotNull("Did not make hostkeys-prove-00 request", req[0]); + assertTrue(latch.await(5, TimeUnit.SECONDS), "Did not get hostkeys-00 message in time"); + assertNotNull(req[0], "Did not make hostkeys-prove-00 request"); // Wait until we have the server's hostkeys-prove-00 reply. - assertTrue("Did not get hostkeys-prove-00 reply in time", req[0].await(DEFAULT_TIMEOUT)); + assertTrue(req[0].await(DEFAULT_TIMEOUT), "Did not get hostkeys-prove-00 reply in time"); Buffer reply = req[0].getBuffer(); - assertNotNull("Got a null hostkeys-prove-00 reply", req[0]); + assertNotNull(req[0], "Got a null hostkeys-prove-00 reply"); // We should have as many signatures as we had gotten keys. Collection> factories = client.getSignatureFactories(); keysFromServer.forEach(k -> { @@ -327,17 +334,17 @@ protected Result handleHostKeys( try { verifier.initVerifier(session, k); verifier.update(session, expected.array(), expected.rpos(), expected.available()); - assertTrue("Signature does not match", verifier.verify(session, signature)); + assertTrue(verifier.verify(session, signature), "Signature does not match"); } catch (Exception e) { throw new RuntimeException("Signature verification failed", e); } }); - assertEquals("Did not consume all bytes from the reply", 0, reply.available()); + assertEquals(0, reply.available(), "Did not consume all bytes from the reply"); } } @Test - public void testGlobalRequestWithReplyHandler() throws Exception { + void globalRequestWithReplyHandler() throws Exception { // This is the same as above, but using a ReplyHandler. The whole key rotation exchange can be done completely // inside the OpenSshHostKeysHandler without any need for any extra threads. The framework's thread handling the // reply message will invoke the handler. @@ -420,8 +427,8 @@ protected Result handleHostKeys( buffer.putBoolean(false); // want-reply session.request(testRequest, buffer, DEFAULT_TIMEOUT); // Wait until all keys verified. - assertTrue("Did not handle hostkeys-prove-00 message in time", replyHandled.await(10, TimeUnit.SECONDS)); - assertEquals("Test failures", "", String.join(System.lineSeparator(), testFailures)); + assertTrue(replyHandled.await(10, TimeUnit.SECONDS), "Did not handle hostkeys-prove-00 message in time"); + assertEquals("", String.join(System.lineSeparator(), testFailures), "Test failures"); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/session/ReservedSessionMessagesHandlerTest.java b/sshd-core/src/test/java/org/apache/sshd/common/session/ReservedSessionMessagesHandlerTest.java index ee5949585..d354045e4 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/session/ReservedSessionMessagesHandlerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/session/ReservedSessionMessagesHandlerTest.java @@ -35,16 +35,19 @@ import org.apache.sshd.common.util.threads.ThreadUtils; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ReservedSessionMessagesHandlerTest extends BaseTestSupport { private SshServer sshd; private SshClient client; @@ -54,8 +57,8 @@ public ReservedSessionMessagesHandlerTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); sshd.start(); port = sshd.getPort(); @@ -63,8 +66,8 @@ public void setUp() throws Exception { client = setupTestClient(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -74,7 +77,7 @@ public void tearDown() throws Exception { } @Test - public void testClientToServer() throws Exception { + void clientToServer() throws Exception { AccumulatingHandler handler = new AccumulatingHandler(); sshd.setReservedSessionMessagesHandler(handler); @@ -90,7 +93,7 @@ public void testClientToServer() throws Exception { } @Test - public void testServerToClient() throws Exception { + void serverToClient() throws Exception { final AccumulatingHandler handler = new AccumulatingHandler(); client.setReservedSessionMessagesHandler(handler); @@ -121,7 +124,7 @@ public void sessionEvent(final Session session, Event event) { = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(CONNECT_TIMEOUT).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); - assertTrue("Failed to complete test on time", signal.tryAcquire(31L, TimeUnit.SECONDS)); + assertTrue(signal.tryAcquire(31L, TimeUnit.SECONDS), "Failed to complete test on time"); } finally { client.stop(); } @@ -151,16 +154,16 @@ private void testIgnoredMessages(Session session, AccumulatingHandler handler) t session.sendIgnoreMessage(data.getBytes(StandardCharsets.UTF_8)); } - assertTrue("Failed to accumulate ignored messages on time", - handler.waitForIgnoreCount(expected.size(), TimeUnit.SECONDS, expected.size() * 2)); + assertTrue(handler.waitForIgnoreCount(expected.size(), TimeUnit.SECONDS, expected.size() * 2), + "Failed to accumulate ignored messages on time"); List actual = handler.getIgnoredMessages(); - assertEquals("Mismatched size of ignored messages", expected.size(), actual.size()); + assertEquals(expected.size(), actual.size(), "Mismatched size of ignored messages"); for (int index = 0; index < actual.size(); index++) { String expValue = expected.get(index); String actValue = new String(actual.get(index), StandardCharsets.UTF_8); - assertEquals("Mismatched ignored message payload at index=" + index, expValue, actValue); + assertEquals(expValue, actValue, "Mismatched ignored message payload at index=" + index); } } @@ -178,16 +181,16 @@ private void testDebugMessages(Session session, AccumulatingHandler handler) thr session.sendDebugMessage(entry.getValue(), entry.getKey(), null); } - assertTrue("Failed to accumulate debug messages on time", - handler.waitForDebugCount(expected.size(), TimeUnit.SECONDS, expected.size() * 2)); + assertTrue(handler.waitForDebugCount(expected.size(), TimeUnit.SECONDS, expected.size() * 2), + "Failed to accumulate debug messages on time"); List> actual = handler.getDebugMessages(); - assertEquals("Mismatched size of debug messages", expected.size(), actual.size()); + assertEquals(expected.size(), actual.size(), "Mismatched size of debug messages"); for (int index = 0; index < actual.size(); index++) { Map.Entry expEntry = expected.get(index); Map.Entry actEntry = actual.get(index); - assertEquals("Mismatched debug entry at index " + index, expEntry, actEntry); + assertEquals(expEntry, actEntry, "Mismatched debug entry at index " + index); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/common/session/helpers/AbstractSessionTest.java b/sshd-core/src/test/java/org/apache/sshd/common/session/helpers/AbstractSessionTest.java index 8d74d51b7..39f461acc 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/session/helpers/AbstractSessionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/session/helpers/AbstractSessionTest.java @@ -51,21 +51,26 @@ import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.core.CoreModuleProperties; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test basic stuff on AbstractSession. * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class AbstractSessionTest extends BaseTestSupport { private MySession session; @@ -73,94 +78,103 @@ public AbstractSessionTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { session = new MySession(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (session != null) { session.close(); } } @Test - public void testReadIdentSimple() throws Exception { + void readIdentSimple() throws Exception { Buffer buf = new ByteArrayBuffer("SSH-2.0-software\r\n".getBytes(StandardCharsets.UTF_8)); String ident = readIdentification(session, buf); assertEquals("SSH-2.0-software", ident); } @Test - public void testReadIdentWithoutCR() throws Exception { + void readIdentWithoutCR() throws Exception { Buffer buf = new ByteArrayBuffer("SSH-2.0-software\n".getBytes(StandardCharsets.UTF_8)); String ident = readIdentification(session, buf); assertEquals("SSH-2.0-software", ident); } @Test - public void testReadIdentWithHeaders() throws Exception { + void readIdentWithHeaders() throws Exception { Buffer buf = new ByteArrayBuffer("a header line\r\nSSH-2.0-software\r\n".getBytes(StandardCharsets.UTF_8)); String ident = readIdentification(session, buf); assertEquals("SSH-2.0-software", ident); } @Test - public void testReadIdentWithSplitPackets() throws Exception { + void readIdentWithSplitPackets() throws Exception { Buffer buf = new ByteArrayBuffer("header line\r\nSSH".getBytes(StandardCharsets.UTF_8)); String ident = readIdentification(session, buf); - assertNull("Unexpected identification for header only", ident); + assertNull(ident, "Unexpected identification for header only"); buf.putRawBytes("-2.0-software\r\n".getBytes(StandardCharsets.UTF_8)); ident = readIdentification(session, buf); assertEquals("SSH-2.0-software", ident); } - @Test(expected = StreamCorruptedException.class) - public void testReadIdentBadLineEnding() throws Exception { - Buffer buf = new ByteArrayBuffer("SSH-2.0-software\ra".getBytes(StandardCharsets.UTF_8)); - String ident = readIdentification(session, buf); - fail("Unexpected success: " + ident); + @Test + void readIdentBadLineEnding() throws Exception { + assertThrows(StreamCorruptedException.class, () -> { + Buffer buf = new ByteArrayBuffer("SSH-2.0-software\ra".getBytes(StandardCharsets.UTF_8)); + String ident = readIdentification(session, buf); + fail("Unexpected success: " + ident); + }); } - @Test(expected = StreamCorruptedException.class) - public void testReadIdentLongLine() throws Exception { - StringBuilder sb = new StringBuilder(SessionContext.MAX_VERSION_LINE_LENGTH + Integer.SIZE); - sb.append("SSH-2.0-software"); - do { - sb.append("01234567890123456789012345678901234567890123456789"); - } while (sb.length() < SessionContext.MAX_VERSION_LINE_LENGTH); - - Buffer buf = new ByteArrayBuffer(sb.toString().getBytes(StandardCharsets.UTF_8)); - String ident = readIdentification(session, buf); - fail("Unexpected success: " + ident); + @Test + void readIdentLongLine() throws Exception { + assertThrows(StreamCorruptedException.class, () -> { + StringBuilder sb = new StringBuilder(SessionContext.MAX_VERSION_LINE_LENGTH + Integer.SIZE); + sb.append("SSH-2.0-software"); + do { + sb.append("01234567890123456789012345678901234567890123456789"); + } while (sb.length() < SessionContext.MAX_VERSION_LINE_LENGTH); + + Buffer buf = new ByteArrayBuffer(sb.toString().getBytes(StandardCharsets.UTF_8)); + String ident = readIdentification(session, buf); + fail("Unexpected success: " + ident); + }); } - @Test(expected = StreamCorruptedException.class) - public void testReadIdentWithNullChar() throws Exception { - String id = "SSH-2.0" + '\0' + "-software\r\n"; - Buffer buf = new ByteArrayBuffer(id.getBytes(StandardCharsets.UTF_8)); - String ident = readIdentification(session, buf); - fail("Unexpected success: " + ident); + @Test + void readIdentWithNullChar() throws Exception { + assertThrows(StreamCorruptedException.class, () -> { + String id = "SSH-2.0" + '\0' + "-software\r\n"; + Buffer buf = new ByteArrayBuffer(id.getBytes(StandardCharsets.UTF_8)); + String ident = readIdentification(session, buf); + fail("Unexpected success: " + ident); + }); } - @Test(expected = StreamCorruptedException.class) - public void testReadIdentLongHeader() throws Exception { - int maxIdentSize = CoreModuleProperties.MAX_IDENTIFICATION_SIZE.getRequiredDefault(); - StringBuilder sb = new StringBuilder(maxIdentSize + Integer.SIZE); - do { - sb.append("01234567890123456789012345678901234567890123456789\r\n"); - } while (sb.length() < maxIdentSize); - sb.append("SSH-2.0-software\r\n"); - - Buffer buf = new ByteArrayBuffer(sb.toString().getBytes(StandardCharsets.UTF_8)); - String ident = readIdentification(session, buf); - fail("Unexpected success: " + ident); + @Test + void readIdentLongHeader() throws Exception { + assertThrows(StreamCorruptedException.class, () -> { + int maxIdentSize = CoreModuleProperties.MAX_IDENTIFICATION_SIZE.getRequiredDefault(); + StringBuilder sb = new StringBuilder(maxIdentSize + Integer.SIZE); + do { + sb.append("01234567890123456789012345678901234567890123456789\r\n"); + } while (sb.length() < maxIdentSize); + sb.append("SSH-2.0-software\r\n"); + + Buffer buf = new ByteArrayBuffer(sb.toString().getBytes(StandardCharsets.UTF_8)); + String ident = readIdentification(session, buf); + fail("Unexpected success: " + ident); + }); } - @Test // see SSHD-619 - public void testMsgIgnorePadding() throws Exception { + // see SSHD-619 + @Test + void msgIgnorePadding() throws Exception { final long frequency = Byte.SIZE; CoreModuleProperties.IGNORE_MESSAGE_SIZE.set(session, Short.SIZE); CoreModuleProperties.IGNORE_MESSAGE_FREQUENCY.set(session, frequency); @@ -182,33 +196,36 @@ public void testMsgIgnorePadding() throws Exception { Buffer data = queue.remove(); if (data != msg) { int cmd = data.getUByte(); - assertEquals("Mismatched buffer command at cycle " + cycle + "[" + index + "]", SshConstants.SSH_MSG_IGNORE, - cmd); + assertEquals(SshConstants.SSH_MSG_IGNORE, + cmd, + "Mismatched buffer command at cycle " + cycle + "[" + index + "]"); int len = data.getInt(); - assertTrue("Mismatched random padding data length at cycle " + cycle + "[" + index + "]: " + len, - len >= Short.SIZE); + assertTrue(len >= Short.SIZE, + "Mismatched random padding data length at cycle " + cycle + "[" + index + "]: " + len); numIgnores++; } } } - assertEquals("Mismatched number of ignore messages", Byte.SIZE, numIgnores); + assertEquals(Byte.SIZE, numIgnores, "Mismatched number of ignore messages"); } - @Test // see SSHD-652 - public void testCloseFutureListenerRegistration() throws Exception { + // see SSHD-652 + @Test + void closeFutureListenerRegistration() throws Exception { AtomicInteger closeCount = new AtomicInteger(); session.addCloseFutureListener(future -> { - assertTrue("Future not marked as closed", future.isClosed()); - assertEquals("Unexpected multiple call to callback", 1, closeCount.incrementAndGet()); + assertTrue(future.isClosed(), "Future not marked as closed"); + assertEquals(1, closeCount.incrementAndGet(), "Unexpected multiple call to callback"); }); session.close(); - assertEquals("Close listener not called", 1, closeCount.get()); + assertEquals(1, closeCount.get(), "Close listener not called"); } - @Test // see SSHD-699 - public void testMalformedUnimplementedMessage() throws Exception { + // see SSHD-699 + @Test + void malformedUnimplementedMessage() throws Exception { session.setReservedSessionMessagesHandler(new ReservedSessionMessagesHandler() { @Override public boolean handleUnimplementedMessage(Session session, int cmd, Buffer buffer) throws Exception { @@ -224,8 +241,9 @@ public boolean handleUnimplementedMessage(Session session, int cmd, Buffer buffe } } - @Test // see SSHD-699 - public void testMalformedIgnoreMessageBadLength() throws Exception { + // see SSHD-699 + @Test + void malformedIgnoreMessageBadLength() throws Exception { session.setReservedSessionMessagesHandler(new ReservedSessionMessagesHandler() { @Override public void handleIgnoreMessage(Session session, Buffer buffer) throws Exception { @@ -240,8 +258,9 @@ public void handleIgnoreMessage(Session session, Buffer buffer) throws Exception } } - @Test // see SSHD-699 - public void testMalformedIgnoreMessageCorruptedData() throws Exception { + // see SSHD-699 + @Test + void malformedIgnoreMessageCorruptedData() throws Exception { session.setReservedSessionMessagesHandler(new ReservedSessionMessagesHandler() { @Override public void handleIgnoreMessage(Session session, Buffer buffer) throws Exception { @@ -258,7 +277,7 @@ public void handleIgnoreMessage(Session session, Buffer buffer) throws Exception } @Test - public void testMalformedDebugMessageContent() throws Exception { + void malformedDebugMessageContent() throws Exception { session.setReservedSessionMessagesHandler(new ReservedSessionMessagesHandler() { @Override public void handleDebugMessage(Session session, Buffer buffer) throws Exception { @@ -280,7 +299,7 @@ public void handleDebugMessage(Session session, Buffer buffer) throws Exception } @Test - public void testMalformedDebugMessageLanguage() throws Exception { + void malformedDebugMessageLanguage() throws Exception { session.setReservedSessionMessagesHandler(new ReservedSessionMessagesHandler() { @Override public void handleDebugMessage(Session session, Buffer buffer) throws Exception { diff --git a/sshd-core/src/test/java/org/apache/sshd/common/signature/OpenSSHCertificateTest.java b/sshd-core/src/test/java/org/apache/sshd/common/signature/OpenSSHCertificateTest.java index d266af89e..002b10cfe 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/signature/OpenSSHCertificateTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/signature/OpenSSHCertificateTest.java @@ -38,39 +38,42 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.junit.AfterClass; -import org.junit.Before; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class OpenSSHCertificateTest extends BaseTestSupport { private static SshServer sshd; private static SshClient client; private static int port; - private final FileHostKeyCertificateProvider certificateProvider; - private final FileKeyPairProvider keyPairProvider; - private final List> signatureFactory; + private FileHostKeyCertificateProvider certificateProvider; + private FileKeyPairProvider keyPairProvider; + private List> signatureFactory; - public OpenSSHCertificateTest(String keyPath, String certPath, List> signatureFactory) { + public void initOpenSSHCertificateTest(String keyPath, String certPath, List> signatureFactory) { Path testResourcesFolder = getTestResourcesFolder(); this.keyPairProvider = new FileKeyPairProvider(testResourcesFolder.resolve(keyPath)); this.certificateProvider = new FileHostKeyCertificateProvider(testResourcesFolder.resolve(certPath)); this.signatureFactory = signatureFactory; + sshd.setKeyPairProvider(keyPairProvider); + sshd.setHostKeyCertificateProvider(certificateProvider); + + CoreModuleProperties.ABORT_ON_INVALID_CERTIFICATE.remove(client); + + client.setSignatureFactories(this.signatureFactory); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestFullSupportServer(OpenSSHCertificateTest.class); sshd.start(); port = sshd.getPort(); @@ -79,8 +82,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -98,7 +101,6 @@ public static void tearDownClientAndServer() throws Exception { } } - @Parameters(name = "type={2}") @SuppressWarnings("deprecation") public static List parameters() { List list = new ArrayList<>(); @@ -123,18 +125,11 @@ public static List parameters() { return Collections.unmodifiableList(list); } - @Before - public void setUp() { - sshd.setKeyPairProvider(keyPairProvider); - sshd.setHostKeyCertificateProvider(certificateProvider); - - CoreModuleProperties.ABORT_ON_INVALID_CERTIFICATE.remove(client); - - client.setSignatureFactories(signatureFactory); - } - - @Test - public void testOpenSshCertificates() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "type={2}") + public void openSshCertificates(String keyPath, String certPath, List> signatureFactory) + throws Exception { + initOpenSSHCertificateTest(keyPath, certPath, signatureFactory); // default client try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT) @@ -144,8 +139,11 @@ public void testOpenSshCertificates() throws Exception { } } - @Test // invalid principal, but continue - public void testContinueOnInvalidPrincipal() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "type={2}") // invalid principal, but continue + public void continueOnInvalidPrincipal(String keyPath, String certPath, List> signatureFactory) + throws Exception { + initOpenSSHCertificateTest(keyPath, certPath, signatureFactory); CoreModuleProperties.ABORT_ON_INVALID_CERTIFICATE.set(client, false); try (ClientSession s = client.connect(getCurrentTestName(), "localhost", port) .verify(CONNECT_TIMEOUT) @@ -155,9 +153,12 @@ public void testContinueOnInvalidPrincipal() throws Exception { } } - @Test // invalid principal, abort + @MethodSource("parameters") + @ParameterizedTest(name = "type={2}") // invalid principal, abort @SuppressWarnings("deprecation") - public void testAbortOnInvalidPrincipal() throws Exception { + public void abortOnInvalidPrincipal(String keyPath, String certPath, List> signatureFactory) + throws Exception { + initOpenSSHCertificateTest(keyPath, certPath, signatureFactory); CoreModuleProperties.ABORT_ON_INVALID_CERTIFICATE.set(client, true); boolean thrown = false; try (ClientSession s = client.connect(getCurrentTestName(), "localhost", port) @@ -170,8 +171,8 @@ public void testAbortOnInvalidPrincipal() throws Exception { assertFalse(client.getSignatureFactories().contains(BuiltinSignatures.rsa_cert)); } catch (SshException e) { assertEquals(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED, e.getDisconnectCode()); - assertTrue("Expected error about invalid principal, got: " + e.getMessage(), - e.getMessage().contains("principal")); + assertTrue(e.getMessage().contains("principal"), + "Expected error about invalid principal, got: " + e.getMessage()); thrown = true; } boolean containsCert = GenericUtils.containsAny(client.getSignatureFactories(), 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 index b9b0bf483..b0b90ad5d 100644 --- 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 @@ -46,37 +46,32 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.junit.AfterClass; -import org.junit.Assume; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class SignatureFactoriesTest extends BaseTestSupport implements KeyTypeIndicator, KeySizeIndicator, OptionalFeature { private static SshServer sshd; private static SshClient client; private static int port; - private final String keyType; - private final int keySize; - private final boolean supported; - private final NamedFactory factory; - private final PublicKeyEntryDecoder pubKeyDecoder; + private String keyType; + private int keySize; + private boolean supported; + private NamedFactory factory; + private PublicKeyEntryDecoder pubKeyDecoder; - public SignatureFactoriesTest(String keyType, NamedFactory factory, - int keySize, boolean supported, PublicKeyEntryDecoder decoder) { + public void initSignatureFactoriesTest( + String keyType, NamedFactory factory, + int keySize, boolean supported, PublicKeyEntryDecoder decoder) { this.keyType = ValidateUtils.checkNotNullAndNotEmpty(keyType, "No key type specified"); this.factory = supported ? Objects.requireNonNull(factory, "No signature factory provided") : factory; if (supported) { @@ -87,7 +82,6 @@ public SignatureFactoriesTest(String keyType, NamedFactory factory, this.pubKeyDecoder = supported ? Objects.requireNonNull(decoder, "No public key decoder provided") : null; } - @Parameters(name = "type={0}, size={2}") @SuppressWarnings("deprecation") public static List parameters() { List list = new ArrayList<>(); @@ -119,8 +113,8 @@ private static void addTests( } } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestFullSupportServer(SignatureFactoriesTest.class); sshd.start(); port = sshd.getPort(); @@ -129,8 +123,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -163,9 +157,13 @@ public final String getKeyType() { return keyType; } - @Test - public void testPublicKeyAuth() throws Exception { - Assume.assumeTrue(isSupported()); + @MethodSource("parameters") + @ParameterizedTest(name = "type={0}, size={2}") + public void publicKeyAuth( + String keyType, NamedFactory factory, int keySize, boolean supported, + PublicKeyEntryDecoder decoder) throws Exception { + initSignatureFactoriesTest(keyType, factory, keySize, supported, decoder); + Assumptions.assumeTrue(isSupported()); testKeyPairProvider(getKeyType(), getKeySize(), pubKeyDecoder, Collections.singletonList(factory)); } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/PasswordAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/PasswordAuthenticatorTest.java index 48e983a2e..d7313fc92 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/PasswordAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/PasswordAuthenticatorTest.java @@ -29,29 +29,30 @@ import org.apache.sshd.server.auth.password.StaticPasswordAuthenticator; import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PasswordAuthenticatorTest extends BaseTestSupport { public PasswordAuthenticatorTest() { super(); } @Test - public void testAcceptAllPasswordAuthenticator() throws Exception { + void acceptAllPasswordAuthenticator() throws Exception { testStaticPasswordAuthenticator(AcceptAllPasswordAuthenticator.INSTANCE); } @Test - public void testRejectAllPasswordAuthenticator() throws Exception { + void rejectAllPasswordAuthenticator() throws Exception { testStaticPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE); } @@ -71,7 +72,7 @@ private void testStaticPasswordAuthenticator(StaticPasswordAuthenticator authent } Object result = method.invoke(authenticator, invArgs); - assertTrue("No boolean result", result instanceof Boolean); + assertTrue(result instanceof Boolean, "No boolean result"); assertEquals("Mismatched result for " + Arrays.toString(invArgs), expected, ((Boolean) result).booleanValue()); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java index ba5b1d4a9..e31f55eda 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java @@ -33,30 +33,31 @@ import org.apache.sshd.server.auth.pubkey.StaticPublickeyAuthenticator; import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PublickeyAuthenticatorTest extends BaseTestSupport { public PublickeyAuthenticatorTest() { super(); } @Test - public void testAcceptAllPublickeyAuthenticator() throws Throwable { + void acceptAllPublickeyAuthenticator() throws Throwable { testStaticPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE); } @Test - public void testRejectAllPublickeyAuthenticator() throws Throwable { + void rejectAllPublickeyAuthenticator() throws Throwable { testStaticPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE); } @@ -96,7 +97,7 @@ private void testStaticPublickeyAuthenticator(StaticPublickeyAuthenticator authe throw t; } - assertTrue("No boolean result", result instanceof Boolean); + assertTrue(result instanceof Boolean, "No boolean result"); assertEquals("Mismatched result for " + Arrays.toString(invArgs), expected, ((Boolean) result).booleanValue()); } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerAuthenticationManagerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerAuthenticationManagerTest.java index 717269d00..979a88406 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/ServerAuthenticationManagerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerAuthenticationManagerTest.java @@ -34,24 +34,27 @@ import org.apache.sshd.server.auth.password.PasswordAuthenticator; import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ServerAuthenticationManagerTest extends BaseTestSupport { public ServerAuthenticationManagerTest() { super(); } @Test - public void testDefaultUserAuthFactoriesMethods() { + void defaultUserAuthFactoriesMethods() { AtomicReference> factoriesHolder = new AtomicReference<>(); @SuppressWarnings("checkstyle:anoninnerlength") ServerAuthenticationManager manager = new ServerAuthenticationManager() { @@ -62,7 +65,7 @@ public List getUserAuthFactories() { @Override public void setUserAuthFactories(List userAuthFactories) { - assertNull("Unexpected multiple invocation", factoriesHolder.getAndSet(userAuthFactories)); + assertNull(factoriesHolder.getAndSet(userAuthFactories), "Unexpected multiple invocation"); } @Override @@ -136,17 +139,16 @@ public void setHostKeyCertificateProvider(HostKeyCertificateProvider provider) { throw new UnsupportedOperationException("setHostKeyCertificateProvider(" + provider + ")"); } }; - assertEquals("Mismatched initial factories list", "", manager.getUserAuthFactoriesNameList()); + assertEquals("", manager.getUserAuthFactoriesNameList(), "Mismatched initial factories list"); String expected = NamedResource.getNames(BuiltinUserAuthFactories.VALUES); manager.setUserAuthFactoriesNameList(expected); - assertEquals("Mismatched updated factories names", expected, manager.getUserAuthFactoriesNameList()); + assertEquals(expected, manager.getUserAuthFactoriesNameList(), "Mismatched updated factories names"); List factories = factoriesHolder.get(); - assertEquals("Mismatched factories count", - BuiltinUserAuthFactories.VALUES.size(), GenericUtils.size(factories)); + assertEquals(BuiltinUserAuthFactories.VALUES.size(), GenericUtils.size(factories), "Mismatched factories count"); for (BuiltinUserAuthFactories f : BuiltinUserAuthFactories.VALUES) { - assertTrue("Missing factory=" + f.name(), factories.contains(f.create())); + assertTrue(factories.contains(f.create()), "Missing factory=" + f.name()); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerDefaultSetupTest.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerDefaultSetupTest.java index efb4c6ec6..699de3920 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/ServerDefaultSetupTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerDefaultSetupTest.java @@ -20,13 +20,13 @@ package org.apache.sshd.server; import org.apache.sshd.DefaultSetupTestSupport; -import org.junit.FixMethodOrder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ServerDefaultSetupTest extends DefaultSetupTestSupport { public ServerDefaultSetupTest() { super(SshServer.setUpDefaultServer()); diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerProxyAcceptorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerProxyAcceptorTest.java index 553142e8a..413494065 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/ServerProxyAcceptorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerProxyAcceptorTest.java @@ -39,16 +39,20 @@ import org.apache.sshd.server.session.ServerProxyAcceptor; import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ServerProxyAcceptorTest extends BaseTestSupport { private SshServer sshd; private SshClient client; @@ -57,15 +61,15 @@ public ServerProxyAcceptorTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); sshd.setShellFactory(new TestEchoShellFactory()); client = setupTestClient(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -75,7 +79,7 @@ public void tearDown() throws Exception { } @Test - public void testClientAddressOverride() throws Exception { + void clientAddressOverride() throws Exception { SshdSocketAddress expectedClientAddress = new SshdSocketAddress("7.3.6.5", 7365); String proxyMetadata = getCurrentTestName() + " " + expectedClientAddress.getHostName() @@ -94,14 +98,15 @@ public boolean acceptServerProxyMetadata(ServerSession session, Buffer buffer) t buffer.getRawBytes(rawData); outputDebugMessage("acceptServerProxyMetadata(%s) proxy data: %s", session, new String(rawData, StandardCharsets.UTF_8)); - assertArrayEquals("Mismatched meta data", metaDataBytes, rawData); + assertArrayEquals(metaDataBytes, rawData, "Mismatched meta data"); int count = invocationCount.incrementAndGet(); if (count == 1) { ((AbstractServerSession) session).setClientAddress(expectedClientAddress); } else { - assertSame("Mismatched client address for invocation #" + count, expectedClientAddress, - session.getClientAddress()); + assertSame(expectedClientAddress, + session.getClientAddress(), + "Mismatched client address for invocation #" + count); } return true; // proxy completed } @@ -125,7 +130,7 @@ public void sessionClosed(Session session) { private void verifyClientAddress(String location, Session session) { assertObjectInstanceOf(location + ": not a server session", ServerSession.class, session); SocketAddress actualClientAddress = ((ServerSession) session).getClientAddress(); - assertSame(location + ": mismatched client address instance", expectedClientAddress, actualClientAddress); + assertSame(expectedClientAddress, actualClientAddress, location + ": mismatched client address instance"); } }); sshd.start(); @@ -140,8 +145,8 @@ private void verifyClientAddress(String location, Session session) { = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()).verify(CONNECT_TIMEOUT).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); - assertTrue("Failed to receive session signal on time", - sessionSignal.tryAcquire(DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); + assertTrue(sessionSignal.tryAcquire(DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS), + "Failed to receive session signal on time"); } finally { client.stop(); } 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 787961654..df991dec9 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,18 +47,23 @@ import org.apache.sshd.server.session.ServerSession; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ServerSessionListenerTest extends BaseTestSupport { private static SshServer sshd; private static int port; @@ -68,8 +73,8 @@ public ServerSessionListenerTest() { super(); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(ServerSessionListenerTest.class); sshd.start(); port = sshd.getPort(); @@ -78,8 +83,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -97,8 +102,9 @@ public static void tearDownClientAndServer() throws Exception { } } - @Test // see https://issues.apache.org/jira/browse/SSHD-456 - public void testServerStillListensIfSessionListenerThrowsException() throws Exception { + // see https://issues.apache.org/jira/browse/SSHD-456 + @Test + void serverStillListensIfSessionListenerThrowsException() throws Exception { final Map eventsMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); final Logger log = LoggerFactory.getLogger(getClass()); SessionListener listener = new SessionListener() { @@ -149,14 +155,14 @@ private void throwException(String phase, Session session) { } synchronized (eventsMap) { - assertTrue("Unexpected premature success at retry # " + retryCount + ": " + eventsMap, - eventsMap.size() >= 3); + assertTrue(eventsMap.size() >= 3, + "Unexpected premature success at retry # " + retryCount + ": " + eventsMap); } } catch (IOException e) { // expected - ignored synchronized (eventsMap) { int nextCount = eventsMap.size(); - assertTrue("No session event generated at retry #" + retryCount, nextCount > curCount); + assertTrue(nextCount > curCount, "No session event generated at retry #" + retryCount); } } } @@ -167,7 +173,7 @@ private void throwException(String phase, Session session) { } @Test - public void testSessionListenerCanModifyKEXNegotiation() throws Exception { + void sessionListenerCanModifyKEXNegotiation() throws Exception { Map kexParams = new EnumMap<>(KexProposalOption.class); kexParams.put(KexProposalOption.ALGORITHMS, getLeastFavorite(KeyExchangeFactory.class, sshd.getKeyExchangeFactories())); kexParams.put(KexProposalOption.S2CENC, getLeastFavorite(CipherFactory.class, sshd.getCipherFactories())); @@ -191,7 +197,7 @@ public void sessionCreated(Session session) { kexParams.forEach((option, factory) -> { String expected = factory.getName(); String actual = session.getNegotiatedKexParameter(option); - assertEquals("Mismatched values for KEX=" + option, expected, actual); + assertEquals(expected, actual, "Mismatched values for KEX=" + option); }); } finally { sshd.removeSessionListener(listener); @@ -199,7 +205,7 @@ public void sessionCreated(Session session) { } @Test - public void testSessionListenerCanModifyAuthentication() throws Exception { + void sessionListenerCanModifyAuthentication() throws Exception { AtomicInteger passCount = new AtomicInteger(0); PasswordAuthenticator defaultPassAuth = sshd.getPasswordAuthenticator(); PasswordAuthenticator passAuth = (username, password, session) -> { @@ -221,11 +227,10 @@ public void sessionCreated(Session session) { sshd.addSessionListener(listener); 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()); + assertNotSame(passAuth, sshd.getPasswordAuthenticator(), "Mismatched default password authenticator"); + assertNotSame(KeyboardInteractiveAuthenticator.NONE, sshd.getKeyboardInteractiveAuthenticator(), + "Mismatched default kb authenticator"); + assertEquals(1, passCount.get(), "Authenticator override not invoked"); } finally { sshd.removeSessionListener(listener); } @@ -234,7 +239,7 @@ public void sessionCreated(Session session) { private static NamedResource getLeastFavorite( Class type, List factories) { int numFactories = GenericUtils.size(factories); - assertTrue("No factories for " + type.getSimpleName(), numFactories > 0); + assertTrue(numFactories > 0, "No factories for " + type.getSimpleName()); return factories.get(numFactories - 1); } 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 9c8235b3e..77e583aac 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 @@ -86,18 +86,26 @@ import org.apache.sshd.util.test.EchoShell; import org.apache.sshd.util.test.EchoShellFactory; import org.apache.sshd.util.test.TestChannelListener; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ServerTest extends BaseTestSupport { private SshServer sshd; private SshClient client; @@ -106,15 +114,15 @@ public ServerTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd = setupTestServer(); sshd.setShellFactory(new TestEchoShellFactory()); client = setupTestClient(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -124,22 +132,22 @@ public void tearDown() throws Exception { } @Test - public void testServerStartedIndicator() throws Exception { + void serverStartedIndicator() throws Exception { sshd.start(); try { - assertTrue("Server not marked as started", sshd.isStarted()); + assertTrue(sshd.isStarted(), "Server not marked as started"); } finally { sshd.stop(); } - assertFalse("Server not marked as stopped", sshd.isStarted()); + assertFalse(sshd.isStarted(), "Server not marked as stopped"); } /* * Send bad password. The server should disconnect after a few attempts */ @Test - public void testFailAuthenticationWithWaitFor() throws Exception { + void failAuthenticationWithWaitFor() throws Exception { final int maxAllowedAuths = 10; CoreModuleProperties.MAX_AUTH_REQUESTS.set(sshd, maxAllowedAuths); @@ -160,16 +168,16 @@ public void testFailAuthenticationWithWaitFor() throws Exception { s.getService(ClientUserAuthServiceOld.class) .auth(new org.apache.sshd.deprecated.UserAuthPassword(s, "ssh-connection", "buggy")); res = s.waitFor(mask, TimeUnit.SECONDS.toMillis(5L)); - assertFalse("Timeout signalled", res.contains(ClientSession.ClientSessionEvent.TIMEOUT)); + assertFalse(res.contains(ClientSession.ClientSessionEvent.TIMEOUT), "Timeout signalled"); } - assertTrue("Number trials (" + nbTrials + ") below min.=" + maxAllowedAuths, nbTrials > maxAllowedAuths); + assertTrue(nbTrials > maxAllowedAuths, "Number trials (" + nbTrials + ") below min.=" + maxAllowedAuths); } finally { client.stop(); } } @Test - public void testFailAuthenticationWithFuture() throws Exception { + void failAuthenticationWithFuture() throws Exception { final int maxAllowedAuths = 10; CoreModuleProperties.MAX_AUTH_REQUESTS.set(sshd, maxAllowedAuths); @@ -185,24 +193,24 @@ public void testFailAuthenticationWithFuture() throws Exception { AuthFuture authFuture; do { nbTrials++; - assertTrue("Number of trials below max.", nbTrials < 100); + assertTrue(nbTrials < 100, "Number of trials below max."); authFuture = s.getService(ClientUserAuthServiceOld.class) .auth(new org.apache.sshd.deprecated.UserAuthPassword(s, "ssh-connection", "buggy")); - assertTrue("Authentication wait failed", authFuture.await(AUTH_TIMEOUT)); - assertTrue("Authentication not done", authFuture.isDone()); - assertFalse("Authentication unexpectedly successful", authFuture.isSuccess()); + assertTrue(authFuture.await(AUTH_TIMEOUT), "Authentication wait failed"); + assertTrue(authFuture.isDone(), "Authentication not done"); + assertFalse(authFuture.isSuccess(), "Authentication unexpectedly successful"); } while (authFuture.getException() == null); Throwable t = authFuture.getException(); - assertNotNull("Missing auth future exception", t); - assertTrue("Number trials (" + nbTrials + ") below min.=" + maxAllowedAuths, nbTrials > maxAllowedAuths); + assertNotNull(t, "Missing auth future exception"); + assertTrue(nbTrials > maxAllowedAuths, "Number trials (" + nbTrials + ") below min.=" + maxAllowedAuths); } finally { client.stop(); } } @Test - public void testAuthenticationTimeout() throws Exception { + void authenticationTimeout() throws Exception { Duration testAuthTimeout = Duration.ofSeconds(4L); CoreModuleProperties.AUTH_TIMEOUT.set(sshd, testAuthTimeout); @@ -234,19 +242,18 @@ public String toString() { Collection res = s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED), testAuthTimeout.multipliedBy(3L)); long waitEnd = System.currentTimeMillis(); - assertTrue("Invalid session state after " + (waitEnd - waitStart) + " ms: " + res, - res.containsAll(EnumSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH))); + assertTrue(res.containsAll(EnumSet.of(ClientSession.ClientSessionEvent.WAIT_AUTH)), + "Invalid session state after " + (waitEnd - waitStart) + " ms: " + res); } finally { client.stop(); } TimeoutIndicator status = timeoutHolder.getAndSet(null); - assertSame("Mismatched timeout status reported", - TimeoutIndicator.TimeoutStatus.AuthTimeout, status.getStatus()); + assertSame(TimeoutIndicator.TimeoutStatus.AuthTimeout, status.getStatus(), "Mismatched timeout status reported"); } @Test - public void testIdleTimeout() throws Exception { + void idleTimeout() throws Exception { final long testIdleTimeout = 2500L; CoreModuleProperties.IDLE_TIMEOUT.set(sshd, Duration.ofMillis(testIdleTimeout)); AtomicReference timeoutHolder = new AtomicReference<>(TimeoutIndicator.NONE); @@ -319,29 +326,29 @@ public String toString() { shell.setErr(err); shell.open().verify(OPEN_TIMEOUT); - assertTrue("No changes in activated channels", - channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS)); - assertTrue("No changes in open channels", - channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS)); + assertTrue(channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS), + "No changes in activated channels"); + assertTrue(channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS), + "No changes in open channels"); long waitStart = System.currentTimeMillis(); Collection res = s.waitFor(EnumSet.of(ClientSession.ClientSessionEvent.CLOSED), 3L * testIdleTimeout); long waitEnd = System.currentTimeMillis(); - assertTrue("Invalid session state after " + (waitEnd - waitStart) + " ms: " + res, - res.containsAll( - EnumSet.of( - ClientSession.ClientSessionEvent.CLOSED, - ClientSession.ClientSessionEvent.AUTHED))); + assertTrue(res.containsAll( + EnumSet.of( + ClientSession.ClientSessionEvent.CLOSED, + ClientSession.ClientSessionEvent.AUTHED)), + "Invalid session state after " + (waitEnd - waitStart) + " ms: " + res); } finally { client.stop(); } - assertTrue("Session latch not signalled in time", latch.await(1L, TimeUnit.SECONDS)); - assertTrue("Shell latch not signalled in time", TestEchoShell.latch.await(1L, TimeUnit.SECONDS)); + assertTrue(latch.await(1L, TimeUnit.SECONDS), "Session latch not signalled in time"); + assertTrue(TestEchoShell.latch.await(1L, TimeUnit.SECONDS), "Shell latch not signalled in time"); TimeoutIndicator status = timeoutHolder.getAndSet(null); - assertSame("Mismatched timeout status", TimeoutStatus.IdleTimeout, status.getStatus()); + assertSame(TimeoutStatus.IdleTimeout, status.getStatus(), "Mismatched timeout status"); } /* @@ -350,7 +357,7 @@ public String toString() { * disconnect message can't be written - the server session is forcibly closed */ @Test - public void testServerIdleTimeoutWithForce() throws Exception { + void serverIdleTimeoutWithForce() throws Exception { final long idleTimeoutValue = TimeUnit.SECONDS.toMillis(5L); CoreModuleProperties.IDLE_TIMEOUT.set(sshd, Duration.ofMillis(idleTimeoutValue)); @@ -402,10 +409,10 @@ public String toString() { shell.setOut(pos); shell.open().verify(OPEN_TIMEOUT); - assertTrue("No changes in activated channels", - channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS)); - assertTrue("No changes in open channels", - channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS)); + assertTrue(channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS), + "No changes in activated channels"); + assertTrue(channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS), + "No changes in open channels"); try (AbstractSession serverSession = GenericUtils.head(sshd.getActiveSessions())) { AbstractConnectionService service = serverSession.getService(AbstractConnectionService.class); @@ -422,7 +429,7 @@ public String toString() { long nanoDuration = nanoEnd - nanoStart; totalNanoTime += nanoDuration; - assertTrue("Waiting for too long on remote window size to reach zero", totalNanoTime < maxWaitNanos); + assertTrue(totalNanoTime < maxWaitNanos, "Waiting for too long on remote window size to reach zero"); } Logger logger = LoggerFactory.getLogger(getClass()); @@ -432,8 +439,8 @@ public String toString() { latch.await(1L, TimeUnit.MINUTES); long t1 = System.currentTimeMillis(); long diff = t1 - t0; - assertTrue("Wait time too low: " + diff, diff > idleTimeoutValue); - assertTrue("Wait time too high: " + diff, diff < maxTimeoutValue); + assertTrue(diff > idleTimeoutValue, "Wait time too low: " + diff); + assertTrue(diff < maxTimeoutValue, "Wait time too high: " + diff); } } } finally { @@ -442,7 +449,7 @@ public String toString() { } @Test - public void testLanguageNegotiation() throws Exception { + void languageNegotiation() throws Exception { sshd.start(); client.setSessionFactory(new org.apache.sshd.client.session.SessionFactory(client) { @@ -473,7 +480,7 @@ public void sessionEvent(Session session, Event event) { for (KexProposalOption option : new KexProposalOption[] { KexProposalOption.S2CLANG, KexProposalOption.C2SLANG }) { - assertNull("Unexpected negotiated language for " + option, session.getNegotiatedKexParameter(option)); + assertNull(session.getNegotiatedKexParameter(option), "Unexpected negotiated language for " + option); } sigSem.release(); @@ -499,14 +506,15 @@ public String toString() { client.start(); try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()) .verify(CONNECT_TIMEOUT).getSession()) { - assertTrue("Failed to receive signal on time", sigSem.tryAcquire(11L, TimeUnit.SECONDS)); + assertTrue(sigSem.tryAcquire(11L, TimeUnit.SECONDS), "Failed to receive signal on time"); } finally { client.stop(); } } - @Test // see SSHD-609 - public void testCompressionNegotiation() throws Exception { + // see SSHD-609 + @Test + void compressionNegotiation() throws Exception { sshd.setSessionFactory(new org.apache.sshd.server.session.SessionFactory(sshd) { @Override protected ServerSessionImpl doCreateSession(IoSession ioSession) throws Exception { @@ -547,7 +555,7 @@ public void sessionCreated(Session session) { @Override public void sessionEvent(Session session, Event event) { - assertNotEquals("Unexpected key establishment success", Event.KeyEstablished, event); + assertNotEquals(Event.KeyEstablished, event, "Unexpected key establishment success"); } @Override @@ -570,12 +578,12 @@ public String toString() { try { try (ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()) .verify(CONNECT_TIMEOUT).getSession()) { - assertTrue("Session closing not signalled on time", sigSem.tryAcquire(5L, TimeUnit.SECONDS)); + assertTrue(sigSem.tryAcquire(5L, TimeUnit.SECONDS), "Session closing not signalled on time"); for (boolean incoming : new boolean[] { true, false }) { - assertNull("Unexpected compression information for incoming=" + incoming, - s.getCompressionInformation(incoming)); + assertNull(s.getCompressionInformation(incoming), + "Unexpected compression information for incoming=" + incoming); } - assertFalse("Session unexpectedly still open", s.isOpen()); + assertFalse(s.isOpen(), "Session unexpectedly still open"); } } finally { client.stop(); @@ -583,7 +591,7 @@ public String toString() { } @Test - public void testKexCompletedEvent() throws Exception { + void kexCompletedEvent() throws Exception { AtomicInteger serverEventCount = new AtomicInteger(0); sshd.addSessionListener(new SessionListener() { @Override @@ -617,16 +625,17 @@ public String toString() { client.start(); try (ClientSession s = createTestClientSession(sshd)) { - assertEquals("Mismatched client events count", 1, clientEventCount.get()); - assertEquals("Mismatched server events count", 1, serverEventCount.get()); + assertEquals(1, clientEventCount.get(), "Mismatched client events count"); + assertEquals(1, serverEventCount.get(), "Mismatched server events count"); s.close(false); } finally { client.stop(); } } - @Test // see SSHD-645 - public void testChannelStateChangeNotifications() throws Exception { + // see SSHD-645 + @Test + void channelStateChangeNotifications() throws Exception { Semaphore exitSignal = new Semaphore(0); sshd.setCommandFactory((session, command) -> new Command() { private ExitCallback cb; @@ -671,31 +680,31 @@ public void start(ChannelSession channel, Environment env) throws IOException { shell.addChannelListener(new ChannelListener() { @Override public void channelStateChanged(Channel channel, String hint) { - assertNotNull("No hint for channel", hint); + assertNotNull(hint, "No hint for channel"); outputDebugMessage("channelStateChanged(%s): %s", channel, hint); stateChangeHints.add(hint); } }); shell.open().verify(OPEN_TIMEOUT); - assertTrue("Timeout while wait for exit signal", exitSignal.tryAcquire(15L, TimeUnit.SECONDS)); + assertTrue(exitSignal.tryAcquire(15L, TimeUnit.SECONDS), "Timeout while wait for exit signal"); Collection result = shell.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(13L)); - assertFalse("Channel close timeout", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Channel close timeout"); Integer status = shell.getExitStatus(); - assertNotNull("No exit status", status); + assertNotNull(status, "No exit status"); } finally { client.stop(); } for (String h : new String[] { "exit-status" }) { - assertTrue("Missing hint=" + h + " in " + stateChangeHints, stateChangeHints.contains(h)); + assertTrue(stateChangeHints.contains(h), "Missing hint=" + h + " in " + stateChangeHints); } } @Test - public void testServerHeartbeat() throws Exception { + void serverHeartbeat() throws Exception { sshd.setSessionHeartbeat(HeartbeatType.IGNORE, Duration.ofMillis(500)); sshd.start(); AtomicInteger ignoreMessageCount = new AtomicInteger(0); @@ -711,11 +720,11 @@ public void handleIgnoreMessage(Session session, Buffer buffer) throws Exception Thread.sleep(2000); } long ignoreMessages = ignoreMessageCount.get(); - assertTrue("Epected some ignore messages (server-side heartbeat)", ignoreMessages > 0 && ignoreMessages <= 5); + assertTrue(ignoreMessages > 0 && ignoreMessages <= 5, "Epected some ignore messages (server-side heartbeat)"); } @Test - public void testEnvironmentVariablesPropagationToServer() throws Exception { + void environmentVariablesPropagationToServer() throws Exception { AtomicReference envHolder = new AtomicReference<>(null); sshd.setCommandFactory((session, command) -> new Command() { private ExitCallback cb; @@ -775,36 +784,37 @@ public void start(ChannelSession channel, Environment env) throws IOException { shell.open().verify(OPEN_TIMEOUT); - assertTrue("No changes in activated channels", channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS)); - assertTrue("No changes in open channels", channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS)); + assertTrue(channelListener.waitForActiveChannelsChange(5L, TimeUnit.SECONDS), "No changes in activated channels"); + assertTrue(channelListener.waitForOpenChannelsChange(5L, TimeUnit.SECONDS), "No changes in open channels"); Collection result = shell.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(17L)); - assertFalse("Channel close timeout", result.contains(ClientChannelEvent.TIMEOUT)); + assertFalse(result.contains(ClientChannelEvent.TIMEOUT), "Channel close timeout"); Integer status = shell.getExitStatus(); - assertNotNull("No exit status", status); - assertEquals("Bad exit status", 0, status.intValue()); + assertNotNull(status, "No exit status"); + assertEquals(0, status.intValue(), "Bad exit status"); } finally { client.stop(); } - assertTrue("No changes in closed channels", channelListener.waitForClosedChannelsChange(5L, TimeUnit.SECONDS)); - assertTrue("Still activated server side channels", GenericUtils.isEmpty(channelListener.getActiveChannels())); + assertTrue(channelListener.waitForClosedChannelsChange(5L, TimeUnit.SECONDS), "No changes in closed channels"); + assertTrue(GenericUtils.isEmpty(channelListener.getActiveChannels()), "Still activated server side channels"); Environment cmdEnv = envHolder.get(); - assertNotNull("No environment set", cmdEnv); + assertNotNull(cmdEnv, "No environment set"); Map vars = cmdEnv.getEnv(); - assertTrue("Mismatched vars count", MapEntryUtils.size(vars) >= MapEntryUtils.size(expected)); + assertTrue(MapEntryUtils.size(vars) >= MapEntryUtils.size(expected), "Mismatched vars count"); expected.forEach((key, expValue) -> { String actValue = vars.get(key); - assertEquals("Mismatched value for " + key, expValue, actValue); + assertEquals(expValue, actValue, "Mismatched value for " + key); }); } - @Test // see SSHD-611 - public void testImmediateAuthFailureOpcode() throws Exception { + // see SSHD-611 + @Test + void immediateAuthFailureOpcode() throws Exception { sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE); sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE); AtomicInteger challengeCount = new AtomicInteger(0); @@ -838,16 +848,16 @@ public boolean authenticate( try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()) .verify(CONNECT_TIMEOUT).getSession()) { AuthFuture auth = session.auth(); - assertTrue("Failed to complete authentication on time", auth.await(CLOSE_TIMEOUT)); - assertFalse("Unexpected authentication success", auth.isSuccess()); - assertEquals("Mismatched interactive challenge calls", 1, challengeCount.get()); + assertTrue(auth.await(CLOSE_TIMEOUT), "Failed to complete authentication on time"); + assertFalse(auth.isSuccess(), "Unexpected authentication success"); + assertEquals(1, challengeCount.get(), "Mismatched interactive challenge calls"); } finally { client.stop(); } } @Test - public void testMaxKeyboardInteractiveTrialsSetting() throws Exception { + void maxKeyboardInteractiveTrialsSetting() throws Exception { sshd.setPasswordAuthenticator(RejectAllPasswordAuthenticator.INSTANCE); sshd.setPublickeyAuthenticator(RejectAllPublickeyAuthenticator.INSTANCE); @@ -909,19 +919,19 @@ public String getUpdatedPassword(ClientSession session, String prompt, String la try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, sshd.getPort()) .verify(CONNECT_TIMEOUT).getSession()) { AuthFuture auth = session.auth(); - assertTrue("Failed to complete authentication on time", auth.await(AUTH_TIMEOUT)); - assertFalse("Unexpected authentication success", auth.isSuccess()); - assertEquals("Mismatched interactive server challenge calls", - CoreModuleProperties.PASSWORD_PROMPTS.getRequiredDefault().intValue(), serverCount.get()); - assertEquals("Mismatched interactive client challenge calls", - CoreModuleProperties.PASSWORD_PROMPTS.getRequiredDefault().intValue(), clientCount.get()); + assertTrue(auth.await(AUTH_TIMEOUT), "Failed to complete authentication on time"); + assertFalse(auth.isSuccess(), "Unexpected authentication success"); + assertEquals(CoreModuleProperties.PASSWORD_PROMPTS.getRequiredDefault().intValue(), serverCount.get(), + "Mismatched interactive server challenge calls"); + assertEquals(CoreModuleProperties.PASSWORD_PROMPTS.getRequiredDefault().intValue(), clientCount.get(), + "Mismatched interactive client challenge calls"); } finally { client.stop(); } } @Test - public void testIdentificationStringsOverrides() throws Exception { + void identificationStringsOverrides() throws Exception { String clientIdent = getCurrentTestName() + "-client"; CoreModuleProperties.CLIENT_IDENTIFICATION.set(client, clientIdent); String expClientIdent = SessionContext.DEFAULT_SSH_VERSION_PREFIX + clientIdent; @@ -937,8 +947,8 @@ public void sessionException(Session session, Throwable t) { @Override public void sessionEvent(Session session, Event event) { if (Event.KexCompleted.equals(event)) { - assertEquals("Mismatched client listener identification", expClientIdent, session.getClientVersion()); - assertEquals("Mismatched server listener identification", expServerIdent, session.getServerVersion()); + assertEquals(expClientIdent, session.getClientVersion(), "Mismatched client listener identification"); + assertEquals(expServerIdent, session.getServerVersion(), "Mismatched server listener identification"); } } @@ -965,15 +975,16 @@ public String toString() { client.start(); try (ClientSession session = createTestClientSession(sshd)) { - assertEquals("Mismatched client identification", expClientIdent, session.getClientVersion()); - assertEquals("Mismatched server identification", expServerIdent, session.getServerVersion()); + assertEquals(expClientIdent, session.getClientVersion(), "Mismatched client identification"); + assertEquals(expServerIdent, session.getServerVersion(), "Mismatched server identification"); } finally { client.stop(); } } - @Test // see SSHD-659 - public void testMultiLineServerIdentification() throws Exception { + // see SSHD-659 + @Test + void multiLineServerIdentification() throws Exception { List expected = Arrays.asList( getClass().getPackage().getName(), getClass().getSimpleName(), @@ -987,7 +998,7 @@ public void testMultiLineServerIdentification() throws Exception { client.setUserInteraction(new UserInteraction() { @Override public void serverVersionInfo(ClientSession session, List lines) { - assertNull("Unexpected extra call", actualHolder.getAndSet(lines)); + assertNull(actualHolder.getAndSet(lines), "Unexpected extra call"); signal.release(); } @@ -1010,18 +1021,19 @@ public String getUpdatedPassword(ClientSession session, String prompt, String la client.start(); try (ClientSession session = createTestClientSession(sshd)) { - assertTrue("No signal received in time", signal.tryAcquire(11L, TimeUnit.SECONDS)); + assertTrue(signal.tryAcquire(11L, TimeUnit.SECONDS), "No signal received in time"); } finally { client.stop(); } List actual = actualHolder.get(); - assertNotNull("Information not signalled", actual); + assertNotNull(actual, "Information not signalled"); assertListEquals("Server information", expected, actual); } - @Test // see SSHD-930 - public void testDelayClientIdentification() throws Exception { + // see SSHD-930 + @Test + void delayClientIdentification() throws Exception { sshd.start(); CoreModuleProperties.SEND_IMMEDIATE_IDENTIFICATION.set(client, false); @@ -1044,7 +1056,7 @@ public void sessionPeerIdentificationReceived(Session session, String version, L try (ClientSession session = createTestClientSession(sshd)) { String version = peerVersion.getAndSet(null); - assertTrue("Peer version not signalled", GenericUtils.isNotEmpty(version)); + assertTrue(GenericUtils.isNotEmpty(version), "Peer version not signalled"); } finally { client.stop(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/SshServerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/SshServerTest.java index a683afb10..f29de1df3 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/SshServerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/SshServerTest.java @@ -22,22 +22,26 @@ import java.util.concurrent.ScheduledExecutorService; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Kohsuke Kawaguchi * @author Michael Heemskerk */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SshServerTest extends BaseTestSupport { public SshServerTest() { super(); } @Test - public void stopMethodShouldBeIdempotent() throws Exception { + void stopMethodShouldBeIdempotent() throws Exception { try (SshServer sshd = new SshServer()) { sshd.stop(); sshd.stop(); @@ -46,7 +50,7 @@ public void stopMethodShouldBeIdempotent() throws Exception { } @Test - public void testExecutorShutdownFalse() throws Exception { + void executorShutdownFalse() throws Exception { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); try (SshServer sshd = setupTestServer()) { @@ -61,7 +65,7 @@ public void testExecutorShutdownFalse() throws Exception { } @Test - public void testExecutorShutdownTrue() throws Exception { + void executorShutdownTrue() throws Exception { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); try (SshServer sshd = setupTestServer()) { @@ -75,7 +79,7 @@ public void testExecutorShutdownTrue() throws Exception { } @Test - public void testDynamicPort() throws Exception { + void dynamicPort() throws Exception { try (SshServer sshd = setupTestServer()) { sshd.setHost(TEST_LOCALHOST); sshd.start(); diff --git a/sshd-core/src/test/java/org/apache/sshd/server/StandardEnvironmentTest.java b/sshd-core/src/test/java/org/apache/sshd/server/StandardEnvironmentTest.java index 7b18a770d..69174f126 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/StandardEnvironmentTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/StandardEnvironmentTest.java @@ -23,24 +23,25 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class StandardEnvironmentTest extends BaseTestSupport { public StandardEnvironmentTest() { super(); } @Test - public void testAddSignalListenerOnDuplicateSignals() { + void addSignalListenerOnDuplicateSignals() { StandardEnvironment environ = new StandardEnvironment(); SignalListener listener = (channel, signal) -> { // ignored @@ -50,7 +51,7 @@ public void testAddSignalListenerOnDuplicateSignals() { environ.addSignalListener(listener, s, s, s, s, s, s); Collection ls = environ.getSignalListeners(s, false); - assertEquals("Mismatched registered listeners count for signal=" + s, 1, GenericUtils.size(ls)); + assertEquals(1, GenericUtils.size(ls), "Mismatched registered listeners count for signal=" + s); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthInteractiveTest.java b/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthInteractiveTest.java index 1bc441a66..6af312fc3 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthInteractiveTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthInteractiveTest.java @@ -25,21 +25,21 @@ import com.jcraft.jsch.UserInfo; import org.apache.sshd.common.channel.Channel; import org.apache.sshd.util.test.JSchLogger; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class AsyncAuthInteractiveTest extends AsyncAuthTestBase { public AsyncAuthInteractiveTest() { super(); } - @BeforeClass - public static void jschInit() { + @BeforeAll + static void jschInit() { JSchLogger.init(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthTest.java b/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthTest.java index 9df0717cf..ba367066f 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthTest.java @@ -25,21 +25,21 @@ import com.jcraft.jsch.UserInfo; import org.apache.sshd.common.channel.Channel; import org.apache.sshd.util.test.JSchLogger; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class AsyncAuthTest extends AsyncAuthTestBase { public AsyncAuthTest() { super(); } - @BeforeClass - public static void jschInit() { + @BeforeAll + static void jschInit() { JSchLogger.init(); } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthTestBase.java b/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthTestBase.java index 46286ec45..d29b4aa28 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthTestBase.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/auth/AsyncAuthTestBase.java @@ -30,8 +30,12 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; import org.apache.sshd.util.test.EchoShellFactory; -import org.junit.After; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project @@ -69,7 +73,7 @@ public void startServer(Duration timeout) throws Exception { port = server.getPort(); } - @After + @AfterEach public void stopServer() throws Exception { if (server != null) { server.stop(); @@ -78,52 +82,52 @@ public void stopServer() throws Exception { } @Test - public void testSyncAuthFailed() throws Exception { + public void syncAuthFailed() throws Exception { startServer(); authenticator = (username, x, sess) -> false; assertFalse(authenticate()); } @Test - public void testSyncAuthSucceeded() throws Exception { + public void syncAuthSucceeded() throws Exception { startServer(); authenticator = (username, x, sess) -> true; assertTrue(authenticate()); } @Test - public void testAsyncAuthFailed() throws Exception { + public void asyncAuthFailed() throws Exception { startServer(); authenticator = (username, x, sess) -> async(200, false); assertFalse(authenticate()); } @Test - public void testAsyncAuthSucceeded() throws Exception { + public void asyncAuthSucceeded() throws Exception { startServer(); authenticator = (username, x, sess) -> async(200, true); assertTrue(authenticate()); } @Test - public void testAsyncAuthTimeout() throws Exception { + public void asyncAuthTimeout() throws Exception { startServer(Duration.ofMillis(500)); authenticator = (username, x, sess) -> asyncTimeout(); try { authenticate(); } catch (JSchException e) { - assertTrue("Unexpected failure " + e.getMessage(), e.getMessage().startsWith("SSH_MSG_DISCONNECT")); + assertTrue(e.getMessage().startsWith("SSH_MSG_DISCONNECT"), "Unexpected failure " + e.getMessage()); } } @Test - public void testAsyncAuthSucceededAfterTimeout() throws Exception { + public void asyncAuthSucceededAfterTimeout() throws Exception { startServer(Duration.ofMillis(500)); authenticator = (username, x, sess) -> async(1000, true); try { authenticate(); } catch (JSchException e) { - assertTrue("Unexpected failure " + e.getMessage(), e.getMessage().startsWith("SSH_MSG_DISCONNECT")); + assertTrue(e.getMessage().startsWith("SSH_MSG_DISCONNECT"), "Unexpected failure " + e.getMessage()); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/auth/BuiltinUserAuthFactoriesTest.java b/sshd-core/src/test/java/org/apache/sshd/server/auth/BuiltinUserAuthFactoriesTest.java index 0f575b201..1600b788d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/auth/BuiltinUserAuthFactoriesTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/auth/BuiltinUserAuthFactoriesTest.java @@ -30,39 +30,36 @@ import org.apache.sshd.server.auth.BuiltinUserAuthFactories.ParseResult; import org.apache.sshd.server.auth.gss.UserAuthGSSFactory; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class BuiltinUserAuthFactoriesTest extends BaseTestSupport { - private final BuiltinUserAuthFactories factory; + private BuiltinUserAuthFactories factory; - public BuiltinUserAuthFactoriesTest(BuiltinUserAuthFactories factory) { + public void initBuiltinUserAuthFactoriesTest(BuiltinUserAuthFactories factory) { this.factory = factory; } - @Parameters(name = "Factory={0}") public static Collection parameters() { return parameterize(BuiltinUserAuthFactories.VALUES); } - @BeforeClass - public static void testAllConstantsCovered() throws Exception { + @BeforeAll + static void testAllConstantsCovered() throws Exception { Field[] fields = UserAuthMethodFactory.class.getDeclaredFields(); Collection factories = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); @@ -82,43 +79,50 @@ public static void testAllConstantsCovered() throws Exception { continue; } - assertTrue("Duplicate factory name constant: " + name, factories.add(name)); + assertTrue(factories.add(name), "Duplicate factory name constant: " + name); } - assertTrue("Unexpected GSS name constant", factories.add(UserAuthGSSFactory.NAME)); - assertEquals("Mismatched factories names count: " + factories, factories.size(), - BuiltinUserAuthFactories.VALUES.size()); + assertTrue(factories.add(UserAuthGSSFactory.NAME), "Unexpected GSS name constant"); + assertEquals(factories.size(), + BuiltinUserAuthFactories.VALUES.size(), + "Mismatched factories names count: " + factories); } - @Test - public void testSingletonFactoryInstance() { + @MethodSource("parameters") + @ParameterizedTest(name = "Factory={0}") + public void singletonFactoryInstance(BuiltinUserAuthFactories factory) { + initBuiltinUserAuthFactoriesTest(factory); UserAuthFactory expected = factory.create(); for (int index = 1; index <= Byte.SIZE; index++) { - assertSame("Mismatched factory instance at invocation #" + index, expected, factory.create()); + assertSame(expected, factory.create(), "Mismatched factory instance at invocation #" + index); } } - @Test - public void testFromFactoryName() { + @MethodSource("parameters") + @ParameterizedTest(name = "Factory={0}") + public void fromFactoryName(BuiltinUserAuthFactories factory) { + initBuiltinUserAuthFactoriesTest(factory); String name = factory.getName(); UserAuthFactory expected = factory.create(); for (int index = 1, count = name.length(); index <= count; index++) { UserAuthFactory actual = BuiltinUserAuthFactories.fromFactoryName(name); - assertSame("Mismatched factory instance for name=" + name, expected, actual); + assertSame(expected, actual, "Mismatched factory instance for name=" + name); name = shuffleCase(name); // prepare for next iteration } } - @Test - public void testParseResult() { + @MethodSource("parameters") + @ParameterizedTest(name = "Factory={0}") + public void parseResult(BuiltinUserAuthFactories factory) { + initBuiltinUserAuthFactoriesTest(factory); ParseResult result = BuiltinUserAuthFactories.parseFactoriesList(factory.getName()); - assertNotNull("No parse result", result); + assertNotNull(result, "No parse result"); List parsed = result.getParsedFactories(); - assertEquals("Mismatched parsed count", 1, GenericUtils.size(parsed)); - assertSame("Mismatched parsed factory instance", factory.create(), parsed.get(0)); + assertEquals(1, GenericUtils.size(parsed), "Mismatched parsed count"); + assertSame(factory.create(), parsed.get(0), "Mismatched parsed factory instance"); Collection unsupported = result.getUnsupportedFactories(); - assertTrue("Unexpected unsupported values: " + unsupported, GenericUtils.isEmpty(unsupported)); + assertTrue(GenericUtils.isEmpty(unsupported), "Unexpected unsupported values: " + unsupported); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/auth/WelcomeBannerPhaseTest.java b/sshd-core/src/test/java/org/apache/sshd/server/auth/WelcomeBannerPhaseTest.java index 2ff9700c6..9eb37792c 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/auth/WelcomeBannerPhaseTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/auth/WelcomeBannerPhaseTest.java @@ -30,23 +30,20 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class WelcomeBannerPhaseTest extends BaseTestSupport { private static SshServer sshd; @@ -55,17 +52,16 @@ public class WelcomeBannerPhaseTest extends BaseTestSupport { private WelcomeBannerPhase phase; - public WelcomeBannerPhaseTest(WelcomeBannerPhase phase) { + public void initWelcomeBannerPhaseTest(WelcomeBannerPhase phase) { this.phase = phase; } - @Parameters(name = "{0}") public static List parameters() { return parameterize(WelcomeBannerPhase.VALUES); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(WelcomeBannerPhaseTest.class); sshd.start(); port = sshd.getPort(); @@ -74,8 +70,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -93,8 +89,10 @@ public static void tearDownClientAndServer() throws Exception { } } - @Test - public void testWelcomeBannerPhase() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void welcomeBannerPhase(WelcomeBannerPhase phase) throws Exception { + initWelcomeBannerPhaseTest(phase); CoreModuleProperties.WELCOME_BANNER_PHASE.set(sshd, phase); CoreModuleProperties.WELCOME_BANNER.set(sshd, phase.name()); @@ -107,7 +105,7 @@ public boolean isInteractionAllowed(ClientSession session) { @Override public void welcome(ClientSession session, String banner, String lang) { - assertNull("Multiple banner invocations", welcomeHolder.getAndSet(banner)); + assertNull(welcomeHolder.getAndSet(banner), "Multiple banner invocations"); } @Override @@ -132,11 +130,11 @@ public String[] interactive( Object banner = welcomeHolder.getAndSet(null); if (WelcomeBannerPhase.NEVER.equals(phase)) { - assertNull("Unexpected banner", banner); + assertNull(banner, "Unexpected banner"); } else { WelcomeBannerPhase value = PropertyResolverUtils.toEnum(WelcomeBannerPhase.class, banner, false, WelcomeBannerPhase.VALUES); - assertSame("Mismatched banner value", phase, value); + assertSame(phase, value, "Mismatched banner value"); } } } 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 3dcb26bfe..9374505d8 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 @@ -39,16 +39,22 @@ import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.AfterClass; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class WelcomeBannerTest extends BaseTestSupport { private static SshServer sshd; @@ -59,8 +65,8 @@ public WelcomeBannerTest() { super(); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { sshd = CoreTestSupportUtils.setupTestServer(WelcomeBannerTest.class); sshd.start(); port = sshd.getPort(); @@ -69,8 +75,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -89,41 +95,42 @@ public static void tearDownClientAndServer() throws Exception { } @Test - public void testSimpleBanner() throws Exception { + void simpleBanner() throws Exception { String expectedWelcome = "Welcome to SSHD WelcomeBannerTest"; CoreModuleProperties.WELCOME_BANNER.set(sshd, expectedWelcome); testBanner(expectedWelcome); } - @Test // see SSHD-686 - public void testAutoGeneratedBanner() throws Exception { + // see SSHD-686 + @Test + void autoGeneratedBanner() throws Exception { KeyPairProvider keys = sshd.getKeyPairProvider(); CoreModuleProperties.WELCOME_BANNER.set(sshd, CoreModuleProperties.AUTO_WELCOME_BANNER_VALUE); testBanner(KeyRandomArt.combine(null, ' ', keys)); } @Test - public void testPathBanner() throws Exception { + void pathBanner() throws Exception { testFileContentBanner(Function.identity()); } @Test - public void testFileBanner() throws Exception { + void fileBanner() throws Exception { testFileContentBanner(Path::toFile); } @Test - public void testURIBanner() throws Exception { + void uriBanner() throws Exception { testFileContentBanner(Path::toUri); } @Test - public void testURIStringBanner() throws Exception { + void uriStringBanner() throws Exception { testFileContentBanner(path -> Objects.toString(path.toUri())); } @Test - public void testURLBanner() throws Exception { + void urlBanner() throws Exception { testFileContentBanner(path -> { try { return path.toUri().toURL(); @@ -134,28 +141,29 @@ public void testURLBanner() throws Exception { } @Test - public void testFileNotExistsBanner() throws Exception { + void fileNotExistsBanner() throws Exception { Path dir = getTempTargetRelativeFile(getClass().getSimpleName()); Path file = assertHierarchyTargetFolderExists(dir).resolve(getCurrentTestName() + ".txt"); Files.deleteIfExists(file); - assertFalse("Banner file not deleted: " + file, Files.exists(file)); + assertFalse(Files.exists(file), "Banner file not deleted: " + file); CoreModuleProperties.WELCOME_BANNER.set(sshd, file); testBanner(null); } @Test - public void testEmptyFileBanner() throws Exception { + void emptyFileBanner() throws Exception { Path dir = getTempTargetRelativeFile(getClass().getSimpleName()); Path file = assertHierarchyTargetFolderExists(dir).resolve(getCurrentTestName() + ".txt"); Files.deleteIfExists(file); Files.write(file, GenericUtils.EMPTY_BYTE_ARRAY); - assertTrue("Empty file not created: " + file, Files.exists(file)); + assertTrue(Files.exists(file), "Empty file not created: " + file); CoreModuleProperties.WELCOME_BANNER.set(sshd, file); testBanner(null); } - @Test // see SSHD-695 - public void testWelcomeBannerBeforeAuthBegins() throws Exception { + // see SSHD-695 + @Test + void welcomeBannerBeforeAuthBegins() throws Exception { UserInteraction ui = client.getUserInteraction(); try { Semaphore sigSem = new Semaphore(0); @@ -187,8 +195,8 @@ public String getUpdatedPassword(ClientSession session, String prompt, String la try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port) .verify(CONNECT_TIMEOUT) .getSession()) { - assertTrue("Welcome not signalled on time", - sigSem.tryAcquire(DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS)); + assertTrue(sigSem.tryAcquire(DEFAULT_TIMEOUT.toMillis(), TimeUnit.MILLISECONDS), + "Welcome not signalled on time"); session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); } @@ -228,7 +236,7 @@ public void serverVersionInfo(ClientSession session, List lines) { @Override public void welcome(ClientSession session, String banner, String lang) { validateSession("welcome", session); - assertNull("Multiple banner invocations", welcomeHolder.getAndSet(banner)); + assertNull(welcomeHolder.getAndSet(banner), "Multiple banner invocations"); } @Override @@ -247,7 +255,7 @@ public String getUpdatedPassword(ClientSession clientSession, String prompt, Str private void validateSession(String phase, ClientSession session) { ClientSession prev = sessionHolder.getAndSet(session); if (prev != null) { - assertSame("Mismatched " + phase + " client session", prev, session); + assertSame(prev, session, "Mismatched " + phase + " client session"); } } }); @@ -257,14 +265,14 @@ private void validateSession(String phase, ClientSession session) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); if (expectedWelcome != null) { - assertSame("Mismatched sessions", session, sessionHolder.get()); + assertSame(session, sessionHolder.get(), "Mismatched sessions"); } else { - assertNull("Unexpected session", sessionHolder.get()); + assertNull(sessionHolder.get(), "Unexpected session"); } } } finally { client.setUserInteraction(ui); } - assertEquals("Mismatched banner", expectedWelcome, welcomeHolder.get()); + assertEquals(expectedWelcome, welcomeHolder.get(), "Mismatched banner"); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/channel/ChannelSessionTest.java b/sshd-core/src/test/java/org/apache/sshd/server/channel/ChannelSessionTest.java index 538de04ff..d16d5d773 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/channel/ChannelSessionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/channel/ChannelSessionTest.java @@ -44,14 +44,16 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.BogusChannel; import org.apache.sshd.util.test.CommandExecutionHelper; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ChannelSessionTest extends BaseTestSupport { public ChannelSessionTest() { super(); @@ -60,8 +62,9 @@ public ChannelSessionTest() { /* * Testing a command closing output stream when it completes */ - @Test // see SSHD-1257 - public void closeOutputStream() throws Exception { + // see SSHD-1257 + @Test + void closeOutputStream() throws Exception { try (SshServer server = setupTestServer(); SshClient client = setupTestClient()) { @@ -97,15 +100,15 @@ protected boolean handleCommandLine(String command) throws Exception { Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(11L)); long waitEnd = System.currentTimeMillis(); - assertTrue("Wrong channel state after " + (waitEnd - waitStart) + " ms.: " + result, - result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED))); + assertTrue(result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)), + "Wrong channel state after " + (waitEnd - waitStart) + " ms.: " + result); byte[] b = new byte[1024]; InputStream invertedOut = channel.getInvertedOut(); int l = invertedOut.read(b); String cmdReceived = (l > 0) ? new String(b, 0, l) : ""; - assertEquals("Mismatched echoed command", cmdSent, cmdReceived); + assertEquals(cmdSent, cmdReceived, "Mismatched echoed command"); } } } @@ -128,21 +131,21 @@ private void chainedCommands(ClientSession session) throws Exception { long waitStart = System.currentTimeMillis(); Collection result = second.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), 10_000); long waitEnd = System.currentTimeMillis(); - assertTrue("Wrong channel state after " + (waitEnd - waitStart) + " ms.: " + result, - result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED))); + assertTrue(result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)), + "Wrong channel state after " + (waitEnd - waitStart) + " ms.: " + result); // Read from the second command's stdout and check the result. try (InputStream invertedOut = second.getInvertedOut()) { byte[] b = new byte[1024]; int l = invertedOut.read(b); String cmdReceived = (l > 0) ? new String(b, 0, l) : ""; - assertEquals("Mismatched echoed command", cmdSent, cmdReceived); + assertEquals(cmdSent, cmdReceived, "Mismatched echoed command"); } } } } @Test - public void pipedInputStream() throws Exception { + void pipedInputStream() throws Exception { try (SshServer server = setupTestServer(); SshClient client = setupTestClient()) { @@ -167,7 +170,7 @@ protected boolean handleCommandLine(String command) throws Exception { } @Test - public void testNoFlush() throws Exception { + void noFlush() throws Exception { try (SshServer server = setupTestServer(); SshClient client = setupTestClient()) { @@ -199,15 +202,15 @@ protected boolean handleCommandLine(String command) throws Exception { Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.SECONDS.toMillis(11L)); long waitEnd = System.currentTimeMillis(); - assertTrue("Wrong channel state after " + (waitEnd - waitStart) + " ms.: " + result, - result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED))); + assertTrue(result.containsAll(EnumSet.of(ClientChannelEvent.CLOSED)), + "Wrong channel state after " + (waitEnd - waitStart) + " ms.: " + result); byte[] b = new byte[1024]; InputStream invertedOut = channel.getInvertedOut(); int l = invertedOut.read(b); String cmdReceived = (l > 0) ? new String(b, 0, l) : ""; - assertEquals("Mismatched echoed command", cmdSent, cmdReceived); + assertEquals(cmdSent, cmdReceived, "Mismatched echoed command"); } } } @@ -217,7 +220,7 @@ protected boolean handleCommandLine(String command) throws Exception { * Test whether onWindowExpanded is called from server session */ @Test - public void testHandleWindowAdjust() throws Exception { + void handleWindowAdjust() throws Exception { Buffer buffer = new ByteArrayBuffer(); buffer.putUInt(1234L); @@ -236,26 +239,28 @@ public void onWindowExpanded() throws IOException { } }; channelSession.handleWindowAdjust(buffer); - assertTrue("Expanded ?", expanded.get()); + assertTrue(expanded.get(), "Expanded ?"); } } - @Test // see SSHD-652 - public void testCloseFutureListenerRegistration() throws Exception { + // see SSHD-652 + @Test + void closeFutureListenerRegistration() throws Exception { AtomicInteger closeCount = new AtomicInteger(); try (ChannelSession session = new ChannelSession()) { session.addCloseFutureListener(future -> { - assertTrue("Future not marted as closed", future.isClosed()); - assertEquals("Unexpected multiple call to callback", 1, closeCount.incrementAndGet()); + assertTrue(future.isClosed(), "Future not marted as closed"); + assertEquals(1, closeCount.incrementAndGet(), "Unexpected multiple call to callback"); }); session.close(); } - assertEquals("Close listener not called", 1, closeCount.get()); + assertEquals(1, closeCount.get(), "Close listener not called"); } - @Test // SSHD-1244 - public void testLargeWindowSizeAdjust() throws Exception { + // SSHD-1244 + @Test + void largeWindowSizeAdjust() throws Exception { try (ChannelSession session = new ChannelSession() { { RemoteWindow wRemote = getRemoteWindow(); @@ -264,14 +269,14 @@ public void testLargeWindowSizeAdjust() throws Exception { }) { RemoteWindow wRemote = session.getRemoteWindow(); long initialSize = wRemote.getSize(); - assertEquals("Bad initial window size", 1024, initialSize); + assertEquals(1024, initialSize, "Bad initial window size"); Buffer buffer = new ByteArrayBuffer(); buffer.putUInt(BufferUtils.MAX_UINT32_VALUE); session.handleWindowAdjust(buffer); long updatedSize = wRemote.getSize(); - assertEquals("Mismatched updated window size", BufferUtils.MAX_UINT32_VALUE, updatedSize); + assertEquals(BufferUtils.MAX_UINT32_VALUE, updatedSize, "Mismatched updated window size"); } } } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/command/CommandFactorySplitterTest.java b/sshd-core/src/test/java/org/apache/sshd/server/command/CommandFactorySplitterTest.java index 2a72fa643..5cddd4488 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/command/CommandFactorySplitterTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/command/CommandFactorySplitterTest.java @@ -24,35 +24,27 @@ import java.util.Collections; import java.util.List; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class CommandFactorySplitterTest extends JUnitTestSupport { - private final String command; - private final List expected; + private String command; + private List expected; - public CommandFactorySplitterTest(String command, List expected) { + public void initCommandFactorySplitterTest(String command, List expected) { this.command = command; this.expected = expected; } - @Parameters(name = "cmd={0}") public static List parameters() { return new ArrayList() { // not serializing it @@ -84,8 +76,10 @@ private void addTestCase(String cmd, List elems) { }; } - @Test - public void testSplitter() { + @MethodSource("parameters") + @ParameterizedTest(name = "cmd={0}") + public void splitter(String command, List expected) { + initCommandFactorySplitterTest(command, expected); List actual = CommandFactory.split(command); assertListEquals(command, expected, actual); } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java index 533a2f28b..0c43ed9fd 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java @@ -39,22 +39,27 @@ import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.apache.sshd.server.session.ServerSession; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class AuthorizedKeysAuthenticatorTest extends AuthorizedKeysTestSupport { public AuthorizedKeysAuthenticatorTest() { super(); } @Test - public void testAutomaticReload() throws Exception { + void automaticReload() throws Exception { Path file = getTempTargetRelativeFile(getCurrentTestName()); if (Files.exists(file)) { Files.delete(file); @@ -66,13 +71,13 @@ public void testAutomaticReload() throws Exception { protected Collection reloadAuthorizedKeys( Path path, String username, ServerSession session) throws IOException, GeneralSecurityException { - assertSame("Mismatched reload path", file, path); + assertSame(file, path, "Mismatched reload path"); reloadCount.incrementAndGet(); return super.reloadAuthorizedKeys(path, username, session); } }; - assertFalse("Unexpected authentication success for missing file " + file, - auth.authenticate(getCurrentTestName(), Mockito.mock(PublicKey.class), null)); + assertFalse(auth.authenticate(getCurrentTestName(), Mockito.mock(PublicKey.class), null), + "Unexpected authentication success for missing file " + file); List keyLines = loadDefaultSupportedKeys(); assertHierarchyTargetFolderExists(file.getParent()); @@ -90,31 +95,31 @@ protected Collection reloadAuthorizedKeys( Files.setLastModifiedTime(file, FileTime.from(Instant.now().minusSeconds(4))); List entries = AuthorizedKeyEntry.readAuthorizedKeys(file); - assertEquals("Mismatched number of loaded entries", keyLines.size(), entries.size()); + assertEquals(keyLines.size(), entries.size(), "Mismatched number of loaded entries"); List keySet = PublicKeyEntry.resolvePublicKeyEntries(null, entries, PublicKeyEntryResolver.FAILING); - assertEquals("Mismatched number of loaded keys", entries.size(), keySet.size()); + assertEquals(entries.size(), keySet.size(), "Mismatched number of loaded keys"); reloadCount.set(0); for (int index = 0; index < keySet.size(); index++) { PublicKey k = keySet.get(index); String keyData = keyLines.get(index); // we know they are 1-1 matching - assertTrue("Failed to authenticate with key #" + (index + 1) + " " + k.getAlgorithm() + "[" + keyData - + "] on file=" + file, - auth.authenticate(getCurrentTestName(), k, null)); + assertTrue(auth.authenticate(getCurrentTestName(), k, null), + "Failed to authenticate with key #" + (index + 1) + " " + k.getAlgorithm() + "[" + keyData + + "] on file=" + file); // we expect EXACTLY ONE re-load call since we did not modify the file during the authentication - assertEquals("Unexpected keys re-loading of " + keyLines.size() + " remaining at key #" + (index + 1) - + " on file=" + file, - 1, reloadCount.get()); + assertEquals(1, reloadCount.get(), + "Unexpected keys re-loading of " + keyLines.size() + " remaining at key #" + (index + 1) + + " on file=" + file); } keyLines.remove(0); } - assertTrue("File no longer exists: " + file, Files.exists(file)); - assertFalse("Unexpected authentication success for empty file " + file, - auth.authenticate(getCurrentTestName(), Mockito.mock(PublicKey.class), null)); + assertTrue(Files.exists(file), "File no longer exists: " + file); + assertFalse(auth.authenticate(getCurrentTestName(), Mockito.mock(PublicKey.class), null), + "Unexpected authentication success for empty file " + file); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/DefaultAuthorizedKeysAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/DefaultAuthorizedKeysAuthenticatorTest.java index 3f04b1eb3..eaafe25f2 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/DefaultAuthorizedKeysAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/DefaultAuthorizedKeysAuthenticatorTest.java @@ -30,22 +30,22 @@ import org.apache.sshd.common.util.OsUtils; import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator; import org.apache.sshd.server.session.ServerSession; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class DefaultAuthorizedKeysAuthenticatorTest extends AuthorizedKeysTestSupport { public DefaultAuthorizedKeysAuthenticatorTest() { super(); } @Test - public void testUsernameValidation() throws Exception { + void usernameValidation() throws Exception { Path file = getTempTargetRelativeFile(getCurrentTestName()); writeDefaultSupportedKeys(file); diff --git a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/ServerIdentityTest.java b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/ServerIdentityTest.java index fb57a6dda..f12a5b644 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/ServerIdentityTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/ServerIdentityTest.java @@ -36,24 +36,27 @@ import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.common.util.io.IoUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ServerIdentityTest extends BaseTestSupport { public ServerIdentityTest() { super(); } @Test - public void testLoadServerIdentities() throws Exception { + void loadServerIdentities() throws Exception { Path resFolder = getTestResourcesFolder(); Collection paths = new ArrayList<>(BuiltinIdentities.VALUES.size()); LinkOption[] options = IoUtils.getLinkOptions(true); @@ -79,25 +82,25 @@ public void testLoadServerIdentities() throws Exception { props.setProperty(ServerIdentity.HOST_KEY_CONFIG_PROP, GenericUtils.join(paths, ',')); Map ids = ServerIdentity.loadIdentities(props, options); - assertEquals("Mismatched loaded ids count", GenericUtils.size(paths), MapEntryUtils.size(ids)); + assertEquals(GenericUtils.size(paths), MapEntryUtils.size(ids), "Mismatched loaded ids count"); Collection pairs = new ArrayList<>(ids.size()); for (BuiltinIdentities type : BuiltinIdentities.VALUES) { if (expected.contains(type)) { KeyPair kp = ids.get(type.getName()); - assertNotNull("No key pair loaded for " + type, kp); + assertNotNull(kp, "No key pair loaded for " + type); pairs.add(kp); } } KeyPairProvider provider = IdentityUtils.createKeyPairProvider(ids, true /* supported only */); - assertNotNull("No provider generated", provider); + assertNotNull(provider, "No provider generated"); Iterable keys = provider.loadKeys(null); for (KeyPair kp : keys) { - assertTrue("Unexpected loaded key: " + kp, pairs.remove(kp)); + assertTrue(pairs.remove(kp), "Unexpected loaded key: " + kp); } - assertEquals("Not all pairs listed", 0, pairs.size()); + assertEquals(0, pairs.size(), "Not all pairs listed"); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/forward/ForwardingFilterTest.java b/sshd-core/src/test/java/org/apache/sshd/server/forward/ForwardingFilterTest.java index 3665586e4..5ab1dcb3d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/forward/ForwardingFilterTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/forward/ForwardingFilterTest.java @@ -22,31 +22,34 @@ import org.apache.sshd.common.session.Session; import org.apache.sshd.common.util.net.SshdSocketAddress; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ForwardingFilterTest extends BaseTestSupport { public ForwardingFilterTest() { super(); } @Test - public void testFromStringForwardingFilterType() { + void fromStringForwardingFilterType() { for (String name : new String[] { null, "", getCurrentTestName() }) { - assertNull("Unexpected value for name='" + name + "'", ForwardingFilter.Type.fromString(name)); + assertNull(ForwardingFilter.Type.fromString(name), "Unexpected value for name='" + name + "'"); } for (ForwardingFilter.Type expected : ForwardingFilter.Type.VALUES) { for (String name : new String[] { expected.name(), expected.getName() }) { for (int index = 0; index < name.length(); index++) { ForwardingFilter.Type actual = ForwardingFilter.Type.fromString(name); - assertSame("Mismatched instance for name=" + name, expected, actual); + assertSame(expected, actual, "Mismatched instance for name=" + name); name = shuffleCase(name); // prepare for next iteration } } @@ -54,12 +57,12 @@ public void testFromStringForwardingFilterType() { } @Test - public void testAcceptAllForwardingFilter() { + void acceptAllForwardingFilter() { testStaticDecisionForwardingFilter(AcceptAllForwardingFilter.INSTANCE, true); } @Test - public void testRejectAllForwardingFilter() { + void rejectAllForwardingFilter() { testStaticDecisionForwardingFilter(RejectAllForwardingFilter.INSTANCE, false); } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/jaas/JaasPasswordAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/jaas/JaasPasswordAuthenticatorTest.java index 50fd5f515..d7688d76a 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/jaas/JaasPasswordAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/jaas/JaasPasswordAuthenticatorTest.java @@ -34,28 +34,32 @@ import javax.security.auth.spi.LoginModule; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class JaasPasswordAuthenticatorTest extends BaseTestSupport { public JaasPasswordAuthenticatorTest() { super(); } - @Before - public void setUp() { + @BeforeEach + void setUp() { Configuration config = new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { @@ -75,18 +79,18 @@ public void refresh() { Configuration.setConfiguration(config); } - @After - public void tearDown() { + @AfterEach + void tearDown() { Configuration.setConfiguration(null); } @Test - public void testAuthenticator() { + void authenticator() { JaasPasswordAuthenticator auth = new JaasPasswordAuthenticator(); - assertNull("Unexpected initial domain", auth.getDomain()); + assertNull(auth.getDomain(), "Unexpected initial domain"); auth.setDomain("domain"); - assertEquals("Mismatched domain", "domain", auth.getDomain()); + assertEquals("domain", auth.getDomain(), "Mismatched domain"); assertTrue(auth.authenticate("sshd", "sshd", null)); assertFalse(auth.authenticate("sshd", "dummy", null)); diff --git a/sshd-core/src/test/java/org/apache/sshd/server/kex/ModuliTest.java b/sshd-core/src/test/java/org/apache/sshd/server/kex/ModuliTest.java index 128a90831..7ef8e6cea 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/kex/ModuliTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/kex/ModuliTest.java @@ -31,62 +31,65 @@ import org.apache.sshd.common.util.security.SecurityUtils; import org.apache.sshd.server.kex.Moduli.DhGroup; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ModuliTest extends JUnitTestSupport { public ModuliTest() { super(); } - @BeforeClass - @AfterClass - public static void clearInternalModuliCache() { + @BeforeAll + @AfterAll + static void clearInternalModuliCache() { Moduli.clearInternalModuliCache(); } - @Before - @After - public void clearCache() { + @BeforeEach + @AfterEach + void clearCache() { clearInternalModuliCache(); } @Test - public void testLoadInternalModuli() throws IOException { + void loadInternalModuli() throws IOException { URL moduli = getClass().getResource(Moduli.INTERNAL_MODULI_RESPATH); - assertNotNull("Missing internal moduli resource", moduli); + assertNotNull(moduli, "Missing internal moduli resource"); List expected = Moduli.loadInternalModuli(moduli); - assertTrue("No moduli groups parsed", GenericUtils.isNotEmpty(expected)); + assertTrue(GenericUtils.isNotEmpty(expected), "No moduli groups parsed"); for (int index = 1; index <= Byte.SIZE; index++) { List actual = Moduli.loadInternalModuli(moduli); - assertSame("Mismatched cached instance at retry #" + index, expected, actual); + assertSame(expected, actual, "Mismatched cached instance at retry #" + index); } } @Test - public void testKeySizesCoverage() throws IOException { + void keySizesCoverage() throws IOException { URL moduli = getClass().getResource(Moduli.INTERNAL_MODULI_RESPATH); List groups = Moduli.loadInternalModuli(moduli); Collection actualSizes = new TreeSet<>(Comparator.naturalOrder()); for (DhGroup g : groups) { int size = g.getSize(); // SSHD-1108 - raised default minimum to 2048... - assertTrue("Size below min. required " + 1024 + ": " + size, size >= 1024); - assertTrue("Size above max. allowed " + SecurityUtils.MAX_DHGEX_KEY_SIZE, size <= SecurityUtils.MAX_DHGEX_KEY_SIZE); + assertTrue(size >= 1024, "Size below min. required " + 1024 + ": " + size); + assertTrue(size <= SecurityUtils.MAX_DHGEX_KEY_SIZE, "Size above max. allowed " + SecurityUtils.MAX_DHGEX_KEY_SIZE); actualSizes.add(size); } diff --git a/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java b/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java index 1a600d77b..f8960926e 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java @@ -33,22 +33,23 @@ import org.apache.sshd.util.test.BogusEnvironment; import org.apache.sshd.util.test.BogusExitCallback; import org.apache.sshd.util.test.BogusInvertedShell; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +import static org.junit.jupiter.api.Assertions.assertEquals; + +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class InvertedShellWrapperTest extends BaseTestSupport { public InvertedShellWrapperTest() { super(); } @Test - public void testStreamsAreFlushedBeforeClosing() throws Exception { + void streamsAreFlushedBeforeClosing() throws Exception { BogusInvertedShell shell = newShell("out", "err"); shell.setAlive(false); @@ -68,17 +69,18 @@ public void testStreamsAreFlushedBeforeClosing() throws Exception { wrapper.pumpStreams(); // check the streams were flushed before exiting - assertEquals("stdin", "in", shell.getInputStream().toString()); - assertEquals("stdout", "out", out.toString()); - assertEquals("stderr", "err", err.toString()); + assertEquals("in", shell.getInputStream().toString(), "stdin"); + assertEquals("out", out.toString(), "stdout"); + assertEquals("err", err.toString(), "stderr"); } finally { wrapper.destroy(channel); } } } - @Test // see SSHD-570 - public void testExceptionWhilePumpStreams() throws Exception { + // see SSHD-570 + @Test + void exceptionWhilePumpStreams() throws Exception { BogusInvertedShell bogusShell = newShell("out", "err"); bogusShell.setAlive(false); @@ -177,13 +179,14 @@ public int available() throws IOException { wrapper.destroy(channel); } - assertEquals("Mismatched exit value", destroyedExitValue, exitCallback.getExitValue()); - assertEquals("Mismatched exit message", EOFException.class.getSimpleName(), exitCallback.getExitMessage()); + assertEquals(destroyedExitValue, exitCallback.getExitValue(), "Mismatched exit value"); + assertEquals(EOFException.class.getSimpleName(), exitCallback.getExitMessage(), "Mismatched exit message"); } } - @Test // see SSHD-576 - public void testShellDiesBeforeAllDataExhausted() throws Exception { + // see SSHD-576 + @Test + void shellDiesBeforeAllDataExhausted() throws Exception { final String inputContent = "shellInput"; final String outputContent = "shellOutput"; final String errorContent = "shellError"; @@ -271,9 +274,9 @@ public void destroy(ChannelSession channel) { wrapper.destroy(channel); } - assertEquals("Mismatched STDIN value", inputContent, shellIn.toString(StandardCharsets.UTF_8.name())); - assertEquals("Mismatched STDOUT value", outputContent, stdout.toString(StandardCharsets.UTF_8.name())); - assertEquals("Mismatched STDERR value", errorContent, stderr.toString(StandardCharsets.UTF_8.name())); + assertEquals(inputContent, shellIn.toString(StandardCharsets.UTF_8.name()), "Mismatched STDIN value"); + assertEquals(outputContent, stdout.toString(StandardCharsets.UTF_8.name()), "Mismatched STDOUT value"); + assertEquals(errorContent, stderr.toString(StandardCharsets.UTF_8.name()), "Mismatched STDERR value"); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java b/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java index 31b908016..3f8173293 100644 --- a/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java @@ -30,12 +30,12 @@ import org.apache.sshd.util.test.CoreTestSupportUtils; import org.apache.sshd.util.test.JSchLogger; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.After; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.springframework.context.support.ClassPathXmlApplicationContext; /** @@ -43,7 +43,7 @@ * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SpringConfigTest extends BaseTestSupport { private ClassPathXmlApplicationContext context; @@ -52,28 +52,28 @@ public SpringConfigTest() { super(); } - @BeforeClass - public static void jschInit() { + @BeforeAll + static void jschInit() { JSchLogger.init(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { Class clazz = getClass(); Package pkg = clazz.getPackage(); context = new ClassPathXmlApplicationContext( "classpath:" + pkg.getName().replace('.', '/') + "/" + clazz.getSimpleName() + ".xml"); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (context != null) { context.close(); } } @Test - public void testSpringConfig() throws Exception { + void springConfig() throws Exception { SshServer server = CoreTestSupportUtils.setupTestFullSupportServer(context.getBean(SshServer.class)); int port = server.getPort(); diff --git a/sshd-core/src/test/java/org/apache/sshd/util/test/BaseTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/util/test/BaseTestSupport.java index 9400ddb0c..9124edb00 100644 --- a/sshd-core/src/test/java/org/apache/sshd/util/test/BaseTestSupport.java +++ b/sshd-core/src/test/java/org/apache/sshd/util/test/BaseTestSupport.java @@ -31,16 +31,19 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.net.SshdSocketAddress; import org.apache.sshd.server.SshServer; -import org.junit.Assume; -import org.junit.Rule; -import org.junit.rules.TestWatcher; -import org.junit.runner.Description; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.extension.AfterEachCallback; +import org.junit.jupiter.api.extension.BeforeEachCallback; +import org.junit.jupiter.api.extension.ExtendWith; +import org.junit.jupiter.api.extension.ExtensionContext; +import org.junit.jupiter.api.extension.TestWatcher; /** * Helper used as base class for all test classes * * @author Apache MINA SSHD Project */ +@ExtendWith(BaseTestSupport.CustomTestWatcher.class) public abstract class BaseTestSupport extends JUnitTestSupport { // can be used to override the 'localhost' with an address other than 127.0.0.1 in case it is required public static final String TEST_LOCALHOST @@ -52,17 +55,18 @@ public abstract class BaseTestSupport extends JUnitTestSupport { public static final Duration DEFAULT_TIMEOUT = CoreTestSupportUtils.getTimeout("default", Duration.ofSeconds(5)); public static final Duration CLOSE_TIMEOUT = CoreTestSupportUtils.getTimeout("close", Duration.ofSeconds(15)); - @Rule - public final TestWatcher rule = new TestWatcher() { + static class CustomTestWatcher implements TestWatcher, BeforeEachCallback, AfterEachCallback { // TODO consider using a ThreadLocal storage for the start time - provided // the code is assured to call starting/finished on the same thread private long startTime; @Override - protected void starting(Description description) { + public void beforeEach(ExtensionContext context) { System.out.append(System.lineSeparator()) - .append("Starting ").append(description.getClassName()) - .append(':').append(description.getMethodName()) + .append("Starting ") + .append(context.getDisplayName()) + //.append(description.getClassName()) + //.append(':').append(description.getMethodName()) .println("..."); try { IoServiceFactoryFactory ioProvider = getIoServiceProvider(); @@ -75,11 +79,13 @@ protected void starting(Description description) { } @Override - protected void finished(Description description) { + public void afterEach(ExtensionContext context) { long duration = System.currentTimeMillis() - startTime; System.out.append(System.lineSeparator()) - .append("Finished ").append(description.getClassName()) - .append(':').append(description.getMethodName()) + .append("Finished ") + .append(context.getDisplayName()) + //.append(description.getClassName()) + //.append(':').append(description.getMethodName()) .append(" in ").append(Long.toString(duration)) .println(" ms"); } @@ -177,6 +183,6 @@ public static void assumeNotIoServiceProvider( .filter(f -> clazzName.equals(f.getFactoryClassName())) .findFirst() .orElse(null); - Assume.assumeTrue(message + " - skip factory=" + match, match == null); + Assumptions.assumeTrue(match == null, message + " - skip factory=" + match); } } diff --git a/sshd-core/src/test/java/org/apache/sshd/util/test/TestChannelListener.java b/sshd-core/src/test/java/org/apache/sshd/util/test/TestChannelListener.java index 2cc265999..a0504d3bd 100644 --- a/sshd-core/src/test/java/org/apache/sshd/util/test/TestChannelListener.java +++ b/sshd-core/src/test/java/org/apache/sshd/util/test/TestChannelListener.java @@ -30,7 +30,8 @@ import org.apache.sshd.common.channel.Channel; import org.apache.sshd.common.channel.ChannelListener; import org.apache.sshd.common.util.logging.AbstractLoggingBean; -import org.junit.Assert; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project @@ -68,7 +69,7 @@ public Collection getActiveChannels() { @Override public void channelInitialized(Channel channel) { - Assert.assertTrue("Same channel instance re-initialized: " + channel, activeChannels.add(channel)); + assertTrue(activeChannels.add(channel), "Same channel instance re-initialized: " + channel); activeChannelsCounter.release(); modificationsCounter.release(); log.info("channelInitialized({})", channel); @@ -84,8 +85,8 @@ public Collection getOpenChannels() { @Override public void channelOpenSuccess(Channel channel) { - Assert.assertTrue("Open channel not activated: " + channel, activeChannels.contains(channel)); - Assert.assertTrue("Same channel instance re-opened: " + channel, openChannels.add(channel)); + assertTrue(activeChannels.contains(channel), "Open channel not activated: " + channel); + assertTrue(openChannels.add(channel), "Same channel instance re-opened: " + channel); openChannelsCounter.release(); modificationsCounter.release(); log.info("channelOpenSuccess({})", channel); @@ -101,8 +102,8 @@ public Collection getFailedChannels() { @Override public void channelOpenFailure(Channel channel, Throwable reason) { - Assert.assertTrue("Failed channel not activated: " + channel, activeChannels.contains(channel)); - Assert.assertTrue("Same channel instance re-failed: " + channel, failedChannels.add(channel)); + assertTrue(activeChannels.contains(channel), "Failed channel not activated: " + channel); + assertTrue(failedChannels.add(channel), "Same channel instance re-failed: " + channel); failedChannelsCounter.release(); modificationsCounter.release(); warn("channelOpenFailure({}) {} : {}", channel, reason.getClass().getSimpleName(), reason.getMessage(), reason); @@ -114,7 +115,7 @@ public boolean waitForFailedChannelsChange(long timeout, TimeUnit unit) throws I @Override public void channelClosed(Channel channel, Throwable reason) { - Assert.assertTrue("Unknown closed channel instance: " + channel, activeChannels.remove(channel)); + assertTrue(activeChannels.remove(channel), "Unknown closed channel instance: " + channel); activeChannelsCounter.release(); closedChannelsCounter.release(); modificationsCounter.release(); diff --git a/sshd-core/src/test/java/org/apache/sshd/util/test/client/simple/BaseSimpleClientTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/util/test/client/simple/BaseSimpleClientTestSupport.java index 786f5c0d2..17c09b673 100644 --- a/sshd-core/src/test/java/org/apache/sshd/util/test/client/simple/BaseSimpleClientTestSupport.java +++ b/sshd-core/src/test/java/org/apache/sshd/util/test/client/simple/BaseSimpleClientTestSupport.java @@ -23,8 +23,8 @@ import org.apache.sshd.client.simple.SimpleClient; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.After; -import org.junit.Before; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; /** * @author Apache MINA SSHD Project @@ -40,7 +40,7 @@ protected BaseSimpleClientTestSupport() { super(); } - @Before + @BeforeEach public void setUp() throws Exception { sshd = setupTestServer(); sshd.start(); @@ -52,7 +52,7 @@ public void setUp() throws Exception { simple.setAuthenticationTimeout(AUTH_TIMEOUT.toMillis()); } - @After + @AfterEach public void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); diff --git a/sshd-git/pom.xml b/sshd-git/pom.xml index 1377fe3a1..dbe93f822 100644 --- a/sshd-git/pom.xml +++ b/sshd-git/pom.xml @@ -40,7 +40,7 @@ sshd-core ${project.version} - + org.bouncycastle bcpg-jdk18on @@ -75,7 +75,7 @@ org.apache.sshd sshd-osgi - + org.bouncycastle bcpg-jdk15on @@ -95,7 +95,7 @@ - + org.apache.sshd sshd-core @@ -116,6 +116,11 @@ ${project.version} test + + org.junit.jupiter + junit-jupiter + test + com.github.mwiede jsch diff --git a/sshd-git/src/test/java/org/apache/sshd/git/pack/GitPackCommandTest.java b/sshd-git/src/test/java/org/apache/sshd/git/pack/GitPackCommandTest.java index ea6f00879..44a77696e 100644 --- a/sshd-git/src/test/java/org/apache/sshd/git/pack/GitPackCommandTest.java +++ b/sshd-git/src/test/java/org/apache/sshd/git/pack/GitPackCommandTest.java @@ -42,22 +42,25 @@ import org.eclipse.jgit.transport.GitProtocolConstants; import org.eclipse.jgit.transport.SshSessionFactory; import org.eclipse.jgit.transport.UsernamePasswordCredentialsProvider; -import org.junit.Assume; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class GitPackCommandTest extends BaseTestSupport { public GitPackCommandTest() { super(); } - @BeforeClass - public static void jschInit() { + @BeforeAll + static void jschInit() { JSchLogger.init(); } @@ -69,8 +72,8 @@ protected SshServer setupTestServer() { } @Test - public void testGitPack() throws Exception { - Assume.assumeFalse("On windows this activates TortoisePlink", OsUtils.isWin32()); + void gitPack() throws Exception { + Assumptions.assumeFalse(OsUtils.isWin32(), "On windows this activates TortoisePlink"); Path gitRootDir = getTempTargetRelativeFile(getClass().getSimpleName()); try (SshServer sshd = setupTestServer()) { @@ -99,19 +102,19 @@ public void testGitPack() throws Exception { + serverDir.getFileName()) .setDirectory(localDir.toFile()) .call()) { - assertTrue("Client not started after clone", client.isStarted()); + assertTrue(client.isStarted(), "Client not started after clone"); git.commit().setMessage("First Commit").setCommitter(getCurrentTestName(), "sshd@apache.org").call(); git.push().call(); - assertTrue("Client not started after 1st push", client.isStarted()); + assertTrue(client.isStarted(), "Client not started after 1st push"); Path readmeFile = Files.createFile(localDir.resolve("readme.txt")); git.add().addFilepattern(readmeFile.getFileName().toString()).call(); git.commit().setMessage(getCurrentTestName()).setCommitter(getCurrentTestName(), "sshd@apache.org").call(); git.push().call(); - assertTrue("Client not started after 2nd push", client.isStarted()); + assertTrue(client.isStarted(), "Client not started after 2nd push"); git.pull().setRebase(true).call(); - assertTrue("Client not started after rebase", client.isStarted()); + assertTrue(client.isStarted(), "Client not started after rebase"); PropertyResolver useProtocolV2 = PropertyResolverUtils .toPropertyResolver( @@ -119,13 +122,13 @@ public void testGitPack() throws Exception { GitProtocolConstants.VERSION_2_REQUEST)); client.setParentPropertyResolver(useProtocolV2); git.fetch().call(); - assertTrue("Client not started after fetch using GIT_PROTOCOL='version=2' env. variable", - client.isStarted()); + assertTrue(client.isStarted(), + "Client not started after fetch using GIT_PROTOCOL='version=2' env. variable"); } finally { client.stop(); } - assertFalse("Client not stopped after exit", client.isStarted()); + assertFalse(client.isStarted(), "Client not stopped after exit"); } finally { sshd.stop(); } diff --git a/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java b/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java index b40d9b520..135db49ea 100644 --- a/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java +++ b/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java @@ -36,20 +36,23 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.eclipse.jgit.api.Git; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; /** */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class GitPgmCommandTest extends BaseTestSupport { public GitPgmCommandTest() { super(); } @Test - public void testGitPgm() throws Exception { + void gitPgm() throws Exception { Path serverDir = getTempTargetRelativeFile(getClass().getSimpleName()); try (SshServer sshd = setupTestServer()) { sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory())); @@ -95,11 +98,11 @@ private void execute(ClientSession session, String command) throws Exception { Collection result = channel.waitFor(EnumSet.of(ClientChannelEvent.CLOSED), TimeUnit.MINUTES.toMillis(1L)); - assertTrue("Command '" + command + "'not completed on time: " + result, result.contains(ClientChannelEvent.CLOSED)); + assertTrue(result.contains(ClientChannelEvent.CLOSED), "Command '" + command + "'not completed on time: " + result); Integer status = channel.getExitStatus(); if (status != null) { - assertEquals("Failed (" + status + ") " + command, 0, status.intValue()); + assertEquals(0, status.intValue(), "Failed (" + status + ") " + command); } } } diff --git a/sshd-ldap/pom.xml b/sshd-ldap/pom.xml index 73f14c3b5..d54218c34 100644 --- a/sshd-ldap/pom.xml +++ b/sshd-ldap/pom.xml @@ -32,7 +32,7 @@ ${project.basedir}/.. - 2.0.0.AM26 + 2.0.0.AM27 --add-opens=java.base/sun.security.util=ALL-UNNAMED --add-opens=java.base/sun.security.x509=ALL-UNNAMED @@ -79,13 +79,13 @@ ${project.version} - - - org.apache.mina - mina-core - test - - + + + org.apache.mina + mina-core + test + + org.apache.directory.server apacheds-test-framework test @@ -112,6 +112,16 @@ test-jar test + + org.junit.jupiter + junit-jupiter + test + + + org.mockito + mockito-junit-jupiter + test + org.apache.sshd sshd-common diff --git a/sshd-ldap/src/test/java/org/apache/sshd/ldap/BaseAuthenticatorTest.java b/sshd-ldap/src/test/java/org/apache/sshd/ldap/BaseAuthenticatorTest.java index d2a37ec9e..17081255e 100644 --- a/sshd-ldap/src/test/java/org/apache/sshd/ldap/BaseAuthenticatorTest.java +++ b/sshd-ldap/src/test/java/org/apache/sshd/ldap/BaseAuthenticatorTest.java @@ -29,25 +29,50 @@ import org.apache.directory.api.ldap.model.entry.Entry; import org.apache.directory.api.ldap.model.ldif.LdifEntry; import org.apache.directory.api.ldap.model.ldif.LdifReader; +import org.apache.directory.ldap.client.template.LdapConnectionTemplate; import org.apache.directory.server.core.api.DirectoryService; import org.apache.directory.server.ldap.LdapServer; import org.apache.directory.server.protocol.shared.transport.Transport; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.ValidateUtils; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Apache MINA SSHD Project */ -@Category({ NoIoTestCase.class }) +@Tag("NoIoTestCase") +@SuppressWarnings("checkstyle:VisibilityModifier") public abstract class BaseAuthenticatorTest extends BaseTestSupport { public static final String BASE_DN_TEST = "ou=People,dc=sshd,dc=apache,dc=org"; + /** The class DirectoryService instance */ + public static DirectoryService classDirectoryService; + + /** The test DirectoryService instance */ + public static DirectoryService methodDirectoryService; + + /** The current DirectoryService instance */ + public static DirectoryService directoryService; + + /** The class LdapServer instance */ + public static LdapServer classLdapServer; + + /** The test LdapServer instance */ + public static LdapServer methodLdapServer; + + /** The current LdapServer instance */ + public static LdapServer ldapServer; + + /** The Ldap connection template */ + public static LdapConnectionTemplate ldapConnectionTemplate; + + /** The current revision */ + public static long revision; + protected BaseAuthenticatorTest() { super(); } diff --git a/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPasswordAuthenticatorTest.java b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPasswordAuthenticatorTest.java index 13b260da7..37ea3cbad 100644 --- a/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPasswordAuthenticatorTest.java +++ b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPasswordAuthenticatorTest.java @@ -26,19 +26,23 @@ import org.apache.directory.server.core.annotations.ApplyLdifFiles; import org.apache.directory.server.core.annotations.CreateDS; import org.apache.directory.server.core.annotations.CreatePartition; -import org.apache.directory.server.core.integ.CreateLdapServerRule; +import org.apache.directory.server.core.integ.ApacheDSTestExtension; import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.server.session.ServerSession; -import org.junit.ClassRule; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@ExtendWith(ApacheDSTestExtension.class) +@TestMethodOrder(MethodName.class) @CreateDS(name = "myDS", partitions = { @CreatePartition(name = "users", suffix = BaseAuthenticatorTest.BASE_DN_TEST) }) @CreateLdapServer(allowAnonymousAccess = true, @@ -46,31 +50,29 @@ @ApplyLdifFiles({ "auth-users.ldif" }) public class LdapPasswordAuthenticatorTest extends BaseAuthenticatorTest { - @ClassRule - public static CreateLdapServerRule serverRule = new CreateLdapServerRule(); - private static Map usersMap; public LdapPasswordAuthenticatorTest() { super(); } - @Test // the user's password is compared with the LDAP stored one - public void testPasswordComparison() throws Exception { - usersMap = populateUsers(serverRule.getLdapServer().getDirectoryService(), + // the user's password is compared with the LDAP stored one + @Test + void passwordComparison() throws Exception { + usersMap = populateUsers(classLdapServer.getDirectoryService(), LdapPasswordAuthenticatorTest.class, LdapPasswordAuthenticator.DEFAULT_PASSWORD_ATTR_NAME); - assertFalse("No users retrieved", MapEntryUtils.isEmpty(usersMap)); + assertFalse(MapEntryUtils.isEmpty(usersMap), "No users retrieved"); LdapPasswordAuthenticator auth = new LdapPasswordAuthenticator(); - auth.setHost(getHost(serverRule.getLdapServer())); - auth.setPort(getPort(serverRule.getLdapServer())); + auth.setHost(getHost(classLdapServer)); + auth.setPort(getPort(classLdapServer)); auth.setBaseDN(BASE_DN_TEST); ServerSession session = Mockito.mock(ServerSession.class); outputDebugMessage("%s: %s", getCurrentTestName(), auth); usersMap.forEach((username, password) -> { outputDebugMessage("Authenticate: user=%s, password=%s", username, password); - assertTrue("Failed to authenticate " + username, auth.authenticate(username, password, session)); + assertTrue(auth.authenticate(username, password, session), "Failed to authenticate " + username); }); } } diff --git a/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPublickeyAuthenticatorTest.java b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPublickeyAuthenticatorTest.java index 1d899e714..827e2692f 100644 --- a/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPublickeyAuthenticatorTest.java +++ b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPublickeyAuthenticatorTest.java @@ -31,22 +31,26 @@ import org.apache.directory.server.core.annotations.ApplyLdifFiles; import org.apache.directory.server.core.annotations.CreateDS; import org.apache.directory.server.core.annotations.CreatePartition; -import org.apache.directory.server.core.integ.CreateLdapServerRule; +import org.apache.directory.server.core.integ.ApacheDSTestExtension; import org.apache.sshd.common.config.keys.AuthorizedKeyEntry; import org.apache.sshd.common.config.keys.KeyUtils; import org.apache.sshd.common.config.keys.PublicKeyEntryResolver; import org.apache.sshd.common.util.MapEntryUtils; import org.apache.sshd.server.session.ServerSession; -import org.junit.ClassRule; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@ExtendWith(ApacheDSTestExtension.class) +@TestMethodOrder(MethodName.class) @CreateDS(name = "myDS", partitions = { @CreatePartition(name = "users", suffix = BaseAuthenticatorTest.BASE_DN_TEST) }) @CreateLdapServer(allowAnonymousAccess = true, @@ -54,9 +58,6 @@ @ApplyLdifFiles({ "auth-users.ldif" }) public class LdapPublickeyAuthenticatorTest extends BaseAuthenticatorTest { - @ClassRule - public static CreateLdapServerRule serverRule = new CreateLdapServerRule(); - private static final Map KEYS_MAP = new TreeMap<>(Comparator.naturalOrder()); // we use this instead of the default since the default requires some extra LDIF manipulation which we don't need private static final String TEST_ATTR_NAME = "description"; @@ -66,10 +67,10 @@ public LdapPublickeyAuthenticatorTest() { } @Test - public void testPublicKeyComparison() throws Exception { - Map credentials = populateUsers(serverRule.getLdapServer().getDirectoryService(), + void publicKeyComparison() throws Exception { + Map credentials = populateUsers(classLdapServer.getDirectoryService(), LdapPublickeyAuthenticatorTest.class, TEST_ATTR_NAME); - assertFalse("No keys retrieved", MapEntryUtils.isEmpty(credentials)); + assertFalse(MapEntryUtils.isEmpty(credentials), "No keys retrieved"); // Cannot use forEach because of the potential GeneraSecurityException being thrown for (Map.Entry ce : credentials.entrySet()) { @@ -81,8 +82,8 @@ public void testPublicKeyComparison() throws Exception { } LdapPublickeyAuthenticator auth = new LdapPublickeyAuthenticator(); - auth.setHost(getHost(serverRule.getLdapServer())); - auth.setPort(getPort(serverRule.getLdapServer())); + auth.setHost(getHost(classLdapServer)); + auth.setPort(getPort(classLdapServer)); auth.setBaseDN(BASE_DN_TEST); auth.setKeyAttributeName(TEST_ATTR_NAME); auth.setRetrievedAttributes(TEST_ATTR_NAME); @@ -92,7 +93,7 @@ public void testPublicKeyComparison() throws Exception { KEYS_MAP.forEach((username, key) -> { outputDebugMessage("Authenticate: user=%s, key-type=%s, fingerprint=%s", username, KeyUtils.getKeyType(key), KeyUtils.getFingerPrint(key)); - assertTrue("Failed to authenticate user=" + username, auth.authenticate(username, key, session)); + assertTrue(auth.authenticate(username, key, session), "Failed to authenticate user=" + username); }); } } diff --git a/sshd-mina/pom.xml b/sshd-mina/pom.xml index d7832526b..dd3032fe3 100644 --- a/sshd-mina/pom.xml +++ b/sshd-mina/pom.xml @@ -62,6 +62,11 @@ test-jar test + + org.junit.jupiter + junit-jupiter + test + org.apache.sshd sshd-common @@ -128,7 +133,7 @@ **/DefaultIoServiceFactoryFactoryTest.java - org.apache.sshd.util.test.NoIoTestCase + NoIoTestCase org.apache.sshd:sshd-core diff --git a/sshd-mina/src/test/java/org/apache/sshd/mina/MinaSessionTest.java b/sshd-mina/src/test/java/org/apache/sshd/mina/MinaSessionTest.java index 3de4497c0..37970305b 100644 --- a/sshd-mina/src/test/java/org/apache/sshd/mina/MinaSessionTest.java +++ b/sshd-mina/src/test/java/org/apache/sshd/mina/MinaSessionTest.java @@ -27,16 +27,18 @@ import org.apache.sshd.common.io.IoServiceFactory; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.test.BaseTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests specific to the MINA connection back-end. * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class MinaSessionTest extends BaseTestSupport { public MinaSessionTest() { @@ -45,17 +47,17 @@ public MinaSessionTest() { private IoProcessor getProcessor(AbstractFactoryManager manager) throws Exception { IoServiceFactory ioServiceFactory = manager.getIoServiceFactory(); - assertTrue("Unexpected type " + ioServiceFactory.getClass(), ioServiceFactory instanceof MinaServiceFactory); + assertTrue(ioServiceFactory instanceof MinaServiceFactory, "Unexpected type " + ioServiceFactory.getClass()); // Get the ioProcessor field Field f = MinaServiceFactory.class.getDeclaredField("ioProcessor"); f.setAccessible(true); Object processor = f.get(ioServiceFactory); - assertTrue("Unexpected type " + processor.getClass(), processor instanceof IoProcessor); + assertTrue(processor instanceof IoProcessor, "Unexpected type " + processor.getClass()); return (IoProcessor) processor; } @Test - public void testIoProcessorClosed() throws Exception { + void ioProcessorClosed() throws Exception { IoProcessor ioProcessor = null; try (SshServer server = setupTestServer()) { server.start(); @@ -63,9 +65,9 @@ public void testIoProcessorClosed() throws Exception { client.start(); ioProcessor = getProcessor(client); } - assertTrue("MINA client IoProcessor should be closed", ioProcessor.isDisposed() || ioProcessor.isDisposing()); + assertTrue(ioProcessor.isDisposed() || ioProcessor.isDisposing(), "MINA client IoProcessor should be closed"); ioProcessor = getProcessor(server); } - assertTrue("MINA server IoProcessor should be closed", ioProcessor.isDisposed() || ioProcessor.isDisposing()); + assertTrue(ioProcessor.isDisposed() || ioProcessor.isDisposing(), "MINA server IoProcessor should be closed"); } } diff --git a/sshd-netty/pom.xml b/sshd-netty/pom.xml index 2c79945b7..6cfc99b34 100644 --- a/sshd-netty/pom.xml +++ b/sshd-netty/pom.xml @@ -63,6 +63,16 @@ + + org.junit.jupiter + junit-jupiter + test + + + org.mockito + mockito-junit-jupiter + test + org.apache.sshd sshd-core @@ -145,7 +155,7 @@ **/OpenSSHCertificateTest.java - org.apache.sshd.util.test.NoIoTestCase + NoIoTestCase org.apache.sshd:sshd-core diff --git a/sshd-netty/src/test/java/org/apache/sshd/netty/NettyTest.java b/sshd-netty/src/test/java/org/apache/sshd/netty/NettyTest.java new file mode 100644 index 000000000..4eb32f23b --- /dev/null +++ b/sshd-netty/src/test/java/org/apache/sshd/netty/NettyTest.java @@ -0,0 +1,31 @@ +/* + * 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.netty; + +import org.junit.jupiter.api.Test; + +// +// Dumb test, as junit 5 fails if there's no tests +// +public class NettyTest { + + @Test + void dummyTest() { + } +} diff --git a/sshd-openpgp/pom.xml b/sshd-openpgp/pom.xml index 928a9a292..1fd402ed8 100644 --- a/sshd-openpgp/pom.xml +++ b/sshd-openpgp/pom.xml @@ -56,15 +56,15 @@ jpgpj 1.3 - + - org.bouncycastle - bcpg-jdk15on + org.bouncycastle + bcpg-jdk15on - + org.apache.sshd sshd-common @@ -72,6 +72,16 @@ test-jar test + + org.junit.jupiter + junit-jupiter + test + + + org.mockito + mockito-junit-jupiter + test + diff --git a/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPKeyPairResourceParserTest.java b/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPKeyPairResourceParserTest.java index 6ca286be2..f84adf5c5 100644 --- a/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPKeyPairResourceParserTest.java +++ b/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPKeyPairResourceParserTest.java @@ -37,35 +37,34 @@ import org.apache.sshd.common.config.keys.KeyUtils; import org.apache.sshd.common.session.SessionContext; import org.apache.sshd.common.util.GenericUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class PGPKeyPairResourceParserTest extends JUnitTestSupport { public static final String PASSWORD = "super secret passphrase"; - private final String resourceName; - private final ResourceDecodeResult result; - private final FilePasswordProvider passwordProvider; + private String resourceName; + private ResourceDecodeResult result; + private FilePasswordProvider passwordProvider; private final AtomicInteger retriesCount = new AtomicInteger(0); private final int maxRetries = 3; - public PGPKeyPairResourceParserTest(String resourceName, ResourceDecodeResult result, String password) { + public void initPGPKeyPairResourceParserTest(String resourceName, ResourceDecodeResult result, String password) { this.resourceName = resourceName; this.result = result; this.passwordProvider = new FilePasswordProvider() { @@ -75,12 +74,12 @@ public String getPassword(SessionContext session, NamedResource resourceKey, int switch (result) { case IGNORE: case TERMINATE: - assertEquals("Mismatched retries invocation count", 0, retryIndex); - assertEquals("Mismatched retries tracking count", retryIndex, retriesCount.get()); + assertEquals(0, retryIndex, "Mismatched retries invocation count"); + assertEquals(retryIndex, retriesCount.get(), "Mismatched retries tracking count"); return "qwertyuiop123456!@#$%^"; case RETRY: { int count = retriesCount.incrementAndGet(); - assertEquals("Mismatched retries count", count, retryIndex + 1); + assertEquals(count, retryIndex + 1, "Mismatched retries count"); if (count == maxRetries) { return PASSWORD; } else { @@ -117,7 +116,6 @@ public String toString() { }; } - @Parameters(name = "{0} / {1}") public static List parameters() { return Collections.unmodifiableList(new ArrayList() { // Not serializing it @@ -138,10 +136,12 @@ public static List parameters() { }); } - @Test - public void testDecodePrivateKeyPair() throws IOException { + @MethodSource("parameters") + @ParameterizedTest(name = "{0} / {1}") + public void decodePrivateKeyPair(String resourceName, ResourceDecodeResult result, String password) throws IOException { + initPGPKeyPairResourceParserTest(resourceName, result, password); InputStream stream = getClass().getResourceAsStream(resourceName); - assertNotNull("Missing " + resourceName, stream); + assertNotNull(stream, "Missing " + resourceName); Collection keys; try { @@ -158,11 +158,11 @@ public void testDecodePrivateKeyPair() throws IOException { switch (result) { case IGNORE: - assertTrue("Unexpected keys recovered", GenericUtils.isEmpty(keys)); + assertTrue(GenericUtils.isEmpty(keys), "Unexpected keys recovered"); return; case RETRY: - assertFalse("No keys recovered", GenericUtils.isEmpty(keys)); + assertFalse(GenericUtils.isEmpty(keys), "No keys recovered"); break; case TERMINATE: // fall through... @@ -173,16 +173,16 @@ public void testDecodePrivateKeyPair() throws IOException { for (KeyPair kp : keys) { PublicKey pubKey = kp.getPublic(); PrivateKey prvKey = kp.getPrivate(); - assertNotNull("No public key for private=" + prvKey, pubKey); - assertNotNull("No private key for public=" + pubKey, prvKey); + assertNotNull(pubKey, "No public key for private=" + prvKey); + assertNotNull(prvKey, "No private key for public=" + pubKey); String pubType = KeyUtils.getKeyType(pubKey); String prvType = KeyUtils.getKeyType(prvKey); - assertEquals("Mismatched public/private key types", pubType, prvType); + assertEquals(pubType, prvType, "Mismatched public/private key types"); int pubSize = KeyUtils.getKeySize(pubKey); int prvSize = KeyUtils.getKeySize(prvKey); - assertEquals("Mismatched public/private key size", pubSize, prvSize); + assertEquals(pubSize, prvSize, "Mismatched public/private key size"); } } diff --git a/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPPublicRingWatcherTest.java b/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPPublicRingWatcherTest.java index fb8ebd77a..f8ab4ae86 100644 --- a/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPPublicRingWatcherTest.java +++ b/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPPublicRingWatcherTest.java @@ -29,24 +29,26 @@ import org.apache.sshd.common.util.io.resource.PathResource; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertFalse; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class PGPPublicRingWatcherTest extends JUnitTestSupport { public PGPPublicRingWatcherTest() { super(); } @Test - public void testDefaultRingPath() { + void defaultRingPath() { Path path = PGPPublicRingWatcher.detectDefaultPublicRingFilePath(); - Assume.assumeTrue("No default ring detected", path != null); + Assumptions.assumeTrue(path != null, "No default ring detected"); try { testPublicRingWatcher(path); @@ -57,21 +59,21 @@ public void testDefaultRingPath() { } @Test - public void testV1ResourcesKeyPath() throws Exception { + void v1ResourcesKeyPath() throws Exception { Path dir = CommonTestSupportUtils.resolve( detectSourcesFolder(), TEST_SUBFOLDER, RESOURCES_SUBFOLDER, "keyring"); Path file = dir.resolve(PGPPublicRingWatcher.GPG_V1_PUBLIC_RING_FILENAME); Map keys = testPublicRingWatcher(file); - assertFalse("No keys extracted", MapEntryUtils.isEmpty(keys)); + assertFalse(MapEntryUtils.isEmpty(keys), "No keys extracted"); } @Test - public void testV2ResourcesKeyPath() throws Exception { + void v2ResourcesKeyPath() throws Exception { Path dir = CommonTestSupportUtils.resolve( detectSourcesFolder(), TEST_SUBFOLDER, RESOURCES_SUBFOLDER, "kbx2ring"); Path file = dir.resolve(PGPPublicRingWatcher.GPG_V2_PUBLIC_RING_FILENAME); Map keys = testPublicRingWatcher(file); - assertFalse("No keys extracted", MapEntryUtils.isEmpty(keys)); + assertFalse(MapEntryUtils.isEmpty(keys), "No keys extracted"); } private NavigableMap testPublicRingWatcher(Path file) throws Exception { diff --git a/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPUtilsKeyFingerprintTest.java b/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPUtilsKeyFingerprintTest.java index 688bf9ad8..503ccb9b7 100644 --- a/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPUtilsKeyFingerprintTest.java +++ b/sshd-openpgp/src/test/java/org/apache/sshd/openpgp/PGPUtilsKeyFingerprintTest.java @@ -40,44 +40,43 @@ import org.apache.sshd.common.session.SessionContext; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.io.IoUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; import org.bouncycastle.openpgp.PGPException; import org.bouncycastle.openpgp.PGPPublicKey; import org.c02e.jpgpj.Key; import org.c02e.jpgpj.Subkey; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Assume; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class PGPUtilsKeyFingerprintTest extends JUnitTestSupport { - private final String resourceName; - private final Key key; + private String resourceName; + private Key key; - public PGPUtilsKeyFingerprintTest(String resourceName) throws IOException, PGPException { + public void initPGPUtilsKeyFingerprintTest(String resourceName) throws IOException, PGPException { this.resourceName = resourceName; InputStream stream = getClass().getResourceAsStream(resourceName); - assertNotNull("Missing " + resourceName, stream); + assertNotNull(stream, "Missing " + resourceName); try { key = new Key(stream); @@ -87,7 +86,6 @@ public PGPUtilsKeyFingerprintTest(String resourceName) throws IOException, PGPEx } } - @Parameters(name = "{0}") public static String[] parameters() { return new String[] { "EC-256-gpg2-public.asc", @@ -99,43 +97,47 @@ public static String[] parameters() { "DSA-2048-gpg4win-3.1.3.asc" }; } - @BeforeClass - @AfterClass - public static void clearAllRegisteredPublicKeyEntryDataResolvers() { + @BeforeAll + @AfterAll + static void clearAllRegisteredPublicKeyEntryDataResolvers() { for (String keyType : PGPPublicKeyEntryDataResolver.PGP_KEY_TYPES) { PublicKeyEntry.unregisterKeyDataEntryResolver(keyType); KeyUtils.unregisterPublicKeyEntryDecoderForKeyType(keyType); } } - @Before - public void setUp() { + @BeforeEach + void setUp() { clearAllRegisteredPublicKeyEntryDataResolvers(); } - @After - public void tearDown() { + @AfterEach + void tearDown() { clearAllRegisteredPublicKeyEntryDataResolvers(); } - @Test - public void testFindSubKeyByFingerprint() { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void findSubKeyByFingerprint(String resourceName) throws Exception { + initPGPUtilsKeyFingerprintTest(resourceName); Collection subKeys = key.getSubkeys(); - assertFalse("No sub keys available in " + resourceName, GenericUtils.isEmpty(subKeys)); + assertFalse(GenericUtils.isEmpty(subKeys), "No sub keys available in " + resourceName); for (Subkey expected : subKeys) { String fingerprint = expected.getFingerprint(); Subkey actual = PGPUtils.findSubkeyByFingerprint(key, fingerprint); - assertSame("Mismatched sub-key match for " + fingerprint, expected, actual); + assertSame(expected, actual, "Mismatched sub-key match for " + fingerprint); } } - @Test - public void testParseAuthorizedKeyEntry() throws IOException { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void parseAuthorizedKeyEntry(String resourceName) throws Exception { + initPGPUtilsKeyFingerprintTest(resourceName); Path dir = getTempTargetRelativeFile(getClass().getSimpleName()); Path file = Files.createDirectories(dir).resolve(resourceName + ".authorized"); Collection subKeys = key.getSubkeys(); - assertFalse("No sub keys available in " + resourceName, GenericUtils.isEmpty(subKeys)); + assertFalse(GenericUtils.isEmpty(subKeys), "No sub keys available in " + resourceName); Collection written = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); try (BufferedWriter out = Files.newBufferedWriter(file, StandardCharsets.UTF_8, IoUtils.EMPTY_OPEN_OPTIONS)) { @@ -153,32 +155,34 @@ public void testParseAuthorizedKeyEntry() throws IOException { .append(' ').append(resourceName) .append(System.lineSeparator()); - assertTrue("Non-unique fingerprint: " + fingerprint, written.add(fingerprint)); + assertTrue(written.add(fingerprint), "Non-unique fingerprint: " + fingerprint); } } // Can happen for ECC or EDDSA keys - Assume.assumeFalse(resourceName + " - no fingerprints written", written.isEmpty()); + Assumptions.assumeFalse(written.isEmpty(), resourceName + " - no fingerprints written"); PGPPublicKeyEntryDataResolver.registerDefaultKeyEntryDataResolvers(); Collection authKeys = AuthorizedKeyEntry.readAuthorizedKeys(file, IoUtils.EMPTY_OPEN_OPTIONS); - assertEquals("Mismatched key entries count", written.size(), authKeys.size()); + assertEquals(written.size(), authKeys.size(), "Mismatched key entries count"); for (PublicKeyEntry entry : authKeys) { PublicKeyEntryDataResolver resolver = entry.getKeyDataResolver(); - assertSame("Mismatched key data resolver for " + entry, PGPPublicKeyEntryDataResolver.DEFAULT, resolver); + assertSame(PGPPublicKeyEntryDataResolver.DEFAULT, resolver, "Mismatched key data resolver for " + entry); String fingerprint = resolver.encodeEntryKeyData(entry.getKeyData()); - assertTrue("Unknown fingerprint recovered: " + fingerprint, written.remove(fingerprint)); + assertTrue(written.remove(fingerprint), "Unknown fingerprint recovered: " + fingerprint); } - assertTrue(resourceName + " - incomplete fingerprints: " + written, written.isEmpty()); + assertTrue(written.isEmpty(), resourceName + " - incomplete fingerprints: " + written); } - @Test - public void testResolveAuthorizedEntries() + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void resolveAuthorizedEntries(String resourceName) throws IOException, GeneralSecurityException, PGPException { + initPGPUtilsKeyFingerprintTest(resourceName); Collection subKeys = key.getSubkeys(); - assertFalse("No sub keys available in " + resourceName, GenericUtils.isEmpty(subKeys)); + assertFalse(GenericUtils.isEmpty(subKeys), "No sub keys available in " + resourceName); Collection available = new ArrayList<>(subKeys.size()); for (Subkey sk : subKeys) { @@ -196,7 +200,7 @@ public void testResolveAuthorizedEntries() } // Can happen for ECC or EDDSA keys - Assume.assumeFalse(resourceName + " - no fingerprints extracted", available.isEmpty()); + Assumptions.assumeFalse(available.isEmpty(), resourceName + " - no fingerprints extracted"); Path dir = getTempTargetRelativeFile(getClass().getSimpleName()); Path file = Files.createDirectories(dir).resolve(resourceName + ".txt"); @@ -209,7 +213,7 @@ public void testResolveAuthorizedEntries() SessionContext session = Mockito.mock(SessionContext.class); for (PublicKeyEntry pke : available) { Collection keys = tracker.loadMatchingAuthorizedEntries(session, Collections.singletonList(pke)); - assertEquals("Mismatched recovered keys count for " + pke, 1, GenericUtils.size(keys)); + assertEquals(1, GenericUtils.size(keys), "Mismatched recovered keys count for " + pke); PublicKey expected = pke.resolvePublicKey(session, Collections.emptyMap(), tracker); PublicKey actual = GenericUtils.head(keys); diff --git a/sshd-putty/pom.xml b/sshd-putty/pom.xml index b815fd023..b3915ea88 100644 --- a/sshd-putty/pom.xml +++ b/sshd-putty/pom.xml @@ -53,14 +53,14 @@ true - + net.i2p.crypto eddsa true - + org.apache.sshd sshd-common @@ -68,6 +68,16 @@ test-jar test + + org.junit.jupiter + junit-jupiter + test + + + org.mockito + mockito-junit-jupiter + test + diff --git a/sshd-putty/src/test/java/org/apache/sshd/putty/AbstractPuttyTestSupport.java b/sshd-putty/src/test/java/org/apache/sshd/putty/AbstractPuttyTestSupport.java index ed6123021..4b42f91c0 100644 --- a/sshd-putty/src/test/java/org/apache/sshd/putty/AbstractPuttyTestSupport.java +++ b/sshd-putty/src/test/java/org/apache/sshd/putty/AbstractPuttyTestSupport.java @@ -33,8 +33,9 @@ import org.apache.sshd.common.config.keys.loader.openssh.OpenSSHKeyPairResourceParser; import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.Assume; -import org.junit.AssumptionViolatedException; + +import static org.junit.jupiter.api.Assumptions.assumeFalse; +import static org.junit.jupiter.api.Assumptions.assumeTrue; /** * @author Apache MINA SSHD Project @@ -48,26 +49,23 @@ protected KeyPair testDecodeEncryptedPuttyKeyFile( String encryptedFile, boolean okIfMissing, String password, String keyType) throws IOException, GeneralSecurityException { PuttyKeyPairResourceParser parser = PuttyKeyUtils.BY_KEY_TYPE.get(keyType); - assertNotNull("No parser found for key type=" + keyType, parser); + assertNotNull(parser, "No parser found for key type=" + keyType); return testDecodeEncryptedPuttyKeyFile(encryptedFile, okIfMissing, password, parser, keyType); } protected KeyPair testDecodeEncryptedPuttyKeyFile( String encryptedFile, boolean okIfMissing, String password, PuttyKeyPairResourceParser parser, String keyType) throws IOException, GeneralSecurityException { - Assume.assumeTrue(BuiltinCiphers.aes256cbc.getTransformation() + " N/A", BuiltinCiphers.aes256cbc.isSupported()); + assumeTrue(BuiltinCiphers.aes256cbc.isSupported(), BuiltinCiphers.aes256cbc.getTransformation() + " N/A"); URL url = getClass().getResource(encryptedFile); if (url == null) { - if (okIfMissing) { - throw new AssumptionViolatedException("Skip non-existent encrypted file: " + encryptedFile); - } - + assumeFalse(okIfMissing, "Skip non-existent encrypted file: " + encryptedFile); fail("Missing test resource: " + encryptedFile); } Collection keys = parser.loadKeyPairs(null, url, (s, r, index) -> password); - assertEquals("Mismatched loaded keys count from " + encryptedFile, 1, GenericUtils.size(keys)); + assertEquals(1, GenericUtils.size(keys), "Mismatched loaded keys count from " + encryptedFile); return assertLoadedKeyPair(encryptedFile, GenericUtils.head(keys), keyType); } @@ -75,19 +73,19 @@ protected KeyPair testDecodeEncryptedPuttyKeyFile( //////////////////////////////////////////////////////////////////////////////////// public static KeyPair assertLoadedKeyPair(String prefix, KeyPair kp, String keyType) throws GeneralSecurityException { - assertNotNull(prefix + ": no key pair loaded", kp); + assertNotNull(kp, prefix + ": no key pair loaded"); PublicKey pubKey = kp.getPublic(); - assertNotNull(prefix + ": no public key loaded", pubKey); - assertEquals(prefix + ": mismatched public key type", keyType, KeyUtils.getKeyType(pubKey)); + assertNotNull(pubKey, prefix + ": no public key loaded"); + assertEquals(keyType, KeyUtils.getKeyType(pubKey), prefix + ": mismatched public key type"); PrivateKey prvKey = kp.getPrivate(); - assertNotNull(prefix + ": no private key loaded", prvKey); - assertEquals(prefix + ": mismatched private key type", keyType, KeyUtils.getKeyType(prvKey)); + assertNotNull(prvKey, prefix + ": no private key loaded"); + assertEquals(keyType, KeyUtils.getKeyType(prvKey), prefix + ": mismatched private key type"); @SuppressWarnings("rawtypes") PrivateKeyEntryDecoder decoder = OpenSSHKeyPairResourceParser.getPrivateKeyEntryDecoder(prvKey); - assertNotNull("No private key decoder", decoder); + assertNotNull(decoder, "No private key decoder"); if (decoder.isPublicKeyRecoverySupported()) { @SuppressWarnings("unchecked") diff --git a/sshd-putty/src/test/java/org/apache/sshd/putty/PuttyKeyUtilsTest.java b/sshd-putty/src/test/java/org/apache/sshd/putty/PuttyKeyUtilsTest.java index 24803c9f9..3fcee43e8 100644 --- a/sshd-putty/src/test/java/org/apache/sshd/putty/PuttyKeyUtilsTest.java +++ b/sshd-putty/src/test/java/org/apache/sshd/putty/PuttyKeyUtilsTest.java @@ -35,35 +35,34 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.functors.UnaryEquator; import org.apache.sshd.common.util.io.IoUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class PuttyKeyUtilsTest extends AbstractPuttyTestSupport { public static final String PASSWORD = "super secret passphrase"; - private final String keyType; - private final String regularFile; - private final String encryptedFile; - private final PuttyKeyPairResourceParser parser; + private String keyType; + private String regularFile; + private String encryptedFile; + private PuttyKeyPairResourceParser parser; - public PuttyKeyUtilsTest(String keyType) { + public void initPuttyKeyUtilsTest(String keyType) { this.keyType = keyType; this.parser = PuttyKeyUtils.BY_KEY_TYPE.get(keyType); this.regularFile = getClass().getSimpleName() @@ -74,17 +73,18 @@ public PuttyKeyUtilsTest(String keyType) { + PuttyKeyPairResourceParser.PPK_FILE_SUFFIX; } - @Parameters(name = "{0}") public static List parameters() { return parameterize(PuttyKeyUtils.BY_KEY_TYPE.keySet()); } - @Test - public void testCanDecodePuttyKeyFile() throws IOException, GeneralSecurityException { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void canDecodePuttyKeyFile(String keyType) throws IOException, GeneralSecurityException { + initPuttyKeyUtilsTest(keyType); for (String resource : new String[] { regularFile, encryptedFile }) { URL url = getClass().getResource(resource); if (UnaryEquator.isSameReference(regularFile, resource)) { - assertNotNull("Missing test resource: " + resource, url); + assertNotNull(url, "Missing test resource: " + resource); } else { if (url == null) { outputDebugMessage("Skip non-existing encrypted file: %s", resource); @@ -94,41 +94,47 @@ public void testCanDecodePuttyKeyFile() throws IOException, GeneralSecurityExcep List lines = IoUtils.readAllLines(url); NamedResource resourceKey = NamedResource.ofName(resource); - assertTrue(resource + " - can extract key pair", parser.canExtractKeyPairs(resourceKey, lines)); + assertTrue(parser.canExtractKeyPairs(resourceKey, lines), resource + " - can extract key pair"); for (PuttyKeyPairResourceParser other : PuttyKeyUtils.BY_KEY_TYPE.values()) { if (parser == other) { continue; } - assertFalse(other.getClass().getSimpleName() + "/" + resource + " - unexpected extraction capability", - other.canExtractKeyPairs(resourceKey, lines)); + assertFalse(other.canExtractKeyPairs(resourceKey, lines), + other.getClass().getSimpleName() + "/" + resource + " - unexpected extraction capability"); } } } - @Test - public void testDecodePuttyKeyFile() throws IOException, GeneralSecurityException { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void decodePuttyKeyFile(String keyType) throws IOException, GeneralSecurityException { + initPuttyKeyUtilsTest(keyType); URL url = getClass().getResource(regularFile); - assertNotNull("Missing test resource: " + regularFile, url); + assertNotNull(url, "Missing test resource: " + regularFile); Collection keys = parser.loadKeyPairs(null, url, null); - assertEquals("Mismatched loaded keys count from " + regularFile, 1, GenericUtils.size(keys)); + assertEquals(1, GenericUtils.size(keys), "Mismatched loaded keys count from " + regularFile); assertLoadedKeyPair(regularFile, GenericUtils.head(keys)); } - @Test - public void testDecodeEncryptedPuttyKeyFile() throws IOException, GeneralSecurityException { + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void decodeEncryptedPuttyKeyFile(String keyType) throws IOException, GeneralSecurityException { + initPuttyKeyUtilsTest(keyType); testDecodeEncryptedPuttyKeyFile(encryptedFile, true, PASSWORD, parser, keyType); } - @Test - public void testDecideEncryptedFileWithRetries() throws IOException, GeneralSecurityException { - Assume.assumeTrue(BuiltinCiphers.aes256cbc.getTransformation() + " N/A", BuiltinCiphers.aes256cbc.isSupported()); + @MethodSource("parameters") + @ParameterizedTest(name = "{0}") + public void decideEncryptedFileWithRetries(String keyType) throws IOException, GeneralSecurityException { + initPuttyKeyUtilsTest(keyType); + Assumptions.assumeTrue(BuiltinCiphers.aes256cbc.isSupported(), BuiltinCiphers.aes256cbc.getTransformation() + " N/A"); URL url = getClass().getResource(encryptedFile); - Assume.assumeTrue("Skip non-existent encrypted file: " + encryptedFile, url != null); - assertNotNull("Missing test resource: " + encryptedFile, url); + Assumptions.assumeTrue(url != null, "Skip non-existent encrypted file: " + encryptedFile); + assertNotNull(url, "Missing test resource: " + encryptedFile); int maxRetries = 3; SessionContext mockSession = Mockito.mock(SessionContext.class); @@ -138,17 +144,17 @@ public void testDecideEncryptedFileWithRetries() throws IOException, GeneralSecu @Override public String getPassword(SessionContext session, NamedResource resourceKey, int retryIndex) throws IOException { - assertSame("Mismatched session context", mockSession, session); + assertSame(mockSession, session, "Mismatched session context"); switch (result) { case IGNORE: case TERMINATE: - assertEquals("Mismatched retries invocation count", 0, retryIndex); - assertEquals("Mismatched retries tracking count", retryIndex, retriesCount.get()); + assertEquals(0, retryIndex, "Mismatched retries invocation count"); + assertEquals(retryIndex, retriesCount.get(), "Mismatched retries tracking count"); return "qwertyuiop123456!@#$%^"; case RETRY: { int count = retriesCount.incrementAndGet(); - assertEquals("Mismatched retries count", retryIndex + 1, count); + assertEquals(retryIndex + 1, count, "Mismatched retries count"); if (count == maxRetries) { return PASSWORD; } else { @@ -164,7 +170,7 @@ public String getPassword(SessionContext session, NamedResource resourceKey, int public ResourceDecodeResult handleDecodeAttemptResult( SessionContext session, NamedResource resourceKey, int retryIndex, String password, Exception err) throws IOException, GeneralSecurityException { - assertSame("Mismatched session context", mockSession, session); + assertSame(mockSession, session, "Mismatched session context"); if (err == null) { return null; } @@ -187,11 +193,11 @@ public String toString() { try { Collection keys = parser.loadKeyPairs(mockSession, url, provider); if (result == ResourceDecodeResult.IGNORE) { - assertEquals("Unexpected loaded keys count from " + encryptedFile, 0, GenericUtils.size(keys)); - assertEquals("Mismatched " + result + " retries count", 0, retriesCount.get()); + assertEquals(0, GenericUtils.size(keys), "Unexpected loaded keys count from " + encryptedFile); + assertEquals(0, retriesCount.get(), "Mismatched " + result + " retries count"); } else { - assertEquals("Mismatched loaded keys count from " + encryptedFile, 1, GenericUtils.size(keys)); - assertEquals("Mismatched " + result + " retries count", maxRetries, retriesCount.get()); + assertEquals(1, GenericUtils.size(keys), "Mismatched loaded keys count from " + encryptedFile); + assertEquals(maxRetries, retriesCount.get(), "Mismatched " + result + " retries count"); assertLoadedKeyPair(encryptedFile, GenericUtils.head(keys)); } } catch (IOException | GeneralSecurityException | RuntimeException e) { @@ -199,7 +205,7 @@ public String toString() { throw e; } - assertEquals("Mismatched " + result + " retries count", 0, retriesCount.get()); + assertEquals(0, retriesCount.get(), "Mismatched " + result + " retries count"); } } } diff --git a/sshd-putty/src/test/java/org/apache/sshd/putty/PuttySpecialKeysTest.java b/sshd-putty/src/test/java/org/apache/sshd/putty/PuttySpecialKeysTest.java index 35f845554..cad8505db 100644 --- a/sshd-putty/src/test/java/org/apache/sshd/putty/PuttySpecialKeysTest.java +++ b/sshd-putty/src/test/java/org/apache/sshd/putty/PuttySpecialKeysTest.java @@ -24,26 +24,26 @@ import java.security.KeyPair; import org.apache.sshd.common.util.security.SecurityUtils; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class PuttySpecialKeysTest extends AbstractPuttyTestSupport { public PuttySpecialKeysTest() { super(); } - @Test // SSHD-1247 - public void testArgon2KeyDerivation() throws Exception { - Assume.assumeTrue("BC provider available", SecurityUtils.isBouncyCastleRegistered()); + // SSHD-1247 + @Test + void argon2KeyDerivation() throws Exception { + Assumptions.assumeTrue(SecurityUtils.isBouncyCastleRegistered(), "BC provider available"); testDecodeSpecialEncryptedPuttyKeyFile("ssh-rsa", "argon2id", "123456"); } diff --git a/sshd-scp/pom.xml b/sshd-scp/pom.xml index afce51b69..4f7fdf9ad 100644 --- a/sshd-scp/pom.xml +++ b/sshd-scp/pom.xml @@ -40,7 +40,7 @@ sshd-core ${project.version} - + org.apache.sshd sshd-core @@ -48,6 +48,16 @@ test-jar test + + org.junit.jupiter + junit-jupiter + test + + + org.mockito + mockito-junit-jupiter + test + org.apache.sshd sshd-common @@ -70,6 +80,11 @@ testcontainers test + + org.testcontainers + junit-jupiter + test + @@ -218,7 +233,7 @@ org.apache.maven.plugins maven-surefire-plugin - org.apache.sshd.util.test.ContainerTestCase + ContainerTestCase diff --git a/sshd-scp/src/test/java/org/apache/sshd/scp/client/AbstractScpTestSupport.java b/sshd-scp/src/test/java/org/apache/sshd/scp/client/AbstractScpTestSupport.java index 80bd14c8a..8dab237c2 100644 --- a/sshd-scp/src/test/java/org/apache/sshd/scp/client/AbstractScpTestSupport.java +++ b/sshd-scp/src/test/java/org/apache/sshd/scp/client/AbstractScpTestSupport.java @@ -39,8 +39,8 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.AfterClass; -import org.junit.Before; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeEach; /** * @author Apache MINA SSHD Project @@ -133,7 +133,7 @@ protected static void setupClientAndServer(Class anchor) throws Exception { client.start(); } - @AfterClass + @AfterAll public static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { @@ -206,7 +206,7 @@ protected static ScpClient createScpClient(ClientSession session) { return creator.createScpClient(session, listener); } - @Before + @BeforeEach public void setUp() throws Exception { sshd.setFileSystemFactory(fileSystemFactory); } diff --git a/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpCharsetTest.java b/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpCharsetTest.java index 5382ea024..fcb4b709e 100644 --- a/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpCharsetTest.java +++ b/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpCharsetTest.java @@ -31,19 +31,22 @@ import org.apache.sshd.scp.common.ScpException; import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.ContainerTestCase; -import org.junit.Rule; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.rules.TemporaryFolder; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.output.Slf4jLogConsumer; import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.images.builder.ImageFromDockerfile; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; import org.testcontainers.utility.MountableFile; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; + /** * Tests transferring a file named "äöü.txt" via SCP from a container that uses ISO-8859-15 as locale. The UTF-8 and * IOS-8859-15 encodings of these characters are different, so the file should not be found when the command is sent as @@ -51,15 +54,16 @@ * * @author Apache MINA SSHD Project */ -@Category(ContainerTestCase.class) +@Tag("ContainerTestCase") +@Testcontainers public class ScpCharsetTest extends BaseTestSupport { private static final Logger LOG = LoggerFactory.getLogger(ScpCharsetTest.class); private static final String TEST_RESOURCES = "org/apache/sshd/scp/client"; - @Rule - public GenericContainer sshdContainer = new GenericContainer<>(new ImageFromDockerfile() + @Container + GenericContainer sshdContainer = new GenericContainer<>(new ImageFromDockerfile() // Alpine would be smaller and start faster, but it has no locales. .withDockerfileFromBuilder(builder -> builder.from("ubuntu:20.04") // .run("apt-get update && apt-get install -y locales openssh-server") // @@ -78,15 +82,15 @@ public class ScpCharsetTest extends BaseTestSupport { .waitingFor(Wait.forLogMessage(".*Server listening on :: port 22.*\\n", 1)).withExposedPorts(22) // .withLogConsumer(new Slf4jLogConsumer(LOG)); - @Rule - public TemporaryFolder tmp = new TemporaryFolder(); + @TempDir + File tmp; public ScpCharsetTest() { super(); } @Test - public void testIsoLatin1() throws Exception { + void isoLatin1() throws Exception { FileKeyPairProvider keyPairProvider = CommonTestSupportUtils.createTestKeyPairProvider(TEST_RESOURCES + "/bob_key"); SshClient client = setupTestClient(); client.setKeyIdentityProvider(keyPairProvider); @@ -99,25 +103,27 @@ public void testIsoLatin1() throws Exception { session.auth().verify(AUTH_TIMEOUT); ScpClientCreator.instance(); ScpClient scpClient = ScpClientCreator.instance().createScpClient(session); - File file1 = new File(tmp.getRoot(), "file1.txt"); + File file1 = new File(tmp, "file1.txt"); scpClient.download("file1.txt", file1.getAbsolutePath()); - assertEquals("Unexpected content in file1.txt -> file1.txt", "test1\n", - new String(Files.readAllBytes(file1.toPath()), StandardCharsets.UTF_8)); - File file2 = new File(tmp.getRoot(), "file2.txt"); + assertEquals("test1\n", + new String(Files.readAllBytes(file1.toPath()), StandardCharsets.UTF_8), + "Unexpected content in file1.txt -> file1.txt"); + File file2 = new File(tmp, "file2.txt"); // Somehow there's only a WARNING in the log? Maybe the exit code is handled wrongly... (1 is taken as a // warning, but for exit codes, probably any non-zero value is an error?) In any case this should fail; // we should not have a "file2" afterwards. try { scpClient.download("äöü.txt", file2.getAbsolutePath()); - assertFalse("No file2.txt expected", file2.exists()); + assertFalse(file2.exists(), "No file2.txt expected"); } catch (NoSuchFileException | FileNotFoundException | ScpException e) { LOG.info("Expected failure for UTF-8 äöü: {}", e.toString()); } // But this should work: (The container uses ISO-8859-15, but the only difference is the Euro sign.) ScpModuleProperties.SCP_OUTGOING_ENCODING.set(session, StandardCharsets.ISO_8859_1); scpClient.download("äöü.txt", file2.getAbsolutePath()); - assertEquals("Unexpected content in file äöü.txt -> file2.txt", "test2\n", - new String(Files.readAllBytes(file2.toPath()), StandardCharsets.UTF_8)); + assertEquals("test2\n", + new String(Files.readAllBytes(file2.toPath()), StandardCharsets.UTF_8), + "Unexpected content in file äöü.txt -> file2.txt"); } } finally { client.stop(); diff --git a/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpRemote2RemoteTransferHelperTest.java b/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpRemote2RemoteTransferHelperTest.java index 2c17caf37..6efaccdf7 100644 --- a/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpRemote2RemoteTransferHelperTest.java +++ b/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpRemote2RemoteTransferHelperTest.java @@ -40,35 +40,34 @@ import org.apache.sshd.scp.common.helpers.ScpTimestampCommandDetails; import org.apache.sshd.scp.server.ScpCommandFactory; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class ScpRemote2RemoteTransferHelperTest extends AbstractScpTestSupport { - protected final Logger log; - private final boolean preserveAttributes; + protected Logger log; + private boolean preserveAttributes; - public ScpRemote2RemoteTransferHelperTest(boolean preserveAttributes) { + public void initScpRemote2RemoteTransferHelperTest(boolean preserveAttributes) { this.preserveAttributes = preserveAttributes; this.log = LoggerFactory.getLogger(getClass()); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { setupClientAndServer(ScpRemote2RemoteTransferHelperTest.class); ScpCommandFactory factory = (ScpCommandFactory) sshd.getCommandFactory(); @@ -118,13 +117,14 @@ public void endFolderEvent( }); } - @Parameters(name = "preserveAttributes={0}") public static List parameters() { return parameterize(Arrays.asList(Boolean.TRUE, Boolean.FALSE)); } - @Test - public void testTransferFiles() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "preserveAttributes={0}") + public void transferFiles(boolean preserveAttributes) throws Exception { + initScpRemote2RemoteTransferHelperTest(preserveAttributes); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path scpRoot = CommonTestSupportUtils.resolve(targetPath, @@ -152,8 +152,8 @@ public void startDirectFileTransfer( ClientSession dstSession, String destination, ScpTimestampCommandDetails timestamp, ScpReceiveFileCommandDetails details) throws IOException { - assertEquals("Mismatched start xfer source path", srcPath, source); - assertEquals("Mismatched start xfer destination path", dstPath, destination); + assertEquals(srcPath, source, "Mismatched start xfer source path"); + assertEquals(dstPath, destination, "Mismatched start xfer destination path"); } @Override @@ -163,11 +163,11 @@ public void endDirectFileTransfer( ScpTimestampCommandDetails timestamp, ScpReceiveFileCommandDetails details, long xferSize, Throwable thrown) throws IOException { - assertEquals("Mismatched end xfer source path", srcPath, source); - assertEquals("Mismatched end xfer destination path", dstPath, destination); + assertEquals(srcPath, source, "Mismatched end xfer source path"); + assertEquals(dstPath, destination, "Mismatched end xfer destination path"); long prev = xferCount.getAndSet(xferSize); - assertEquals("Mismatched 1st end file xfer size", 0L, prev); + assertEquals(0L, prev, "Mismatched 1st end file xfer size"); } @Override @@ -193,14 +193,16 @@ public void endDirectDirectoryTransfer( }); helper.transferFile(srcPath, dstPath, preserveAttributes); } - assertEquals("Mismatched transfer size", expectedData.length, xferCount.getAndSet(0L)); + assertEquals(expectedData.length, xferCount.getAndSet(0L), "Mismatched transfer size"); byte[] actualData = Files.readAllBytes(dstFile); - assertArrayEquals("Mismatched transfer contents", expectedData, actualData); + assertArrayEquals(expectedData, actualData, "Mismatched transfer contents"); } - @Test - public void testTransferDirectoriesRecursively() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "preserveAttributes={0}") + public void transferDirectoriesRecursively(boolean preserveAttributes) throws Exception { + initScpRemote2RemoteTransferHelperTest(preserveAttributes); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path scpRoot = CommonTestSupportUtils.resolve(targetPath, @@ -292,9 +294,9 @@ private static void validateXferDirContents(Path srcPath, Path dstPath) throws E } else { byte[] srcData = Files.readAllBytes(srcFile); byte[] dstData = Files.readAllBytes(dstFile); - assertEquals(name + "[DATA]", - new String(srcData, StandardCharsets.UTF_8), - new String(dstData, StandardCharsets.UTF_8)); + assertEquals(new String(srcData, StandardCharsets.UTF_8), + new String(dstData, StandardCharsets.UTF_8), + name + "[DATA]"); } } } @@ -304,9 +306,9 @@ private static void validateXferDirContents(Path srcPath, Path dstPath) throws E String name = dstFile.getFileName().toString(); Path srcFile = srcPath.resolve(name); if (Files.isDirectory(dstFile)) { - assertTrue(name + ": unmatched destination folder", Files.isDirectory(srcFile)); + assertTrue(Files.isDirectory(srcFile), name + ": unmatched destination folder"); } else { - assertTrue(name + ": unmatched destination file", Files.exists(srcFile)); + assertTrue(Files.exists(srcFile), name + ": unmatched destination file"); } } } diff --git a/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpTest.java b/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpTest.java index 658121eaf..d3ddac123 100644 --- a/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpTest.java +++ b/sshd-scp/src/test/java/org/apache/sshd/scp/client/ScpTest.java @@ -74,30 +74,37 @@ import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.JSchLogger; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * Test for SCP support. * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ScpTest extends AbstractScpTestSupport { public ScpTest() { super(); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { JSchLogger.init(); setupClientAndServer(ScpTest.class); } @Test - public void testNormalizedScpRemotePaths() throws Exception { + void normalizedScpRemotePaths() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path scpRoot = CommonTestSupportUtils.resolve(targetPath, @@ -133,13 +140,13 @@ public void testNormalizedScpRemotePaths() throws Exception { String path = sb.toString(); scp.upload(localPath, path); - assertTrue("Remote file not ready for " + path, - waitForFile(remoteFile, data.length, TimeUnit.SECONDS.toMillis(5L))); + assertTrue(waitForFile(remoteFile, data.length, TimeUnit.SECONDS.toMillis(5L)), + "Remote file not ready for " + path); byte[] actual = Files.readAllBytes(remoteFile); - assertArrayEquals("Mismatched uploaded data for " + path, data, actual); + assertArrayEquals(data, actual, "Mismatched uploaded data for " + path); Files.delete(remoteFile); - assertFalse("Remote file (" + remoteFile + ") not deleted for " + path, Files.exists(remoteFile)); + assertFalse(Files.exists(remoteFile), "Remote file (" + remoteFile + ") not deleted for " + path); } } } @@ -154,7 +161,7 @@ private static int slashify(StringBuilder sb, Random rnd) { } @Test - public void testUploadAbsoluteDriveLetter() throws Exception { + void uploadAbsoluteDriveLetter() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path scpRoot = CommonTestSupportUtils.resolve(targetPath, @@ -187,7 +194,7 @@ public void testUploadAbsoluteDriveLetter() throws Exception { } @Test - public void testScpUploadOverwrite() throws Exception { + void scpUploadOverwrite() throws Exception { String data = getClass().getName() + "#" + getCurrentTestName() + IoUtils.EOL; Path targetPath = detectTargetFolder(); @@ -213,7 +220,7 @@ public void testScpUploadOverwrite() throws Exception { } @Test - public void testScpUploadZeroLengthFile() throws Exception { + void scpUploadZeroLengthFile() throws Exception { Path targetPath = detectTargetFolder(); Path scpRoot = CommonTestSupportUtils.resolve(targetPath, ScpHelper.SCP_COMMAND_PREFIX, getClass().getSimpleName(), getCurrentTestName()); @@ -227,7 +234,7 @@ public void testScpUploadZeroLengthFile() throws Exception { fch.truncate(0L); } } - assertEquals("Non-zero size for local file=" + zeroLocal, 0L, Files.size(zeroLocal)); + assertEquals(0L, Files.size(zeroLocal), "Non-zero size for local file=" + zeroLocal); Path zeroRemote = remoteDir.resolve(zeroLocal.getFileName()); if (Files.exists(zeroRemote)) { @@ -242,7 +249,7 @@ public void testScpUploadZeroLengthFile() throws Exception { } @Test - public void testScpDownloadZeroLengthFile() throws Exception { + void scpDownloadZeroLengthFile() throws Exception { Path targetPath = detectTargetFolder(); Path scpRoot = CommonTestSupportUtils.resolve(targetPath, ScpHelper.SCP_COMMAND_PREFIX, getClass().getSimpleName(), getCurrentTestName()); @@ -260,7 +267,7 @@ public void testScpDownloadZeroLengthFile() throws Exception { fch.truncate(0L); } } - assertEquals("Non-zero size for remote file=" + zeroRemote, 0L, Files.size(zeroRemote)); + assertEquals(0L, Files.size(zeroRemote), "Non-zero size for remote file=" + zeroRemote); String remotePath = CommonTestSupportUtils.resolveRelativeRemotePath(targetPath.getParent(), zeroRemote); try (CloseableScpClient scp = createCloseableScpClient()) { @@ -270,7 +277,7 @@ public void testScpDownloadZeroLengthFile() throws Exception { } @Test - public void testScpNativeOnSingleFile() throws Exception { + void scpNativeOnSingleFile() throws Exception { String data = getClass().getName() + "#" + getCurrentTestName() + IoUtils.EOL; Path targetPath = detectTargetFolder(); @@ -287,7 +294,7 @@ public void testScpNativeOnSingleFile() throws Exception { try (CloseableScpClient scp = createCloseableScpClient()) { CommonTestSupportUtils.writeFile(localOutFile, data); - assertFalse("Remote folder already exists: " + remoteDir, Files.exists(remoteDir)); + assertFalse(Files.exists(remoteDir), "Remote folder already exists: " + remoteDir); String localOutPath = localOutFile.toString(); String remoteOutPath = CommonTestSupportUtils.resolveRelativeRemotePath(parentPath, remoteOutFile); @@ -319,7 +326,7 @@ public void testScpNativeOnSingleFile() throws Exception { } @Test - public void testScpNativeOnMultipleFiles() throws Exception { + void scpNativeOnMultipleFiles() throws Exception { try (CloseableScpClient scp = createCloseableScpClient()) { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); @@ -392,7 +399,7 @@ public void testScpNativeOnMultipleFiles() throws Exception { } @Test - public void testScpNativeOnRecursiveDirs() throws Exception { + void scpNativeOnRecursiveDirs() throws Exception { try (CloseableScpClient scp = createCloseableScpClient()) { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); @@ -425,8 +432,9 @@ public void testScpNativeOnRecursiveDirs() throws Exception { } } - @Test // see SSHD-893 - public void testScpNativeOnDirWithPattern() throws Exception { + // see SSHD-893 + @Test + void scpNativeOnDirWithPattern() throws Exception { try (CloseableScpClient scp = createCloseableScpClient()) { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); @@ -456,7 +464,7 @@ public void testScpNativeOnDirWithPattern() throws Exception { } @Test - public void testScpVirtualOnDirWithPattern() throws Exception { + void scpVirtualOnDirWithPattern() throws Exception { Path remoteDir = getTempTargetRelativeFile( getClass().getSimpleName(), getCurrentTestName(), ScpHelper.SCP_COMMAND_PREFIX, "virtual"); CommonTestSupportUtils.deleteRecursive(remoteDir); // start fresh @@ -499,7 +507,7 @@ public void testScpVirtualOnDirWithPattern() throws Exception { } @Test - public void testScpNativeOnMixedDirAndFiles() throws Exception { + void scpNativeOnMixedDirAndFiles() throws Exception { try (CloseableScpClient scp = createCloseableScpClient()) { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); @@ -528,7 +536,7 @@ public void testScpNativeOnMixedDirAndFiles() throws Exception { scp.download(remotePath + "/*", localDir); assertFileLength(local1, data.length, DEFAULT_TIMEOUT); - assertFalse("Unexpected recursive local file: " + localSub2, Files.exists(localSub2)); + assertFalse(Files.exists(localSub2), "Unexpected recursive local file: " + localSub2); Files.delete(local1); scp.download(remotePath + "/*", localDir, ScpClient.Option.Recursive); @@ -538,7 +546,7 @@ public void testScpNativeOnMixedDirAndFiles() throws Exception { } @Test - public void testScpNativePreserveAttributes() throws Exception { + void scpNativePreserveAttributes() throws Exception { try (CloseableScpClient scp = createCloseableScpClient()) { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); @@ -595,7 +603,7 @@ public void testScpNativePreserveAttributes() throws Exception { } @Test - public void testStreamsUploadAndDownload() throws Exception { + void streamsUploadAndDownload() throws Exception { try (CloseableScpClient scp = createCloseableScpClient()) { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); @@ -612,16 +620,17 @@ public void testStreamsUploadAndDownload() throws Exception { assertFileLength(remoteFile, data.length, DEFAULT_TIMEOUT); byte[] uploaded = Files.readAllBytes(remoteFile); - assertArrayEquals("Mismatched uploaded data", data, uploaded); + assertArrayEquals(data, uploaded, "Mismatched uploaded data"); outputDebugMessage("Download data from %s", remotePath); byte[] downloaded = scp.downloadBytes(remotePath); - assertArrayEquals("Mismatched downloaded data", uploaded, downloaded); + assertArrayEquals(uploaded, downloaded, "Mismatched downloaded data"); } } - @Test // see SSHD-649 - public void testScpFileOpener() throws Exception { + // see SSHD-649 + @Test + void scpFileOpener() throws Exception { class TrackingFileOpener extends DefaultScpFileOpener { private final AtomicInteger readCount = new AtomicInteger(0); private final AtomicInteger writeCount = new AtomicInteger(0); @@ -686,32 +695,33 @@ public OutputStream openWrite( assertFileLength(remoteFile, data.length, DEFAULT_TIMEOUT); AtomicInteger serverRead = serverOpener.getReadCount(); - assertEquals("Mismatched server upload open read count", 0, serverRead.get()); + assertEquals(0, serverRead.get(), "Mismatched server upload open read count"); AtomicInteger serverWrite = serverOpener.getWriteCount(); - assertEquals("Mismatched server upload write count", 1, serverWrite.getAndSet(0)); + assertEquals(1, serverWrite.getAndSet(0), "Mismatched server upload write count"); AtomicInteger clientRead = clientOpener.getReadCount(); - assertEquals("Mismatched client upload read count", 1, clientRead.getAndSet(0)); + assertEquals(1, clientRead.getAndSet(0), "Mismatched client upload read count"); AtomicInteger clientWrite = clientOpener.getWriteCount(); - assertEquals("Mismatched client upload write count", 0, clientWrite.get()); + assertEquals(0, clientWrite.get(), "Mismatched client upload write count"); Files.delete(localFile); scp.download(remotePath, localFile); assertFileLength(localFile, data.length, DEFAULT_TIMEOUT); - assertEquals("Mismatched server download open read count", 1, serverRead.getAndSet(0)); - assertEquals("Mismatched server download write count", 0, serverWrite.get()); - assertEquals("Mismatched client download read count", 0, clientRead.get()); - assertEquals("Mismatched client download write count", 1, clientWrite.getAndSet(0)); + assertEquals(1, serverRead.getAndSet(0), "Mismatched server download open read count"); + assertEquals(0, serverWrite.get(), "Mismatched server download write count"); + assertEquals(0, clientRead.get(), "Mismatched client download read count"); + assertEquals(1, clientWrite.getAndSet(0), "Mismatched client download write count"); } finally { factory.setScpFileOpener(opener); } } - @Test // see SSHD-628 - public void testScpExitStatusPropagation() throws Exception { + // see SSHD-628 + @Test + void scpExitStatusPropagation() throws Exception { int testExitValue = 7365; class InternalScpCommand extends ScpCommand { @@ -765,8 +775,8 @@ public Command createCommand(ChannelSession channel, String command) { outputDebugMessage("Upload success to %s", remotePath); } catch (ScpException e) { Integer exitCode = e.getExitStatus(); - assertNotNull("No upload exit status", exitCode); - assertEquals("Mismatched upload exit status", testExitValue, exitCode.intValue()); + assertNotNull(exitCode, "No upload exit status"); + assertEquals(testExitValue, exitCode.intValue(), "Mismatched upload exit status"); } if (Files.deleteIfExists(remoteFile)) { @@ -782,8 +792,8 @@ public Command createCommand(ChannelSession channel, String command) { outputDebugMessage("Download success to %s: %s", remotePath, new String(downloaded, StandardCharsets.UTF_8)); } catch (ScpException e) { Integer exitCode = e.getExitStatus(); - assertNotNull("No download exit status", exitCode); - assertEquals("Mismatched download exit status", testExitValue, exitCode.intValue()); + assertNotNull(exitCode, "No download exit status"); + assertEquals(testExitValue, exitCode.intValue(), "Mismatched download exit status"); } } finally { sshd.setCommandFactory(factory); @@ -819,12 +829,13 @@ private static void assertLastModifiedTimeEquals(File file, boolean modSuccess, .println(); } } else { - assertEquals("Mismatched last modified time for " + file.getAbsolutePath(), expectedSeconds, actualSeconds); + assertEquals(expectedSeconds, actualSeconds, "Mismatched last modified time for " + file.getAbsolutePath()); } } - @Test // see GH-428 - public void testMissingRemoteFile() throws Exception { + // see GH-428 + @Test + void missingRemoteFile() throws Exception { Path targetPath = detectTargetFolder(); Path scpRoot = CommonTestSupportUtils.resolve(targetPath, ScpHelper.SCP_COMMAND_PREFIX, getClass().getSimpleName(), getCurrentTestName()); @@ -834,20 +845,20 @@ public void testMissingRemoteFile() throws Exception { Path missingRemote = remoteDir.resolve(missingLocal.getFileName()); Files.deleteIfExists(missingLocal); Files.deleteIfExists(missingRemote); - assertFalse("Remote file not deleted", Files.exists(missingRemote)); + assertFalse(Files.exists(missingRemote), "Remote file not deleted"); String remotePath = CommonTestSupportUtils.resolveRelativeRemotePath(targetPath.getParent(), missingRemote); try (CloseableScpClient scp = createCloseableScpClient()) { scp.download(remotePath, missingLocal.toString()); fail("Unexpected success to copy non-existent remote file"); } catch (ScpException e) { - assertEquals("Mismatched SCP failure code", ScpAckInfo.ERROR, e.getExitStatus().intValue()); + assertEquals(ScpAckInfo.ERROR, e.getExitStatus().intValue(), "Mismatched SCP failure code"); } } @Test - public void testJschScp() throws Exception { + void jschScp() throws Exception { com.jcraft.jsch.Session session = getJschSession(); try { String data = getCurrentTestName() + "\n"; @@ -859,15 +870,15 @@ public void testJschScp() throws Exception { Path target = Paths.get(unixPath); CommonTestSupportUtils.deleteRecursive(root); Files.createDirectories(root); - assertTrue("Failed to ensure existence of " + root, Files.exists(root)); + assertTrue(Files.exists(root), "Failed to ensure existence of " + root); Files.deleteIfExists(target); - assertFalse("Failed to delete 1st time: " + target, Files.exists(target)); + assertFalse(Files.exists(target), "Failed to delete 1st time: " + target); sendFile(session, unixPath, target, data); assertFileLength(target, data.length(), DEFAULT_TIMEOUT); Files.deleteIfExists(target); - assertFalse("Failed to delete 2nd time: " + target, Files.exists(target)); + assertFalse(Files.exists(target), "Failed to delete 2nd time: " + target); sendFile(session, unixDir, target, data); assertFileLength(target, data.length(), DEFAULT_TIMEOUT); @@ -875,8 +886,8 @@ public void testJschScp() throws Exception { readFileError(session, unixDir); - assertEquals("Mismatched file data", data, readFile(session, unixPath, target)); - assertEquals("Mismatched dir data", data, readDir(session, unixDir, target)); + assertEquals(data, readFile(session, unixPath, target), "Mismatched file data"); + assertEquals(data, readDir(session, unixDir, target), "Mismatched dir data"); Files.deleteIfExists(target); Files.deleteIfExists(root); @@ -897,7 +908,7 @@ protected com.jcraft.jsch.Session getJschSession() throws JSchException { } @Test - public void testWithGanymede() throws Exception { + void withGanymede() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path scpRoot = CommonTestSupportUtils.resolve(targetPath, @@ -923,26 +934,26 @@ public void testWithGanymede() throws Exception { info.keyExchangeAlgorithm, info.serverHostKeyAlgorithm, info.clientToServerCryptoAlgorithm, info.serverToClientCryptoAlgorithm, info.clientToServerMACAlgorithm, info.serverToClientMACAlgorithm); - assertTrue("Failed to authenticate", conn.authenticateWithPassword(getCurrentTestName(), getCurrentTestName())); + assertTrue(conn.authenticateWithPassword(getCurrentTestName(), getCurrentTestName()), "Failed to authenticate"); SCPClient scpClient = new SCPClient(conn); try (OutputStream output = scpClient.put(fileName, expected.length, remotePath, mode)) { output.write(expected); } - assertTrue("Remote file not created: " + remoteFile, Files.exists(remoteFile)); + assertTrue(Files.exists(remoteFile), "Remote file not created: " + remoteFile); byte[] remoteData = Files.readAllBytes(remoteFile); - assertArrayEquals("Mismatched remote put data", expected, remoteData); + assertArrayEquals(expected, remoteData, "Mismatched remote put data"); Arrays.fill(remoteData, (byte) 0); // make sure we start with a clean slate try (InputStream input = scpClient.get(remotePath + "/" + fileName)) { int readLen = input.read(remoteData); - assertEquals("Mismatched remote get data size", expected.length, readLen); + assertEquals(expected.length, readLen, "Mismatched remote get data size"); // make sure we reached EOF - assertEquals("Unexpected extra data after read expected size", -1, input.read()); + assertEquals(-1, input.read(), "Unexpected extra data after read expected size"); } - assertArrayEquals("Mismatched remote get data", expected, remoteData); + assertArrayEquals(expected, remoteData, "Mismatched remote get data"); } finally { conn.close(); } @@ -964,7 +975,7 @@ protected String readFile(com.jcraft.jsch.Session session, String path, Path tar String expHeader = ScpReceiveFileCommandDetails.COMMAND_NAME + ScpReceiveFileCommandDetails.DEFAULT_FILE_OCTAL_PERMISSIONS + " " + Files.size(target) + " " + fileName; - assertEquals("Mismatched header for " + path, expHeader, header); + assertEquals(expHeader, header, "Mismatched header for " + path); String lenValue = header.substring(6, header.indexOf(' ', 6)); int length = Integer.parseInt(lenValue); @@ -973,7 +984,7 @@ protected String readFile(com.jcraft.jsch.Session session, String path, Path tar byte[] buffer = new byte[length]; length = is.read(buffer, 0, buffer.length); - assertEquals("Mismatched read data length for " + path, length, buffer.length); + assertEquals(length, buffer.length, "Mismatched read data length for " + path); assertAckReceived(is, "Read data of " + path); os.write(0); @@ -997,7 +1008,7 @@ protected String readDir(com.jcraft.jsch.Session session, String path, Path targ String header = ScpIoUtils.readLine(is, StandardCharsets.UTF_8, false); String expPrefix = ScpReceiveDirCommandDetails.COMMAND_NAME + ScpReceiveDirCommandDetails.DEFAULT_DIR_OCTAL_PERMISSIONS + " 0 "; - assertTrue("Bad header prefix for " + path + ": " + header, header.startsWith(expPrefix)); + assertTrue(header.startsWith(expPrefix), "Bad header prefix for " + path + ": " + header); ScpAckInfo.sendOk(os, StandardCharsets.UTF_8); header = ScpIoUtils.readLine(is, StandardCharsets.UTF_8, false); @@ -1005,19 +1016,19 @@ protected String readDir(com.jcraft.jsch.Session session, String path, Path targ String expHeader = ScpReceiveFileCommandDetails.COMMAND_NAME + ScpReceiveFileCommandDetails.DEFAULT_FILE_OCTAL_PERMISSIONS + " " + Files.size(target) + " " + fileName; - assertEquals("Mismatched dir header for " + path, expHeader, header); + assertEquals(expHeader, header, "Mismatched dir header for " + path); int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6))); ScpAckInfo.sendOk(os, StandardCharsets.UTF_8); byte[] buffer = new byte[length]; length = is.read(buffer, 0, buffer.length); - assertEquals("Mismatched read buffer size for " + path, length, buffer.length); + assertEquals(length, buffer.length, "Mismatched read buffer size for " + path); assertAckReceived(is, "Read date of " + path); ScpAckInfo.sendOk(os, StandardCharsets.UTF_8); header = ScpIoUtils.readLine(is, StandardCharsets.UTF_8, false); - assertEquals("Mismatched end value for " + path, "E", header); + assertEquals("E", header, "Mismatched end value for " + path); ScpAckInfo.sendOk(os, StandardCharsets.UTF_8); return new String(buffer, StandardCharsets.UTF_8); @@ -1036,7 +1047,7 @@ protected void readFileError(com.jcraft.jsch.Session session, String path) throw c.connect(); ScpAckInfo.sendOk(os, StandardCharsets.UTF_8); - assertEquals("Mismatched response for command: " + command, ScpAckInfo.ERROR, is.read()); + assertEquals(ScpAckInfo.ERROR, is.read(), "Mismatched response for command: " + command); } finally { c.disconnect(); } @@ -1078,7 +1089,7 @@ protected void assertAckReceived(OutputStream os, InputStream is, String command } protected void assertAckReceived(InputStream is, String command) throws IOException { - assertEquals("No ACK for command=" + command, 0, is.read()); + assertEquals(0, is.read(), "No ACK for command=" + command); } protected void sendFileError(com.jcraft.jsch.Session session, String path, String name, String data) throws Exception { @@ -1094,7 +1105,7 @@ protected void sendFileError(com.jcraft.jsch.Session session, String path, Strin command = "C7777 " + data.length() + " " + name; ScpIoUtils.writeLine(os, StandardCharsets.UTF_8, command); - assertEquals("Mismatched response for command=" + command, ScpAckInfo.ERROR, is.read()); + assertEquals(ScpAckInfo.ERROR, is.read(), "Mismatched response for command=" + command); } finally { c.disconnect(); } diff --git a/sshd-scp/src/test/java/org/apache/sshd/scp/client/SimpleScpClientTest.java b/sshd-scp/src/test/java/org/apache/sshd/scp/client/SimpleScpClientTest.java index 6e1f9ad65..3ac76d541 100644 --- a/sshd-scp/src/test/java/org/apache/sshd/scp/client/SimpleScpClientTest.java +++ b/sshd-scp/src/test/java/org/apache/sshd/scp/client/SimpleScpClientTest.java @@ -31,14 +31,19 @@ import org.apache.sshd.scp.server.ScpCommandFactory; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.client.simple.BaseSimpleClientTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SimpleScpClientTest extends BaseSimpleClientTestSupport { private final Path targetPath; private final Path parentPath; @@ -51,6 +56,7 @@ public SimpleScpClientTest() throws Exception { fileSystemFactory = new VirtualFileSystemFactory(parentPath); } + @BeforeEach @Override public void setUp() throws Exception { super.setUp(); @@ -61,21 +67,21 @@ public void setUp() throws Exception { } @Test - public void testSessionClosedWhenClientClosed() throws Exception { + void sessionClosedWhenClientClosed() throws Exception { try (CloseableScpClient scp = login()) { - assertTrue("SCP not open", scp.isOpen()); + assertTrue(scp.isOpen(), "SCP not open"); Session session = scp.getClientSession(); - assertTrue("Session not open", session.isOpen()); + assertTrue(session.isOpen(), "Session not open"); scp.close(); - assertFalse("Session not closed", session.isOpen()); - assertFalse("SCP not closed", scp.isOpen()); + assertFalse(session.isOpen(), "Session not closed"); + assertFalse(scp.isOpen(), "SCP not closed"); } } @Test - public void testScpUploadProxy() throws Exception { + void scpUploadProxy() throws Exception { try (CloseableScpClient scp = login()) { Path scpRoot = CommonTestSupportUtils.resolve(targetPath, ScpHelper.SCP_COMMAND_PREFIX, getClass().getSimpleName(), getCurrentTestName()); @@ -92,12 +98,12 @@ public void testScpUploadProxy() throws Exception { scp.upload(localFile, remotePath); byte[] uploaded = Files.readAllBytes(remoteFile); - assertArrayEquals("Mismatched uploaded data", written, uploaded); + assertArrayEquals(written, uploaded, "Mismatched uploaded data"); } } @Test - public void testScpDownloadProxy() throws Exception { + void scpDownloadProxy() throws Exception { try (CloseableScpClient scp = login()) { Path scpRoot = CommonTestSupportUtils.resolve(targetPath, ScpHelper.SCP_COMMAND_PREFIX, getClass().getSimpleName(), getCurrentTestName()); @@ -113,7 +119,7 @@ public void testScpDownloadProxy() throws Exception { scp.download(remotePath, localFile); byte[] downloaded = Files.readAllBytes(localFile); - assertArrayEquals("Mismatched downloaded data", written, downloaded); + assertArrayEquals(written, downloaded, "Mismatched downloaded data"); } } diff --git a/sshd-scp/src/test/java/org/apache/sshd/scp/common/ScpLocationParsingTest.java b/sshd-scp/src/test/java/org/apache/sshd/scp/common/ScpLocationParsingTest.java index 9aa52ca83..1cfa7a165 100644 --- a/sshd-scp/src/test/java/org/apache/sshd/scp/common/ScpLocationParsingTest.java +++ b/sshd-scp/src/test/java/org/apache/sshd/scp/common/ScpLocationParsingTest.java @@ -23,36 +23,30 @@ import java.util.List; import org.apache.sshd.common.SshConstants; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class ScpLocationParsingTest extends JUnitTestSupport { - private final String value; - private final ScpLocation location; + private String value; + private ScpLocation location; - public ScpLocationParsingTest(String value, ScpLocation location) { + public void initScpLocationParsingTest(String value, ScpLocation location) { this.value = value; this.location = location; } - @Parameters(name = "value={0}") public static List parameters() { return new ArrayList() { // not serializing it @@ -75,17 +69,21 @@ private void addTestCase(String value, ScpLocation expected) { }; } - @Test - public void testLocationParsing() { + @MethodSource("parameters") + @ParameterizedTest(name = "value={0}") + public void locationParsing(String value, ScpLocation location) { + initScpLocationParsingTest(value, location); ScpLocation actual = ScpLocation.parse(value); assertEquals(location, actual); } - @Test - public void testLocationToString() { - Assume.assumeTrue("No expected value to compate", location != null); - Assume.assumeTrue("Default port being used", - location.isLocal() || (location.resolvePort() != SshConstants.DEFAULT_PORT)); + @MethodSource("parameters") + @ParameterizedTest(name = "value={0}") + public void locationToString(String value, ScpLocation location) { + initScpLocationParsingTest(value, location); + Assumptions.assumeTrue(location != null, "No expected value to compate"); + Assumptions.assumeTrue(location.isLocal() || (location.resolvePort() != SshConstants.DEFAULT_PORT), + "Default port being used"); String spec = location.toString(); assertEquals(value, spec); } diff --git a/sshd-scp/src/test/java/org/apache/sshd/scp/common/helpers/AbstractScpCommandDetailsTest.java b/sshd-scp/src/test/java/org/apache/sshd/scp/common/helpers/AbstractScpCommandDetailsTest.java index 8bfcfc7ef..ce260bb47 100644 --- a/sshd-scp/src/test/java/org/apache/sshd/scp/common/helpers/AbstractScpCommandDetailsTest.java +++ b/sshd-scp/src/test/java/org/apache/sshd/scp/common/helpers/AbstractScpCommandDetailsTest.java @@ -23,37 +23,31 @@ import java.util.ArrayList; import java.util.List; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @param Generic {@link AbstractScpCommandDetails} type * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class AbstractScpCommandDetailsTest extends JUnitTestSupport { - private final String header; - private final Constructor ctor; + private String header; + private Constructor ctor; - public AbstractScpCommandDetailsTest(String header, Class cmdClass) throws Exception { + public void initAbstractScpCommandDetailsTest(String header, Class cmdClass) throws Exception { this.header = header; this.ctor = cmdClass.getDeclaredConstructor(String.class); } - @Parameters(name = "cmd={0}") public static List parameters() { return new ArrayList() { // not serializing it @@ -72,17 +66,21 @@ private void addTestCase(String header, Class cmdClass) throws Exception { + initAbstractScpCommandDetailsTest(header, cmdClass); C details = ctor.newInstance(header); assertEquals(header, details.toHeader()); } - @Test - public void testDetailsEquality() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "cmd={0}") + public void detailsEquality(String header, Class cmdClass) throws Exception { + initAbstractScpCommandDetailsTest(header, cmdClass); C d1 = ctor.newInstance(header); C d2 = ctor.newInstance(header); - assertEquals("HASH ?", d1.hashCode(), d2.hashCode()); - assertEquals("EQ ?", d1, d2); + assertEquals(d1.hashCode(), d2.hashCode(), "HASH ?"); + assertEquals(d1, d2, "EQ ?"); } } diff --git a/sshd-scp/src/test/java/org/apache/sshd/scp/server/ScpCommandFactoryTest.java b/sshd-scp/src/test/java/org/apache/sshd/scp/server/ScpCommandFactoryTest.java index 335522c82..476c9eb13 100644 --- a/sshd-scp/src/test/java/org/apache/sshd/scp/server/ScpCommandFactoryTest.java +++ b/sshd-scp/src/test/java/org/apache/sshd/scp/server/ScpCommandFactoryTest.java @@ -25,18 +25,22 @@ import org.apache.sshd.scp.common.ScpHelper; import org.apache.sshd.server.command.CommandFactory; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ScpCommandFactoryTest extends BaseTestSupport { public ScpCommandFactoryTest() { super(); @@ -46,19 +50,19 @@ public ScpCommandFactoryTest() { * Make sure that the builder returns a factory with the default values if no {@code withXXX} method is invoked */ @Test - public void testBuilderDefaultFactoryValues() { + void builderDefaultFactoryValues() { ScpCommandFactory factory = new ScpCommandFactory.Builder().build(); - assertNull("Mismatched delegate", factory.getDelegateCommandFactory()); - assertNull("Mismatched executor", factory.getExecutorServiceProvider()); - assertEquals("Mismatched send size", ScpHelper.DEFAULT_SEND_BUFFER_SIZE, factory.getSendBufferSize()); - assertEquals("Mismatched receive size", ScpHelper.DEFAULT_RECEIVE_BUFFER_SIZE, factory.getReceiveBufferSize()); + assertNull(factory.getDelegateCommandFactory(), "Mismatched delegate"); + assertNull(factory.getExecutorServiceProvider(), "Mismatched executor"); + assertEquals(ScpHelper.DEFAULT_SEND_BUFFER_SIZE, factory.getSendBufferSize(), "Mismatched send size"); + assertEquals(ScpHelper.DEFAULT_RECEIVE_BUFFER_SIZE, factory.getReceiveBufferSize(), "Mismatched receive size"); } /** * Make sure that the builder initializes correctly the built factory */ @Test - public void testBuilderCorrectlyInitializesFactory() { + void builderCorrectlyInitializesFactory() { CommandFactory delegate = dummyFactory(); CloseableExecutorService service = dummyExecutor(); Supplier provider = () -> service; @@ -70,10 +74,10 @@ public void testBuilderCorrectlyInitializesFactory() { .withSendBufferSize(sendSize) .withReceiveBufferSize(receiveSize) .build(); - assertSame("Mismatched delegate", delegate, factory.getDelegateCommandFactory()); - assertSame("Mismatched executor", provider, factory.getExecutorServiceProvider()); - assertEquals("Mismatched send size", sendSize, factory.getSendBufferSize()); - assertEquals("Mismatched receive size", receiveSize, factory.getReceiveBufferSize()); + assertSame(delegate, factory.getDelegateCommandFactory(), "Mismatched delegate"); + assertSame(provider, factory.getExecutorServiceProvider(), "Mismatched executor"); + assertEquals(sendSize, factory.getSendBufferSize(), "Mismatched send size"); + assertEquals(receiveSize, factory.getReceiveBufferSize(), "Mismatched receive size"); } /** @@ -85,15 +89,15 @@ public void testBuilderCorrectlyInitializesFactory() { * {@link ScpCommandFactory.Builder#build()} method Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class ScpReceiveDirCommandDetailsTest extends JUnitTestSupport { public ScpReceiveDirCommandDetailsTest() { super(); } @Test - public void testLengthDoesNotInfluenceEquality() { + void lengthDoesNotInfluenceEquality() { ScpReceiveDirCommandDetails d1 = new ScpReceiveDirCommandDetails("D0555 0 " + getCurrentTestName()); ScpReceiveDirCommandDetails d2 = new ScpReceiveDirCommandDetails(d1.toHeader()); d2.setLength(d1.getLength() + 1234L); - assertNotEquals("Len ?", d1.getLength(), d2.getLength()); - assertEquals("Hash ?", d1.hashCode(), d2.hashCode()); - assertEquals("EQ", d1, d2); + assertNotEquals(d1.getLength(), d2.getLength(), "Len ?"); + assertEquals(d1.hashCode(), d2.hashCode(), "Hash ?"); + assertEquals(d1, d2, "EQ"); } } diff --git a/sshd-sftp/pom.xml b/sshd-sftp/pom.xml index f98db9ac9..eedf20d87 100644 --- a/sshd-sftp/pom.xml +++ b/sshd-sftp/pom.xml @@ -40,7 +40,7 @@ sshd-core ${project.version} - + org.apache.sshd sshd-core @@ -48,6 +48,16 @@ test-jar test + + org.junit.jupiter + junit-jupiter + test + + + org.mockito + mockito-junit-jupiter + test + org.apache.sshd sshd-common @@ -65,6 +75,11 @@ testcontainers test + + org.testcontainers + junit-jupiter + test + org.testcontainers toxiproxy diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/AbstractSftpClientTestSupport.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/AbstractSftpClientTestSupport.java index ed3dbad7f..bc529bfec 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/AbstractSftpClientTestSupport.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/AbstractSftpClientTestSupport.java @@ -33,8 +33,11 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CoreTestSupportUtils; import org.apache.sshd.util.test.JSchLogger; -import org.junit.AfterClass; -import org.junit.BeforeClass; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project @@ -46,13 +49,13 @@ public abstract class AbstractSftpClientTestSupport extends BaseTestSupport { protected final FileSystemFactory fileSystemFactory; - protected AbstractSftpClientTestSupport() throws IOException { + protected AbstractSftpClientTestSupport() { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); fileSystemFactory = new VirtualFileSystemFactory(parentPath); } - @BeforeClass + @BeforeAll public static void setupClientAndServer() throws Exception { JSchLogger.init(); sshd = CoreTestSupportUtils.setupTestFullSupportServer(AbstractSftpClientTestSupport.class); @@ -64,7 +67,7 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass + @AfterAll public static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { @@ -123,8 +126,8 @@ protected SftpClient createSftpClient(ClientSession session, int selector) throw protected static E assertExtensionCreated(SftpClient sftp, Class type) { E instance = sftp.getExtension(type); - assertNotNull("Extension not created: " + type.getSimpleName(), instance); - assertTrue("Extension not supported: " + instance.getName(), instance.isSupported()); + assertNotNull(instance, "Extension not created: " + type.getSimpleName()); + assertTrue(instance.isSupported(), "Extension not supported: " + instance.getName()); return instance; } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/ClientTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/ClientTest.java index 5b01a1843..3f797a806 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/ClientTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/ClientTest.java @@ -66,18 +66,24 @@ import org.apache.sshd.util.test.EchoShell; import org.apache.sshd.util.test.EchoShellFactory; import org.apache.sshd.util.test.TestChannelListener; -import org.junit.After; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) @SuppressWarnings("checkstyle:MethodCount") public class ClientTest extends BaseTestSupport { private SshServer sshd; @@ -92,25 +98,25 @@ public class ClientTest extends BaseTestSupport { @Override public void sessionCreated(Session session) { assertObjectInstanceOf("Non client session creation notification", ClientSession.class, session); - assertNull("Multiple creation notifications", clientSessionHolder.getAndSet((ClientSession) session)); + assertNull(clientSessionHolder.getAndSet((ClientSession) session), "Multiple creation notifications"); } @Override public void sessionEvent(Session session, Event event) { assertObjectInstanceOf("Non client session event notification: " + event, ClientSession.class, session); - assertSame("Mismatched client session event instance: " + event, clientSessionHolder.get(), session); + assertSame(clientSessionHolder.get(), session, "Mismatched client session event instance: " + event); } @Override public void sessionException(Session session, Throwable t) { assertObjectInstanceOf("Non client session exception notification", ClientSession.class, session); - assertNotNull("No session exception data", t); + assertNotNull(t, "No session exception data"); } @Override public void sessionClosed(Session session) { assertObjectInstanceOf("Non client session closure notification", ClientSession.class, session); - assertSame("Mismatched client session closure instance", clientSessionHolder.getAndSet(null), session); + assertSame(clientSessionHolder.getAndSet(null), session, "Mismatched client session closure instance"); } }; @@ -118,8 +124,8 @@ public ClientTest() { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { authLatch = new CountDownLatch(0); channelLatch = new CountDownLatch(0); @@ -172,8 +178,8 @@ public String toString() { client.addSessionListener(clientSessionListener); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (sshd != null) { sshd.stop(true); } @@ -184,22 +190,22 @@ public void tearDown() throws Exception { } @Test - public void testSimpleClientListener() throws Exception { + void simpleClientListener() throws Exception { AtomicReference channelHolder = new AtomicReference<>(null); client.addChannelListener(new ChannelListener() { @Override public void channelOpenSuccess(Channel channel) { - assertSame("Mismatched opened channel instances", channel, channelHolder.get()); + assertSame(channel, channelHolder.get(), "Mismatched opened channel instances"); } @Override public void channelOpenFailure(Channel channel, Throwable reason) { - assertSame("Mismatched failed open channel instances", channel, channelHolder.get()); + assertSame(channel, channelHolder.get(), "Mismatched failed open channel instances"); } @Override public void channelInitialized(Channel channel) { - assertNull("Multiple channel initialization notifications", channelHolder.getAndSet(channel)); + assertNull(channelHolder.getAndSet(channel), "Multiple channel initialization notifications"); } @Override @@ -209,7 +215,7 @@ public void channelStateChanged(Channel channel, String hint) { @Override public void channelClosed(Channel channel, Throwable reason) { - assertSame("Mismatched closed channel instances", channel, channelHolder.getAndSet(null)); + assertSame(channel, channelHolder.getAndSet(null), "Mismatched closed channel instances"); } }); sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory())); @@ -247,7 +253,7 @@ public void channelClosed(Channel channel, Throwable reason) { private void testClientListener( AtomicReference channelHolder, Class channelType, Factory factory) throws Exception { - assertNull(channelType.getSimpleName() + ": Unexpected currently active channel", channelHolder.get()); + assertNull(channelHolder.get(), channelType.getSimpleName() + ": Unexpected currently active channel"); try (C instance = factory.create()) { Channel expectedChannel; @@ -260,14 +266,14 @@ private void testClientListener( } Channel actualChannel = channelHolder.get(); - assertSame("Mismatched listener " + channelType.getSimpleName() + " instances", expectedChannel, actualChannel); + assertSame(expectedChannel, actualChannel, "Mismatched listener " + channelType.getSimpleName() + " instances"); } - assertNull(channelType.getSimpleName() + ": Active channel closure not signalled", channelHolder.get()); + assertNull(channelHolder.get(), channelType.getSimpleName() + ": Active channel closure not signalled"); } @Test - public void testCreateChannelByType() throws Exception { + void createChannelByType() throws Exception { client.start(); Collection channels = new LinkedList<>(); @@ -281,7 +287,7 @@ public void testCreateChannelByType() throws Exception { Set ids = new HashSet<>(channels.size()); for (ClientChannel c : channels) { long id = c.getChannelId(); - assertTrue("Channel ID repeated: " + id, ids.add(id)); + assertTrue(ids.add(id), "Channel ID repeated: " + id); } } finally { for (Closeable c : channels) { @@ -294,7 +300,7 @@ public void testCreateChannelByType() throws Exception { client.stop(); } - assertNull("Session closure not signalled", clientSessionHolder.get()); + assertNull(clientSessionHolder.get(), "Session closure not signalled"); } /** @@ -304,7 +310,7 @@ public void testCreateChannelByType() throws Exception { * @throws Exception If failed */ @Test - public void testChannelListenersPropagation() throws Exception { + void channelListenersPropagation() throws Exception { Map clientListeners = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); addChannelListener(clientListeners, client, new TestChannelListener(client.getClass().getSimpleName())); @@ -347,24 +353,24 @@ private static void assertListenerSizes( for (TestChannelListener l : listeners) { if (activeSize >= 0) { - assertEquals(phase + ": mismatched active channels size for " + l.getName() + " listener", - activeSize, GenericUtils.size(l.getActiveChannels())); + assertEquals(activeSize, GenericUtils.size(l.getActiveChannels()), + phase + ": mismatched active channels size for " + l.getName() + " listener"); } if (openSize >= 0) { - assertEquals(phase + ": mismatched open channels size for " + l.getName() + " listener", - openSize, GenericUtils.size(l.getOpenChannels())); + assertEquals(openSize, GenericUtils.size(l.getOpenChannels()), + phase + ": mismatched open channels size for " + l.getName() + " listener"); } - assertEquals(phase + ": unexpected failed channels size for " + l.getName() + " listener", - 0, GenericUtils.size(l.getFailedChannels())); + assertEquals(0, GenericUtils.size(l.getFailedChannels()), + phase + ": unexpected failed channels size for " + l.getName() + " listener"); } } private static void addChannelListener( Map listeners, ChannelListenerManager manager, L listener) { String name = listener.getName(); - assertNull("Duplicate listener named " + name, listeners.put(name, listener)); + assertNull(listeners.put(name, listener), "Duplicate listener named " + name); manager.addChannelListener(listener); } @@ -372,7 +378,7 @@ private ClientSession createTestClientSession() throws IOException { ClientSession session = createTestClientSession(TEST_LOCALHOST); try { InetSocketAddress addr = SshdSocketAddress.toInetSocketAddress(session.getConnectAddress()); - assertEquals("Mismatched connect host", TEST_LOCALHOST, addr.getHostString()); + assertEquals(TEST_LOCALHOST, addr.getHostString(), "Mismatched connect host"); ClientSession returnValue = session; session = null; // avoid 'finally' close @@ -388,13 +394,13 @@ private ClientSession createTestClientSession(String host) throws IOException { ClientSession session = client.connect(getCurrentTestName(), host, port) .verify(CONNECT_TIMEOUT).getSession(); try { - assertNotNull("Client session creation not signalled", clientSessionHolder.get()); + assertNotNull(clientSessionHolder.get(), "Client session creation not signalled"); session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(AUTH_TIMEOUT); InetSocketAddress addr = SshdSocketAddress.toInetSocketAddress(session.getConnectAddress()); - assertNotNull("No reported connect address", addr); - assertEquals("Mismatched connect port", port, addr.getPort()); + assertNotNull(addr, "No reported connect address"); + assertEquals(port, addr.getPort(), "Mismatched connect port"); ClientSession returnValue = session; session = null; // avoid 'finally' close diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/DefaultCloseableHandleTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/DefaultCloseableHandleTest.java index d5762a7b4..a03a5c887 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/DefaultCloseableHandleTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/DefaultCloseableHandleTest.java @@ -27,53 +27,56 @@ import org.apache.sshd.sftp.client.SftpClient.Handle; import org.apache.sshd.sftp.client.impl.DefaultCloseableHandle; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.ArgumentMatchers; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class DefaultCloseableHandleTest extends JUnitTestSupport { public DefaultCloseableHandleTest() { super(); } @Test - public void testChannelBehavior() throws IOException { + void channelBehavior() throws IOException { final byte[] id = getCurrentTestName().getBytes(StandardCharsets.UTF_8); SftpClient client = Mockito.mock(SftpClient.class); Mockito.doAnswer(invocation -> { Object[] args = invocation.getArguments(); Handle handle = (Handle) args[0]; - assertArrayEquals("Mismatched closing handle", id, handle.getIdentifier()); + assertArrayEquals(id, handle.getIdentifier(), "Mismatched closing handle"); return null; }).when(client).close(ArgumentMatchers.any(Handle.class)); CloseableHandle handle = new DefaultCloseableHandle(client, getCurrentTestName(), id); try { - assertTrue("Handle not initially open", handle.isOpen()); + assertTrue(handle.isOpen(), "Handle not initially open"); } finally { handle.close(); } - assertFalse("Handle not marked as closed", handle.isOpen()); + assertFalse(handle.isOpen(), "Handle not marked as closed"); // make sure close was called Mockito.verify(client).close(handle); } @Test - public void testCloseIdempotent() throws IOException { + void closeIdempotent() throws IOException { SftpClient client = Mockito.mock(SftpClient.class); final AtomicBoolean closeCalled = new AtomicBoolean(false); Mockito.doAnswer(invocation -> { Object[] args = invocation.getArguments(); - assertFalse("Close already called on handle=" + args[0], closeCalled.getAndSet(true)); + assertFalse(closeCalled.getAndSet(true), "Close already called on handle=" + args[0]); return null; }).when(client).close(ArgumentMatchers.any(Handle.class)); @@ -83,6 +86,6 @@ public void testCloseIdempotent() throws IOException { handle.close(); } - assertTrue("Close method not called", closeCalled.get()); + assertTrue(closeCalled.get(), "Close method not called"); } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpPerformanceTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpPerformanceTest.java index 488a52f7b..51eb5f341 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpPerformanceTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpPerformanceTest.java @@ -40,15 +40,15 @@ import org.apache.sshd.sftp.client.SftpClient.OpenMode; import org.apache.sshd.sftp.client.fs.SftpFileSystem; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.Ignore; import org.junit.Rule; -import org.junit.Test; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.Network; import org.testcontainers.containers.ToxiproxyContainer; import org.testcontainers.containers.ToxiproxyContainer.ContainerProxy; -@Ignore("Special class used for development only - not really a test just useful to run as such") +@Disabled("Special class used for development only - not really a test just useful to run as such") public class SftpPerformanceTest { public static final Duration SFTP_CONNECT_TIMEOUT = CoreTestSupportUtils.getTimeout("sftp.connect", Duration.ofSeconds(30)); public static final Duration SFTP_AUTH_TIMEOUT = CoreTestSupportUtils.getTimeout("sftp.auth", Duration.ofSeconds(15)); @@ -78,7 +78,7 @@ public SftpPerformanceTest() { } @Test - public void testUploadLatency() throws IOException { + void uploadLatency() throws IOException { final ContainerProxy proxy = toxiproxy.getProxy(sftp, 22); for (int latency : Arrays.asList(0, 1, 5, 10, 50, 100, 500)) { Latency toxic = proxy.toxics().latency("latency", ToxicDirection.DOWNSTREAM, latency); @@ -102,7 +102,7 @@ public void testUploadLatency() throws IOException { } @Test - public void testDownloadLatency() throws IOException { + void downloadLatency() throws IOException { final ContainerProxy proxy = toxiproxy.getProxy(sftp, 22); for (int latency : Arrays.asList(0, 1, 5, 10, 50, 100, 500)) { Latency toxic = proxy.toxics().latency("latency", ToxicDirection.DOWNSTREAM, latency); diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTest.java index d03f92c5a..c541c53a6 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTest.java @@ -111,20 +111,26 @@ import org.apache.sshd.sftp.server.SftpSubsystemProxy; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.SimpleUserInfo; -import org.junit.After; -import org.junit.Assume; -import org.junit.Before; -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.jupiter.api.AfterEach; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) +@TestMethodOrder(MethodName.class) @SuppressWarnings("checkstyle:MethodCount") public class SftpTest extends AbstractSftpClientTestSupport { private static final Map EXPECTED_EXTENSIONS @@ -132,13 +138,13 @@ public class SftpTest extends AbstractSftpClientTestSupport { private com.jcraft.jsch.Session session; - private final int sftpHandleSize; + private int sftpHandleSize; - public SftpTest(int handleSize) throws IOException { + public void initSftpTest(int handleSize) throws Exception { sftpHandleSize = handleSize; + setUp(); } - @Parameterized.Parameters(name = "FILE_HANDLE_SIZE {0}") public static List getParameters() { List result = new ArrayList<>(); result.add(Integer.valueOf(4)); @@ -146,8 +152,7 @@ public static List getParameters() { return result; } - @Before - public void setUp() throws Exception { + void setUp() throws Exception { setupServer(); Map props = sshd.getProperties(); @@ -163,15 +168,17 @@ public void setUp() throws Exception { session.connect(); } - @After - public void tearDown() throws Exception { + @AfterEach + void tearDown() throws Exception { if (session != null) { session.disconnect(); } } - @Test // see SSHD-547 - public void testWriteOffsetIgnoredForAppendMode() throws IOException { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-547 + public void writeOffsetIgnoredForAppendMode(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve( @@ -200,29 +207,30 @@ public void testWriteOffsetIgnoredForAppendMode() throws IOException { // Read the full random data byte[] actualRandom = new byte[expectedRandom.length]; readLen = sftp.read(handle, 0L, actualRandom); - assertEquals("Incomplete random data read", expectedRandom.length, readLen); - assertArrayEquals("Mismatched read random data", expectedRandom, actualRandom); + assertEquals(expectedRandom.length, readLen, "Incomplete random data read"); + assertArrayEquals(expectedRandom, actualRandom, "Mismatched read random data"); // Read the data from the second write byte[] actualText = new byte[expectedText.length]; readLen = sftp.read(handle, actualRandom.length, actualText); - assertEquals("Incomplete text data read", actualText.length, readLen); - assertArrayEquals("Mismatched read text data", expectedText, actualText); + assertEquals(actualText.length, readLen, "Incomplete text data read"); + assertArrayEquals(expectedText, actualText, "Mismatched read text data"); } byte[] actualBytes = Files.readAllBytes(testFile); - assertEquals("Mismatched result file size", - expectedRandom.length + expectedText.length, actualBytes.length); + assertEquals(expectedRandom.length + expectedText.length, actualBytes.length, "Mismatched result file size"); byte[] actualRandom = Arrays.copyOfRange(actualBytes, 0, expectedRandom.length); - assertArrayEquals("Mismatched random part", expectedRandom, actualRandom); + assertArrayEquals(expectedRandom, actualRandom, "Mismatched random part"); byte[] actualText = Arrays.copyOfRange(actualBytes, expectedRandom.length, actualBytes.length); - assertArrayEquals("Mismatched text part", expectedText, actualText); + assertArrayEquals(expectedText, actualText, "Mismatched text part"); } - @Test // see SSHD-545 - public void testReadBufferLimit() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-545 + public void readBufferLimit(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve( @@ -243,21 +251,24 @@ public void testReadBufferLimit() throws Exception { try (SftpClient sftp = createSingleSessionClient(); CloseableHandle handle = sftp.open(file, OpenMode.Read)) { int readLen = sftp.read(handle, 0L, actual); - assertEquals("Mismatched read len", maxAllowed, readLen); + assertEquals(maxAllowed, readLen, "Mismatched read len"); for (int index = 0; index < readLen; index++) { byte expByte = expected[index]; byte actByte = actual[index]; - assertEquals("Mismatched values at index=" + index, Integer.toHexString(expByte & 0xFF), - Integer.toHexString(actByte & 0xFF)); + assertEquals(Integer.toHexString(expByte & 0xFF), + Integer.toHexString(actByte & 0xFF), + "Mismatched values at index=" + index); } } finally { SftpModuleProperties.MAX_READDATA_PACKET_LENGTH.remove(sshd); } } - @Test // see SSHD-1287 - public void testReadWithLargeBuffer() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-1287 + public void readWithLargeBuffer(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), @@ -284,23 +295,26 @@ public void testReadWithLargeBuffer() throws Exception { } off += n; } - assertEquals("Short read", actual.length, off); + assertEquals(actual.length, off, "Short read"); if (n >= 0) { n = in.read(); - assertTrue("Stream not at eof", n < 0); + assertTrue(n < 0, "Stream not at eof"); } } for (int index = 0; index < actual.length; index++) { byte expByte = expected[index]; byte actByte = actual[index]; - assertEquals("Mismatched values at index=" + index, Integer.toHexString(expByte & 0xFF), - Integer.toHexString(actByte & 0xFF)); + assertEquals(Integer.toHexString(expByte & 0xFF), + Integer.toHexString(actByte & 0xFF), + "Mismatched values at index=" + index); } } } - @Test // see SSHD-1287 - public void testZeroRead() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-1287 + public void zeroRead(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), @@ -329,25 +343,28 @@ public void testZeroRead() throws Exception { break; } } - assertEquals("Short read", actual.length, off); + assertEquals(actual.length, off, "Short read"); if (n >= 0) { n = in.read(); - assertTrue("Stream not at eof", n < 0); + assertTrue(n < 0, "Stream not at eof"); } } for (int index = 0; index < actual.length; index++) { byte expByte = expected[index]; byte actByte = actual[index]; - assertEquals("Mismatched values at index=" + index, Integer.toHexString(expByte & 0xFF), - Integer.toHexString(actByte & 0xFF)); + assertEquals(Integer.toHexString(expByte & 0xFF), + Integer.toHexString(actByte & 0xFF), + "Mismatched values at index=" + index); } } } - @Test // see SSHD-1288 - public void testReadWriteDownload() throws Exception { - Assume.assumeTrue("Not sure appending to a file opened for reading works on Windows", - OsUtils.isUNIX() || OsUtils.isOSX()); + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-1288 + public void readWriteDownload(int handleSize) throws Exception { + initSftpTest(handleSize); + Assumptions.assumeTrue(OsUtils.isUNIX() || OsUtils.isOSX(), + "Not sure appending to a file opened for reading works on Windows"); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), @@ -374,23 +391,26 @@ public void testReadWriteDownload() throws Exception { } actual = buf.toByteArray(); } - assertEquals("Short read", 2 * expected.length, actual.length); + assertEquals(2 * expected.length, actual.length, "Short read"); for (int i = 0, j = 0; i < actual.length; i++, j++) { if (j >= expected.length) { j = 0; } byte expByte = expected[j]; byte actByte = actual[i]; - assertEquals("Mismatched values at index=" + i, Integer.toHexString(expByte & 0xFF), - Integer.toHexString(actByte & 0xFF)); + assertEquals(Integer.toHexString(expByte & 0xFF), + Integer.toHexString(actByte & 0xFF), + "Mismatched values at index=" + i); } } } - @Test - public void testEmptyFileDownload() throws Exception { - Assume.assumeTrue("Not sure appending to a file opened for reading works on Windows", - OsUtils.isUNIX() || OsUtils.isOSX()); + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void emptyFileDownload(int handleSize) throws Exception { + initSftpTest(handleSize); + Assumptions.assumeTrue(OsUtils.isUNIX() || OsUtils.isOSX(), + "Not sure appending to a file opened for reading works on Windows"); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), @@ -408,8 +428,10 @@ public void testEmptyFileDownload() throws Exception { } } - @Test // see extra fix for SSHD-538 - public void testNavigateBeyondRootFolder() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see extra fix for SSHD-538 + public void navigateBeyondRootFolder(int handleSize) throws Exception { + initSftpTest(handleSize); Path rootLocation = Paths.get(OsUtils.isUNIX() ? "/" : "C:\\"); FileSystem fsRoot = rootLocation.getFileSystem(); sshd.setFileSystemFactory(new FileSystemFactory() { @@ -427,17 +449,21 @@ public FileSystem createFileSystem(SessionContext session) throws IOException { try (SftpClient sftp = createSingleSessionClient()) { String rootDir = sftp.canonicalPath("/"); String upDir = sftp.canonicalPath(rootDir + "/.."); - assertEquals("Mismatched root dir parent", rootDir, upDir); + assertEquals(rootDir, upDir, "Mismatched root dir parent"); } } - @Test // see SSHD-605 - public void testCannotEscapeUserAbsoluteRoot() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-605 + public void cannotEscapeUserAbsoluteRoot(int handleSize) throws Exception { + initSftpTest(handleSize); testCannotEscapeRoot(true); } - @Test // see SSHD-605 - public void testCannotEscapeUserRelativeRoot() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-605 + public void cannotEscapeUserRelativeRoot(int handleSize) throws Exception { + initSftpTest(handleSize); testCannotEscapeRoot(false); } @@ -467,14 +493,16 @@ private void testCannotEscapeRoot(boolean useAbsolutePath) throws Exception { int expected = OsUtils.isWin32() && useAbsolutePath ? SftpConstants.SSH_FX_INVALID_FILENAME : SftpConstants.SSH_FX_NO_SUCH_FILE; - assertEquals("Mismatched status for " + escapePath, - SftpConstants.getStatusName(expected), - SftpConstants.getStatusName(e.getStatus())); + assertEquals(SftpConstants.getStatusName(expected), + SftpConstants.getStatusName(e.getStatus()), + "Mismatched status for " + escapePath); } } - @Test - public void testNormalizeRemoteRootValues() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void normalizeRemoteRootValues(int handleSize) throws Exception { + initSftpTest(handleSize); try (SftpClient sftp = createSingleSessionClient()) { String expected = sftp.canonicalPath("/"); StringBuilder sb = new StringBuilder(Long.SIZE + 1); @@ -489,13 +517,15 @@ public void testNormalizeRemoteRootValues() throws Exception { String remotePath = sb.toString(); String actual = sftp.canonicalPath(remotePath); - assertEquals("Mismatched roots for " + remotePath.length() + " slashes", expected, actual); + assertEquals(expected, actual, "Mismatched roots for " + remotePath.length() + " slashes"); } } } - @Test - public void testNormalizeRemotePathsValues() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void normalizeRemotePathsValues(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve( @@ -528,7 +558,7 @@ public void testNormalizeRemotePathsValues() throws Exception { String remotePath = sb.toString(); String actual = sftp.canonicalPath(remotePath); - assertEquals("Mismatched canonical value for " + remotePath, expected, actual); + assertEquals(expected, actual, "Mismatched canonical value for " + remotePath); } } } @@ -542,8 +572,10 @@ private static int slashify(StringBuilder sb, Random rnd) { return slashes; } - @Test - public void testOpen() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void open(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve( @@ -565,7 +597,7 @@ public void testOpen() throws Exception { // NOTE: on Windows files are always readable // see https://svn.apache.org/repos/asf/harmony/enhanced/java/branches/java6/classlib/modules/ // luni/src/test/api/windows/org/apache/harmony/luni/tests/java/io/WinFileTest.java - assertTrue("Empty read should have failed on " + file, isWindows); + assertTrue(isWindows, "Empty read should have failed on " + file); } catch (IOException e) { if (isWindows) { throw e; @@ -580,7 +612,7 @@ public void testOpen() throws Exception { try (SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Truncate))) { // NOTE: on Windows files are always readable - assertTrue("Empty truncate should have failed on " + file, isWindows); + assertTrue(isWindows, "Empty truncate should have failed on " + file); } catch (IOException e) { // ok } @@ -589,14 +621,14 @@ public void testOpen() throws Exception { int perms = sftp.stat(file).getPermissions(); int readMask = isWindows ? 0 : SftpConstants.S_IRUSR; int permsMask = SftpConstants.S_IWUSR | readMask; - assertEquals("Mismatched permissions for " + file + ": 0x" + Integer.toHexString(perms), 0, perms & permsMask); + assertEquals(0, perms & permsMask, "Mismatched permissions for " + file + ": 0x" + Integer.toHexString(perms)); javaFile.setWritable(true, false); try (SftpClient.CloseableHandle h = sftp.open( file, EnumSet.of(SftpClient.OpenMode.Truncate, SftpClient.OpenMode.Write))) { // OK should succeed - assertTrue("Handle not marked as open for file=" + file, h.isOpen()); + assertTrue(h.isOpen(), "Handle not marked as open for file=" + file); } byte[] d = "0123456789\n".getBytes(StandardCharsets.UTF_8); @@ -617,7 +649,7 @@ public void testOpen() throws Exception { try (SftpClient.CloseableHandle h = sftp.open(file /* no mode == read */)) { // NOTE: on Windows files are always readable - assertTrue("Data read should have failed on " + file, isWindows); + assertTrue(isWindows, "Data read should have failed on " + file); } catch (IOException e) { if (isWindows) { throw e; @@ -631,13 +663,15 @@ public void testOpen() throws Exception { int l = sftp.read(h, 2L, buf, 0, buf.length); String expected = new String(d, 2, l, StandardCharsets.UTF_8); String actual = new String(buf, 0, l, StandardCharsets.UTF_8); - assertEquals("Mismatched read data", expected, actual); + assertEquals(expected, actual, "Mismatched read data"); } } } - @Test // SSHD-899 - public void testNoAttributeImpactOnOpen() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // SSHD-899 + public void noAttributeImpactOnOpen(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve( @@ -652,19 +686,19 @@ public void testNoAttributeImpactOnOpen() throws Exception { try (SftpClient sftp = createSingleSessionClient()) { Collection initialPermissions = IoUtils.getPermissions(testFile); - assertTrue("File does not have enough initial permissions: " + initialPermissions, - initialPermissions.containsAll( - EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE))); + assertTrue(initialPermissions.containsAll( + EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE)), + "File does not have enough initial permissions: " + initialPermissions); try (CloseableHandle handle = sendRawAttributeImpactOpen(file, sftp)) { outputDebugMessage("%s - handle=%s", getCurrentTestName(), handle); } Collection updatedPermissions = IoUtils.getPermissions(testFile); - assertEquals("Mismatched updated permissions count", initialPermissions.size(), updatedPermissions.size()); - assertTrue("File does not preserve initial permissions: expected=" + initialPermissions + ", actual=" - + updatedPermissions, - updatedPermissions.containsAll(initialPermissions)); + assertEquals(initialPermissions.size(), updatedPermissions.size(), "Mismatched updated permissions count"); + assertTrue(updatedPermissions.containsAll(initialPermissions), + "File does not preserve initial permissions: expected=" + initialPermissions + ", actual=" + + updatedPermissions); } finally { Files.delete(testFile); } @@ -694,14 +728,16 @@ private CloseableHandle sendRawAttributeImpactOpen(String path, SftpClient sftpC private byte[] getRawFileHandle(Buffer buffer) { buffer.getUInt(); // length int type = buffer.getUByte(); - assertEquals("Mismatched response type", SftpConstants.SSH_FXP_HANDLE, type); + assertEquals(SftpConstants.SSH_FXP_HANDLE, type, "Mismatched response type"); buffer.getInt(); // id return ValidateUtils.checkNotNullAndNotEmpty( buffer.getBytes(), "Null/empty handle in buffer", GenericUtils.EMPTY_OBJECT_ARRAY); } - @Test - public void testInputStreamSkipAndReset() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void inputStreamSkipAndReset(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path localFile = CommonTestSupportUtils.resolve( @@ -719,25 +755,27 @@ public void testInputStreamSkipAndReset() throws Exception { byte[] actual = new byte[readLen]; readLen = stream.read(actual); - assertEquals("Failed to read fully reset data", actual.length, readLen); - assertArrayEquals("Mismatched re-read data contents", expected, actual); + assertEquals(actual.length, readLen, "Failed to read fully reset data"); + assertArrayEquals(expected, actual, "Mismatched re-read data contents"); System.arraycopy(data, 0, expected, 0, expected.length); - assertArrayEquals("Mismatched original data contents", expected, actual); + assertArrayEquals(expected, actual, "Mismatched original data contents"); long skipped = stream.skip(readLen); - assertEquals("Mismatched skipped forward size", readLen, skipped); + assertEquals(readLen, skipped, "Mismatched skipped forward size"); readLen = stream.read(actual); - assertEquals("Failed to read fully skipped forward data", actual.length, readLen); + assertEquals(actual.length, readLen, "Failed to read fully skipped forward data"); System.arraycopy(data, expected.length + readLen, expected, 0, expected.length); - assertArrayEquals("Mismatched skipped forward data contents", expected, actual); + assertArrayEquals(expected, actual, "Mismatched skipped forward data contents"); } } - @Test // see SSHD-1182 - public void testInputStreamSkipBeforeRead() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-1182 + public void inputStreamSkipBeforeRead(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path localFile = CommonTestSupportUtils.resolve( @@ -757,19 +795,21 @@ public void testInputStreamSkipBeforeRead() throws Exception { System.arraycopy(data, toSkip, expected, 0, readLen); long skipped = stream.skip(toSkip); - assertEquals("Mismatched skipped forward size", toSkip, skipped); + assertEquals(toSkip, skipped, "Mismatched skipped forward size"); int actuallyRead = IoUtils.read(stream, actual); - assertEquals("Failed to read fully skipped forward data", readLen, actuallyRead); + assertEquals(readLen, actuallyRead, "Failed to read fully skipped forward data"); - assertArrayEquals("Unexpected data read after skipping", expected, actual); + assertArrayEquals(expected, actual, "Unexpected data read after skipping"); } } - @Test - public void testSftpFileSystemAccessor() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void sftpFileSystemAccessor(int handleSize) throws Exception { + initSftpTest(handleSize); List factories = sshd.getSubsystemFactories(); - assertEquals("Mismatched subsystem factories count", 1, GenericUtils.size(factories)); + assertEquals(1, GenericUtils.size(factories), "Mismatched subsystem factories count"); SubsystemFactory f = factories.get(0); assertObjectInstanceOf("Not an SFTP subsystem factory", SftpSubsystemFactory.class, f); @@ -821,9 +861,9 @@ public String toString() { } Path remoteFile = fileHolder.getAndSet(null); - assertNotNull("No remote file holder value", remoteFile); - assertEquals("Mismatched opened local files", localFile.toFile(), remoteFile.toFile()); - assertArrayEquals("Mismatched retrieved file contents", expected, actual); + assertNotNull(remoteFile, "No remote file holder value"); + assertEquals(localFile.toFile(), remoteFile.toFile(), "Mismatched opened local files"); + assertArrayEquals(expected, actual, "Mismatched retrieved file contents"); Path localParent = localFile.getParent(); String localName = Objects.toString(localFile.getFileName(), null); @@ -831,9 +871,9 @@ public String toString() { CommonTestSupportUtils.resolveRelativeRemotePath(parentPath, localParent))) { List entries = sftp.readDir(handle); Path remoteParent = dirHolder.getAndSet(null); - assertNotNull("No remote folder holder value", remoteParent); - assertEquals("Mismatched opened folder", localParent.toFile(), remoteParent.toFile()); - assertFalse("No dir entries", GenericUtils.isEmpty(entries)); + assertNotNull(remoteParent, "No remote folder holder value"); + assertEquals(localParent.toFile(), remoteParent.toFile(), "Mismatched opened folder"); + assertFalse(GenericUtils.isEmpty(entries), "No dir entries"); for (DirEntry de : entries) { Attributes attrs = de.getAttributes(); @@ -854,11 +894,13 @@ public String toString() { } } - @Test + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") @SuppressWarnings({ "checkstyle:anoninnerlength", "checkstyle:methodlength" }) - public void testClient() throws Exception { + public void client(int handleSize) throws Exception { + initSftpTest(handleSize); List factories = sshd.getSubsystemFactories(); - assertEquals("Mismatched subsystem factories count", 1, GenericUtils.size(factories)); + assertEquals(1, GenericUtils.size(factories), "Mismatched subsystem factories count"); SubsystemFactory f = factories.get(0); assertObjectInstanceOf("Not an SFTP subsystem factory", SftpSubsystemFactory.class, f); @@ -882,15 +924,15 @@ public void testClient() throws Exception { @Override public void initialized(ServerSession session, int version) { log.info("initialized(" + session + ") version: " + version); - assertTrue("Initialized version below minimum", version >= SftpSubsystemEnvironment.LOWER_SFTP_IMPL); - assertTrue("Initialized version above maximum", version <= SftpSubsystemEnvironment.HIGHER_SFTP_IMPL); - assertTrue("Initializion re-called", versionHolder.getAndSet(version) < 0); + assertTrue(version >= SftpSubsystemEnvironment.LOWER_SFTP_IMPL, "Initialized version below minimum"); + assertTrue(version <= SftpSubsystemEnvironment.HIGHER_SFTP_IMPL, "Initialized version above maximum"); + assertTrue(versionHolder.getAndSet(version) < 0, "Initializion re-called"); } @Override public void destroying(ServerSession session) { log.info("destroying(" + session + ")"); - assertTrue("Initialization method not called", versionHolder.get() > 0); + assertTrue(versionHolder.get() > 0, "Initialization method not called"); } @Override @@ -1052,20 +1094,20 @@ public void closing(ServerSession session, String remoteHandle, Handle localHand factory.addSftpEventListener(listener); try (SftpClient sftp = createSingleSessionClient()) { - assertEquals("Mismatched negotiated version", sftp.getVersion(), versionHolder.get()); + assertEquals(sftp.getVersion(), versionHolder.get(), "Mismatched negotiated version"); testClient(client, sftp); - assertEquals("Mismatched open/close count", openCount.get(), closeCount.get()); - assertTrue("No entries read", entriesCount.get() > 0); - assertTrue("No data read", readSize.get() > 0L); - assertTrue("No data written", writeSize.get() > 0L); - assertEquals("Mismatched removal counts", removingFileCount.get(), removedFileCount.get()); - assertEquals("Mismatched directory removal counts", removingDirectoryCount.get(), removedDirectoryCount.get()); - assertTrue("No removals signalled", removedFileCount.get() > 0); - assertEquals("Mismatched creation counts", creatingCount.get(), createdCount.get()); - assertTrue("No creations signalled", creatingCount.get() > 0); - assertEquals("Mismatched modification counts", modifyingCount.get(), modifiedCount.get()); - assertTrue("No modifications signalled", modifiedCount.get() > 0); + assertEquals(openCount.get(), closeCount.get(), "Mismatched open/close count"); + assertTrue(entriesCount.get() > 0, "No entries read"); + assertTrue(readSize.get() > 0L, "No data read"); + assertTrue(writeSize.get() > 0L, "No data written"); + assertEquals(removingFileCount.get(), removedFileCount.get(), "Mismatched removal counts"); + assertEquals(removingDirectoryCount.get(), removedDirectoryCount.get(), "Mismatched directory removal counts"); + assertTrue(removedFileCount.get() > 0, "No removals signalled"); + assertEquals(creatingCount.get(), createdCount.get(), "Mismatched creation counts"); + assertTrue(creatingCount.get() > 0, "No creations signalled"); + assertEquals(modifyingCount.get(), modifiedCount.get(), "Mismatched modification counts"); + assertTrue(modifiedCount.get() > 0, "No modifications signalled"); } finally { factory.removeSftpEventListener(listener); } @@ -1078,8 +1120,10 @@ public void closing(ServerSession session, String remoteHandle, Handle localHand * * @throws Exception upon any uncaught exception or failure */ - @Test - public void testWriteChunking() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void writeChunking(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -1126,8 +1170,10 @@ public void testWriteChunking() throws Exception { } } - @Test // SSHD-1215 - public void testWriteCreateAppend() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // SSHD-1215 + public void writeCreateAppend(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -1149,10 +1195,12 @@ public void testWriteCreateAppend() throws Exception { } } - @Test - public void testHandleSize() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void handleSize(int handleSize) throws Exception { + initSftpTest(handleSize); List factories = sshd.getSubsystemFactories(); - assertEquals("Mismatched subsystem factories count", 1, GenericUtils.size(factories)); + assertEquals(1, GenericUtils.size(factories), "Mismatched subsystem factories count"); SubsystemFactory f = factories.get(0); assertObjectInstanceOf("Not an SFTP subsystem factory", SftpSubsystemFactory.class, f); @@ -1167,7 +1215,6 @@ public void open(ServerSession session, String remoteHandle, Handle localHandle) } }; factory.addSftpEventListener(listener); - int handleSize = SftpModuleProperties.FILE_HANDLE_SIZE.getRequired(sshd).intValue(); try { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, @@ -1184,54 +1231,56 @@ public void open(ServerSession session, String remoteHandle, Handle localHandle) // Write some files byte[] data = "something".getBytes(StandardCharsets.US_ASCII); try (CloseableHandle handle = sftp.open(dir + "/first.bin", OpenMode.Write, OpenMode.Create)) { - assertEquals("Unexpected handle size", handleSize, handle.getIdentifier().length); + assertEquals(handleSize, handle.getIdentifier().length, "Unexpected handle size"); sftp.write(handle, 0, data, 0, data.length); } - assertEquals("Unexpected number of handles", 1, handles.size()); + assertEquals(1, handles.size(), "Unexpected number of handles"); try (CloseableHandle handle1 = sftp.open(dir + "/second.bin", OpenMode.Write, OpenMode.Create); CloseableHandle handle2 = sftp.open(dir + "/third.bin", OpenMode.Write, OpenMode.Create)) { - assertEquals("Unexpected handle size", handleSize, handle1.getIdentifier().length); - assertEquals("Unexpected handle size", handleSize, handle2.getIdentifier().length); + assertEquals(handleSize, handle1.getIdentifier().length, "Unexpected handle size"); + assertEquals(handleSize, handle2.getIdentifier().length, "Unexpected handle size"); sftp.write(handle1, 0, data, 0, data.length); sftp.write(handle2, 0, data, 0, data.length); } if (handleSize == Integer.BYTES) { - assertEquals("Unexpected number of handles", 2, handles.size()); + assertEquals(2, handles.size(), "Unexpected number of handles"); } else { - assertTrue("Unexpected number of handles", handles.size() <= 3); + assertTrue(handles.size() <= 3, "Unexpected number of handles"); } try (CloseableHandle handle1 = sftp.open(dir + "/fourth.bin", OpenMode.Write, OpenMode.Create)) { - assertEquals("Unexpected handle size", handleSize, handle1.getIdentifier().length); + assertEquals(handleSize, handle1.getIdentifier().length, "Unexpected handle size"); byte[] id2; try (CloseableHandle handle2 = sftp.open(dir + "/fifth.bin", OpenMode.Write, OpenMode.Create)) { id2 = handle2.getIdentifier(); - assertEquals("Unexpected handle size", handleSize, id2.length); + assertEquals(handleSize, id2.length, "Unexpected handle size"); sftp.write(handle2, 0, data, 0, data.length); } byte[] id3; try (CloseableHandle handle3 = sftp.open(dir + "/sixth.bin", OpenMode.Write, OpenMode.Create)) { id3 = handle3.getIdentifier(); - assertEquals("Unexpected handle size", handleSize, id3.length); + assertEquals(handleSize, id3.length, "Unexpected handle size"); if (handleSize == Integer.BYTES) { // Should have been re-used - assertArrayEquals("Expected handles to be the same", id2, id3); + assertArrayEquals(id2, id3, "Expected handles to be the same"); } sftp.write(handle3, 0, data, 0, data.length); } sftp.write(handle1, 0, data, 0, data.length); } - assertArrayEquals("Unexpected data in first.bin", data, Files.readAllBytes(clientFolder.resolve("first.bin"))); - assertArrayEquals("Unexpected data in second.bin", data, - Files.readAllBytes(clientFolder.resolve("second.bin"))); - assertArrayEquals("Unexpected data in third.bin", data, Files.readAllBytes(clientFolder.resolve("third.bin"))); - assertArrayEquals("Unexpected data in fourth.bin", data, - Files.readAllBytes(clientFolder.resolve("fourth.bin"))); - assertArrayEquals("Unexpected data in fifth.bin", data, Files.readAllBytes(clientFolder.resolve("fifth.bin"))); - assertArrayEquals("Unexpected data in sixth.bin", data, Files.readAllBytes(clientFolder.resolve("sixth.bin"))); + assertArrayEquals(data, Files.readAllBytes(clientFolder.resolve("first.bin")), "Unexpected data in first.bin"); + assertArrayEquals(data, + Files.readAllBytes(clientFolder.resolve("second.bin")), + "Unexpected data in second.bin"); + assertArrayEquals(data, Files.readAllBytes(clientFolder.resolve("third.bin")), "Unexpected data in third.bin"); + assertArrayEquals(data, + Files.readAllBytes(clientFolder.resolve("fourth.bin")), + "Unexpected data in fourth.bin"); + assertArrayEquals(data, Files.readAllBytes(clientFolder.resolve("fifth.bin")), "Unexpected data in fifth.bin"); + assertArrayEquals(data, Files.readAllBytes(clientFolder.resolve("sixth.bin")), "Unexpected data in sixth.bin"); if (handleSize == Integer.BYTES) { - assertEquals("Unexpected number of handles", 2, handles.size()); + assertEquals(2, handles.size(), "Unexpected number of handles"); } else { - assertTrue("Unexpected number of handles", handles.size() <= 6); + assertTrue(handles.size() <= 6, "Unexpected number of handles"); } } } finally { @@ -1280,7 +1329,7 @@ private void testInvalidParams(SftpClient sftp, Path file, String filePath) thro } sftp.remove(filePath); - assertFalse("File should not be there: " + file.toString(), Files.exists(file)); + assertFalse(Files.exists(file), "File should not be there: " + file.toString()); } private void uploadAndVerifyFile( @@ -1309,16 +1358,18 @@ private void uploadAndVerifyFile( // verify results Path resultPath = clientFolder.resolve(filename); - assertTrue("File should exist on disk: " + resultPath, Files.exists(resultPath)); - assertEquals("Mismatched file contents: " + resultPath, expectedData, readFile(remotePath)); + assertTrue(Files.exists(resultPath), "File should exist on disk: " + resultPath); + assertEquals(expectedData, readFile(remotePath), "Mismatched file contents: " + resultPath); // cleanup sftp.remove(remotePath); - assertFalse("File should have been removed: " + resultPath, Files.exists(resultPath)); + assertFalse(Files.exists(resultPath), "File should have been removed: " + resultPath); } - @Test - public void testSftp() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void sftp(int handleSize) throws Exception { + initSftpTest(handleSize); String d = getCurrentTestName() + "\n"; Path targetPath = detectTargetFolder(); @@ -1346,8 +1397,10 @@ public void testSftp() throws Exception { } } - @Test - public void testReadWriteWithOffset() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void readWriteWithOffset(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -1364,8 +1417,8 @@ public void testReadWriteWithOffset() throws Exception { try { c.put(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)), remotePath); - assertTrue("Remote file not created after initial write: " + localPath, Files.exists(localPath)); - assertEquals("Mismatched data read from " + remotePath, data, readFile(remotePath)); + assertTrue(Files.exists(localPath), "Remote file not created after initial write: " + localPath); + assertEquals(data, readFile(remotePath), "Mismatched data read from " + remotePath); try (OutputStream os = c.put(remotePath, null, ChannelSftp.APPEND, appendOffset)) { os.write(extraData.getBytes(StandardCharsets.UTF_8)); @@ -1374,15 +1427,17 @@ public void testReadWriteWithOffset() throws Exception { c.disconnect(); } - assertTrue("Remote file not created after data update: " + localPath, Files.exists(localPath)); + assertTrue(Files.exists(localPath), "Remote file not created after data update: " + localPath); String expected = data.substring(0, data.length() + appendOffset) + extraData; String actual = readFile(remotePath); - assertEquals("Mismatched final file data in " + remotePath, expected, actual); + assertEquals(expected, actual, "Mismatched final file data in " + remotePath); } - @Test - public void testReadDir() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void readDir(int handleSize) throws Exception { + initSftpTest(handleSize); Path cwdPath = Paths.get(System.getProperty("user.dir")).toAbsolutePath(); Path tgtPath = detectTargetFolder(); Collection expNames = OsUtils.isUNIX() @@ -1395,7 +1450,7 @@ public void testReadDir() throws Exception { continue; } - assertTrue("Failed to accumulate " + n, expNames.add(n)); + assertTrue(expNames.add(n), "Failed to accumulate " + n); } } @@ -1416,17 +1471,19 @@ public void testReadDir() throws Exception { continue; } - assertTrue("Entry not found: " + name, expNames.remove(name)); + assertTrue(expNames.remove(name), "Entry not found: " + name); } - assertTrue("Un-listed names: " + expNames, GenericUtils.isEmpty(expNames)); + assertTrue(GenericUtils.isEmpty(expNames), "Un-listed names: " + expNames); } finally { c.disconnect(); } } - @Test - public void testRename() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void rename(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -1449,8 +1506,8 @@ public void testRename() throws Exception { sftp.rename(file2Path, file3Path); fail("Unxpected rename success of " + file2Path + " => " + file3Path); } catch (SftpException e) { - assertEquals("Mismatched status for failed rename of " + file2Path + " => " + file3Path, - SftpConstants.SSH_FX_NO_SUCH_FILE, e.getStatus()); + assertEquals(SftpConstants.SSH_FX_NO_SUCH_FILE, e.getStatus(), + "Mismatched status for failed rename of " + file2Path + " => " + file3Path); } try (OutputStream os = sftp.write(file2Path, SftpClient.MIN_WRITE_BUFFER_SIZE)) { @@ -1461,16 +1518,18 @@ public void testRename() throws Exception { sftp.rename(file1Path, file2Path); fail("Unxpected rename success of " + file1Path + " => " + file2Path); } catch (SftpException e) { - assertEquals("Mismatched status for failed rename of " + file1Path + " => " + file2Path, - SftpConstants.SSH_FX_FILE_ALREADY_EXISTS, e.getStatus()); + assertEquals(SftpConstants.SSH_FX_FILE_ALREADY_EXISTS, e.getStatus(), + "Mismatched status for failed rename of " + file1Path + " => " + file2Path); } sftp.rename(file1Path, file2Path, SftpClient.CopyMode.Overwrite); } } - @Test - public void testServerExtensionsDeclarations() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void serverExtensionsDeclarations(int handleSize) throws Exception { + initSftpTest(handleSize); try (SftpClient sftp = createSingleSessionClient()) { Map extensions = sftp.getServerExtensions(); for (String name : new String[] { @@ -1478,7 +1537,7 @@ public void testServerExtensionsDeclarations() throws Exception { SftpConstants.EXT_VENDOR_ID, SftpConstants.EXT_ACL_SUPPORTED, SftpConstants.EXT_SUPPORTED, SftpConstants.EXT_SUPPORTED2 }) { - assertTrue("Missing extension=" + name, extensions.containsKey(name)); + assertTrue(extensions.containsKey(name), "Missing extension=" + name); } Map data = ParserUtils.parse(extensions); @@ -1506,11 +1565,12 @@ public void testServerExtensionsDeclarations() throws Exception { for (OpenSSHExtension expected : AbstractSftpSubsystemHelper.DEFAULT_OPEN_SSH_EXTENSIONS) { String name = expected.getName(); Object value = data.get(name); - assertNotNull("OpenSSH extension not declared: " + name, value); + assertNotNull(value, "OpenSSH extension not declared: " + name); OpenSSHExtension actual = (OpenSSHExtension) value; - assertEquals("Mismatched version for OpenSSH extension=" + name, expected.getVersion(), - actual.getVersion()); + assertEquals(expected.getVersion(), + actual.getVersion(), + "Mismatched version for OpenSSH extension=" + name); } for (BuiltinSftpClientExtensions type : BuiltinSftpClientExtensions.VALUES) { @@ -1518,66 +1578,69 @@ public void testServerExtensionsDeclarations() throws Exception { boolean isOpenSSHExtension = extensionName.endsWith("@openssh.com"); SftpClientExtension instance = sftp.getExtension(extensionName); - assertNotNull("Extension not implemented:" + extensionName, instance); - assertEquals("Mismatched instance name", extensionName, instance.getName()); + assertNotNull(instance, "Extension not implemented:" + extensionName); + assertEquals(extensionName, instance.getName(), "Mismatched instance name"); if (instance.isSupported()) { if (isOpenSSHExtension) { - assertTrue("Unlisted default OpenSSH extension: " + extensionName, - AbstractSftpSubsystemHelper.DEFAULT_OPEN_SSH_EXTENSIONS_NAMES.contains(extensionName)); + assertTrue(AbstractSftpSubsystemHelper.DEFAULT_OPEN_SSH_EXTENSIONS_NAMES.contains(extensionName), + "Unlisted default OpenSSH extension: " + extensionName); } } else { - assertTrue("Unsupported non-OpenSSH extension: " + extensionName, isOpenSSHExtension); - assertFalse("Unsupported default OpenSSH extension: " + extensionName, - AbstractSftpSubsystemHelper.DEFAULT_OPEN_SSH_EXTENSIONS_NAMES.contains(extensionName)); + assertTrue(isOpenSSHExtension, "Unsupported non-OpenSSH extension: " + extensionName); + assertFalse(AbstractSftpSubsystemHelper.DEFAULT_OPEN_SSH_EXTENSIONS_NAMES.contains(extensionName), + "Unsupported default OpenSSH extension: " + extensionName); } } } } private static void assertSupportedExtensions(String extName, Collection extensionNames) { - assertEquals(extName + "[count]", EXPECTED_EXTENSIONS.size(), GenericUtils.size(extensionNames)); + assertEquals(EXPECTED_EXTENSIONS.size(), GenericUtils.size(extensionNames), extName + "[count]"); EXPECTED_EXTENSIONS.forEach((name, f) -> { if (!f.isSupported()) { - assertFalse(extName + " - unsupported feature reported: " + name, extensionNames.contains(name)); + assertFalse(extensionNames.contains(name), extName + " - unsupported feature reported: " + name); } else { - assertTrue(extName + " - missing " + name, extensionNames.contains(name)); + assertTrue(extensionNames.contains(name), extName + " - missing " + name); } }); } private static void assertSupportedVersions(Versions vers) { List values = vers.getVersions(); - assertEquals("Mismatched reported versions size: " + values, - 1 + SftpSubsystemEnvironment.HIGHER_SFTP_IMPL - SftpSubsystemEnvironment.LOWER_SFTP_IMPL, - GenericUtils.size(values)); + assertEquals(1 + SftpSubsystemEnvironment.HIGHER_SFTP_IMPL - SftpSubsystemEnvironment.LOWER_SFTP_IMPL, + GenericUtils.size(values), + "Mismatched reported versions size: " + values); for (int expected = SftpSubsystemEnvironment.LOWER_SFTP_IMPL, index = 0; expected <= SftpSubsystemEnvironment.HIGHER_SFTP_IMPL; expected++, index++) { String e = Integer.toString(expected); String a = values.get(index); - assertEquals("Missing value at index=" + index + ": " + values, e, a); + assertEquals(e, a, "Missing value at index=" + index + ": " + values); } } private static void assertNewlineValue(Newline nl) { - assertEquals("Mismatched NL value", - BufferUtils.toHex(':', IoUtils.EOL.getBytes(StandardCharsets.UTF_8)), - BufferUtils.toHex(':', nl.getNewline().getBytes(StandardCharsets.UTF_8))); + assertEquals(BufferUtils.toHex(':', IoUtils.EOL.getBytes(StandardCharsets.UTF_8)), + BufferUtils.toHex(':', nl.getNewline().getBytes(StandardCharsets.UTF_8)), + "Mismatched NL value"); } private static void assertSupportedAclCapabilities(AclCapabilities caps) { Set actual = AclCapabilities.deconstructAclCapabilities(caps.getCapabilities()); - assertEquals("Mismatched ACL capabilities count", AbstractSftpSubsystemHelper.DEFAULT_ACL_SUPPORTED_MASK.size(), - actual.size()); - assertTrue("Missing capabilities - expected=" + AbstractSftpSubsystemHelper.DEFAULT_ACL_SUPPORTED_MASK + ", actual=" - + actual, - actual.containsAll(AbstractSftpSubsystemHelper.DEFAULT_ACL_SUPPORTED_MASK)); + assertEquals(AbstractSftpSubsystemHelper.DEFAULT_ACL_SUPPORTED_MASK.size(), + actual.size(), + "Mismatched ACL capabilities count"); + assertTrue(actual.containsAll(AbstractSftpSubsystemHelper.DEFAULT_ACL_SUPPORTED_MASK), + "Missing capabilities - expected=" + AbstractSftpSubsystemHelper.DEFAULT_ACL_SUPPORTED_MASK + ", actual=" + + actual); } - @Test - public void testSftpVersionSelector() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void sftpVersionSelector(int handleSize) throws Exception { + initSftpTest(handleSize); AtomicInteger selected = new AtomicInteger(-1); SftpVersionSelector selector = (session, initial, current, available) -> { int value = initial @@ -1592,15 +1655,17 @@ public void testSftpVersionSelector() throws Exception { try (ClientSession session = createAuthenticatedClientSession(); SftpClient sftp = SftpClientFactory.instance().createSftpClient(session, selector)) { - assertEquals("Mismatched negotiated version", selected.get(), sftp.getVersion()); + assertEquals(selected.get(), sftp.getVersion(), "Mismatched negotiated version"); testClient(client, sftp); } } - @Test // see SSHD-621 - public void testServerDoesNotSupportSftp() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-621 + public void serverDoesNotSupportSftp(int handleSize) throws Exception { + initSftpTest(handleSize); List factories = sshd.getSubsystemFactories(); - assertEquals("Mismatched subsystem factories count", 1, GenericUtils.size(factories)); + assertEquals(1, GenericUtils.size(factories), "Mismatched subsystem factories count"); sshd.setSubsystemFactories(null); try (ClientSession session = createAuthenticatedClientSession()) { @@ -1636,7 +1701,7 @@ private void testClient(FactoryManager manager, SftpClient sftp) throws Exceptio sftp.write(h, d.length, d, 0, d.length); SftpClient.Attributes attrs = sftp.stat(h); - assertNotNull("No handle attributes", attrs); + assertNotNull(attrs, "No handle attributes"); } try (SftpClient.CloseableHandle h = sftp.openDir(dir)) { @@ -1655,10 +1720,10 @@ private void testClient(FactoryManager manager, SftpClient sftp) throws Exceptio } } - assertTrue("Dot entry not listed", dotFiltered); - assertTrue("Dot-dot entry not listed", dotdotFiltered); - assertEquals("Mismatched number of listed entries", 1, dirEntries.size()); - assertNull("Unexpected extra entry read after listing ended", sftp.readDir(h)); + assertTrue(dotFiltered, "Dot entry not listed"); + assertTrue(dotdotFiltered, "Dot-dot entry not listed"); + assertEquals(1, dirEntries.size(), "Mismatched number of listed entries"); + assertNull(sftp.readDir(h), "Unexpected extra entry read after listing ended"); } sftp.remove(file); @@ -1669,11 +1734,11 @@ private void testClient(FactoryManager manager, SftpClient sftp) throws Exceptio } try (InputStream is = sftp.read(file)) { int readLen = is.read(smallBuf); - assertEquals("Mismatched read data length", smallBuf.length, readLen); + assertEquals(smallBuf.length, readLen, "Mismatched read data length"); assertEquals("Hello world", new String(smallBuf, StandardCharsets.UTF_8)); int i = is.read(); - assertEquals("Unexpected read past EOF", -1, i); + assertEquals(-1, i, "Unexpected read past EOF"); } final int sizeFactor = Short.SIZE; @@ -1689,23 +1754,23 @@ private void testClient(FactoryManager manager, SftpClient sftp) throws Exceptio // force several internal read cycles to satisfy the full read try (InputStream is = sftp.read(file, workBuf.length / sizeFactor)) { int readLen = is.read(workBuf); - assertEquals("Mismatched read data length", workBuf.length, readLen); + assertEquals(workBuf.length, readLen, "Mismatched read data length"); int i = is.read(); - assertEquals("Unexpected read past EOF", -1, i); + assertEquals(-1, i, "Unexpected read past EOF"); } SftpClient.Attributes attributes = sftp.stat(file); - assertTrue("Test file not detected as regular", attributes.isRegularFile()); + assertTrue(attributes.isRegularFile(), "Test file not detected as regular"); attributes = sftp.stat(dir); - assertTrue("Test directory not reported as such", attributes.isDirectory()); + assertTrue(attributes.isDirectory(), "Test directory not reported as such"); int nb = 0; boolean dotFiltered = false; boolean dotdotFiltered = false; for (SftpClient.DirEntry entry : sftp.readDir(dir)) { - assertNotNull("Unexpected null entry", entry); + assertNotNull(entry, "Unexpected null entry"); String name = entry.getFilename(); outputDebugMessage("readDir(%s) overwritten file: %s", dir, name); @@ -1717,19 +1782,21 @@ private void testClient(FactoryManager manager, SftpClient sftp) throws Exceptio nb++; } } - assertTrue("Dot entry not read", dotFiltered); - assertTrue("Dot-dot entry not read", dotdotFiltered); - assertEquals("Mismatched read dir entries", 1, nb); + assertTrue(dotFiltered, "Dot entry not read"); + assertTrue(dotdotFiltered, "Dot-dot entry not read"); + assertEquals(1, nb, "Mismatched read dir entries"); sftp.remove(file); sftp.rmdir(dir); } - @Test - public void testCreateSymbolicLink() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") + public void createSymbolicLink(int handleSize) throws Exception { + initSftpTest(handleSize); // Do not execute on windows as the file system does not support symlinks - Assume.assumeTrue("Skip non-Unix O/S", OsUtils.isUNIX() || OsUtils.isOSX()); + Assumptions.assumeTrue(OsUtils.isUNIX() || OsUtils.isOSX(), "Skip non-Unix O/S"); List factories = sshd.getSubsystemFactories(); - assertEquals("Mismatched subsystem factories count", 1, GenericUtils.size(factories)); + assertEquals(1, GenericUtils.size(factories), "Mismatched subsystem factories count"); SubsystemFactory f = factories.get(0); assertObjectInstanceOf("Not an SFTP subsystem factory", SftpSubsystemFactory.class, f); @@ -1739,18 +1806,18 @@ public void testCreateSymbolicLink() throws Exception { SftpEventListener listener = new AbstractSftpEventListenerAdapter() { @Override public void linking(ServerSession session, Path src, Path target, boolean symLink) { - assertNull("Multiple linking calls", linkDataHolder.getAndSet(new LinkData(src, target, symLink))); + assertNull(linkDataHolder.getAndSet(new LinkData(src, target, symLink)), "Multiple linking calls"); } @Override public void linked( ServerSession session, Path src, Path target, boolean symLink, Throwable thrown) { LinkData data = linkDataHolder.get(); - assertNotNull("No previous linking call", data); - assertSame("Mismatched source", data.getSource(), src); - assertSame("Mismatched target", data.getTarget(), target); + assertNotNull(data, "No previous linking call"); + assertSame(data.getSource(), src, "Mismatched source"); + assertSame(data.getTarget(), target, "Mismatched target"); assertEquals("Mismatched link type", data.isSymLink(), symLink); - assertNull("Unexpected failure", thrown); + assertNull(thrown, "Unexpected failure"); } }; @@ -1784,8 +1851,8 @@ public void linked( try (InputStream dataStream = new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8))) { c.put(dataStream, remSrcPath); } - assertTrue("Source file not created: " + sourcePath, Files.exists(sourcePath)); - assertEquals("Mismatched stored data in " + remSrcPath, data, readFile(remSrcPath)); + assertTrue(Files.exists(sourcePath), "Source file not created: " + sourcePath); + assertEquals(data, readFile(remSrcPath), "Mismatched stored data in " + remSrcPath); Path linkPath = lclSftp.resolve("link-" + sourcePath.getFileName()); String remLinkPath = "/" + CommonTestSupportUtils.resolveRelativeRemotePath(parentPath, linkPath); @@ -1793,17 +1860,17 @@ public void linked( if (Files.exists(linkPath, options)) { Files.delete(linkPath); } - assertFalse("Target link exists before linking: " + linkPath, Files.exists(linkPath, options)); + assertFalse(Files.exists(linkPath, options), "Target link exists before linking: " + linkPath); outputDebugMessage("Symlink %s => %s", remLinkPath, remSrcPath); c.symlink(remSrcPath, remLinkPath); - assertTrue("Symlink not created: " + linkPath, Files.exists(linkPath, options)); - assertEquals("Mismatched link data in " + remLinkPath, data, readFile(remLinkPath)); + assertTrue(Files.exists(linkPath, options), "Symlink not created: " + linkPath); + assertEquals(data, readFile(remLinkPath), "Mismatched link data in " + remLinkPath); String str1 = c.readlink(remLinkPath); String str2 = c.realpath(remSrcPath); - assertEquals("Mismatched link vs. real path", str1, str2); + assertEquals(str1, str2, "Mismatched link vs. real path"); } finally { c.disconnect(); } @@ -1811,14 +1878,16 @@ public void linked( factory.removeSftpEventListener(listener); } - assertNotNull("No symlink signalled", linkDataHolder.getAndSet(null)); + assertNotNull(linkDataHolder.getAndSet(null), "No symlink signalled"); } - @Test // see SSHD-903 - public void testForcedVersionNegotiation() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-903 + public void forcedVersionNegotiation(int handleSize) throws Exception { + initSftpTest(handleSize); SftpModuleProperties.SFTP_VERSION.set(sshd, SftpConstants.SFTP_V3); try (SftpClient sftp = createSingleSessionClient()) { - assertEquals("Mismatched negotiated version", SftpConstants.SFTP_V3, sftp.getVersion()); + assertEquals(SftpConstants.SFTP_V3, sftp.getVersion(), "Mismatched negotiated version"); } } @@ -1857,8 +1926,10 @@ private static String randomString(int size) { return sb.toString(); } - @Test // see SSHD-1022 - public void testFlushOutputStreamWithoutWrite() throws Exception { + @MethodSource("getParameters") + @ParameterizedTest(name = "FILE_HANDLE_SIZE {0}") // see SSHD-1022 + public void flushOutputStreamWithoutWrite(int handleSize) throws Exception { + initSftpTest(handleSize); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTransferTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTransferTest.java index a5b4354a0..e7998524d 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTransferTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpTransferTest.java @@ -31,25 +31,24 @@ import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.core.CoreModuleProperties; import org.apache.sshd.sftp.client.fs.SftpFileSystem; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; - -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.fail; + +@TestMethodOrder(MethodName.class) public class SftpTransferTest extends AbstractSftpClientTestSupport { private static final int BUFFER_SIZE = 8192; - private final long rekeyBlockSize; + private long rekeyBlockSize; - public SftpTransferTest(long rekeyBlockSize) throws IOException { + public void initSftpTransferTest(long rekeyBlockSize) throws IOException { this.rekeyBlockSize = rekeyBlockSize; } - @Parameterized.Parameters(name = "REKEY_BLOCK_SIZE {0}") public static List getParameters() { List params = new ArrayList<>(); params.add(Long.valueOf(0)); @@ -57,15 +56,19 @@ public static List getParameters() { return params; } - @Test - public void testTransferIntegrity() throws IOException { + @MethodSource("getParameters") + @ParameterizedTest(name = "REKEY_BLOCK_SIZE {0}") + public void transferIntegrity(long rekeyBlockSize) throws IOException { + initSftpTransferTest(rekeyBlockSize); for (int i = 0; i < 10; i++) { doTestTransferIntegrity(0); } } - @Test - public void testTransferIntegrityWithBufferLargerThanPacket() throws IOException { + @MethodSource("getParameters") + @ParameterizedTest(name = "REKEY_BLOCK_SIZE {0}") + public void transferIntegrityWithBufferLargerThanPacket(long rekeyBlockSize) throws IOException { + initSftpTransferTest(rekeyBlockSize); for (int i = 0; i < 10; i++) { doTestTransferIntegrity(65536); } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionResolverTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionResolverTest.java index 527fc8e67..6d54ad429 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionResolverTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionResolverTest.java @@ -24,36 +24,31 @@ import org.apache.sshd.common.NamedResource; import org.apache.sshd.sftp.client.SftpVersionSelector.NamedVersionSelector; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Assume; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; /** * @author Apache MINA SSHD Project */ -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SftpVersionResolverTest extends JUnitTestSupport { - private final NamedVersionSelector expected; - private final NamedVersionSelector actual; + private NamedVersionSelector expected; + private NamedVersionSelector actual; - public SftpVersionResolverTest(String selector, NamedVersionSelector expected) { + public void initSftpVersionResolverTest(String selector, NamedVersionSelector expected) { this.expected = expected; this.actual = SftpVersionSelector.resolveVersionSelector(selector); } - @Parameters(name = "selector={0}") public static Collection parameters() { return new LinkedList() { // Not serializing it @@ -79,17 +74,21 @@ private void addTestCase(String selector, NamedVersionSelector expected) { }; } - @Test - public void testResolvedResult() { + @MethodSource("parameters") + @ParameterizedTest(name = "selector={0}") + public void resolvedResult(String selector, NamedVersionSelector expected) { + initSftpVersionResolverTest(selector, expected); assertEquals(expected, actual); } - @Test - public void testPreDefinedSelectorResolution() { - Assume.assumeTrue("Pre-defined selector ?", - (NamedResource.safeCompareByName(SftpVersionSelector.CURRENT, expected, false) == 0) - || (NamedResource.safeCompareByName(SftpVersionSelector.MINIMUM, expected, false) == 0) - || (NamedResource.safeCompareByName(SftpVersionSelector.MAXIMUM, expected, false) == 0)); + @MethodSource("parameters") + @ParameterizedTest(name = "selector={0}") + public void preDefinedSelectorResolution(String selector, NamedVersionSelector expected) { + initSftpVersionResolverTest(selector, expected); + Assumptions.assumeTrue((NamedResource.safeCompareByName(SftpVersionSelector.CURRENT, expected, false) == 0) + || (NamedResource.safeCompareByName(SftpVersionSelector.MINIMUM, expected, false) == 0) + || (NamedResource.safeCompareByName(SftpVersionSelector.MAXIMUM, expected, false) == 0), + "Pre-defined selector ?"); assertSame(expected, actual); } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionSelectorTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionSelectorTest.java index fcb538176..abfd0a92b 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionSelectorTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionSelectorTest.java @@ -28,25 +28,27 @@ import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.sftp.server.SftpSubsystemEnvironment; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SftpVersionSelectorTest extends JUnitTestSupport { public SftpVersionSelectorTest() { super(); } @Test - public void testCurrentVersionSelector() { + void currentVersionSelector() { List available = new ArrayList<>(); Random rnd = new Random(System.nanoTime()); ClientSession session = Mockito.mock(ClientSession.class); @@ -54,8 +56,9 @@ public void testCurrentVersionSelector() { expected <= SftpSubsystemEnvironment.HIGHER_SFTP_IMPL; expected++) { for (boolean initial : new boolean[] { true, false }) { - assertEquals("Mismatched directly selected for initial=" + initial + "/available=" + available, expected, - SftpVersionSelector.CURRENT.selectVersion(session, initial, expected, available)); + assertEquals(expected, + SftpVersionSelector.CURRENT.selectVersion(session, initial, expected, available), + "Mismatched directly selected for initial=" + initial + "/available=" + available); available.add(expected); } } @@ -66,22 +69,24 @@ public void testCurrentVersionSelector() { for (boolean initial : new boolean[] { true, false }) { for (int index = 0; index < available.size(); index++) { Collections.shuffle(available, rnd); - assertEquals("Mismatched suffling selected for initial=" + initial + ", current=" + expected - + ", available=" + available, - expected, SftpVersionSelector.CURRENT.selectVersion(session, initial, expected, available)); + assertEquals( + expected, SftpVersionSelector.CURRENT.selectVersion(session, initial, expected, + available), + "Mismatched suffling selected for initial=" + initial + ", current=" + expected + + ", available=" + available); } } } } @Test - public void testFixedVersionSelector() { + void fixedVersionSelector() { final int fixedValue = 7365; testVersionSelector(SftpVersionSelector.fixedVersionSelector(fixedValue), fixedValue); } @Test - public void testPreferredVersionSelector() { + void preferredVersionSelector() { List available = new ArrayList<>(); for (int version = SftpSubsystemEnvironment.LOWER_SFTP_IMPL; version <= SftpSubsystemEnvironment.HIGHER_SFTP_IMPL; @@ -103,9 +108,9 @@ public void testPreferredVersionSelector() { current <= SftpSubsystemEnvironment.HIGHER_SFTP_IMPL; current++) { assertEquals( + expected, selector.selectVersion(session, initial, current, available), "Mismatched selected for current= " + current + ", available=" + available + ", preferred=" - + preferred, - expected, selector.selectVersion(session, initial, current, available)); + + preferred); try { Collections.shuffle(unavailable, rnd); @@ -124,12 +129,12 @@ public void testPreferredVersionSelector() { } @Test - public void testMaximumVersionSelector() { + void maximumVersionSelector() { testVersionSelector(SftpVersionSelector.MAXIMUM, SftpSubsystemEnvironment.HIGHER_SFTP_IMPL); } @Test - public void testMinimumVersionSelector() { + void minimumVersionSelector() { testVersionSelector(SftpVersionSelector.MINIMUM, SftpSubsystemEnvironment.LOWER_SFTP_IMPL); } @@ -148,8 +153,8 @@ private static void testVersionSelector(SftpVersionSelector selector, int expect current++) { for (boolean initial : new boolean[] { true, false }) { for (int index = 0; index < available.size(); index++) { - assertEquals("Mismatched selection for current=" + current + ", available=" + available, - expected, selector.selectVersion(session, initial, current, available)); + assertEquals(expected, selector.selectVersion(session, initial, current, available), + "Mismatched selection for current=" + current + ", available=" + available); Collections.shuffle(available, rnd); } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionsTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionsTest.java index c18a3d7cd..1a8ad9c98 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionsTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SftpVersionsTest.java @@ -70,41 +70,40 @@ import org.apache.sshd.sftp.server.SftpSubsystemEnvironment; import org.apache.sshd.sftp.server.SftpSubsystemFactory; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.junit.Before; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class SftpVersionsTest extends AbstractSftpClientTestSupport { private static final List VERSIONS = Collections.unmodifiableList( IntStream.rangeClosed(SftpSubsystemEnvironment.LOWER_SFTP_IMPL, SftpSubsystemEnvironment.HIGHER_SFTP_IMPL) .boxed() .collect(Collectors.toList())); - private final int testVersion; + private int testVersion; - public SftpVersionsTest(int version) throws IOException { + public void initSftpVersionsTest(int version) throws Exception { testVersion = version; + setUp(); } - @Parameters(name = "version={0}") public static Collection parameters() { return parameterize(VERSIONS); } - @Before - public void setUp() throws Exception { + void setUp() throws Exception { setupServer(); Map props = sshd.getProperties(); @@ -118,8 +117,10 @@ public final int getTestedVersion() { return testVersion; } - @Test // See SSHD-749 - public void testSftpOpenFlags() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "version={0}") // See SSHD-749 + public void sftpOpenFlags(int version) throws Exception { + initSftpVersionsTest(version); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -134,13 +135,15 @@ public void testSftpOpenFlags() throws Exception { try (OutputStream out = sftp.write(remotePath, OpenMode.Create, OpenMode.Write)) { out.write(getCurrentTestName().getBytes(StandardCharsets.UTF_8)); } - assertTrue("File should exist on disk: " + lclFile, Files.exists(lclFile)); + assertTrue(Files.exists(lclFile), "File should exist on disk: " + lclFile); sftp.remove(remotePath); } } - @Test - public void testSftpCreateNew() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "version={0}") + public void sftpCreateNew(int version) throws Exception { + initSftpVersionsTest(version); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -161,8 +164,10 @@ public void testSftpCreateNew() throws Exception { } } - @Test - public void testSftpRenameNoReplace() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "version={0}") + public void sftpRenameNoReplace(int version) throws Exception { + initSftpVersionsTest(version); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -196,16 +201,20 @@ public void testSftpRenameNoReplace() throws Exception { } } - @Test - public void testSftpVersionSelector() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "version={0}") + public void sftpVersionSelector(int version) throws Exception { + initSftpVersionsTest(version); try (ClientSession session = createAuthenticatedClientSession(); SftpClient sftp = createSftpClient(session, getTestedVersion())) { - assertEquals("Mismatched negotiated version", getTestedVersion(), sftp.getVersion()); + assertEquals(getTestedVersion(), sftp.getVersion(), "Mismatched negotiated version"); } } - @Test // see SSHD-572 - public void testSftpFileTimesUpdate() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "version={0}") // see SSHD-572 + public void sftpFileTimesUpdate(int version) throws Exception { + initSftpVersionsTest(version); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -238,8 +247,10 @@ public void testSftpFileTimesUpdate() throws Exception { } } - @Test // see SSHD-573 - public void testSftpFileTypeAndPermissionsUpdate() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "version={0}") // see SSHD-573 + public void sftpFileTypeAndPermissionsUpdate(int version) throws Exception { + initSftpVersionsTest(version); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -262,18 +273,20 @@ public void testSftpFileTypeAndPermissionsUpdate() throws Exception { Attributes attrs = validateSftpFileTypeAndPermissions(fileName, getTestedVersion(), entry.getAttributes()); if (subFolderName.equals(fileName)) { - assertEquals("Mismatched sub-folder type", SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY, attrs.getType()); - assertTrue("Sub-folder not marked as directory", attrs.isDirectory()); + assertEquals(SftpConstants.SSH_FILEXFER_TYPE_DIRECTORY, attrs.getType(), "Mismatched sub-folder type"); + assertTrue(attrs.isDirectory(), "Sub-folder not marked as directory"); } else if (lclFileName.equals(fileName)) { - assertEquals("Mismatched sub-file type", SftpConstants.SSH_FILEXFER_TYPE_REGULAR, attrs.getType()); - assertTrue("Sub-folder not marked as directory", attrs.isRegularFile()); + assertEquals(SftpConstants.SSH_FILEXFER_TYPE_REGULAR, attrs.getType(), "Mismatched sub-file type"); + assertTrue(attrs.isRegularFile(), "Sub-folder not marked as directory"); } } } } - @Test // see SSHD-574 - public void testSftpACLEncodeDecode() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "version={0}") // see SSHD-574 + public void sftpACLEncodeDecode(int version) throws Exception { + initSftpVersionsTest(version); AclEntryType[] types = AclEntryType.values(); final List aclExpected = new ArrayList<>(types.length); for (AclEntryType t : types) { @@ -337,7 +350,7 @@ public void modifyingAttributes(ServerSession session, Path path, Map if (getTestedVersion() > SftpConstants.SFTP_V3) { assertListEquals("Mismatched modifying ACL for file=" + path, aclExpected, aclActual); } else { - assertNull("Unexpected modifying ACL for file=" + path, aclActual); + assertNull(aclActual, "Unexpected modifying ACL for file=" + path); } } @@ -350,7 +363,7 @@ public void modifiedAttributes( if (getTestedVersion() > SftpConstants.SFTP_V3) { assertListEquals("Mismatched modified ACL for file=" + path, aclExpected, aclActual); } else { - assertNull("Unexpected modified ACL for file=" + path, aclActual); + assertNull(aclActual, "Unexpected modified ACL for file=" + path); } } }); @@ -380,7 +393,7 @@ public void modifiedAttributes( Attributes attrs = validateSftpFileTypeAndPermissions(fileName, getTestedVersion(), entry.getAttributes()); List aclActual = attrs.getAcl(); if (getTestedVersion() == SftpConstants.SFTP_V3) { - assertNull("Unexpected ACL for entry=" + fileName, aclActual); + assertNull(aclActual, "Unexpected ACL for entry=" + fileName); } else { assertListEquals("Mismatched ACL for entry=" + fileName, aclExpected, aclActual); } @@ -396,11 +409,13 @@ public void modifiedAttributes( sshd.setSubsystemFactories(factories); } - assertEquals("Mismatched invocations count", numInvoked, numInvocations.get()); + assertEquals(numInvoked, numInvocations.get(), "Mismatched invocations count"); } - @Test // see SSHD-575 - public void testSftpExtensionsEncodeDecode() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "version={0}") // see SSHD-575 + public void sftpExtensionsEncodeDecode(int version) throws Exception { + initSftpVersionsTest(version); Class anchor = getClass(); Map expExtensions = NavigableMapBuilder. builder(String.CASE_INSENSITIVE_ORDER) .put("class", anchor.getSimpleName()) @@ -441,11 +456,11 @@ protected void setFileExtensions(Path file, Map extensions, Link int currentVersion = getTestedVersion(); try { super.setFileExtensions(file, extensions, options); - assertFalse("Expected exception not generated for version=" + currentVersion, - currentVersion >= SftpConstants.SFTP_V6); + assertFalse(currentVersion >= SftpConstants.SFTP_V6, + "Expected exception not generated for version=" + currentVersion); } catch (UnsupportedOperationException e) { - assertTrue("Unexpected exception for version=" + currentVersion, - currentVersion >= SftpConstants.SFTP_V6); + assertTrue(currentVersion >= SftpConstants.SFTP_V6, + "Unexpected exception for version=" + currentVersion); } } }; @@ -512,15 +527,16 @@ public void modifiedAttributes(ServerSession session, Path path, Map sshd.setSubsystemFactories(factories); } - assertEquals("Mismatched invocations count", numInvoked, numInvocations.get()); + assertEquals(numInvoked, numInvocations.get(), "Mismatched invocations count"); } - @Test // see SSHD-623 - public void testEndOfListIndicator() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "version={0}") // see SSHD-623 + public void endOfListIndicator(int version) throws Exception { + initSftpVersionsTest(version); try (ClientSession session = createAuthenticatedClientSession(); SftpClient sftp = createSftpClient(session, getTestedVersion())) { AtomicReference eolIndicator = new AtomicReference<>(); - int version = sftp.getVersion(); Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); String remotePath = CommonTestSupportUtils.resolveRelativeRemotePath(parentPath, targetPath); @@ -530,9 +546,9 @@ public void testEndOfListIndicator() throws Exception { for (int index = 1; entries != null; entries = sftp.readDir(handle, eolIndicator), index++) { Boolean value = eolIndicator.get(); if (version < SftpConstants.SFTP_V6) { - assertNull("Unexpected indicator value at iteration #" + index, value); + assertNull(value, "Unexpected indicator value at iteration #" + index); } else { - assertNotNull("No indicator returned at iteration #" + index, value); + assertNotNull(value, "No indicator returned at iteration #" + index); if (value) { break; } @@ -542,12 +558,12 @@ public void testEndOfListIndicator() throws Exception { Boolean value = eolIndicator.get(); if (version < SftpConstants.SFTP_V6) { - assertNull("Unexpected end-of-list indication received at end of entries", value); - assertNull("Unexpected no last entries indication", entries); + assertNull(value, "Unexpected end-of-list indication received at end of entries"); + assertNull(entries, "Unexpected no last entries indication"); } else { - assertNotNull("No end-of-list indication received at end of entries", value); - assertNotNull("No last received entries", entries); - assertTrue("Bad end-of-list value", value); + assertNotNull(value, "No end-of-list indication received at end of entries"); + assertNotNull(entries, "No last received entries"); + assertTrue(value, "Bad end-of-list value"); } } } @@ -566,12 +582,12 @@ private static Attributes validateSftpFileTypeAndPermissions(String fileName, in int actualPerms = attrs.getPermissions(); if (version == SftpConstants.SFTP_V3) { int expected = SftpHelper.permissionsToFileType(actualPerms); - assertEquals(fileName + ": Mismatched file type", expected, attrs.getType()); + assertEquals(expected, attrs.getType(), fileName + ": Mismatched file type"); } else { int expected = SftpHelper.fileTypeToPermission(attrs.getType()); - assertTrue(fileName + ": Missing permision=0x" + Integer.toHexString(expected) + " in 0x" - + Integer.toHexString(actualPerms), - (actualPerms & expected) == expected); + assertEquals((actualPerms & expected), expected, + fileName + ": Missing permision=0x" + Integer.toHexString(expected) + " in 0x" + + Integer.toHexString(actualPerms)); } return attrs; diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SimpleSftpClientTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SimpleSftpClientTest.java index 7a5e26a97..f7ce68087 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SimpleSftpClientTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/SimpleSftpClientTest.java @@ -35,14 +35,21 @@ import org.apache.sshd.sftp.server.SftpSubsystemFactory; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.client.simple.BaseSimpleClientTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SimpleSftpClientTest extends BaseSimpleClientTestSupport { private final Path targetPath; private final Path parentPath; @@ -55,6 +62,7 @@ public SimpleSftpClientTest() throws Exception { fileSystemFactory = new VirtualFileSystemFactory(parentPath); } + @BeforeEach @Override public void setUp() throws Exception { super.setUp(); @@ -65,21 +73,21 @@ public void setUp() throws Exception { } @Test - public void testSessionClosedWhenClientClosed() throws Exception { + void sessionClosedWhenClientClosed() throws Exception { try (SftpClient sftp = login()) { - assertTrue("SFTP not open", sftp.isOpen()); + assertTrue(sftp.isOpen(), "SFTP not open"); Session session = sftp.getClientSession(); - assertTrue("Session not open", session.isOpen()); + assertTrue(session.isOpen(), "Session not open"); sftp.close(); - assertFalse("Session not closed", session.isOpen()); - assertFalse("SFTP not closed", sftp.isOpen()); + assertFalse(session.isOpen(), "Session not closed"); + assertFalse(sftp.isOpen(), "SFTP not closed"); } } @Test - public void testSftpProxyCalls() throws Exception { + void sftpProxyCalls() throws Exception { Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); CommonTestSupportUtils.deleteRecursive(lclSftp); @@ -99,13 +107,13 @@ public void testSftpProxyCalls() throws Exception { sftp.write(h, 0L, written); SftpClient.Attributes attrs = sftp.stat(h); - assertNotNull("No handle attributes", attrs); - assertEquals("Mismatched remote file size", written.length, attrs.getSize()); + assertNotNull(attrs, "No handle attributes"); + assertEquals(written.length, attrs.getSize(), "Mismatched remote file size"); } - assertTrue("Remote file not created: " + clientFile, Files.exists(clientFile, IoUtils.EMPTY_LINK_OPTIONS)); + assertTrue(Files.exists(clientFile, IoUtils.EMPTY_LINK_OPTIONS), "Remote file not created: " + clientFile); byte[] local = Files.readAllBytes(clientFile); - assertArrayEquals("Mismatched remote written data", written, local); + assertArrayEquals(written, local, "Mismatched remote written data"); try (SftpClient.CloseableHandle h = sftp.openDir(remoteFileDir)) { boolean matchFound = false; @@ -117,11 +125,11 @@ public void testSftpProxyCalls() throws Exception { } } - assertTrue("No directory entry found for " + clientFileName, matchFound); + assertTrue(matchFound, "No directory entry found for " + clientFileName); } sftp.remove(remoteFilePath); - assertFalse("Remote file not removed: " + clientFile, Files.exists(clientFile, IoUtils.EMPTY_LINK_OPTIONS)); + assertFalse(Files.exists(clientFile, IoUtils.EMPTY_LINK_OPTIONS), "Remote file not removed: " + clientFile); } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/BuiltinSftpClientExtensionsTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/BuiltinSftpClientExtensionsTest.java index 8e03c68b2..7640f0fcc 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/BuiltinSftpClientExtensionsTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/BuiltinSftpClientExtensionsTest.java @@ -22,56 +22,59 @@ import org.apache.sshd.sftp.client.RawSftpClient; import org.apache.sshd.sftp.client.SftpClient; import org.apache.sshd.util.test.BaseTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class BuiltinSftpClientExtensionsTest extends BaseTestSupport { public BuiltinSftpClientExtensionsTest() { super(); } @Test - public void testFromName() { + void fromName() { for (String name : new String[] { null, "", getCurrentTestName() }) { - assertNull("Unexpected result for name='" + name + "'", BuiltinSftpClientExtensions.fromName(name)); + assertNull(BuiltinSftpClientExtensions.fromName(name), "Unexpected result for name='" + name + "'"); } for (BuiltinSftpClientExtensions expected : BuiltinSftpClientExtensions.VALUES) { String name = expected.getName(); for (int index = 0; index < name.length(); index++) { BuiltinSftpClientExtensions actual = BuiltinSftpClientExtensions.fromName(name); - assertSame(name, expected, actual); + assertSame(expected, actual, name); name = shuffleCase(name); } } } @Test - public void testFromType() { + void fromType() { for (Class clazz : new Class[] { null, getClass(), SftpClientExtension.class }) { - assertNull("Unexpected value for class=" + clazz, BuiltinSftpClientExtensions.fromType(clazz)); + assertNull(BuiltinSftpClientExtensions.fromType(clazz), "Unexpected value for class=" + clazz); } for (BuiltinSftpClientExtensions expected : BuiltinSftpClientExtensions.VALUES) { Class type = expected.getType(); BuiltinSftpClientExtensions actual = BuiltinSftpClientExtensions.fromType(type); - assertSame(type.getSimpleName(), expected, actual); + assertSame(expected, actual, type.getSimpleName()); } } @Test - public void testFromInstance() { + void fromInstance() { for (Object instance : new Object[] { null, this }) { - assertNull("Unexpected value for " + instance, BuiltinSftpClientExtensions.fromInstance(instance)); + assertNull(BuiltinSftpClientExtensions.fromInstance(instance), "Unexpected value for " + instance); } SftpClient mockClient = Mockito.mock(SftpClient.class); @@ -80,8 +83,8 @@ public void testFromInstance() { for (BuiltinSftpClientExtensions expected : BuiltinSftpClientExtensions.VALUES) { SftpClientExtension e = expected.create(mockClient, mockRaw); BuiltinSftpClientExtensions actual = BuiltinSftpClientExtensions.fromInstance(e); - assertSame(expected.getName(), expected, actual); - assertEquals("Mismatched extension name", expected.getName(), actual.getName()); + assertSame(expected, actual, expected.getName()); + assertEquals(expected.getName(), actual.getName(), "Mismatched extension name"); } } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/SftpExtensionsTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/SftpExtensionsTest.java index 1dbeb45a6..e434dd82e 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/SftpExtensionsTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/SftpExtensionsTest.java @@ -47,19 +47,23 @@ import org.apache.sshd.sftp.server.SftpSubsystemFactory; import org.apache.sshd.sftp.server.SftpSubsystemProxy; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.testcontainers.shaded.com.google.common.base.Objects; -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +@TestMethodOrder(MethodName.class) public class SftpExtensionsTest extends AbstractSftpClientTestSupport { public SftpExtensionsTest() throws IOException { super(); } - @Test // see SSHD-890 - public void testUnsupportedExtension() throws IOException { + // see SSHD-890 + @Test + void unsupportedExtension() throws IOException { try (SftpClient sftpClient = createSingleSessionClient()) { RawSftpClient sftp = assertObjectInstanceOf("Not a raw SFTP client", RawSftpClient.class, sftpClient); @@ -75,13 +79,14 @@ public void testUnsupportedExtension() throws IOException { responseBuffer.getInt(); // Ignoring message ID int substatus = responseBuffer.getInt(); - assertEquals("Type is not STATUS", SftpConstants.SSH_FXP_STATUS, type); - assertEquals("Sub-Type is not UNSUPPORTED", SftpConstants.SSH_FX_OP_UNSUPPORTED, substatus); + assertEquals(SftpConstants.SSH_FXP_STATUS, type, "Type is not STATUS"); + assertEquals(SftpConstants.SSH_FX_OP_UNSUPPORTED, substatus, "Sub-Type is not UNSUPPORTED"); } } - @Test // see SSHD-1166 - public void testCustomFileExtensionAttributes() throws IOException { + // see SSHD-1166 + @Test + void customFileExtensionAttributes() throws IOException { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path localFile = CommonTestSupportUtils.resolve( @@ -91,7 +96,7 @@ public void testCustomFileExtensionAttributes() throws IOException { StandardCharsets.UTF_8); List factories = sshd.getSubsystemFactories(); - assertEquals("Mismatched subsystem factories count", 1, GenericUtils.size(factories)); + assertEquals(1, GenericUtils.size(factories), "Mismatched subsystem factories count"); SubsystemFactory f = factories.get(0); assertObjectInstanceOf("Not an SFTP subsystem factory", SftpSubsystemFactory.class, f); @@ -135,7 +140,7 @@ public NavigableMap resolveReportedFileAttributes( } Map extsMap = attrs.getExtensions(); - assertTrue("No extended attributes provided", MapEntryUtils.isNotEmpty(extsMap)); + assertTrue(MapEntryUtils.isNotEmpty(extsMap), "No extended attributes provided"); Map actual = extsMap.entrySet() .stream() diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/VersionParserTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/VersionParserTest.java index 7e6b0598e..8801f55fd 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/VersionParserTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/VersionParserTest.java @@ -25,21 +25,22 @@ import org.apache.sshd.sftp.common.extensions.VersionsParser.Versions; import org.apache.sshd.util.test.JUnitTestSupport; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class VersionParserTest extends JUnitTestSupport { public VersionParserTest() { super(); } - @Test // see SSHD-909 - public void testIgnoreNonNumbersWhenResolvingAvailableVersions() { + // see SSHD-909 + @Test + void ignoreNonNumbersWhenResolvingAvailableVersions() { List expected = Arrays.asList(3, 4, 5, 6); List values = expected.stream() .map(Object::toString) diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/AbstractCheckFileExtensionTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/AbstractCheckFileExtensionTest.java index c7ac8fab8..7eb7703e7 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/AbstractCheckFileExtensionTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/AbstractCheckFileExtensionTest.java @@ -48,22 +48,21 @@ import org.apache.sshd.sftp.common.SftpConstants; import org.apache.sshd.sftp.common.SftpException; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.junit.Before; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSupport { private static final Collection DATA_SIZES = Collections.unmodifiableList( Arrays.asList( @@ -97,28 +96,29 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor PARAMETERS = list; } - private final String algorithm; - private final int dataSize; - private final int blockSize; + private String algorithm; + private int dataSize; + private int blockSize; - public AbstractCheckFileExtensionTest(String algorithm, int dataSize, int blockSize) throws IOException { + public void initAbstractCheckFileExtensionTest(String algorithm, int dataSize, int blockSize) throws IOException { this.algorithm = algorithm; this.dataSize = dataSize; this.blockSize = blockSize; } - @Parameters(name = "{0} - dataSize={1}, blockSize={2}") public static Collection parameters() { return PARAMETERS; } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { setupServer(); } - @Test - public void testCheckFileExtension() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "{0} - dataSize={1}, blockSize={2}") + public void checkFileExtension(String algorithm, int dataSize, int blockSize) throws Exception { + initAbstractCheckFileExtensionTest(algorithm, dataSize, blockSize); testCheckFileExtension(algorithm, dataSize, blockSize); } @@ -180,7 +180,7 @@ private void testCheckFileExtension( Map.Entry result = file.checkFileName(srcFolder, algorithms, 0L, 0L, hashBlockSize); fail("Unexpected success to hash folder=" + srcFolder + ": " + result.getKey()); } catch (IOException e) { // expected - not allowed to hash a folder - assertTrue("Not an SftpException", e instanceof SftpException); + assertTrue(e instanceof SftpException, "Not an SftpException"); } CheckFileHandleExtension hndl = assertExtensionCreated(sftp, CheckFileHandleExtension.class); @@ -189,7 +189,7 @@ private void testCheckFileExtension( Map.Entry result = hndl.checkFileHandle(dirHandle, algorithms, 0L, 0L, hashBlockSize); fail("Unexpected handle success on folder=" + srcFolder + ": " + result.getKey()); } catch (IOException e) { // expected - not allowed to hash a folder - assertTrue("Not an SftpException", e instanceof SftpException); + assertTrue(e instanceof SftpException, "Not an SftpException"); } } @@ -207,12 +207,12 @@ private void validateHashResult( NamedResource hasher, Map.Entry> result, String expectedAlgorithm, byte[] expectedHash) { String name = hasher.getName(); - assertNotNull("No result for hash=" + name, result); - assertEquals("Mismatched hash algorithms for " + name, expectedAlgorithm, result.getKey()); + assertNotNull(result, "No result for hash=" + name); + assertEquals(expectedAlgorithm, result.getKey(), "Mismatched hash algorithms for " + name); if (NumberUtils.length(expectedHash) > 0) { Collection values = result.getValue(); - assertEquals("Mismatched hash values count for " + name, 1, GenericUtils.size(values)); + assertEquals(1, GenericUtils.size(values), "Mismatched hash values count for " + name); byte[] actualHash = GenericUtils.head(values); if (!Arrays.equals(expectedHash, actualHash)) { diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/AbstractMD5HashExtensionTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/AbstractMD5HashExtensionTest.java index 460fc20be..bdad7e006 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/AbstractMD5HashExtensionTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/AbstractMD5HashExtensionTest.java @@ -42,24 +42,21 @@ import org.apache.sshd.sftp.common.SftpConstants; import org.apache.sshd.sftp.common.SftpException; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.junit.Assume; -import org.junit.Before; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class AbstractMD5HashExtensionTest extends AbstractSftpClientTestSupport { private static final List DATA_SIZES = Collections.unmodifiableList( Arrays.asList( @@ -68,29 +65,30 @@ public class AbstractMD5HashExtensionTest extends AbstractSftpClientTestSupport IoUtils.DEFAULT_COPY_SIZE, Byte.SIZE * IoUtils.DEFAULT_COPY_SIZE)); - private final int size; + private int size; - public AbstractMD5HashExtensionTest(int size) throws IOException { + public void initAbstractMD5HashExtensionTest(int size) throws IOException { this.size = size; } - @Parameters(name = "dataSize={0}") public static Collection parameters() { return parameterize(DATA_SIZES); } - @BeforeClass - public static void checkMD5Supported() { - Assume.assumeTrue("MD5 not supported", BuiltinDigests.md5.isSupported()); + @BeforeAll + static void checkMD5Supported() { + Assumptions.assumeTrue(BuiltinDigests.md5.isSupported(), "MD5 not supported"); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { setupServer(); } - @Test - public void testMD5HashExtension() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "dataSize={0}") + public void md5HashExtension(int size) throws Exception { + initAbstractMD5HashExtensionTest(size); testMD5HashExtension(size); } @@ -138,7 +136,7 @@ private void testMD5HashExtension(byte[] data) throws Exception { 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); + assertTrue(e instanceof SftpException, "Not an SftpException for file hash on " + srcFolder); } MD5HandleExtension hndl = assertExtensionCreated(sftp, MD5HandleExtension.class); @@ -147,7 +145,7 @@ private void testMD5HashExtension(byte[] data) throws Exception { 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(e instanceof SftpException, "Not an SftpException for handle hash on " + srcFolder); } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/CopyDataExtensionImplTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/CopyDataExtensionImplTest.java index 8d3867942..44127f503 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/CopyDataExtensionImplTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/CopyDataExtensionImplTest.java @@ -42,22 +42,19 @@ import org.apache.sshd.sftp.client.extensions.CopyDataExtension; import org.apache.sshd.sftp.common.SftpConstants; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; -import org.junit.Before; -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; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests public class CopyDataExtensionImplTest extends AbstractSftpClientTestSupport { private static final List PARAMETERS = Collections.unmodifiableList( Arrays.asList( @@ -91,25 +88,26 @@ public class CopyDataExtensionImplTest extends AbstractSftpClientTestSupport { private int length; private long dstOffset; - public CopyDataExtensionImplTest(int size, int srcOffset, int length, long dstOffset) throws IOException { + public void initCopyDataExtensionImplTest(int size, int srcOffset, int length, long dstOffset) throws IOException { this.size = size; this.srcOffset = srcOffset; this.length = length; this.dstOffset = dstOffset; } - @Parameters(name = "size={0}, readOffset={1}, readLength={2}, writeOffset={3}") public static Collection parameters() { return PARAMETERS; } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { setupServer(); } - @Test - public void testCopyDataExtension() throws Exception { + @MethodSource("parameters") + @ParameterizedTest(name = "size={0}, readOffset={1}, readLength={2}, writeOffset={3}") + public void copyDataExtension(int size, int srcOffset, int length, long dstOffset) throws Exception { + initCopyDataExtensionImplTest(size, srcOffset, length, dstOffset); testCopyDataExtension(size, srcOffset, length, dstOffset); } @@ -177,8 +175,8 @@ private void testCopyDataExtension(byte[] data, int readOffset, int readLength, byte[] actual = new byte[expected.length]; try (FileChannel channel = FileChannel.open(dstFile, IoUtils.EMPTY_OPEN_OPTIONS)) { int readLen = channel.read(ByteBuffer.wrap(actual), writeOffset); - assertEquals("Mismatched read data size", expected.length, readLen); + assertEquals(expected.length, readLen, "Mismatched read data size"); } - assertArrayEquals("Mismatched copy data", expected, actual); + assertArrayEquals(expected, actual, "Mismatched copy data"); } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/CopyFileExtensionImplTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/CopyFileExtensionImplTest.java index f2e5dd33c..95889c1db 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/CopyFileExtensionImplTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/CopyFileExtensionImplTest.java @@ -32,27 +32,32 @@ import org.apache.sshd.sftp.common.SftpConstants; import org.apache.sshd.sftp.common.SftpException; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class CopyFileExtensionImplTest extends AbstractSftpClientTestSupport { public CopyFileExtensionImplTest() throws IOException { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { setupServer(); } @Test - public void testCopyFileExtension() throws Exception { + void copyFileExtension() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -68,22 +73,22 @@ public void testCopyFileExtension() throws Exception { String dstPath = CommonTestSupportUtils.resolveRelativeRemotePath(parentPath, dstFile); LinkOption[] options = IoUtils.getLinkOptions(true); - assertFalse("Destination file unexpectedly exists", Files.exists(dstFile, options)); + assertFalse(Files.exists(dstFile, options), "Destination file unexpectedly exists"); try (SftpClient sftp = createSingleSessionClient()) { 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)); + assertTrue(Files.exists(srcFile, options), "Source file not preserved"); + assertTrue(Files.exists(dstFile, options), "Destination file not created"); byte[] actual = Files.readAllBytes(dstFile); - assertArrayEquals("Mismatched copied data", data, actual); + assertArrayEquals(data, actual, "Mismatched copied data"); try { ext.copyFile(srcPath, dstPath, false); fail("Unexpected success to overwrite existing destination: " + dstFile); } catch (IOException e) { - assertTrue("Not an SftpException", e instanceof SftpException); + assertTrue(e instanceof SftpException, "Not an SftpException"); } } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/SpaceAvailableExtensionImplTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/SpaceAvailableExtensionImplTest.java index 7eaa8f4d3..8f21566fd 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/SpaceAvailableExtensionImplTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/helpers/SpaceAvailableExtensionImplTest.java @@ -38,27 +38,29 @@ import org.apache.sshd.sftp.server.SftpSubsystem; import org.apache.sshd.sftp.server.SftpSubsystemFactory; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SpaceAvailableExtensionImplTest extends AbstractSftpClientTestSupport { public SpaceAvailableExtensionImplTest() throws IOException { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { setupServer(); } @Test - public void testFileStoreReport() throws Exception { + void fileStoreReport() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -88,7 +90,7 @@ protected SpaceAvailableExtensionInfo doSpaceAvailable(int id, String path) thro try (SftpClient sftp = createSingleSessionClient()) { SpaceAvailableExtension ext = assertExtensionCreated(sftp, SpaceAvailableExtension.class); SpaceAvailableExtensionInfo actual = ext.available(queryPath); - assertEquals("Mismatched information", expected, actual); + assertEquals(expected, actual, "Mismatched information"); } finally { sshd.setSubsystemFactories(factories); } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/openssh/helpers/OpenSSHExtensionsTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/openssh/helpers/OpenSSHExtensionsTest.java index 84278445c..144cc106d 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/openssh/helpers/OpenSSHExtensionsTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/extensions/openssh/helpers/OpenSSHExtensionsTest.java @@ -54,27 +54,31 @@ import org.apache.sshd.sftp.server.SftpSubsystem; import org.apache.sshd.sftp.server.SftpSubsystemFactory; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class OpenSSHExtensionsTest extends AbstractSftpClientTestSupport { public OpenSSHExtensionsTest() throws IOException { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { setupServer(); } @Test - public void testPosixRename() throws IOException { + void posixRename() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -99,8 +103,8 @@ public void testPosixRename() throws IOException { rename.posixRename(file2Path, file3Path); fail("Unxpected rename success of " + file2Path + " => " + file3Path); } catch (SftpException e) { - assertEquals("Mismatched status for failed rename of " + file2Path + " => " + file3Path, - SftpConstants.SSH_FX_NO_SUCH_FILE, e.getStatus()); + assertEquals(SftpConstants.SSH_FX_NO_SUCH_FILE, e.getStatus(), + "Mismatched status for failed rename of " + file2Path + " => " + file3Path); } try (OutputStream os = sftp.write(file2Path, SftpClient.MIN_WRITE_BUFFER_SIZE)) { @@ -112,7 +116,7 @@ public void testPosixRename() throws IOException { } @Test - public void testFsync() throws IOException { + void fsync() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -128,13 +132,13 @@ public void testFsync() throws IOException { fsync.fsync(fileHandle); byte[] actual = Files.readAllBytes(srcFile); - assertArrayEquals("Mismatched written data", expected, actual); + assertArrayEquals(expected, actual, "Mismatched written data"); } } } @Test - public void testStat() throws Exception { + void stat() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -205,21 +209,22 @@ protected void executeExtendedCommand(Buffer buffer, int id, String extension) t OpenSSHStatPathExtension pathStat = assertExtensionCreated(sftp, OpenSSHStatPathExtension.class); OpenSSHStatExtensionInfo actual = pathStat.stat(srcPath); String invokedExtension = extensionHolder.getAndSet(null); - assertEquals("Mismatched invoked extension", pathStat.getName(), invokedExtension); + assertEquals(pathStat.getName(), invokedExtension, "Mismatched invoked extension"); assertFieldsEqual(invokedExtension, expected, actual); try (CloseableHandle handle = sftp.open(srcPath)) { OpenSSHStatHandleExtension handleStat = assertExtensionCreated(sftp, OpenSSHStatHandleExtension.class); actual = handleStat.stat(handle); invokedExtension = extensionHolder.getAndSet(null); - assertEquals("Mismatched invoked extension", handleStat.getName(), invokedExtension); + assertEquals(handleStat.getName(), invokedExtension, "Mismatched invoked extension"); assertFieldsEqual(invokedExtension, expected, actual); } } } - @Test // see SSHD-1233 - public void testLimits() throws Exception { + // see SSHD-1233 + @Test + void limits() throws Exception { try (SftpClient sftp = createSingleSessionClient()) { OpenSSHLimitsExtension ext = assertExtensionCreated(sftp, OpenSSHLimitsExtension.class); OpenSSHLimitsExtensionInfo expected = new OpenSSHLimitsExtensionInfo(sftp.getClientChannel()); diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/AbstractSftpFilesSystemSupport.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/AbstractSftpFilesSystemSupport.java index 5750d1177..0786bcc03 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/AbstractSftpFilesSystemSupport.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/AbstractSftpFilesSystemSupport.java @@ -55,6 +55,13 @@ import org.apache.sshd.sftp.common.SftpConstants; import org.apache.sshd.util.test.CommonTestSupportUtils; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Apache MINA SSHD Project */ @@ -84,38 +91,40 @@ protected void testFileSystem(FileSystem fs, int version) throws Exception { outputDebugMessage("Write initial data to %s", file1); Files.write(file1, expected.getBytes(StandardCharsets.UTF_8)); String buf = new String(Files.readAllBytes(file1), StandardCharsets.UTF_8); - assertEquals("Mismatched read test data", expected, buf); + assertEquals(expected, buf, "Mismatched read test data"); try (OutputStream out = file1.getFileSystem().provider().newOutputStream(file1, StandardOpenOption.APPEND)) { out.write("xyz".getBytes(StandardCharsets.US_ASCII)); } expected += "xyz"; buf = new String(Files.readAllBytes(file1), StandardCharsets.UTF_8); - assertEquals("Mismatched read test data", expected, buf); + assertEquals(expected, buf, "Mismatched read test data"); // Neither WRITE nor APPEND given: READ is default, and CREATE_NEW or TRUNCATE_EXISTING should be ignored. - assertEquals("Mismatched read test data", expected, - readFromChannel(file1, StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING)); + assertEquals(expected, + readFromChannel(file1, StandardOpenOption.CREATE_NEW, StandardOpenOption.TRUNCATE_EXISTING), + "Mismatched read test data"); IllegalArgumentException ex = assertThrows(IllegalArgumentException.class, () -> readFromChannel(file1, StandardOpenOption.APPEND, StandardOpenOption.TRUNCATE_EXISTING)); - assertTrue("unexpected exception message " + ex.getMessage(), ex.getMessage().contains("APPEND")); - assertTrue("unexpected exception message " + ex.getMessage(), ex.getMessage().contains("TRUNCATE_EXISTING")); + assertTrue(ex.getMessage().contains("APPEND"), "unexpected exception message " + ex.getMessage()); + assertTrue(ex.getMessage().contains("TRUNCATE_EXISTING"), "unexpected exception message " + ex.getMessage()); ex = assertThrows(IllegalArgumentException.class, () -> readFromChannel(file1, StandardOpenOption.APPEND, StandardOpenOption.READ)); - assertTrue("unexpected exception message " + ex.getMessage(), ex.getMessage().contains("APPEND")); - assertTrue("unexpected exception message " + ex.getMessage(), ex.getMessage().contains("READ")); + assertTrue(ex.getMessage().contains("APPEND"), "unexpected exception message " + ex.getMessage()); + assertTrue(ex.getMessage().contains("READ"), "unexpected exception message " + ex.getMessage()); - assertEquals("Mismatched read test data", expected, - readFromChannel(file1, StandardOpenOption.READ, StandardOpenOption.WRITE)); + assertEquals(expected, + readFromChannel(file1, StandardOpenOption.READ, StandardOpenOption.WRITE), + "Mismatched read test data"); if (version >= SftpConstants.SFTP_V4) { testAclFileAttributeView(file1); } - assertEquals("Mismatched read test data", "", readFromChannel(file1, StandardOpenOption.READ, StandardOpenOption.WRITE, - StandardOpenOption.TRUNCATE_EXISTING)); + assertEquals("", readFromChannel(file1, StandardOpenOption.READ, StandardOpenOption.WRITE, + StandardOpenOption.TRUNCATE_EXISTING), "Mismatched read test data"); // Restore file contents, other tests need it. Files.write(file1, expected.getBytes(StandardCharsets.UTF_8)); @@ -160,7 +169,7 @@ protected void testFileSystem(FileSystem fs, int version) throws Exception { attrs = Files.readAttributes(file1, "*", LinkOption.NOFOLLOW_LINKS); outputDebugMessage("%s no-follow attributes: %s", file1, attrs); - assertEquals("Mismatched symlink data", expected, new String(Files.readAllBytes(file1), StandardCharsets.UTF_8)); + assertEquals(expected, new String(Files.readAllBytes(file1), StandardCharsets.UTF_8), "Mismatched symlink data"); if (version == SftpConstants.SFTP_V6) { testFileChannelLock(file1); @@ -194,8 +203,8 @@ protected static Iterable testRootDirs(FileSystem fs) throws IOException { try (DirectoryStream ds = Files.newDirectoryStream(root)) { for (Path child : ds) { String name = child.getFileName().toString(); - assertNotEquals("Unexpected dot name", ".", name); - assertNotEquals("Unexpected dotdot name", "..", name); + assertNotEquals(".", name, "Unexpected dot name"); + assertNotEquals("..", name, "Unexpected dotdot name"); outputDebugMessage("[%s] %s", rootName, child); } } catch (IOException | RuntimeException e) { @@ -219,11 +228,11 @@ protected static AclFileAttributeView testAclFileAttributeView(Path file) throws outputDebugMessage("getFileAttributeView(%s)", file); AclFileAttributeView aclView = Files.getFileAttributeView(file, AclFileAttributeView.class, LinkOption.NOFOLLOW_LINKS); - assertNotNull("No ACL view for " + file, aclView); + assertNotNull(aclView, "No ACL view for " + file); Map attrs = Files.readAttributes(file, "acl:*", LinkOption.NOFOLLOW_LINKS); outputDebugMessage("readAttributes(%s) %s", file, attrs); - assertEquals("Mismatched owner for " + file, aclView.getOwner(), attrs.get(IoUtils.OWNER_VIEW_ATTR)); + assertEquals(aclView.getOwner(), attrs.get(IoUtils.OWNER_VIEW_ATTR), "Mismatched owner for " + file); @SuppressWarnings("unchecked") List acl = (List) attrs.get(IoUtils.ACL_VIEW_ATTR); @@ -236,10 +245,10 @@ protected static AclFileAttributeView testAclFileAttributeView(Path file) throws protected static void testSymbolicLinks(Path link, Path relPath) throws IOException { outputDebugMessage("Create symlink %s => %s", link, relPath); Files.createSymbolicLink(link, relPath); - assertTrue("Not a symbolic link: " + link, Files.isSymbolicLink(link)); + assertTrue(Files.isSymbolicLink(link), "Not a symbolic link: " + link); Path symLink = Files.readSymbolicLink(link); - assertEquals("mismatched symbolic link name", relPath.toString(), symLink.toString()); + assertEquals(relPath.toString(), symLink.toString(), "mismatched symbolic link name"); outputDebugMessage("Delete symlink %s", link); Files.delete(link); diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpDirectoryScannersTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpDirectoryScannersTest.java index 4ca0c2ae2..006397214 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpDirectoryScannersTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpDirectoryScannersTest.java @@ -42,32 +42,38 @@ import org.apache.sshd.sftp.client.SftpClient.DirEntry; import org.apache.sshd.sftp.client.fs.SftpClientDirectoryScanner.ScanDirEntry; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class SftpDirectoryScannersTest extends AbstractSftpFilesSystemSupport { public SftpDirectoryScannersTest() throws IOException { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { setupServer(); } @Test - public void testSftpPathDirectoryScannerDeepScanning() throws IOException { + void sftpPathDirectoryScannerDeepScanning() throws IOException { testSftpPathDirectoryScanner(setupDeepScanning(), "**/*"); } @Test - public void testSftpPathDirectoryScannerFileSuffixMatching() throws IOException { + void sftpPathDirectoryScannerFileSuffixMatching() throws IOException { testSftpPathDirectoryScanner(setupFileSuffixMatching(), "*.txt"); } @@ -86,17 +92,18 @@ private void testSftpPathDirectoryScanner(SetupDetails setup, String pattern) th } @Test - public void testSftpClientDirectoryScannerDeepScanning() throws IOException { + void sftpClientDirectoryScannerDeepScanning() throws IOException { testSftpClientDirectoryScanner(setupDeepScanning(), "**/*"); } @Test - public void testSftpClientDirectoryScannerFileSuffixMatching() throws IOException { + void sftpClientDirectoryScannerFileSuffixMatching() throws IOException { testSftpClientDirectoryScanner(setupFileSuffixMatching(), "*.txt"); } - @Test // see SSHD-1102 - public void testDirectoryStreamFilter() throws IOException { + // see SSHD-1102 + @Test + void directoryStreamFilter() throws IOException { SetupDetails details = setupFileSuffixMatching(); List expected = details.getExpected(); List actual = new ArrayList<>(); @@ -125,7 +132,7 @@ private static void collectMatchingFiles( throws IOException { try (DirectoryStream ds = Files.newDirectoryStream(dir, filter)) { for (Path p : ds) { - assertTrue("Unfiltered path: " + p, filter.accept(p)); + assertTrue(filter.accept(p), "Unfiltered path: " + p); if (Files.isDirectory(p)) { collectMatchingFiles(p, filter, matches); @@ -136,40 +143,44 @@ private static void collectMatchingFiles( } } - @Test(expected = IllegalStateException.class) - public void testClosedDirectoryStreamIteration() throws IOException { - SetupDetails details = setupDeepScanning(); - try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), Collections.emptyMap())) { - Path dir = fs.getPath(details.getRemoteFilePath()); - try (DirectoryStream ds = Files.newDirectoryStream(dir)) { - ds.close(); - - for (Path p : ds) { - fail("Unexpected iterated path: " + p); + @Test + void closedDirectoryStreamIteration() throws IOException { + assertThrows(IllegalStateException.class, () -> { + SetupDetails details = setupDeepScanning(); + try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), Collections.emptyMap())) { + Path dir = fs.getPath(details.getRemoteFilePath()); + try (DirectoryStream ds = Files.newDirectoryStream(dir)) { + ds.close(); + + for (Path p : ds) { + fail("Unexpected iterated path: " + p); + } } } - } + }); } - @Test(expected = IllegalStateException.class) - public void testDirectoryStreamRepeatedIteration() throws IOException { - SetupDetails details = setupDeepScanning(); - try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), Collections.emptyMap())) { - Path dir = fs.getPath(details.getRemoteFilePath()); - try (DirectoryStream ds = Files.newDirectoryStream(dir)) { - for (Path p : ds) { - assertNotNull(p); - } + @Test + void directoryStreamRepeatedIteration() throws IOException { + assertThrows(IllegalStateException.class, () -> { + SetupDetails details = setupDeepScanning(); + try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), Collections.emptyMap())) { + Path dir = fs.getPath(details.getRemoteFilePath()); + try (DirectoryStream ds = Files.newDirectoryStream(dir)) { + for (Path p : ds) { + assertNotNull(p); + } - for (Path p : ds) { - fail("Unexpected iterated path: " + p); + for (Path p : ds) { + fail("Unexpected iterated path: " + p); + } } } - } + }); } @Test - public void testDirectoryStreamClosedEarly() throws IOException { + void directoryStreamClosedEarly() throws IOException { Path targetPath = detectTargetFolder(); Path rootDir = CommonTestSupportUtils.resolve(targetPath, TEMP_SUBFOLDER_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -197,8 +208,8 @@ public void testDirectoryStreamClosedEarly() throws IOException { n++; } - assertTrue("Expected some read-ahead", n > 1); - assertTrue("Expected early stream end", n < 2000); + assertTrue(n > 1, "Expected some read-ahead"); + assertTrue(n < 2000, "Expected early stream end"); assertThrows(NoSuchElementException.class, () -> entries.next()); } } @@ -213,7 +224,7 @@ private void testSftpClientDirectoryScanner(SetupDetails setup, String pattern) actual = ds.scan(sftp, () -> new ArrayList<>(expected.size())); } - assertEquals("Mismatched result size", expected.size(), actual.size()); + assertEquals(expected.size(), actual.size(), "Mismatched result size"); Collections.sort(expected, PathUtils.BY_CASE_INSENSITIVE_FILENAME); Collections.sort(actual, DirEntry.BY_CASE_SENSITIVE_FILENAME); @@ -223,11 +234,11 @@ private void testSftpClientDirectoryScanner(SetupDetails setup, String pattern) Path lclPath = expected.get(index); ScanDirEntry remEntry = actual.get(index); String filename = remEntry.getFilename(); - assertEquals("Mismatched name", Objects.toString(lclPath.getFileName()), filename); + assertEquals(Objects.toString(lclPath.getFileName()), filename, "Mismatched name"); Path relPath = lclRoot.relativize(lclPath); String lclRelative = Objects.toString(relPath).replace(File.separatorChar, '/'); - assertEquals("Mismatched relative path", lclRelative, remEntry.getRelativePath()); + assertEquals(lclRelative, remEntry.getRelativePath(), "Mismatched relative path"); Attributes attrs = remEntry.getAttributes(); assertEquals("Mismatched directory indicator for " + filename, Files.isDirectory(lclPath), attrs.isDirectory()); diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpFileSystemTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpFileSystemTest.java index 82d9876cb..d76220e14 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpFileSystemTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpFileSystemTest.java @@ -88,19 +88,30 @@ import org.apache.sshd.util.test.CoreTestSupportUtils; import org.hamcrest.BaseMatcher; import org.hamcrest.Description; -import org.hamcrest.MatcherAssert; -import org.junit.Assume; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) @SuppressWarnings("checkstyle:MethodCount") public class SftpFileSystemTest extends AbstractSftpFilesSystemSupport { @@ -110,28 +121,28 @@ public SftpFileSystemTest() throws IOException { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { setupServer(); } @Test - public void testFileSystem() throws Exception { + void fileSystem() throws Exception { try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), defaultOptions())) { - assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Not an SftpFileSystem"); testFileSystem(fs, ((SftpFileSystem) fs).getVersion()); } } @Test - public void testFileSystemWriteAppend() throws Exception { + void fileSystemWriteAppend() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); CommonTestSupportUtils.deleteRecursive(lclSftp); try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), defaultOptions())) { - assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Not an SftpFileSystem"); Path parentPath = targetPath.getParent(); Path clientFolder = lclSftp.resolve("client"); assertHierarchyTargetFolderExists(clientFolder); @@ -150,19 +161,20 @@ public void testFileSystemWriteAppend() throws Exception { out.write(buf); } byte[] data = Files.readAllBytes(remoteFile); - assertEquals("Unexpected length", 64005, data.length); + assertEquals(64005, data.length, "Unexpected length"); assertArrayEquals("Hello".getBytes(StandardCharsets.UTF_8), Arrays.copyOf(data, 5)); for (int i = 5; i < buf.length; i++) { - assertEquals("Mismatched data at " + i, (byte) (i - 5), data[i]); - assertEquals("Mismatched data at " + (i + buf.length), (byte) (i - 5), data[i + buf.length]); + assertEquals((byte) (i - 5), data[i], "Mismatched data at " + i); + assertEquals((byte) (i - 5), data[i + buf.length], "Mismatched data at " + (i + buf.length)); } } } - @Test // See GH-325 - public void testDeleteLink() throws Exception { + // See GH-325 + @Test + void deleteLink() throws Exception { // This test creates symbolic links. - Assume.assumeFalse(OsUtils.isWin32()); + Assumptions.assumeFalse(OsUtils.isWin32()); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -170,7 +182,7 @@ public void testDeleteLink() throws Exception { List toRemove = new ArrayList<>(); try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), defaultOptions())) { - assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Not an SftpFileSystem"); Path parentPath = targetPath.getParent(); Path clientFolder = lclSftp.resolve("client"); assertHierarchyTargetFolderExists(clientFolder); @@ -198,10 +210,11 @@ public void testDeleteLink() throws Exception { } } - @Test // See GH-325 - public void testDeleteNonexistingLink() throws Exception { + // See GH-325 + @Test + void deleteNonexistingLink() throws Exception { // This test creates symbolic links. - Assume.assumeFalse(OsUtils.isWin32()); + Assumptions.assumeFalse(OsUtils.isWin32()); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -209,7 +222,7 @@ public void testDeleteNonexistingLink() throws Exception { List toRemove = new ArrayList<>(); try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), defaultOptions())) { - assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Not an SftpFileSystem"); Path parentPath = targetPath.getParent(); Path clientFolder = lclSftp.resolve("client"); assertHierarchyTargetFolderExists(clientFolder); @@ -232,10 +245,11 @@ public void testDeleteNonexistingLink() throws Exception { } } - @Test // See GH-325 - public void testDeleteDirectoryLink() throws Exception { + // See GH-325 + @Test + void deleteDirectoryLink() throws Exception { // This test creates symbolic links. - Assume.assumeFalse(OsUtils.isWin32()); + Assumptions.assumeFalse(OsUtils.isWin32()); Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -243,7 +257,7 @@ public void testDeleteDirectoryLink() throws Exception { List toRemove = new ArrayList<>(); try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), defaultOptions())) { - assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Not an SftpFileSystem"); Path parentPath = targetPath.getParent(); Path clientFolder = lclSftp.resolve("client"); assertHierarchyTargetFolderExists(clientFolder); @@ -271,15 +285,16 @@ public void testDeleteDirectoryLink() throws Exception { } } - @Test // See GH-325 - public void testDeleteNonexistingFile() throws Exception { + // See GH-325 + @Test + void deleteNonexistingFile() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); CommonTestSupportUtils.deleteRecursive(lclSftp); try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), defaultOptions())) { - assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Not an SftpFileSystem"); Path parentPath = targetPath.getParent(); Path clientFolder = lclSftp.resolve("client"); assertHierarchyTargetFolderExists(clientFolder); @@ -318,8 +333,9 @@ public FileSystem createFileSystem(SessionContext session) throws IOException { return sshd; } - @Test // see SSHD-1217 - public void testFileSystemListDirIndirect() throws Exception { + // see SSHD-1217 + @Test + void fileSystemListDirIndirect() throws Exception { // Instrument the upstream server to verify what gets called there SftpSubsystemFactory factory = (SftpSubsystemFactory) NamedResource.findByName(SftpConstants.SFTP_SUBSYSTEM_NAME, String.CASE_INSENSITIVE_ORDER, sshd.getSubsystemFactories()); @@ -347,12 +363,12 @@ public void received(ServerSession session, int type, int id) throws IOException CommonTestSupportUtils.deleteRecursive(lclSftp); FileSystem secondHop = FileSystems.newFileSystem(createDefaultFileSystemURI(), defaultOptions()); - assertTrue("Not an SftpFileSystem", secondHop instanceof SftpFileSystem); + assertTrue(secondHop instanceof SftpFileSystem, "Not an SftpFileSystem"); SshServer intermediary = createIntermediaryServer(secondHop); try (FileSystem fs = FileSystems.newFileSystem( createFileSystemURI(getCurrentTestName(), intermediary.getPort(), Collections.emptyMap()), defaultOptions())) { - assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Not an SftpFileSystem"); Path parentPath = targetPath.getParent(); Path clientFolder = lclSftp.resolve("client"); @@ -368,7 +384,7 @@ public void received(ServerSession session, int type, int id) throws IOException assertHierarchyTargetFolderExists(remoteDir); // Clear counters; verifying the remote dir calls (L)STAT statCount.set(0); - assertEquals("READ_DIR should not have been called yet", 0, readDirCount.get()); + assertEquals(0, readDirCount.get(), "READ_DIR should not have been called yet"); SftpPath sftpPath = (SftpPath) remoteDir; @@ -386,10 +402,10 @@ public void received(ServerSession session, int type, int id) throws IOException "{}: directory listing with {} files from intermediary server took {}ms, got {} entries; upstream READDIR called {} times, (L)STAT called {} times", getCurrentTestName(), numberOfFiles, System.currentTimeMillis() - start, i, readDirCount, statCount); assertEquals(numberOfFiles + 2, i); // . and .. - assertTrue("Upstream server not called", readDirCount.get() > 0); + assertTrue(readDirCount.get() > 0, "Upstream server not called"); // The current implementation stats 3 times: once to detect whether the directory exists, is a directory, // and is readable; once again for the "." entry, and the parent directory once for "..". - MatcherAssert.assertThat( + assertThat( "Files.getAttributes() should have been called at most a few times for the directory itself", statCount.get(), new BaseMatcher() { @@ -423,8 +439,8 @@ public void describeTo(Description description) { } long elapsed = System.currentTimeMillis() - start; directTime += elapsed; - assertTrue("Upstream server not called", readDirCount.get() > 0); - assertEquals("(L)STAT should not have been called on upstream server", 0, statCount.get()); + assertTrue(readDirCount.get() > 0, "Upstream server not called"); + assertEquals(0, statCount.get(), "(L)STAT should not have been called on upstream server"); LOG.info( "{}: directory listing with {} files from upstream server took {}ms, got {} entries: READDIR called {} times, (L)STAT called {} times", getCurrentTestName(), numberOfFiles, elapsed, i, readDirCount, statCount); @@ -442,7 +458,7 @@ public void describeTo(Description description) { } elapsed = System.currentTimeMillis() - start; indirectTime += elapsed; - assertTrue("Upstream server not called", readDirCount.get() > 0); + assertTrue(readDirCount.get() > 0, "Upstream server not called"); LOG.info( "{}: directory listing with {} files from intermediary server took {}ms, got {} entries: READDIR called {} times, (L)STAT called {} times", getCurrentTestName(), numberOfFiles, elapsed, i, readDirCount, statCount); @@ -459,8 +475,9 @@ public void describeTo(Description description) { } } - @Test // SSHD-1220 - public void testAttributeCache() throws Exception { + // SSHD-1220 + @Test + void attributeCache() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -470,7 +487,7 @@ public void testAttributeCache() throws Exception { MapBuilder. builder() .put(SftpModuleProperties.READ_BUFFER_SIZE.getName(), IoUtils.DEFAULT_COPY_SIZE) .put(SftpModuleProperties.WRITE_BUFFER_SIZE.getName(), IoUtils.DEFAULT_COPY_SIZE).build())) { - assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Not an SftpFileSystem"); Path parentPath = targetPath.getParent(); Path clientFolder = lclSftp.resolve("client"); assertHierarchyTargetFolderExists(clientFolder); @@ -485,43 +502,44 @@ MapBuilder. builder() try (DirectoryStream directory = Files.newDirectoryStream(remoteFile.getParent())) { for (Path p : directory) { n++; - assertTrue("Expected an SftpPath", p instanceof SftpPath); + assertTrue(p instanceof SftpPath, "Expected an SftpPath"); SftpClient.Attributes cached = ((SftpPath) p).getAttributes(); - assertNotNull("Path should have cached attributes", cached); - assertEquals("Unexpected size reported", 5, cached.getSize()); + assertNotNull(cached, "Path should have cached attributes"); + assertEquals(5, cached.getSize(), "Unexpected size reported"); // Now modify the file and fetch attributes again Files.write(p, "Bye".getBytes(StandardCharsets.UTF_8)); BasicFileAttributes attributes = Files.readAttributes(p, BasicFileAttributes.class); - assertNotEquals("Sizes should be different", attributes.size(), cached.getSize()); - assertEquals("Unexpected size after modification", 3, attributes.size()); - assertNull("Path should not have cached attributes anymore", ((SftpPath) p).getAttributes()); + assertNotEquals(attributes.size(), cached.getSize(), "Sizes should be different"); + assertEquals(3, attributes.size(), "Unexpected size after modification"); + assertNull(((SftpPath) p).getAttributes(), "Path should not have cached attributes anymore"); } } - assertEquals("Unexpected number of files", 2, n); + assertEquals(2, n, "Unexpected number of files"); // And again List obtained = new ArrayList<>(2); try (DirectoryStream directory = Files.newDirectoryStream(remoteFile.getParent())) { for (Path p : directory) { - assertTrue("Expected an SftpPath", p instanceof SftpPath); + assertTrue(p instanceof SftpPath, "Expected an SftpPath"); SftpClient.Attributes cached = ((SftpPath) p).getAttributes(); - assertNotNull("Path should have cached attributes", cached); - assertEquals("Unexpected size reported", 3, cached.getSize()); + assertNotNull(cached, "Path should have cached attributes"); + assertEquals(3, cached.getSize(), "Unexpected size reported"); obtained.add(p); } } - assertEquals("Unexpected number of files", 2, obtained.size()); + assertEquals(2, obtained.size(), "Unexpected number of files"); // Now modify the files and fetch attributes again for (Path p : obtained) { Files.write(p, "Again".getBytes(StandardCharsets.UTF_8)); BasicFileAttributes attributes = Files.readAttributes(p, BasicFileAttributes.class); // If this fails because the size is 3, we mistakenly got data from previously cached SFTP attributes - assertEquals("Unexpected file size reported via attributes", 5, attributes.size()); + assertEquals(5, attributes.size(), "Unexpected file size reported via attributes"); } } } - @Test // see SSHD-578 - public void testFileSystemURIParameters() throws Exception { + // see SSHD-578 + @Test + void fileSystemURIParameters() throws Exception { Map params = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); params.put("test-class-name", getClass().getSimpleName()); params.put("test-pkg-name", getClass().getPackage().getName()); @@ -532,7 +550,7 @@ public void testFileSystemURIParameters() throws Exception { try (SftpFileSystem fs = (SftpFileSystem) FileSystems.newFileSystem(createDefaultFileSystemURI(params), Collections. emptyMap())) { try (SftpClient sftpClient = fs.getClient()) { - assertEquals("Mismatched negotiated version", expectedVersion, sftpClient.getVersion()); + assertEquals(expectedVersion, sftpClient.getVersion(), "Mismatched negotiated version"); Session session = sftpClient.getClientSession(); params.forEach((key, expected) -> { @@ -541,14 +559,14 @@ Collections. emptyMap())) { } Object actual = session.getObject(key); - assertEquals("Mismatched value for param '" + key + "'", expected, actual); + assertEquals(expected, actual, "Mismatched value for param '" + key + "'"); }); } } } @Test - public void testAttributes() throws IOException { + void attributes() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -568,7 +586,7 @@ MapBuilder. builder() Files.write(file, (getCurrentTestName() + "\n").getBytes(StandardCharsets.UTF_8)); Map attrs = Files.readAttributes(file, "posix:*"); - assertNotNull("No attributes read for " + file, attrs); + assertNotNull(attrs, "No attributes read for " + file); Files.setAttribute(file, "basic:size", 2L); Files.setAttribute(file, "posix:permissions", PosixFilePermissions.fromString("rwxr-----")); @@ -594,7 +612,7 @@ MapBuilder. builder() } @Test - public void testRootFileSystem() throws IOException { + void rootFileSystem() throws IOException { Path targetPath = detectTargetFolder(); Path rootNative = targetPath.resolve("root").toAbsolutePath(); CommonTestSupportUtils.deleteRecursive(rootNative); @@ -606,8 +624,9 @@ public void testRootFileSystem() throws IOException { } } - @Test // see SSHD-697 - public void testFileChannel() throws IOException { + // see SSHD-697 + @Test + void fileChannel() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -626,24 +645,24 @@ public void testFileChannel() throws IOException { try (FileChannel fc = provider.newFileChannel(file, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE))) { int writeLen = fc.write(ByteBuffer.wrap(expected)); - assertEquals("Mismatched written length", expected.length, writeLen); + assertEquals(expected.length, writeLen, "Mismatched written length"); FileChannel fcPos = fc.position(0L); - assertSame("Mismatched positioned file channel", fc, fcPos); + assertSame(fc, fcPos, "Mismatched positioned file channel"); byte[] actual = new byte[expected.length]; int readLen = fc.read(ByteBuffer.wrap(actual)); - assertEquals("Mismatched read len", writeLen, readLen); - assertArrayEquals("Mismatched read data", expected, actual); + assertEquals(writeLen, readLen, "Mismatched read len"); + assertArrayEquals(expected, actual, "Mismatched read data"); } } byte[] actual = Files.readAllBytes(lclFile); - assertArrayEquals("Mismatched persisted data", expected, actual); + assertArrayEquals(expected, actual, "Mismatched persisted data"); } @Test - public void testFileCopy() throws IOException { + void fileCopy() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -664,28 +683,28 @@ public void testFileCopy() throws IOException { try (FileChannel fc = provider.newFileChannel(file, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE))) { int writeLen = fc.write(ByteBuffer.wrap(expected)); - assertEquals("Mismatched written length", expected.length, writeLen); + assertEquals(expected.length, writeLen, "Mismatched written length"); FileChannel fcPos = fc.position(0L); - assertSame("Mismatched positioned file channel", fc, fcPos); + assertSame(fc, fcPos, "Mismatched positioned file channel"); byte[] actual = new byte[expected.length]; int readLen = fc.read(ByteBuffer.wrap(actual)); - assertEquals("Mismatched read len", writeLen, readLen); - assertArrayEquals("Mismatched read data", expected, actual); + assertEquals(writeLen, readLen, "Mismatched read len"); + assertArrayEquals(expected, actual, "Mismatched read data"); } Path sibling = file.getParent().resolve(file.getFileName().toString() + '2'); Files.copy(file, sibling); } byte[] actual = Files.readAllBytes(lclFile); - assertArrayEquals("Mismatched persisted data", expected, actual); + assertArrayEquals(expected, actual, "Mismatched persisted data"); actual = Files.readAllBytes(lclFile2); - assertArrayEquals("Mismatched copied data", expected, actual); + assertArrayEquals(expected, actual, "Mismatched copied data"); } @Test - public void testFileWriteRead() throws IOException { + void fileWriteRead() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -706,40 +725,40 @@ public void testFileWriteRead() throws IOException { try (ByteArrayOutputStream out = new ByteArrayOutputStream(); InputStream in = client.read(remFilePath)) { IoUtils.copy(in, out); - assertArrayEquals("Mismatched persisted data", expected, out.toByteArray()); + assertArrayEquals(expected, out.toByteArray(), "Mismatched persisted data"); } } } byte[] actual = Files.readAllBytes(lclFile); - assertArrayEquals("Mismatched persisted data", expected, actual); + assertArrayEquals(expected, actual, "Mismatched persisted data"); } @Test - public void testFileStore() throws IOException { + void fileStore() throws IOException { try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), Collections.emptyMap())) { Iterable iter = fs.getFileStores(); - assertTrue("Not a list", iter instanceof List); + assertTrue(iter instanceof List, "Not a list"); List list = (List) iter; - assertEquals("Mismatched stores count", 1, list.size()); + assertEquals(1, list.size(), "Mismatched stores count"); FileStore store = list.get(0); - assertEquals("Mismatched type", SftpConstants.SFTP_SUBSYSTEM_NAME, store.type()); - assertFalse("Read-only ?", store.isReadOnly()); + assertEquals(SftpConstants.SFTP_SUBSYSTEM_NAME, store.type(), "Mismatched type"); + assertFalse(store.isReadOnly(), "Read-only ?"); for (String name : fs.supportedFileAttributeViews()) { - assertTrue("Unsupported view name: " + name, store.supportsFileAttributeView(name)); + assertTrue(store.supportsFileAttributeView(name), "Unsupported view name: " + name); } for (Class type : SftpFileSystemProvider.UNIVERSAL_SUPPORTED_VIEWS) { - assertTrue("Unsupported view type: " + type.getSimpleName(), store.supportsFileAttributeView(type)); + assertTrue(store.supportsFileAttributeView(type), "Unsupported view type: " + type.getSimpleName()); } } } @Test - public void testMultipleFileStoresOnSameProvider() throws IOException { + void multipleFileStoresOnSameProvider() throws IOException { SftpFileSystemProvider provider = new SftpFileSystemProvider(client); Collection fsList = new LinkedList<>(); try { @@ -751,17 +770,17 @@ public void testMultipleFileStoresOnSameProvider() throws IOException { fsList.add(expected); String id = expected.getId(); - assertTrue("Non unique file system id: " + id, idSet.add(id)); + assertTrue(idSet.add(id), "Non unique file system id: " + id); SftpFileSystem actual = provider.getFileSystem(id); - assertSame("Mismatched cached instances for " + id, expected, actual); + assertSame(expected, actual, "Mismatched cached instances for " + id); outputDebugMessage("Created file system id: %s", id); } for (SftpFileSystem fs : fsList) { String id = fs.getId(); fs.close(); - assertNull("File system not removed from cache: " + id, provider.getFileSystem(id)); + assertNull(provider.getFileSystem(id), "File system not removed from cache: " + id); } } finally { IOException err = null; @@ -780,7 +799,7 @@ public void testMultipleFileStoresOnSameProvider() throws IOException { } @Test - public void testSftpVersionSelector() throws Exception { + void sftpVersionSelector() throws Exception { AtomicInteger selected = new AtomicInteger(-1); SftpVersionSelector selector = (session, initial, current, available) -> { int value = initial @@ -795,18 +814,18 @@ public void testSftpVersionSelector() throws Exception { try (ClientSession session = createAuthenticatedClientSession(); FileSystem fs = createSftpFileSystem(session, selector)) { - assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Not an SftpFileSystem"); Collection views = fs.supportedFileAttributeViews(); - assertTrue("Universal views (" + SftpFileSystem.UNIVERSAL_SUPPORTED_VIEWS + ") not supported: " + views, - views.containsAll(SftpFileSystem.UNIVERSAL_SUPPORTED_VIEWS)); + assertTrue(views.containsAll(SftpFileSystem.UNIVERSAL_SUPPORTED_VIEWS), + "Universal views (" + SftpFileSystem.UNIVERSAL_SUPPORTED_VIEWS + ") not supported: " + views); int expectedVersion = selected.get(); - assertEquals("Mismatched negotiated version", expectedVersion, ((SftpFileSystem) fs).getVersion()); + assertEquals(expectedVersion, ((SftpFileSystem) fs).getVersion(), "Mismatched negotiated version"); testFileSystem(fs, expectedVersion); } } @Test - public void testSessionNotClosed() throws Exception { + void sessionNotClosed() throws Exception { try (ClientSession session = createAuthenticatedClientSession()) { List channels = new ArrayList<>(); session.addChannelListener(new ChannelListener() { @@ -827,14 +846,14 @@ public void channelClosed(Channel channel, Throwable reason) { } finally { fs.close(); } - assertFalse("File system should not be open", fs.isOpen()); - assertEquals("No open channels expected", "[]", channels.toString()); - assertTrue("Non-owned session should still be open", session.isOpen()); + assertFalse(fs.isOpen(), "File system should not be open"); + assertEquals("[]", channels.toString(), "No open channels expected"); + assertTrue(session.isOpen(), "Non-owned session should still be open"); } } @Test - public void testSessionClosed() throws Exception { + void sessionClosed() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -847,7 +866,7 @@ public void testSessionClosed() throws Exception { ClientSession session; FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), Collections.emptyMap()); try { - assertTrue("Should be an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Should be an SftpFileSystem"); Path remotePath = fs.getPath(CommonTestSupportUtils.resolveRelativeRemotePath(targetPath.getParent(), lclFile)); Files.write(remotePath, expected); session = ((SftpFileSystem) fs).getClientSession(); @@ -855,13 +874,13 @@ public void testSessionClosed() throws Exception { fs.close(); } byte[] actual = Files.readAllBytes(lclFile); - assertArrayEquals("Mismatched persisted data", expected, actual); - assertFalse("File system should not be open", fs.isOpen()); - assertFalse("Owned session should not be open", session.isOpen()); + assertArrayEquals(expected, actual, "Mismatched persisted data"); + assertFalse(fs.isOpen(), "File system should not be open"); + assertFalse(session.isOpen(), "Owned session should not be open"); } @Test - public void testSessionRecreate() throws Exception { + void sessionRecreate() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -874,33 +893,33 @@ public void testSessionRecreate() throws Exception { ClientSession session; FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), Collections.emptyMap()); try { - assertTrue("Should be an SftpFileSystem", fs instanceof SftpFileSystem); + assertTrue(fs instanceof SftpFileSystem, "Should be an SftpFileSystem"); Path remotePath = fs.getPath(CommonTestSupportUtils.resolveRelativeRemotePath(targetPath.getParent(), lclFile)); Files.write(remotePath, "foo".getBytes(StandardCharsets.US_ASCII)); session = ((SftpFileSystem) fs).getClientSession(); session.close(); Files.write(remotePath, expected); ClientSession session2 = ((SftpFileSystem) fs).getClientSession(); - assertNotNull("Expected a session", session2); - assertNotSame("Expected different sessions", session, session2); + assertNotNull(session2, "Expected a session"); + assertNotSame(session, session2, "Expected different sessions"); session = session2; - assertTrue("Second session should still be open", session.isOpen()); - assertTrue("Recreated session should be owned by the file system", - session.getAttribute(SftpFileSystem.OWNED_SESSION)); + assertTrue(session.isOpen(), "Second session should still be open"); + assertTrue(session.getAttribute(SftpFileSystem.OWNED_SESSION), + "Recreated session should be owned by the file system"); } finally { fs.close(); } byte[] actual = Files.readAllBytes(lclFile); - assertArrayEquals("Mismatched persisted data", expected, actual); - assertFalse("File system should not be open", fs.isOpen()); - assertFalse("Owned session should not be open", session.isOpen()); + assertArrayEquals(expected, actual, "Mismatched persisted data"); + assertFalse(fs.isOpen(), "File system should not be open"); + assertFalse(session.isOpen(), "Owned session should not be open"); } @Test - public void testFileSystemProviderServiceEntry() throws IOException { + void fileSystemProviderServiceEntry() throws IOException { Path configFile = CommonTestSupportUtils.resolve(detectSourcesFolder(), MAIN_SUBFOLDER, "filtered-resources", "META-INF", "services", FileSystemProvider.class.getName()); - assertTrue("Missing " + configFile, Files.exists(configFile)); + assertTrue(Files.exists(configFile), "Missing " + configFile); boolean found = false; try (InputStream stream = Files.newInputStream(configFile); @@ -913,12 +932,12 @@ public void testFileSystemProviderServiceEntry() throws IOException { continue; } - assertFalse("Multiple configurations: " + line, found); - assertEquals("Mismatched configuration", SftpFileSystemProvider.class.getName(), line); + assertFalse(found, "Multiple configurations: " + line); + assertEquals(SftpFileSystemProvider.class.getName(), line, "Mismatched configuration"); found = true; } } - assertTrue("No configuration found", found); + assertTrue(found, "No configuration found"); } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpFileSystemURITest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpFileSystemURITest.java index b45cbb1bb..99629d631 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpFileSystemURITest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/fs/SftpFileSystemURITest.java @@ -31,35 +31,31 @@ import org.apache.sshd.common.auth.BasicCredentialsProvider; import org.apache.sshd.common.util.net.SshdSocketAddress; import org.apache.sshd.sftp.common.SftpConstants; -import org.apache.sshd.util.test.JUnit4ClassRunnerWithParametersFactory; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runner.RunWith; -import org.junit.runners.MethodSorters; -import org.junit.runners.Parameterized; -import org.junit.runners.Parameterized.Parameters; -import org.junit.runners.Parameterized.UseParametersRunnerFactory; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@RunWith(Parameterized.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests -@UseParametersRunnerFactory(JUnit4ClassRunnerWithParametersFactory.class) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) // see https://github.com/junit-team/junit/wiki/Parameterized-tests +@Tag("NoIoTestCase") public class SftpFileSystemURITest extends JUnitTestSupport { - private final String host; - private final int port; - private final String username; - private final String password; - private final Map params; + private String host; + private int port; + private String username; + private String password; + private Map params; - public SftpFileSystemURITest(String host, int port, String username, String password, Map params) { + public void initSftpFileSystemURITest(String host, int port, String username, String password, Map params) { this.host = host; this.port = port; this.username = username; @@ -67,7 +63,6 @@ public SftpFileSystemURITest(String host, int port, String username, String pass this.params = params; } - @Parameters(name = "host={0}, port={1}, user={2}, password={3}, params={4}") public static List parameters() { return new ArrayList() { // Not serializing it @@ -96,29 +91,33 @@ public static List parameters() { }; } - @Test - public void testFullURIEncoding() { + @MethodSource("parameters") + @ParameterizedTest(name = "host={0}, port={1}, user={2}, password={3}, params={4}") + public void fullURIEncoding(String host, int port, String username, String password, Map params) { + initSftpFileSystemURITest(host, port, username, password, params); URI uri = SftpFileSystemProvider.createFileSystemURI(host, port, username, password, params); - assertEquals("Mismatched scheme", SftpConstants.SFTP_SUBSYSTEM_NAME, uri.getScheme()); - assertEquals("Mismatched host", host, uri.getHost()); - assertEquals("Mismatched port", port, uri.getPort()); + assertEquals(SftpConstants.SFTP_SUBSYSTEM_NAME, uri.getScheme(), "Mismatched scheme"); + assertEquals(host, uri.getHost(), "Mismatched host"); + assertEquals(port, uri.getPort(), "Mismatched port"); BasicCredentialsProvider credentials = SftpFileSystemProvider.parseCredentials(uri); - assertNotNull("No credentials provided", credentials); - assertEquals("Mismatched user", username, credentials.getUsername()); - assertEquals("Mismatched password", password, credentials.getPassword()); + assertNotNull(credentials, "No credentials provided"); + assertEquals(username, credentials.getUsername(), "Mismatched user"); + assertEquals(password, credentials.getPassword(), "Mismatched password"); Map uriParams = SftpFileSystemProvider.parseURIParameters(uri); assertMapEquals(getCurrentTestName(), params, uriParams, (v1, v2) -> Objects.equals(v1.toString(), v2.toString())); } - @Test - public void testEncodeDecodeCredentials() { + @MethodSource("parameters") + @ParameterizedTest(name = "host={0}, port={1}, user={2}, password={3}, params={4}") + public void encodeDecodeCredentials(String host, int port, String username, String password, Map params) { + initSftpFileSystemURITest(host, port, username, password, params); String userInfo = SftpFileSystemProvider.encodeCredentials(username, password); BasicCredentialsProvider credentials = SftpFileSystemProvider.parseCredentials(userInfo); - assertNotNull("No credentials provided", credentials); - assertEquals("Mismatched user", username, credentials.getUsername()); - assertEquals("Mismatched password", password, credentials.getPassword()); + assertNotNull(credentials, "No credentials provided"); + assertEquals(username, credentials.getUsername(), "Mismatched user"); + assertEquals(password, credentials.getPassword(), "Mismatched password"); } @Override diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/impl/SftpRemotePathChannelTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/impl/SftpRemotePathChannelTest.java index 44e5e5913..3049ec648 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/impl/SftpRemotePathChannelTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/impl/SftpRemotePathChannelTest.java @@ -29,6 +29,7 @@ import java.nio.file.StandardOpenOption; import java.util.Date; import java.util.EnumSet; +import java.util.concurrent.TimeUnit; import org.apache.sshd.common.Factory; import org.apache.sshd.common.io.IoSession; @@ -44,31 +45,37 @@ import org.apache.sshd.sftp.client.SftpClient.OpenMode; import org.apache.sshd.sftp.common.SftpConstants; import org.apache.sshd.util.test.CommonTestSupportUtils; -import org.junit.Before; -import org.junit.FixMethodOrder; -import org.junit.Ignore; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; +import org.junit.jupiter.api.Timeout; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.junit.jupiter.api.Assertions.assertArrayEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) @SuppressWarnings("checkstyle:MethodCount") public class SftpRemotePathChannelTest extends AbstractSftpClientTestSupport { public SftpRemotePathChannelTest() throws IOException { super(); } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { setupServer(); } - @Test // see SSHD-697 - public void testFileChannel() throws IOException { + // see SSHD-697 + @Test + void fileChannel() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -85,23 +92,24 @@ public void testFileChannel() throws IOException { remFilePath, EnumSet.of( StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE))) { int writeLen = fc.write(ByteBuffer.wrap(expected)); - assertEquals("Mismatched written length", expected.length, writeLen); + assertEquals(expected.length, writeLen, "Mismatched written length"); FileChannel fcPos = fc.position(0L); - assertSame("Mismatched positioned file channel", fc, fcPos); + assertSame(fc, fcPos, "Mismatched positioned file channel"); byte[] actual = new byte[expected.length]; int readLen = fc.read(ByteBuffer.wrap(actual)); - assertEquals("Mismatched read len", writeLen, readLen); - assertArrayEquals("Mismatched read data", expected, actual); + assertEquals(writeLen, readLen, "Mismatched read len"); + assertArrayEquals(expected, actual, "Mismatched read data"); } byte[] actual = Files.readAllBytes(lclFile); - assertArrayEquals("Mismatched persisted data", expected, actual); + assertArrayEquals(expected, actual, "Mismatched persisted data"); } - @Test // see SSHD-967 - public void testTransferToFileChannel() throws IOException { + // see SSHD-967 + @Test + void transferToFileChannel() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -129,16 +137,17 @@ public void testTransferToFileChannel() throws IOException { FileChannel dstChannel = FileChannel.open(dstFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { long numXfered = srcChannel.transferTo(0L, expected.length, dstChannel); - assertEquals("Mismatched reported transfer count", expected.length, numXfered); + assertEquals(expected.length, numXfered, "Mismatched reported transfer count"); } byte[] actual = Files.readAllBytes(dstFile); - assertEquals("Mismatched transferred size", expected.length, actual.length); - assertArrayEquals("Mismatched transferred data", expected, actual); + assertEquals(expected.length, actual.length, "Mismatched transferred size"); + assertArrayEquals(expected, actual, "Mismatched transferred data"); } - @Test // see SSHD-1182 - public void testTransferToFileChannelWithOffset() throws IOException { + // see SSHD-1182 + @Test + void transferToFileChannelWithOffset() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -170,16 +179,18 @@ public void testTransferToFileChannelWithOffset() throws IOException { FileChannel dstChannel = FileChannel.open(dstFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) { long numXfered = srcChannel.transferTo(offset, expected.length, dstChannel); - assertEquals("Mismatched reported transfer count", expected.length, numXfered); + assertEquals(expected.length, numXfered, "Mismatched reported transfer count"); } byte[] actual = Files.readAllBytes(dstFile); - assertEquals("Mismatched transferred size", expected.length, actual.length); - assertArrayEquals("Mismatched transferred data", expected, actual); + assertEquals(expected.length, actual.length, "Mismatched transferred size"); + assertArrayEquals(expected, actual, "Mismatched transferred data"); } - @Test(timeout = 10000) // see SSHD-970 - public void testTransferToFileChannelLoopFile() throws IOException { + // see SSHD-970 + @Test + @Timeout(value = 10000, unit = TimeUnit.MILLISECONDS) + void transferToFileChannelLoopFile() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -205,16 +216,17 @@ public void testTransferToFileChannelLoopFile() throws IOException { // SftpRemotePathChannel.DEFAULT_TRANSFER_BUFFER_SIZE > expected.length => Infinite loop long numXfered = srcChannel.transferTo(0L, SftpModuleProperties.COPY_BUF_SIZE.getRequiredDefault(), dstChannel); - assertEquals("Mismatched reported transfer count", expected.length, numXfered); + assertEquals(expected.length, numXfered, "Mismatched reported transfer count"); } byte[] actual = Files.readAllBytes(dstFile); - assertEquals("Mismatched transferred size", expected.length, actual.length); - assertArrayEquals("Mismatched transferred data", expected, actual); + assertEquals(expected.length, actual.length, "Mismatched transferred size"); + assertArrayEquals(expected, actual, "Mismatched transferred data"); } - @Test // see SSHD-967 - public void testTransferFromFileChannel() throws IOException { + // see SSHD-967 + @Test + void transferFromFileChannel() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -241,16 +253,16 @@ public void testTransferFromFileChannel() throws IOException { remFilePath, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE)); FileChannel srcChannel = FileChannel.open(srcFile, StandardOpenOption.READ)) { long numXfered = dstChannel.transferFrom(srcChannel, 0L, expected.length); - assertEquals("Mismatched reported transfer count", expected.length, numXfered); + assertEquals(expected.length, numXfered, "Mismatched reported transfer count"); } byte[] actual = Files.readAllBytes(dstFile); - assertEquals("Mismatched transferred size", expected.length, actual.length); - assertArrayEquals("Mismatched transferred data", expected, actual); + assertEquals(expected.length, actual.length, "Mismatched transferred size"); + assertArrayEquals(expected, actual, "Mismatched transferred data"); } @Test - public void testTransferFromFileChannelWithOffset() throws IOException { + void transferFromFileChannelWithOffset() throws IOException { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve( targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName()); @@ -281,12 +293,12 @@ public void testTransferFromFileChannelWithOffset() throws IOException { remFilePath, EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE)); FileChannel srcChannel = FileChannel.open(srcFile, StandardOpenOption.READ)) { long numXfered = dstChannel.transferFrom(srcChannel, offset, expected.length - offset); - assertEquals("Mismatched reported transfer count", expected.length - offset, numXfered); + assertEquals(expected.length - offset, numXfered, "Mismatched reported transfer count"); } byte[] actual = Files.readAllBytes(dstFile); - assertEquals("Mismatched transferred size", expected.length, actual.length); - assertArrayEquals("Mismatched transferred data", expected, actual); + assertEquals(expected.length, actual.length, "Mismatched transferred size"); + assertArrayEquals(expected, actual, "Mismatched transferred data"); } /* @@ -296,9 +308,10 @@ public void testTransferFromFileChannelWithOffset() throws IOException { * To test, the available heap memory of the server must be below the value set in requested_data_volume * limit the available heap memory of the junit execution by passing "-Xmx256m" to the VM. */ - @Test(timeout = 5L * 60L * 1000L) // see SSHD-1125 - @Ignore("Used only for debugging SSHD-1125") - public void testReadRequestsOutOfMemory() throws Exception { + @Test + @Timeout(value = 5L * 60L * 1000L, unit = TimeUnit.MILLISECONDS) // see SSHD-1125 + @Disabled("Used only for debugging SSHD-1125") + void readRequestsOutOfMemory() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve( diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/impl/SftpStatusTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/impl/SftpStatusTest.java index 53c3893d9..6ebdc75e8 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/impl/SftpStatusTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/client/impl/SftpStatusTest.java @@ -21,19 +21,18 @@ import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; import org.apache.sshd.sftp.common.SftpConstants; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Tests for {@link SftpStatus}. */ -@Category(NoIoTestCase.class) +@Tag("NoIoTestCase") public class SftpStatusTest { public SftpStatusTest() { @@ -41,50 +40,50 @@ public SftpStatusTest() { } @Test - public void testOkStatus() { + void okStatus() { Buffer buffer = new ByteArrayBuffer(); buffer.putInt(SftpConstants.SSH_FX_OK); buffer.putString("An error message"); buffer.putString("en"); SftpStatus status = SftpStatus.parse(buffer); - assertEquals("Unexpected status code", SftpConstants.SSH_FX_OK, status.getStatusCode()); - assertEquals("Unexpected error message", "An error message", status.getMessage()); - assertEquals("Unexpected language tag", "en", status.getLanguage()); - assertTrue("Status should be OK", status.isOk()); + assertEquals(SftpConstants.SSH_FX_OK, status.getStatusCode(), "Unexpected status code"); + assertEquals("An error message", status.getMessage(), "Unexpected error message"); + assertEquals("en", status.getLanguage(), "Unexpected language tag"); + assertTrue(status.isOk(), "Status should be OK"); } @Test - public void testOkStatusNoMessage() { + void okStatusNoMessage() { Buffer buffer = new ByteArrayBuffer(); buffer.putInt(SftpConstants.SSH_FX_OK); SftpStatus status = SftpStatus.parse(buffer); - assertEquals("Unexpected status code", SftpConstants.SSH_FX_OK, status.getStatusCode()); - assertNull("Unexpected error message", status.getMessage()); - assertNull("Unexpected language tag", status.getLanguage()); - assertTrue("Status should be OK", status.isOk()); + assertEquals(SftpConstants.SSH_FX_OK, status.getStatusCode(), "Unexpected status code"); + assertNull(status.getMessage(), "Unexpected error message"); + assertNull(status.getLanguage(), "Unexpected language tag"); + assertTrue(status.isOk(), "Status should be OK"); } @Test - public void testNokStatus() { + void nokStatus() { Buffer buffer = new ByteArrayBuffer(); buffer.putInt(SftpConstants.SSH_FX_EOF); buffer.putString("An error message"); buffer.putString("en"); SftpStatus status = SftpStatus.parse(buffer); - assertEquals("Unexpected status code", SftpConstants.SSH_FX_EOF, status.getStatusCode()); - assertEquals("Unexpected error message", "An error message", status.getMessage()); - assertEquals("Unexpected language tag", "en", status.getLanguage()); - assertFalse("Status should be OK", status.isOk()); + assertEquals(SftpConstants.SSH_FX_EOF, status.getStatusCode(), "Unexpected status code"); + assertEquals("An error message", status.getMessage(), "Unexpected error message"); + assertEquals("en", status.getLanguage(), "Unexpected language tag"); + assertFalse(status.isOk(), "Status should be OK"); } @Test - public void testNokStatusNoMessage() { + void nokStatusNoMessage() { Buffer buffer = new ByteArrayBuffer(); buffer.putInt(SftpConstants.SSH_FX_FAILURE); SftpStatus status = SftpStatus.parse(buffer); - assertEquals("Unexpected status code", SftpConstants.SSH_FX_FAILURE, status.getStatusCode()); - assertNull("Unexpected error message", status.getMessage()); - assertNull("Unexpected language tag", status.getLanguage()); - assertFalse("Status should be OK", status.isOk()); + assertEquals(SftpConstants.SSH_FX_FAILURE, status.getStatusCode(), "Unexpected status code"); + assertNull(status.getMessage(), "Unexpected error message"); + assertNull(status.getLanguage(), "Unexpected language tag"); + assertFalse(status.isOk(), "Status should be OK"); } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpConstantsTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpConstantsTest.java index da16fc0ee..94c55f8cb 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpConstantsTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpConstantsTest.java @@ -21,55 +21,57 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SftpConstantsTest extends JUnitTestSupport { public SftpConstantsTest() { super(); } @Test - public void testRenameModesNotMarkedAsOpcodes() { + void renameModesNotMarkedAsOpcodes() { for (int cmd : new int[] { SftpConstants.SSH_FXP_RENAME_OVERWRITE, SftpConstants.SSH_FXP_RENAME_ATOMIC, SftpConstants.SSH_FXP_RENAME_NATIVE }) { String name = SftpConstants.getCommandMessageName(cmd); - assertFalse("Mismatched name for " + cmd + ": " + name, name.startsWith("SSH_FXP_RENAME_")); + assertFalse(name.startsWith("SSH_FXP_RENAME_"), "Mismatched name for " + cmd + ": " + name); } } @Test - public void testRealPathModesNotMarkedAsOpcodes() { + void realPathModesNotMarkedAsOpcodes() { for (int cmd = SftpConstants.SSH_FXP_REALPATH_NO_CHECK; cmd <= SftpConstants.SSH_FXP_REALPATH_STAT_IF; cmd++) { String name = SftpConstants.getCommandMessageName(cmd); - assertFalse("Mismatched name for " + cmd + ": " + name, name.startsWith("SSH_FXP_REALPATH_")); + assertFalse(name.startsWith("SSH_FXP_REALPATH_"), "Mismatched name for " + cmd + ": " + name); } } @Test - public void testSubstatusNameResolution() { + void substatusNameResolution() { for (int status = SftpConstants.SSH_FX_OK; status <= SftpConstants.SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK; status++) { String name = SftpConstants.getStatusName(status); - assertTrue("Failed to convert status=" + status + ": " + name, name.startsWith("SSH_FX_")); + assertTrue(name.startsWith("SSH_FX_"), "Failed to convert status=" + status + ": " + name); } } @Test - public void testSubstatusMessageResolution() { + void substatusMessageResolution() { for (int status = SftpConstants.SSH_FX_OK; status <= SftpConstants.SSH_FX_NO_MATCHING_BYTE_RANGE_LOCK; status++) { String message = SftpHelper.resolveStatusMessage(status); - assertTrue("Missing message for status=" + status, GenericUtils.isNotEmpty(message)); + assertTrue(GenericUtils.isNotEmpty(message), "Missing message for status=" + status); } } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpHelperTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpHelperTest.java index 40ba9dc92..7359082a1 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpHelperTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpHelperTest.java @@ -21,17 +21,18 @@ import org.apache.sshd.sftp.client.SftpClient.Attributes; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SftpHelperTest extends JUnitTestSupport { public SftpHelperTest() { @@ -39,12 +40,12 @@ public SftpHelperTest() { } @Test - public void testPermissionsToFile() { + void permissionsToFile() { assertEquals(SftpConstants.SSH_FILEXFER_TYPE_SOCKET, SftpHelper.permissionsToFileType(SftpConstants.S_IFSOCK)); } @Test - public void testCompleteAttributesNoLongName() { + void completeAttributesNoLongName() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1B6); @@ -54,7 +55,7 @@ public void testCompleteAttributesNoLongName() { } @Test - public void testCompleteAttributesLongName() { + void completeAttributesLongName() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1B6); @@ -64,7 +65,7 @@ public void testCompleteAttributesLongName() { } @Test - public void testCompleteAttributesLongNameDir() { + void completeAttributesLongNameDir() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1FF); @@ -74,7 +75,7 @@ public void testCompleteAttributesLongNameDir() { } @Test - public void testCompleteAttributesLongNameT() { + void completeAttributesLongNameT() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1FD); @@ -84,7 +85,7 @@ public void testCompleteAttributesLongNameT() { } @Test - public void testCompleteAttributesLongNameS() { + void completeAttributesLongNameS() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1BD); @@ -94,7 +95,7 @@ public void testCompleteAttributesLongNameS() { } @Test - public void testCompleteAttributesLongNameLink() { + void completeAttributesLongNameLink() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1FF); @@ -104,7 +105,7 @@ public void testCompleteAttributesLongNameLink() { } @Test - public void testCompleteAttributesSolarWindsLongName() { + void completeAttributesSolarWindsLongName() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1B6); @@ -114,7 +115,7 @@ public void testCompleteAttributesSolarWindsLongName() { } @Test - public void testCompleteAttributesWinLongName() { + void completeAttributesWinLongName() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1B6); @@ -124,7 +125,7 @@ public void testCompleteAttributesWinLongName() { } @Test - public void testCompleteAttributesOsxLongName() { + void completeAttributesOsxLongName() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1B6); @@ -134,7 +135,7 @@ public void testCompleteAttributesOsxLongName() { } @Test - public void testCompleteAttributesUnknownLongName() { + void completeAttributesUnknownLongName() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1B6); @@ -144,7 +145,7 @@ public void testCompleteAttributesUnknownLongName() { } @Test - public void testCompleteAttributesBrokenLongName() { + void completeAttributesBrokenLongName() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1B6); @@ -154,7 +155,7 @@ public void testCompleteAttributesBrokenLongName() { } @Test - public void testCompleteAttributesBrokenLongName2() { + void completeAttributesBrokenLongName2() { Attributes attrs = new Attributes(); attrs.setType(SftpConstants.SSH_FILEXFER_TYPE_UNKNOWN); attrs.setPermissions(0x1B6); diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpUniversalOwnerAndGroupTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpUniversalOwnerAndGroupTest.java index 83458c827..7d149d027 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpUniversalOwnerAndGroupTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/common/SftpUniversalOwnerAndGroupTest.java @@ -21,28 +21,33 @@ import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.fail; /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SftpUniversalOwnerAndGroupTest extends JUnitTestSupport { public SftpUniversalOwnerAndGroupTest() { super(); } @Test - public void testNameFormat() { + void nameFormat() { for (SftpUniversalOwnerAndGroup value : SftpUniversalOwnerAndGroup.VALUES) { String name = value.getName(); - assertFalse(value.name() + ": empty name", GenericUtils.isEmpty(name)); - assertEquals(value.name() + ": bad suffix", '@', name.charAt(name.length() - 1)); + assertFalse(GenericUtils.isEmpty(name), value.name() + ": empty name"); + assertEquals('@', name.charAt(name.length() - 1), value.name() + ": bad suffix"); for (int index = 0; index < name.length() - 1; index++) { char ch = name.charAt(index); @@ -54,15 +59,15 @@ public void testNameFormat() { } @Test - public void testFromName() { + void fromName() { for (String name : new String[] { null, "", getCurrentTestName() }) { - assertNull("Unexpected value for '" + name + "'", SftpUniversalOwnerAndGroup.fromName(name)); + assertNull(SftpUniversalOwnerAndGroup.fromName(name), "Unexpected value for '" + name + "'"); } for (SftpUniversalOwnerAndGroup expected : SftpUniversalOwnerAndGroup.VALUES) { String name = expected.getName(); for (int index = 0; index < name.length(); index++) { - assertSame(name, expected, SftpUniversalOwnerAndGroup.fromName(name)); + assertSame(expected, SftpUniversalOwnerAndGroup.fromName(name), name); name = shuffleCase(name); } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/HandleTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/HandleTest.java index 0e84cf221..93ba10739 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/HandleTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/HandleTest.java @@ -23,13 +23,12 @@ import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.BufferUtils; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.Test; -import org.junit.experimental.categories.Category; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; -import static org.junit.Assert.assertEquals; +import static org.junit.jupiter.api.Assertions.assertEquals; -@Category({ NoIoTestCase.class }) +@Tag("NoIoTestCase") public class HandleTest { public HandleTest() { @@ -44,15 +43,15 @@ private void roundtrip(long x) { Buffer buffer = new ByteArrayBuffer(); buffer.putString(s, StandardCharsets.ISO_8859_1); String t = buffer.getString(StandardCharsets.ISO_8859_1); - assertEquals("Hash for " + x + " different", h, t.hashCode()); - assertEquals("String for " + x + " different", s, t); + assertEquals(h, t.hashCode(), "Hash for " + x + " different"); + assertEquals(s, t, "String for " + x + " different"); byte[] b = t.getBytes(StandardCharsets.ISO_8859_1); long j = BufferUtils.getUInt(b); - assertEquals("Values different", x, j); + assertEquals(x, j, "Values different"); } @Test - public void testIntegerStringRoundtrip() { + void integerStringRoundtrip() { final int limit = 100_000; for (long i = 0; i <= limit; i++) { roundtrip(i); diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/SftpServerTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/SftpServerTest.java index 9efcc432e..c036c8105 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/SftpServerTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/SftpServerTest.java @@ -45,9 +45,13 @@ import org.apache.sshd.util.test.BaseTestSupport; import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.CoreTestSupportUtils; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Multi-thread tests for {@link SftpFileSystem}. @@ -68,8 +72,8 @@ public SftpServerTest() { super(); } - @Before - public void setup() throws Exception { + @BeforeEach + void setup() throws Exception { server = CoreTestSupportUtils.setupTestFullSupportServer(SftpServerTest.class); serverHasNoSftpSubsystem = new CountDownLatch(1); SftpSubsystemFactory factory = new SftpSubsystemFactory(); @@ -96,8 +100,8 @@ public void destroying(ServerSession session) throws IOException { client.start(); } - @After - public void shutdown() throws Exception { + @AfterEach + void shutdown() throws Exception { if (client != null) { client.stop(); } @@ -120,12 +124,12 @@ private String download(Path remote) throws Exception { }); worker.start(); worker.join(TimeUnit.SECONDS.toMillis(3)); - assertFalse("Thread should have terminated", worker.isAlive()); + assertFalse(worker.isAlive(), "Thread should have terminated"); return actual.get(); } @Test - public void testSequentialThreads() throws Exception { + void sequentialThreads() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), @@ -138,27 +142,27 @@ public void testSequentialThreads() throws Exception { try (ClientSession session = createAuthenticatedClientSession(client, server.getPort())) { try (SftpFileSystem fs = SftpClientFactory.instance().createSftpFileSystem(session)) { Path remote = fs.getPath(fileName); - assertTrue("Should be an SftpPath", remote instanceof SftpPath); + assertTrue(remote instanceof SftpPath, "Should be an SftpPath"); String actual = download(remote); - assertEquals("Mismatched content", expected, actual); + assertEquals(expected, actual, "Mismatched content"); // And again actual = download(remote); - assertEquals("Mismatched content", expected, actual); + assertEquals(expected, actual, "Mismatched content"); // And again actual = download(remote); - assertEquals("Mismatched content", expected, actual); + assertEquals(expected, actual, "Mismatched content"); // Yes, we had three threads, but no concurrency at all. There should be only a single server-side // SftpSubsystem. - assertEquals("Unexpected number of SftpSubsystems", 1, numberOfSubsystems.get()); + assertEquals(1, numberOfSubsystems.get(), "Unexpected number of SftpSubsystems"); } - assertTrue("Session should still be open", session.isOpen()); - assertTrue("Server did not close SftpSubsystem", serverHasNoSftpSubsystem.await(3, TimeUnit.SECONDS)); - assertEquals("SftpSubsystem count should be zero", 0, numberOfSubsystems.get()); + assertTrue(session.isOpen(), "Session should still be open"); + assertTrue(serverHasNoSftpSubsystem.await(3, TimeUnit.SECONDS), "Server did not close SftpSubsystem"); + assertEquals(0, numberOfSubsystems.get(), "SftpSubsystem count should be zero"); } } @Test - public void testConcurrentThreads() throws Exception { + void concurrentThreads() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), @@ -171,7 +175,7 @@ public void testConcurrentThreads() throws Exception { try (ClientSession session = createAuthenticatedClientSession(client, server.getPort())) { try (SftpFileSystem fs = SftpClientFactory.instance().createSftpFileSystem(session)) { Path remote = fs.getPath(fileName); - assertTrue("Should be an SftpPath", remote instanceof SftpPath); + assertTrue(remote instanceof SftpPath, "Should be an SftpPath"); AtomicReference actual1 = new AtomicReference<>(); CountDownLatch secondThreadIsReady = new CountDownLatch(1); Thread worker1 = new Thread(() -> { @@ -221,20 +225,20 @@ public void testConcurrentThreads() throws Exception { worker2.start(); worker1.join(TimeUnit.SECONDS.toMillis(3)); worker2.join(TimeUnit.SECONDS.toMillis(3)); - assertFalse("Worker 1 should have finished", worker1.isAlive()); - assertFalse("Worker 2 should have finished", worker2.isAlive()); - assertEquals("Mismatched content", expected, actual1.get()); - assertEquals("Mismatched content", expected, actual2.get()); - assertEquals("Unexpected number of SftpSubsystems", 2, numberOfChannels.get()); + assertFalse(worker1.isAlive(), "Worker 1 should have finished"); + assertFalse(worker2.isAlive(), "Worker 2 should have finished"); + assertEquals(expected, actual1.get(), "Mismatched content"); + assertEquals(expected, actual2.get(), "Mismatched content"); + assertEquals(2, numberOfChannels.get(), "Unexpected number of SftpSubsystems"); } - assertTrue("Session should still be open", session.isOpen()); - assertTrue("Server did not close SftpSubsystem", serverHasNoSftpSubsystem.await(3, TimeUnit.SECONDS)); - assertEquals("SftpSubsystem count", 0, numberOfSubsystems.get()); + assertTrue(session.isOpen(), "Session should still be open"); + assertTrue(serverHasNoSftpSubsystem.await(3, TimeUnit.SECONDS), "Server did not close SftpSubsystem"); + assertEquals(0, numberOfSubsystems.get(), "SftpSubsystem count"); } } @Test - public void testHandOffStream() throws Exception { + void handOffStream() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), @@ -247,7 +251,7 @@ public void testHandOffStream() throws Exception { try (ClientSession session = createAuthenticatedClientSession(client, server.getPort())) { try (SftpFileSystem fs = SftpClientFactory.instance().createSftpFileSystem(session)) { Path remote = fs.getPath(fileName); - assertTrue("Should be an SftpPath", remote instanceof SftpPath); + assertTrue(remote instanceof SftpPath, "Should be an SftpPath"); InputStream is = Files.newInputStream(remote); AtomicReference actual = new AtomicReference<>(); Thread worker = new Thread(() -> { @@ -262,14 +266,14 @@ public void testHandOffStream() throws Exception { }); worker.start(); worker.join(TimeUnit.SECONDS.toMillis(3)); - assertFalse("Worker should have terminated", worker.isAlive()); - assertEquals("Mismatched content", expected, actual.get()); + assertFalse(worker.isAlive(), "Worker should have terminated"); + assertEquals(expected, actual.get(), "Mismatched content"); } } } @Test - public void testDirectoryStream() throws Exception { + void directoryStream() throws Exception { Path targetPath = detectTargetFolder(); Path parentPath = targetPath.getParent(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), @@ -283,7 +287,7 @@ public void testDirectoryStream() throws Exception { try (ClientSession session = createAuthenticatedClientSession(client, server.getPort())) { try (SftpFileSystem fs = SftpClientFactory.instance().createSftpFileSystem(session)) { Path remote = fs.getPath(dirName); - assertTrue("Should be an SftpPath", remote instanceof SftpPath); + assertTrue(remote instanceof SftpPath, "Should be an SftpPath"); int numberOfFiles = 0; try (DirectoryStream dir = Files.newDirectoryStream(remote)) { // Pretend we did something with the directory listing. @@ -293,7 +297,7 @@ public void testDirectoryStream() throws Exception { } } } - assertEquals("Unexpected number of files", 1, numberOfFiles); // We don't get . and .. + assertEquals(1, numberOfFiles, "Unexpected number of files"); // We don't get . and .. } } } diff --git a/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/SftpSubsystemFactoryTest.java b/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/SftpSubsystemFactoryTest.java index 2a4550e3e..0ce9d4398 100644 --- a/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/SftpSubsystemFactoryTest.java +++ b/sshd-sftp/src/test/java/org/apache/sshd/sftp/server/SftpSubsystemFactoryTest.java @@ -21,18 +21,21 @@ import org.apache.sshd.common.util.threads.CloseableExecutorService; import org.apache.sshd.util.test.JUnitTestSupport; -import org.apache.sshd.util.test.NoIoTestCase; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.experimental.categories.Category; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.mockito.Mockito; +import static org.junit.jupiter.api.Assertions.assertNotSame; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; + /** * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) -@Category({ NoIoTestCase.class }) +@TestMethodOrder(MethodName.class) +@Tag("NoIoTestCase") public class SftpSubsystemFactoryTest extends JUnitTestSupport { public SftpSubsystemFactoryTest() { super(); @@ -42,27 +45,28 @@ public SftpSubsystemFactoryTest() { * Make sure that the builder returns a factory with the default values if no {@code withXXX} method is invoked */ @Test - public void testBuilderDefaultFactoryValues() { + void builderDefaultFactoryValues() { SftpSubsystemFactory factory = new SftpSubsystemFactory.Builder().build(); - assertNull("Mismatched executor", factory.resolveExecutorService()); - assertSame("Mismatched unsupported attribute policy", SftpSubsystemFactory.DEFAULT_POLICY, - factory.getUnsupportedAttributePolicy()); + assertNull(factory.resolveExecutorService(), "Mismatched executor"); + assertSame(SftpSubsystemFactory.DEFAULT_POLICY, + factory.getUnsupportedAttributePolicy(), + "Mismatched unsupported attribute policy"); } /** * Make sure that the builder initializes correctly the built factory */ @Test - public void testBuilderCorrectlyInitializesFactory() { + void builderCorrectlyInitializesFactory() { SftpSubsystemFactory.Builder builder = new SftpSubsystemFactory.Builder(); CloseableExecutorService service = dummyExecutor(); SftpSubsystemFactory factory = builder.withExecutorServiceProvider(() -> service) .build(); - assertSame("Mismatched executor", service, factory.resolveExecutorService()); + assertSame(service, factory.resolveExecutorService(), "Mismatched executor"); for (UnsupportedAttributePolicy policy : UnsupportedAttributePolicy.VALUES) { SftpSubsystemFactory actual = builder.withUnsupportedAttributePolicy(policy).build(); - assertSame("Mismatched unsupported attribute policy", policy, actual.getUnsupportedAttributePolicy()); + assertSame(policy, actual.getUnsupportedAttributePolicy(), "Mismatched unsupported attribute policy"); } } @@ -75,17 +79,17 @@ public void testBuilderCorrectlyInitializesFactory() { * {@link SftpSubsystemFactory.Builder#build()} method service1).build(); SftpSubsystemFactory f2 = builder.build(); - assertNotSame("No new instance built", f1, f2); - assertSame("Mismatched executors", f1.resolveExecutorService(), f2.resolveExecutorService()); + assertNotSame(f1, f2, "No new instance built"); + assertSame(f1.resolveExecutorService(), f2.resolveExecutorService(), "Mismatched executors"); CloseableExecutorService service2 = dummyExecutor(); SftpSubsystemFactory f3 = builder.withExecutorServiceProvider(() -> service2).build(); - assertNotSame("Executor service not changed", f1.resolveExecutorService(), f3.resolveExecutorService()); + assertNotSame(f1.resolveExecutorService(), f3.resolveExecutorService(), "Executor service not changed"); } private static CloseableExecutorService dummyExecutor() { diff --git a/sshd-spring-sftp/pom.xml b/sshd-spring-sftp/pom.xml index 02726c09a..29c173d4a 100644 --- a/sshd-spring-sftp/pom.xml +++ b/sshd-spring-sftp/pom.xml @@ -68,7 +68,7 @@ spring-integration-file - + org.springframework.integration spring-integration-sftp @@ -86,6 +86,11 @@ test-jar test + + org.junit.jupiter + junit-jupiter + test + org.apache.sshd sshd-common diff --git a/sshd-spring-sftp/src/test/java/org/apache/sshd/sftp/spring/integration/ApacheSshdSftpSessionFactoryTest.java b/sshd-spring-sftp/src/test/java/org/apache/sshd/sftp/spring/integration/ApacheSshdSftpSessionFactoryTest.java index 35127bf9b..df7c02340 100644 --- a/sshd-spring-sftp/src/test/java/org/apache/sshd/sftp/spring/integration/ApacheSshdSftpSessionFactoryTest.java +++ b/sshd-spring-sftp/src/test/java/org/apache/sshd/sftp/spring/integration/ApacheSshdSftpSessionFactoryTest.java @@ -53,22 +53,27 @@ import org.apache.sshd.util.test.CommonTestSupportUtils; import org.apache.sshd.util.test.CoreTestSupportUtils; import org.apache.sshd.util.test.JSchLogger; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.FixMethodOrder; -import org.junit.Test; -import org.junit.runners.MethodSorters; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.MethodOrderer.MethodName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestMethodOrder; import org.springframework.integration.file.remote.session.Session; import org.springframework.integration.file.remote.session.SessionFactory; import org.springframework.integration.sftp.session.DefaultSftpSessionFactory; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * TODO Add javadoc * * @author Apache MINA SSHD Project */ -@FixMethodOrder(MethodSorters.NAME_ASCENDING) +@TestMethodOrder(MethodName.class) public class ApacheSshdSftpSessionFactoryTest extends BaseTestSupport { private static final Comparator BY_CASE_INSENSITIVE_FILENAME = new Comparator() { @Override @@ -99,8 +104,8 @@ public ApacheSshdSftpSessionFactoryTest() { fileSystemFactory = new VirtualFileSystemFactory(parentPath); } - @BeforeClass - public static void setupClientAndServer() throws Exception { + @BeforeAll + static void setupClientAndServer() throws Exception { JSchLogger.init(); sshd = CoreTestSupportUtils.setupTestFullSupportServer(ApacheSshdSftpSessionFactoryTest.class); sshd.setSubsystemFactories(Collections.singletonList(new SftpSubsystemFactory())); @@ -111,8 +116,8 @@ public static void setupClientAndServer() throws Exception { client.start(); } - @AfterClass - public static void tearDownClientAndServer() throws Exception { + @AfterAll + static void tearDownClientAndServer() throws Exception { if (sshd != null) { try { sshd.stop(true); @@ -130,41 +135,41 @@ public static void tearDownClientAndServer() throws Exception { } } - @Before - public void setUp() throws Exception { + @BeforeEach + void setUp() throws Exception { sshd.setFileSystemFactory(fileSystemFactory); // just making sure } @Test - public void testOpenCloseStateReport() throws Exception { + void openCloseStateReport() throws Exception { SessionFactory sshdFactory = getSshdSessionFactory(); try (Session sshdSession = sshdFactory.getSession()) { - assertTrue("Session not reported as open", sshdSession.isOpen()); + assertTrue(sshdSession.isOpen(), "Session not reported as open"); sshdSession.close(); - assertFalse("Session not reported as closed", sshdSession.isOpen()); + assertFalse(sshdSession.isOpen(), "Session not reported as closed"); } } @Test - public void testSharedSessionInstance() throws Exception { + void sharedSessionInstance() throws Exception { ApacheSshdSftpSessionFactory sshdFactory = getSshdSessionFactory(true); ClientSession sessionInstance; try (Session sshdSession = sshdFactory.getSession()) { SftpClient client = (SftpClient) sshdSession.getClientInstance(); sessionInstance = client.getClientSession(); - assertSame("Mismatched factory session instance", sshdFactory.getSharedClientSession(), sessionInstance); + assertSame(sshdFactory.getSharedClientSession(), sessionInstance, "Mismatched factory session instance"); } for (int index = 1; index <= Byte.SIZE; index++) { try (Session sshdSession = sshdFactory.getSession()) { SftpClient client = (SftpClient) sshdSession.getClientInstance(); - assertSame("Mismatched session #" + index + " session instance", sessionInstance, client.getClientSession()); + assertSame(sessionInstance, client.getClientSession(), "Mismatched session #" + index + " session instance"); } } } @Test - public void testWriteRemoteFileContents() throws Exception { + void writeRemoteFileContents() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -193,14 +198,14 @@ private static void testWriteRemoteFileContents( try (InputStream inputStream = Files.newInputStream(srcFile)) { session.write(inputStream, remotePath); } - assertTrue(type + ": destination file not created", Files.exists(dstFile)); + assertTrue(Files.exists(dstFile), type + ": destination file not created"); List actualLines = Files.readAllLines(dstFile, StandardCharsets.UTF_8); assertListEquals(type, expectedLines, actualLines); } @Test - public void testRetrieveRemoteFileContents() throws Exception { + void retrieveRemoteFileContents() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -248,7 +253,7 @@ private static List readRemoteFileLines(Session session, String remot } @Test - public void testListContents() throws Exception { + void listContents() throws Exception { Path targetPath = detectTargetFolder(); Path lclSftp = CommonTestSupportUtils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); @@ -340,12 +345,13 @@ public void testListContents() throws Exception { } private static void assertLocalEntriesEqual(List expected, List actual, boolean dirs) { - assertEquals("Mismatched dir=" + dirs + " entries count", expected.size(), actual.size()); + assertEquals(expected.size(), actual.size(), "Mismatched dir=" + dirs + " entries count"); for (int index = 0; index < expected.size(); index++) { Path path = expected.get(index); SftpClient.DirEntry de = actual.get(index); - assertEquals("Mismatched filename at dirs=" + dirs + " index=" + index, Objects.toString(path.getFileName(), null), - de.getFilename()); + assertEquals(Objects.toString(path.getFileName(), null), + de.getFilename(), + "Mismatched filename at dirs=" + dirs + " index=" + index); Attributes deAttrs = de.getAttributes(); assertEquals("Mismatched SSHD directory indicator for " + path, dirs, deAttrs.isDirectory()); @@ -353,11 +359,11 @@ private static void assertLocalEntriesEqual(List expected, List expected, List actual, boolean dirs) { - assertEquals("Mismatched dir=" + dirs + " entries count", expected.size(), actual.size()); + assertEquals(expected.size(), actual.size(), "Mismatched dir=" + dirs + " entries count"); for (int index = 0; index < expected.size(); index++) { LsEntry lse = expected.get(index); SftpClient.DirEntry de = actual.get(index); - assertEquals("Mismatched filename at dirs=" + dirs + " index=" + index, lse.getFilename(), de.getFilename()); + assertEquals(lse.getFilename(), de.getFilename(), "Mismatched filename at dirs=" + dirs + " index=" + index); SftpATTRS lsAttrs = lse.getAttrs(); Attributes deAttrs = de.getAttributes();